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): add Oracle-family trigger and native job management
efeirefe9d0024f880
diff --git a/agents/common/src/main/java/com/dbx/agent/AbstractJdbcAgent.java b/agents/common/src/main/java/com/dbx/agent/AbstractJdbcAgent.javaindex ccdb74b91e..46fc452aff 100644--- a/agents/common/src/main/java/com/dbx/agent/AbstractJdbcAgent.java+++ b/agents/common/src/main/java/com/dbx/agent/AbstractJdbcAgent.java@@ -31,6 +31,7 @@ public abstract class AbstractJdbcAgent extends BaseDatabaseAgent {private boolean leasePinnedAtRequestStart;private boolean sessionAffinity;private boolean pooledConnectionPoisoned;+ private boolean nativeJobConnection;@Overridepublic boolean supportsQueryTiming() { return true; }@@ -53,6 +54,7 @@ public abstract class AbstractJdbcAgent extends BaseDatabaseAgent {requestActive = false;leasePinnedAtRequestStart = false;pooledConnectionPoisoned = false;+ nativeJobConnection = false;loadDriver(params);configuredDatabase = params.getDatabase();connectParams = params;@@ -289,6 +291,7 @@ public abstract class AbstractJdbcAgent extends BaseDatabaseAgent {requestActive = false;leasePinnedAtRequestStart = false;pooledConnectionPoisoned = false;+ nativeJobConnection = false;identifierQuote = "";});}@@ -347,6 +350,7 @@ public abstract class AbstractJdbcAgent extends BaseDatabaseAgent {String identity;JdbcConnectionPoolRegistry registry;synchronized (this) {+ if (nativeJobConnection) return;if (poolRegistry == null) {return;}@@ -395,6 +399,7 @@ public abstract class AbstractJdbcAgent extends BaseDatabaseAgent {boolean endsSessionAffinity,boolean preservesSchemaContext) {+ if (nativeJobConnection) return;if (poolRegistry == null) {return;}@@ -445,6 +450,53 @@ public abstract class AbstractJdbcAgent extends BaseDatabaseAgent {releasePooledConnection(!preparePooledConnectionForReturn());}+ final synchronized void requireIdleNativeJobSession(JdbcExecutor executor) throws Exception {+ if (connectParams == null) throw new IllegalStateException("Not connected");+ if (JdbcSessionRole.from(connectParams.getSessionRole()) != JdbcSessionRole.METADATA) {+ throw new IllegalStateException("native_job_metadata_session_required");+ }+ if (nativeJobConnection || requestActive || pooledLease != null || sessionAffinity+ || executor.hasOpenSessions() || executor.hasActiveStatements() || hasRetainedResultResources()+ || (connection != null && !connection.getAutoCommit())) {+ throw new IllegalStateException("native_job_session_busy");+ }+ }++ final synchronized Connection openNativeJobConnection() throws Exception {+ nativeJobConnection = true;+ try {+ ConnectParams params = connectParams;+ if (connection == null) {+ connection = poolRegistry == null ? openInitializedConnection(params)+ : poolRegistry.openDedicatedConnection(() -> openInitializedConnection(params));+ afterConnect(params, connection);+ }+ connection.setAutoCommit(false);+ return connection;+ } catch (Exception | LinkageError error) {+ try {+ closeNativeJobConnection();+ } catch (Exception | LinkageError closeError) {+ error.addSuppressed(closeError);+ throw AgentRpcError.resource("close",+ new JdbcConnectionPoolRegistry.PhysicalConnectionStateUnknownException(error));+ }+ if (!JdbcConnectionPoolRegistry.requiresRuntimeReplacement(error)) nativeJobConnection = false;+ throw error;+ }+ }++ final synchronized void closeNativeJobConnection() throws Exception {+ if (!nativeJobConnection) return;+ Connection owned = connection;+ connection = null;+ if (owned != null) owned.close();+ }++ final synchronized boolean hasNativeJobConnection() {+ return nativeJobConnection;+ }+private static String resolveIdentifierQuote(ConnectParams params, Connection connection) {if (isPostgresCompatibleJdbc(params)) {try (Statement statement = connection.createStatement()) {diff --git a/agents/common/src/main/java/com/dbx/agent/AgentProtocol.java b/agents/common/src/main/java/com/dbx/agent/AgentProtocol.javaindex 2f9ac6d2eb..ed8a1e1978 100644--- a/agents/common/src/main/java/com/dbx/agent/AgentProtocol.java+++ b/agents/common/src/main/java/com/dbx/agent/AgentProtocol.java@@ -49,6 +49,12 @@ public final class AgentProtocol {public static final String METHOD_BEGIN_MANUAL_TRANSACTION = "begin_manual_transaction";public static final String METHOD_COMMIT_MANUAL_TRANSACTION = "commit_manual_transaction";public static final String METHOD_ROLLBACK_MANUAL_TRANSACTION = "rollback_manual_transaction";+ public static final String METHOD_PREPARE_LEGACY_JOB = "prepare_legacy_job";+ public static final String METHOD_COMMIT_LEGACY_JOB = "commit_legacy_job";+ public static final String METHOD_ROLLBACK_LEGACY_JOB = "rollback_legacy_job";+ public static final String METHOD_LEGACY_JOB_STATUS = "legacy_job_status";+ public static final String METHOD_OPEN_NATIVE_JOB_SESSION = "open_native_job_session";+ public static final String METHOD_CLOSE_NATIVE_JOB_SESSION = "close_native_job_session";public static final String METHOD_DISCONNECT = "disconnect";public static final String METHOD_SHUTDOWN = "shutdown";@@ -144,6 +150,9 @@ public final class AgentProtocol {public static final String CAPABILITY_MULTI_SESSION = "multi_session";public static final String CAPABILITY_STRUCTURED_ERROR_V1 = "structured_error_v1";public static final String CAPABILITY_BLOB_BIND_STATEMENTS_V1 = "blob_bind_statements_v1";+ public static final String CAPABILITY_NATIVE_JOB_LEGACY_V1 = "native_job_legacy_v1";+ public static final String CAPABILITY_NATIVE_JOB_LEGACY_OB_V1 = "native_job_legacy_ob_v1";+ public static final String CAPABILITY_NATIVE_JOB_SESSION_V1 = "native_job_session_v1";public static final String CAPABILITY_EXACT_METADATA_IDENTITY_V1 = "exact_metadata_identity_v1";public static final List<String> CAPABILITIES = Collections.unmodifiableList(Arrays.asList(@@ -183,6 +192,8 @@ public final class AgentProtocol {CAPABILITY_MONGO_BULK_WRITE,CAPABILITY_MONGO_RENAME_COLLECTION,CAPABILITY_MONGO_FIND_CURSOR,+ CAPABILITY_NATIVE_JOB_LEGACY_V1,+ CAPABILITY_NATIVE_JOB_SESSION_V1,CAPABILITY_EXACT_METADATA_IDENTITY_V1));@@ -236,6 +247,16 @@ public final class AgentProtocol {));public static final List<String> MULTI_SESSION_METHODS;+ public static final List<String> NATIVE_JOB_LEGACY_METHODS = Collections.unmodifiableList(Arrays.asList(+ METHOD_PREPARE_LEGACY_JOB,+ METHOD_COMMIT_LEGACY_JOB,+ METHOD_ROLLBACK_LEGACY_JOB,+ METHOD_LEGACY_JOB_STATUS+ ));+ public static final List<String> NATIVE_JOB_SESSION_METHODS = Collections.unmodifiableList(Arrays.asList(+ METHOD_OPEN_NATIVE_JOB_SESSION,+ METHOD_CLOSE_NATIVE_JOB_SESSION+ ));static {List<String> capabilities = new java.util.ArrayList<>(CAPABILITIES);@@ -275,6 +296,7 @@ public final class AgentProtocol {List<String> jdbcAllCapabilities = new java.util.ArrayList<>(MULTI_SESSION_ALL_CAPABILITIES);jdbcAllCapabilities.add(CAPABILITY_STRUCTURED_ERROR_V1);jdbcAllCapabilities.add(CAPABILITY_BLOB_BIND_STATEMENTS_V1);+ jdbcAllCapabilities.add(CAPABILITY_NATIVE_JOB_LEGACY_OB_V1);MULTI_SESSION_JDBC_ALL_CAPABILITIES = Collections.unmodifiableList(jdbcAllCapabilities);List<String> methods = new java.util.ArrayList<>(COMMON_METHODS);@@ -399,9 +421,19 @@ public final class AgentProtocol {}public static HandshakeResult multiSessionJdbcHandshakeResult(boolean blobBindStatements) {- if (!blobBindStatements) return multiSessionJdbcHandshakeResult();+ return multiSessionJdbcHandshakeResult(blobBindStatements, false);+ }++ public static HandshakeResult multiSessionJdbcHandshakeResult(boolean blobBindStatements, boolean nativeJobSessions) {+ return multiSessionJdbcHandshakeResult(blobBindStatements, nativeJobSessions, false);+ }++ public static HandshakeResult multiSessionJdbcHandshakeResult(boolean blobBindStatements, boolean nativeJobSessions, boolean nativeLegacyJobs) {+ if (!blobBindStatements && !nativeJobSessions && !nativeLegacyJobs) return multiSessionJdbcHandshakeResult();java.util.ArrayList<String> capabilities = new java.util.ArrayList<>(MULTI_SESSION_JDBC_CAPABILITIES);- capabilities.add(CAPABILITY_BLOB_BIND_STATEMENTS_V1);+ if (blobBindStatements) capabilities.add(CAPABILITY_BLOB_BIND_STATEMENTS_V1);+ if (nativeJobSessions) capabilities.add(CAPABILITY_NATIVE_JOB_SESSION_V1);+ if (nativeLegacyJobs) capabilities.add(CAPABILITY_NATIVE_JOB_LEGACY_OB_V1);return new HandshakeResult(MULTI_SESSION_PROTOCOL_VERSION, MULTI_SESSION_PROTOCOL_VERSION, capabilities);}diff --git a/agents/common/src/main/java/com/dbx/agent/DatabaseAgent.java b/agents/common/src/main/java/com/dbx/agent/DatabaseAgent.javaindex 761ca63821..29eebdbaf9 100644--- a/agents/common/src/main/java/com/dbx/agent/DatabaseAgent.java+++ b/agents/common/src/main/java/com/dbx/agent/DatabaseAgent.java@@ -16,6 +16,12 @@ public interface DatabaseAgent {default boolean supportsBlobBindStatements() { return false; }+ /** Opt in to an operation-owned physical connection for native Job configuration. */+ default boolean supportsNativeJobSessions() { return false; }++ /** Opt in to OB's operation-owned Legacy SUBMIT/first-commit protocol. */+ default boolean supportsNativeLegacyJobs() { return false; }+/** Opt in only when dictionary-derived owner/name values are preserved without fallback. */default boolean supportsExactMetadataIdentity() { return false; }@@ -86,6 +92,10 @@ public interface DatabaseAgent {return MetadataListConstraints.orNone(constraints).filterObjects(listObjects(schema));}+ default List<ObjectInfo> listObjects(String schema, MetadataListConstraints constraints, MetadataReadOptions options) {+ return listObjects(schema, constraints);+ }+default List<String> listDataTypes() {return Collections.emptyList();}@@ -104,6 +114,10 @@ public interface DatabaseAgent {throw new UnsupportedOperationException("Object source is not supported");}+ default ObjectSource getObjectSource(String schema, String name, String objectType, MetadataReadOptions options) {+ return getObjectSource(schema, name, objectType);+ }+default ObjectSource getObjectSourceWithOrigin(String schema, String name, String objectType) {return getObjectSource(schema, name, objectType);}@@ -184,6 +198,10 @@ public interface DatabaseAgent {List<TriggerInfo> listTriggers(String schema, String table);+ default List<TriggerInfo> listTriggers(String schema, String table, MetadataReadOptions options) {+ return listTriggers(schema, table);+ }+default List<PartitionInfo> listPartitions(String schema, String table) {return Collections.emptyList();}diff --git a/agents/common/src/main/java/com/dbx/agent/JdbcConnectionPoolRegistry.java b/agents/common/src/main/java/com/dbx/agent/JdbcConnectionPoolRegistry.javaindex a9e5594ade..171f023507 100644--- a/agents/common/src/main/java/com/dbx/agent/JdbcConnectionPoolRegistry.java+++ b/agents/common/src/main/java/com/dbx/agent/JdbcConnectionPoolRegistry.java@@ -121,6 +121,29 @@ final class JdbcConnectionPoolRegistry implements AutoCloseable {return pools.size();}+ /** Uses the existing physical budget and watchdogs, but never enters a reusable pool. */+ Connection openDedicatedConnection(ConnectionFactory connectionFactory) throws SQLException {+ if (closed.get()) throw new IllegalStateException("JDBC connection pool registry is closed");+ SQLException failure = runtimeFailure.get();+ if (failure != null) throw AgentRpcError.resource("connect", failure);+ ConnectionFactoryDataSource source = new ConnectionFactoryDataSource(connectionFactory,+ physicalConnectionBudget, physicalConnectionOpener, physicalConnectionCloser,+ settings.connectionTimeoutMillis);+ OperationDeadline deadline = new OperationDeadline(settings.connectionTimeoutMillis);+ try (ConnectionFactoryDataSource.DeadlineRegistration ignored = source.registerCheckout(deadline)) {+ Connection opened = source.getConnection();+ // No Hikari setup follows on this path: the initialized physical connection is ready.+ ((HikariSetupTrackedConnection) opened).completeHikariSetup();+ return opened;+ } catch (SQLException error) {+ if (contains(error, PhysicalConnectionLimitException.class)) {+ throw AgentRpcError.backpressure("connect", error);+ }+ if (requiresRuntimeReplacement(error)) throw AgentRpcError.resource("connect", error);+ throw error;+ }+ }+boolean isEnabled() {return settings.enabled;}diff --git a/agents/common/src/main/java/com/dbx/agent/JsonRpcServer.java b/agents/common/src/main/java/com/dbx/agent/JsonRpcServer.javaindex 36603560e6..5f9b98c0e5 100644--- a/agents/common/src/main/java/com/dbx/agent/JsonRpcServer.java+++ b/agents/common/src/main/java/com/dbx/agent/JsonRpcServer.java@@ -39,6 +39,8 @@ public final class JsonRpcServer {.create();private ConnectParams lastConnectParams;private long lastConnectionValidationTimeMillis;+ private NativeJobSession nativeJobSession;+ private NativeLegacyJobSession nativeLegacyJobSession;public JsonRpcServer(DatabaseAgent agent) {this.agent = agent;@@ -110,6 +112,7 @@ public final class JsonRpcServer {private Object dispatchWithConnection(String method, JsonObject params) throws Exception {return AgentExecutionContext.withJdbcExecutor(jdbcExecutor, () -> {+ authorizeNativeJobRequest(method, params);AbstractJdbcAgent jdbcAgent = pooledJdbcAgent();if (AgentProtocol.METHOD_VALIDATE_CONNECTION.equals(method)&& jdbcAgent != null@@ -182,6 +185,28 @@ public final class JsonRpcServer {}private Object dispatch(String method, JsonObject params) throws Exception {+ authorizeNativeJobRequest(method, params);+ if (NativeLegacyJobSession.isControl(method)) return legacyJob(method, params);+ if (AgentProtocol.METHOD_OPEN_NATIVE_JOB_SESSION.equals(method)) {+ String operationId = NativeJobSession.operationId(params);+ if (nativeJobSession != null) return nativeJobSession.openedFor(operationId);+ if (!(agent instanceof AbstractJdbcAgent jdbcAgent) || !agent.supportsNativeJobSessions()) {+ throw new UnsupportedOperationException("native_job_session_not_supported");+ }+ jdbcAgent.requireIdleNativeJobSession(jdbcExecutor);+ nativeJobSession = new NativeJobSession(jdbcAgent, operationId);+ try {+ nativeJobSession.open();+ return nativeJobSession.openedFor(operationId);+ } catch (Exception | LinkageError error) {+ if (!nativeJobSession.openOutcomeUnknown()) nativeJobSession = null;+ throw error;+ }+ }+ if (AgentProtocol.METHOD_CLOSE_NATIVE_JOB_SESSION.equals(method)) {+ if (nativeJobSession == null) throw new IllegalStateException("native_job_session_unavailable");+ return nativeJobSession.close(params);+ }if (agent instanceof AbstractJdbcAgent observingAgent) {observingAgent.beforeAgentMethod(method, stringOrNull(params, "sessionId"));}@@ -253,6 +278,8 @@ public final class JsonRpcServer {}if (AgentProtocol.METHOD_LIST_OBJECTS.equals(method)) {switchCatalog(params);+ MetadataReadOptions options = metadataReadOptions(params);+ if (options.exact()) return agent.listObjects(params.get("schema").getAsString(), metadataListConstraints(params), options);return agent.listObjects(params.get("schema").getAsString(), metadataListConstraints(params));}if (AgentProtocol.METHOD_LIST_DATA_TYPES.equals(method)) {@@ -265,13 +292,16 @@ public final class JsonRpcServer {}if (AgentProtocol.METHOD_GET_OBJECT_SOURCE.equals(method)) {switchCatalog(params);+ MetadataReadOptions options = metadataReadOptions(params);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);+ ObjectSource source = options.exact()+ ? agent.getObjectSource(schema, name, objectType, options)+ : includeOrigin+ ? agent.getObjectSourceWithOrigin(schema, name, objectType)+ : agent.getObjectSource(schema, name, objectType);if (includeOrigin) {JsonObject result = gson.toJsonTree(source).getAsJsonObject();if (source.getSourceOrigin() != null) {@@ -303,6 +333,8 @@ public final class JsonRpcServer {}if (AgentProtocol.METHOD_LIST_TRIGGERS.equals(method)) {switchCatalog(params);+ MetadataReadOptions options = metadataReadOptions(params);+ if (options.exact()) return agent.listTriggers(params.get("schema").getAsString(), params.get("table").getAsString(), options);return agent.listTriggers(params.get("schema").getAsString(), params.get("table").getAsString());}if (AgentProtocol.METHOD_LIST_CONSTRAINTS.equals(method)) {@@ -424,22 +456,77 @@ public final class JsonRpcServer {() -> agent.executeBatch(statements, stringOrNull(params, "schema")));}if (AgentProtocol.METHOD_DISCONNECT.equals(method)) {- jdbcExecutor.closeAllQuerySessions();- jdbcExecutor.closeAllTableReadSessions();- agent.disconnect();- lastConnectParams = null;+ disconnect();return Collections.singletonMap("ok", true);}if (AgentProtocol.METHOD_SHUTDOWN.equals(method)) {- jdbcExecutor.closeAllQuerySessions();- jdbcExecutor.closeAllTableReadSessions();- agent.disconnect();- lastConnectParams = null;+ disconnect();return Collections.singletonMap("ok", true);}throw new IllegalArgumentException("Unknown method: " + method);}+ private void authorizeNativeJobRequest(String method, JsonObject params) throws Exception {+ if (AgentProtocol.METHOD_HANDSHAKE.equals(method)+ || AgentProtocol.METHOD_DISCONNECT.equals(method) || AgentProtocol.METHOD_SHUTDOWN.equals(method)) return;+ if (nativeLegacyJobSession != null && !NativeLegacyJobSession.isControl(method)) {+ throw new IllegalStateException("native_job_session_reserved");+ }+ if (NativeLegacyJobSession.isControl(method)) {+ if (nativeJobSession != null) throw new IllegalStateException("native_job_session_reserved");+ return;+ }+ if (NativeJobSession.isControl(method)) return;+ if (nativeJobSession != null) {+ nativeJobSession.authorize(method, params);+ } else if (params.has("nativeJobSessionToken") || params.has("nativeJobOperationId")) {+ // A replacement logical session must not borrow a connection for an old lease token.+ throw new IllegalStateException("native_job_session_unavailable");+ }+ }++ private void disconnect() {+ jdbcExecutor.closeAllQuerySessions();+ jdbcExecutor.closeAllTableReadSessions();+ JsonObject nativeClose = nativeJobSession == null ? null : nativeJobSession.dispose();+ JsonObject legacyClose = nativeLegacyJobSession == null ? null : nativeLegacyJobSession.dispose();+ agent.disconnect();+ lastConnectParams = null;+ if ((nativeClose != null && !"closed".equals(nativeClose.get("phase").getAsString()))+ || (legacyClose != null && (!legacyClose.has("disposalConfirmed") || !legacyClose.get("disposalConfirmed").getAsBoolean()))) {+ throw AgentRpcError.resource("close", new JdbcConnectionPoolRegistry.PhysicalConnectionStateUnknownException(+ new IllegalStateException("native_job_session_dispose_unknown")));+ }+ }++ private JsonObject legacyJob(String method, JsonObject params) throws Exception {+ String operationId = NativeJobSession.operationId(params);+ if (AgentProtocol.METHOD_PREPARE_LEGACY_JOB.equals(method)) {+ if (!(agent instanceof AbstractJdbcAgent jdbcAgent) || !agent.supportsNativeLegacyJobs()) {+ throw new UnsupportedOperationException("native_job_legacy_protocol_unavailable");+ }+ NativeLegacyJobSession candidate;+ try { candidate = new NativeLegacyJobSession(jdbcAgent, params); }+ catch (IllegalArgumentException invalid) {+ return NativeLegacyJobSession.failure(operationId, "not_started", invalid.getMessage());+ }+ if (nativeLegacyJobSession != null) {+ return nativeLegacyJobSession.sameRequest(candidate) ? nativeLegacyJobSession.status(operationId)+ : NativeLegacyJobSession.failure(operationId, "unknown", "native_job_operation_mismatch");+ }+ jdbcAgent.requireIdleNativeJobSession(jdbcExecutor);+ nativeLegacyJobSession = candidate;+ candidate.prepare();+ return candidate.status(operationId);+ }+ if (nativeLegacyJobSession == null) {+ return NativeLegacyJobSession.failure(operationId, "unknown", "native_job_legacy_session_unavailable");+ }+ if (AgentProtocol.METHOD_LEGACY_JOB_STATUS.equals(method)) return nativeLegacyJobSession.status(operationId);+ return nativeLegacyJobSession.finish(operationId, stringOrNull(params, "jobId") == null ? "" : stringOrNull(params, "jobId"),+ AgentProtocol.METHOD_COMMIT_LEGACY_JOB.equals(method));+ }+private QueryResult executeStatementsWithTimeout(int timeoutSecs, DatabaseAgent.ThrowingSupplier<QueryResult> execute) throws Exception {try (JdbcExecutor.NativeOperation operation = jdbcExecutor.beginNativeOperation()) {return AgentExecutionContext.withStatementTimeout(timeoutSecs, operation,@@ -504,6 +591,7 @@ public final class JsonRpcServer {}private void ensureLiveConnection(String method) {+ if (agent instanceof AbstractJdbcAgent jdbcAgent && jdbcAgent.hasNativeJobConnection()) return;if (!agent.permitsAutomaticReconnect()) return;if (lastConnectParams == null || !shouldValidateConnection(method)) {return;@@ -547,6 +635,8 @@ public final class JsonRpcServer {return !AgentProtocol.METHOD_HANDSHAKE.equals(method)&& !AgentProtocol.METHOD_CONNECT.equals(method)&& !AgentProtocol.METHOD_TEST_CONNECTION.equals(method)+ && !NativeJobSession.isControl(method)+ && !NativeLegacyJobSession.isControl(method)&& !AgentProtocol.METHOD_VALIDATE_CONNECTION.equals(method)&& !AgentProtocol.METHOD_FETCH_QUERY_PAGE.equals(method)&& !AgentProtocol.METHOD_CLOSE_QUERY_SESSION.equals(method)@@ -567,6 +657,8 @@ public final class JsonRpcServer {return !AgentProtocol.METHOD_HANDSHAKE.equals(method)&& !AgentProtocol.METHOD_CONNECT.equals(method)&& !AgentProtocol.METHOD_TEST_CONNECTION.equals(method)+ && !NativeJobSession.isControl(method)+ && !NativeLegacyJobSession.isControl(method)&& !AgentProtocol.METHOD_DISCONNECT.equals(method)&& !AgentProtocol.METHOD_SHUTDOWN.equals(method);}@@ -669,6 +761,15 @@ public final class JsonRpcServer {);}+ private static MetadataReadOptions metadataReadOptions(JsonObject params) {+ String mode = stringOrNull(params, "identity_mode");+ String alias = stringOrNull(params, "identityMode");+ if (mode != null && alias != null && !mode.equals(alias)) {+ throw new IllegalArgumentException("Conflicting metadata identity modes");+ }+ return MetadataReadOptions.fromIdentityMode(mode != null ? mode : alias);+ }+private static int intOrDefault(JsonObject object, String key, int defaultValue) {Integer value = intOrNull(object, key);return value == null ? defaultValue : value;diff --git a/agents/common/src/main/java/com/dbx/agent/MetadataReadOptions.java b/agents/common/src/main/java/com/dbx/agent/MetadataReadOptions.javanew file mode 100644index 0000000000..1e97e27e68--- /dev/null+++ b/agents/common/src/main/java/com/dbx/agent/MetadataReadOptions.java@@ -0,0 +1,13 @@+package com.dbx.agent;++/** Optional read semantics; accepting an option is not proof of provider support. */+public record MetadataReadOptions(boolean exact) {+ public static final MetadataReadOptions DEFAULT = new MetadataReadOptions(false);+ public static final MetadataReadOptions EXACT = new MetadataReadOptions(true);++ public static MetadataReadOptions fromIdentityMode(String mode) {+ if (mode == null) return DEFAULT;+ if ("exact".equals(mode)) return EXACT;+ throw new IllegalArgumentException("Unsupported metadata identity mode");+ }+}diff --git a/agents/common/src/main/java/com/dbx/agent/MultiSessionJsonRpcServer.java b/agents/common/src/main/java/com/dbx/agent/MultiSessionJsonRpcServer.javaindex 38e6c142c0..ec7bff5a75 100644--- a/agents/common/src/main/java/com/dbx/agent/MultiSessionJsonRpcServer.java+++ b/agents/common/src/main/java/com/dbx/agent/MultiSessionJsonRpcServer.java@@ -46,6 +46,8 @@ public final class MultiSessionJsonRpcServer implements AutoCloseable {private final AtomicBoolean closed = new AtomicBoolean();private ScheduledExecutorService maintenance;private boolean blobBindStatements;+ private boolean nativeJobSessions;+ private boolean nativeLegacyJobs;private boolean exactMetadataIdentity;public MultiSessionJsonRpcServer(Supplier<? extends DatabaseAgent> agentFactory) {@@ -99,6 +101,19 @@ public final class MultiSessionJsonRpcServer implements AutoCloseable {return server;}+ public static MultiSessionJsonRpcServer withNativeJobSessions(Supplier<? extends DatabaseAgent> agentFactory) {+ MultiSessionJsonRpcServer server = new MultiSessionJsonRpcServer(agentFactory);+ server.nativeJobSessions = true;+ return server;+ }++ public static MultiSessionJsonRpcServer withNativeLegacyJobs(Supplier<? extends DatabaseAgent> agentFactory, boolean blobBindings) {+ MultiSessionJsonRpcServer server = new MultiSessionJsonRpcServer(agentFactory);+ server.nativeLegacyJobs = true;+ server.blobBindStatements = blobBindings;+ return server;+ }+public MultiSessionJsonRpcServer withExactMetadataIdentity() {exactMetadataIdentity = true;return this;@@ -152,7 +167,7 @@ public final class MultiSessionJsonRpcServer implements AutoCloseable {Object result;if (AgentProtocol.METHOD_HANDSHAKE.equals(method)) {result = sessionHandlerFactory == null- ? AgentProtocol.withExactMetadataIdentity(AgentProtocol.multiSessionJdbcHandshakeResult(blobBindStatements), exactMetadataIdentity)+ ? AgentProtocol.withExactMetadataIdentity(AgentProtocol.multiSessionJdbcHandshakeResult(blobBindStatements, nativeJobSessions, nativeLegacyJobs), exactMetadataIdentity): customHandshake();} else if (AgentProtocol.METHOD_OPEN_SESSION.equals(method)) {result = openSession(requiredSessionId(params), params);diff --git a/agents/common/src/main/java/com/dbx/agent/NativeJobSession.java b/agents/common/src/main/java/com/dbx/agent/NativeJobSession.javanew file mode 100644index 0000000000..01369508b3--- /dev/null+++ b/agents/common/src/main/java/com/dbx/agent/NativeJobSession.java@@ -0,0 +1,116 @@+package com.dbx.agent;++import com.google.gson.JsonObject;+import java.sql.Connection;+import java.util.UUID;++/** Owns only the connection; Core owns native configuration phases, SQL and dispatch deduplication. */+final class NativeJobSession {+ private final AbstractJdbcAgent agent;+ private final String operationId;+ private final String token = UUID.randomUUID().toString();+ private final JsonObject receipt = new JsonObject();+ private Connection owned;+ private boolean closeAttempted;++ NativeJobSession(AbstractJdbcAgent agent, String operationId) {+ this.agent = agent;+ this.operationId = operationId;+ receipt.addProperty("operationId", operationId);+ receipt.addProperty("sessionToken", token);+ receipt.addProperty("phase", "not_started");+ }++ static String operationId(JsonObject params) {+ String id = text(params, "operationId");+ if (id.isEmpty() || id.length() > 128 || id.indexOf('\0') >= 0) {+ throw new IllegalArgumentException("native_job_request_invalid");+ }+ return id;+ }++ static boolean isControl(String method) {+ return AgentProtocol.METHOD_OPEN_NATIVE_JOB_SESSION.equals(method)+ || AgentProtocol.METHOD_CLOSE_NATIVE_JOB_SESSION.equals(method);+ }++ void open() throws Exception {+ try {+ owned = agent.openNativeJobConnection();+ receipt.addProperty("phase", "opened");+ } catch (Exception | LinkageError error) {+ if (JdbcConnectionPoolRegistry.requiresRuntimeReplacement(error)) {+ closeAttempted = true;+ receipt.addProperty("phase", "unknown");+ receipt.addProperty("reason", "native_job_session_open_unknown");+ }+ throw error;+ }+ }++ JsonObject openedFor(String id) throws Exception {+ requireOperation(id);+ if ("opened".equals(receipt.get("phase").getAsString())) requireOwnedConnection();+ return receipt.deepCopy();+ }++ void authorize(String method, JsonObject params) throws Exception {+ if (!AgentProtocol.METHOD_EXECUTE_QUERY.equals(method) && !AgentProtocol.METHOD_CONNECTION_INFO.equals(method)) {+ throw new IllegalStateException("native_job_session_reserved");+ }+ requireOperation(text(params, "nativeJobOperationId"));+ if (!token.equals(text(params, "nativeJobSessionToken"))) {+ throw new IllegalStateException("native_job_session_token_invalid");+ }+ requireOwnedConnection();+ }++ private void requireOperation(String id) {+ if (!operationId.equals(id)) throw new IllegalStateException("native_job_operation_mismatch");+ }++ private void requireOwnedConnection() throws Exception {+ if (!"opened".equals(receipt.get("phase").getAsString())+ || owned == null || agent.getConnection() != owned || owned.isClosed()) {+ throw new IllegalStateException("native_job_session_unavailable");+ }+ }++ JsonObject close(JsonObject params) {+ requireOperation(operationId(params));+ String requestedToken = text(params, "sessionToken");+ // The known operation may dispose its own connection after losing the open receipt.+ if (!requestedToken.isEmpty() && !token.equals(requestedToken)) {+ throw new IllegalStateException("native_job_session_token_invalid");+ }+ return dispose();+ }++ JsonObject dispose() {+ if (closeAttempted) return receipt.deepCopy();+ closeAttempted = true;+ try {+ agent.closeNativeJobConnection();+ receipt.addProperty("phase", "closed");+ } catch (Exception | LinkageError error) {+ receipt.addProperty("phase", "unknown");+ receipt.addProperty("reason", "native_job_session_dispose_unknown");+ JsonObject diagnostics = AgentRpcError.toJson(error, AgentProtocol.METHOD_CLOSE_NATIVE_JOB_SESSION, null)+ .getAsJsonObject("data");+ if (diagnostics.has("vendorCode")) receipt.add("vendorCode", diagnostics.get("vendorCode"));+ }+ return receipt.deepCopy();+ }++ boolean openOutcomeUnknown() {+ return "unknown".equals(receipt.get("phase").getAsString());+ }++ private static String text(JsonObject params, String key) {+ if (!params.has(key) || params.get(key).isJsonNull()) return "";+ if (!params.get(key).isJsonPrimitive() || !params.getAsJsonPrimitive(key).isString()) {+ throw new IllegalArgumentException("native_job_request_invalid");+ }+ return params.get(key).getAsString();+ }+}diff --git a/agents/common/src/main/java/com/dbx/agent/NativeLegacyJobSession.java b/agents/common/src/main/java/com/dbx/agent/NativeLegacyJobSession.javanew file mode 100644index 0000000000..a4fe3fd9e8--- /dev/null+++ b/agents/common/src/main/java/com/dbx/agent/NativeLegacyJobSession.java@@ -0,0 +1,271 @@+package com.dbx.agent;++import com.google.gson.JsonElement;+import com.google.gson.JsonObject;+import java.sql.CallableStatement;+import java.sql.Connection;+import java.sql.PreparedStatement;+import java.sql.ResultSet;+import java.sql.Types;+import java.time.LocalDateTime;+import java.time.format.DateTimeFormatter;+import java.time.format.ResolverStyle;+import java.util.Objects;++/** Owns one OB SUBMIT transaction until Core records its OUT ID and authorizes the first commit. */+final class NativeLegacyJobSession {+ private static final DateTimeFormatter DATE = DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss")+ .withResolverStyle(ResolverStyle.STRICT);+ private final AbstractJdbcAgent agent;+ private final String operationId;+ private final String what;+ private final String nextDate;+ private final String interval;+ private final String schema;+ private final String zone;+ private final boolean enabled;+ private final int timeoutSecs;+ private final JsonObject receipt;+ private Connection connection;+ private boolean transactionActive;+ private boolean closeAttempted;+ private boolean disposalConfirmed = true;++ NativeLegacyJobSession(AbstractJdbcAgent agent, JsonObject params) {+ this.agent = agent;+ operationId = NativeJobSession.operationId(params);+ what = text(params, "what", "");+ nextDate = text(params, "nextDate", "");+ interval = text(params, "interval", "");+ schema = text(params, "schema", "");+ zone = params.has("zone") && !params.get("zone").isJsonNull() ? text(params, "zone", "") : null;+ if (!"oceanbase-oracle".equals(text(params, "dialect", "")) || integer(params, "instance") != 0+ || what.isBlank() || what.indexOf('\0') >= 0 || interval.indexOf('\0') >= 0 || schema.indexOf('\0') >= 0+ || (zone != null && (zone.isEmpty() || zone.indexOf('\0') >= 0))+ || !params.has("enabled") || !params.get("enabled").isJsonPrimitive()+ || !params.getAsJsonPrimitive("enabled").isBoolean()) {+ throw new IllegalArgumentException("native_job_request_invalid");+ }+ enabled = params.get("enabled").getAsBoolean();+ timeoutSecs = integer(params, "timeoutSecs");+ try {+ if (!nextDate.matches("[0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}:[0-9]{2}")+ || LocalDateTime.parse(nextDate, DATE).getYear() < 1) throw new IllegalArgumentException();+ } catch (RuntimeException invalid) {+ throw new IllegalArgumentException("native_job_date_invalid");+ }+ receipt = failure(operationId, "not_started", null);+ }++ static boolean isControl(String method) {+ return AgentProtocol.NATIVE_JOB_LEGACY_METHODS.contains(method);+ }++ static JsonObject failure(String operationId, String phase, String reason) {+ JsonObject result = new JsonObject();+ result.addProperty("operationId", operationId);+ result.addProperty("phase", phase);+ if (reason != null) result.addProperty("reason", reason);+ return result;+ }++ boolean sameRequest(NativeLegacyJobSession other) {+ return operationId.equals(other.operationId) && what.equals(other.what) && nextDate.equals(other.nextDate)+ && interval.equals(other.interval) && schema.equals(other.schema) && Objects.equals(zone, other.zone)+ && enabled == other.enabled && timeoutSecs == other.timeoutSecs;+ }++ void prepare() {+ String reason = "native_job_session_open_failed";+ try {+ connection = agent.openNativeJobConnection();+ reason = "native_job_dialect_unverified";+ if (!"OceanBase".equalsIgnoreCase(connection.getMetaData().getDatabaseProductName())) {+ receipt.addProperty("reason", reason);+ close();+ return;+ }+ transactionActive = true;+ reason = "native_job_schema_not_selected";+ if (!schema.isEmpty()) {+ try (var statement = connection.createStatement()) {+ statement.setQueryTimeout(timeoutSecs);+ statement.execute("ALTER SESSION SET CURRENT_SCHEMA = \"" + schema.replace("\"", "\"\"") + "\"");+ }+ }+ reason = "native_job_initial_identity_unverified";+ String user;+ try (PreparedStatement statement = connection.prepareStatement("SELECT USER AS DBX_SESSION_USER FROM DUAL")) {+ statement.setQueryTimeout(timeoutSecs);+ try (ResultSet rows = statement.executeQuery()) {+ if (!rows.next()) throw new IllegalStateException(reason);+ user = rows.getString(1);+ if (user == null || user.isEmpty() || rows.next()) throw new IllegalStateException(reason);+ }+ }+ receipt.addProperty("phase", "submitting");+ reason = "native_job_submit_failed";+ try (CallableStatement statement = connection.prepareCall("""+ DECLARE native_id BINARY_INTEGER;+ BEGIN+ SYS.DBMS_JOB.SUBMIT(job => native_id, what => ?, next_date => TO_DATE(?, 'YYYY-MM-DD HH24:MI:SS'), interval => ?, no_parse => FALSE, zone => ?, force => FALSE);+ ? := TO_CHAR(native_id);+ END;+ """)) {+ statement.setQueryTimeout(timeoutSecs);+ statement.setString(1, what);+ statement.setString(2, nextDate);+ statement.setString(3, interval);+ if (zone == null) statement.setNull(4, Types.VARCHAR);+ else statement.setString(4, zone);+ statement.registerOutParameter(5, Types.VARCHAR);+ statement.execute();+ reason = "native_job_out_read_failed";+ String id = statement.getString(5);+ if (numericId(id)) receipt.addProperty("jobId", id);+ }+ if (!receipt.has("jobId")) {+ rollback("native_job_out_id_unverified", null);+ return;+ }+ receipt.addProperty("phase", "configuring");+ reason = "native_job_initial_state_failed";+ try (CallableStatement statement = connection.prepareCall(+ "BEGIN SYS.DBMS_JOB.BROKEN(TO_NUMBER(?), ? = 1, TO_DATE(?, 'YYYY-MM-DD HH24:MI:SS')); END;")) {+ statement.setQueryTimeout(timeoutSecs);+ statement.setString(1, receipt.get("jobId").getAsString());+ statement.setInt(2, enabled ? 0 : 1);+ statement.setString(3, nextDate);+ statement.execute();+ }+ // OB BROKEN(TRUE) replaces NEXT_DATE with 4000-01-01 even when a date is supplied.+ try (CallableStatement statement = connection.prepareCall(+ "BEGIN SYS.DBMS_JOB.NEXT_DATE(TO_NUMBER(?), TO_DATE(?, 'YYYY-MM-DD HH24:MI:SS')); END;")) {+ statement.setQueryTimeout(timeoutSecs);+ statement.setString(1, receipt.get("jobId").getAsString());+ statement.setString(2, nextDate);+ statement.execute();+ }+ reason = "native_job_initial_read_failed";+ boolean verified;+ try (PreparedStatement statement = connection.prepareStatement("""+ SELECT TO_CHAR(JOB), WHAT, TO_CHAR(NEXT_DATE, 'YYYY-MM-DD HH24:MI:SS'), INTERVAL,+ BROKEN, INSTANCE, LOG_USER, PRIV_USER, SCHEMA_USER+ FROM SYS.USER_JOBS WHERE JOB = TO_NUMBER(?)+ """)) {+ statement.setQueryTimeout(timeoutSecs);+ statement.setString(1, receipt.get("jobId").getAsString());+ try (ResultSet rows = statement.executeQuery()) {+ verified = rows.next() && receipt.get("jobId").getAsString().equals(rows.getString(1))+ && what.equals(rows.getString(2)) && nextDate.equals(rows.getString(3))+ && interval.equals(Objects.requireNonNullElse(rows.getString(4), ""))+ && (enabled ? "N" : "Y").equals(rows.getString(5)) && Objects.equals(zone, rows.getString(6))+ && user.equals(rows.getString(7)) && user.equals(rows.getString(8))+ && (schema.isEmpty() || schema.equals(rows.getString(9))) && !rows.next();+ }+ }+ if (!verified) {+ rollback("native_job_initial_state_unverified", null);+ return;+ }+ receipt.addProperty("phase", "prepared");+ } catch (Exception | LinkageError error) {+ if (transactionActive) rollback(reason, error);+ else {+ receipt.addProperty("reason", reason);+ diagnostics(error);+ if (connection == null) {+ boolean unknown = JdbcConnectionPoolRegistry.requiresRuntimeReplacement(error);+ receipt.addProperty("phase", unknown ? "unknown" : "not_started");+ receipt.addProperty("disposalConfirmed", !unknown);+ disposalConfirmed = !unknown;+ closeAttempted = true;+ } else close();+ }+ }+ }++ JsonObject status(String id) {+ return operationId.equals(id) ? receipt.deepCopy()+ : failure(id, "unknown", "native_job_session_unavailable");+ }++ JsonObject finish(String operation, String id, boolean commit) {+ if (!operationId.equals(operation) || !"prepared".equals(receipt.get("phase").getAsString())) return status(operation);+ if ((commit || !id.isEmpty()) && (!numericId(id) || !id.equals(receipt.get("jobId").getAsString()))) {+ return failure(operation, "unknown", "native_job_identity_mismatch");+ }+ if (!commit) {+ rollback("native_job_canceled_before_commit", null);+ return status(operation);+ }+ receipt.addProperty("phase", "commit_sent");+ transactionActive = false;+ try {+ connection.commit();+ receipt.addProperty("phase", "committed");+ } catch (Exception | LinkageError error) {+ receipt.addProperty("phase", "unknown");+ receipt.addProperty("reason", "native_job_commit_unknown");+ diagnostics(error);+ } finally { close(); }+ return status(operation);+ }++ private void rollback(String reason, Throwable cause) {+ receipt.addProperty("reason", reason);+ diagnostics(cause);+ transactionActive = false;+ try {+ connection.rollback();+ receipt.addProperty("phase", "rolled_back");+ } catch (Exception | LinkageError error) {+ disposalConfirmed = false;+ receipt.addProperty("phase", "unknown");+ receipt.addProperty("reason", "native_job_rollback_unknown");+ diagnostics(error);+ } finally { close(); }+ }++ JsonObject dispose() {+ if (transactionActive) rollback("native_job_session_closed_before_commit", null);+ else close();+ return receipt.deepCopy();+ }++ private void close() {+ if (closeAttempted) return;+ closeAttempted = true;+ connection = null;+ try { agent.closeNativeJobConnection(); }+ catch (Exception | LinkageError error) {+ disposalConfirmed = false;+ diagnostics(error);+ }+ receipt.addProperty("disposalConfirmed", disposalConfirmed);+ }++ private void diagnostics(Throwable error) {+ if (error == null) return;+ JsonObject data = AgentRpcError.toJson(error, AgentProtocol.METHOD_PREPARE_LEGACY_JOB, null).getAsJsonObject("data");+ for (String field : new String[]{"vendorCode", "sqlState"}) {+ if (data.has(field)) receipt.add(field, data.get(field));+ }+ }++ private static boolean numericId(String id) { return id != null && id.matches("[1-9][0-9]*"); }+ private static String text(JsonObject params, String key, String fallback) {+ JsonElement value = params.get(key);+ if (value == null || value.isJsonNull()) return fallback;+ if (!value.isJsonPrimitive() || !value.getAsJsonPrimitive().isString()) throw new IllegalArgumentException("native_job_request_invalid");+ return value.getAsString();+ }+ private static int integer(JsonObject params, String key) {+ if (!params.has(key)) return 0;+ JsonElement value = params.get(key);+ try {+ if (!value.isJsonPrimitive() || !value.getAsJsonPrimitive().isNumber() || !value.getAsString().matches("0|[1-9][0-9]*")) throw new NumberFormatException();+ return Integer.parseInt(value.getAsString());+ } catch (RuntimeException invalid) { throw new IllegalArgumentException("native_job_request_invalid"); }+ }+}diff --git a/agents/common/src/main/java/com/dbx/agent/ObjectInfo.java b/agents/common/src/main/java/com/dbx/agent/ObjectInfo.javaindex ef21b9ea72..2ed21e8b38 100644--- a/agents/common/src/main/java/com/dbx/agent/ObjectInfo.java+++ b/agents/common/src/main/java/com/dbx/agent/ObjectInfo.java@@ -10,6 +10,7 @@ public final class ObjectInfo {private Boolean valid;private String parent_name;private String parent_schema;+ private TriggerInfo trigger;public ObjectInfo() {this("", "", null, null, null);@@ -71,14 +72,6 @@ public final class ObjectInfo {this.valid = valid;}- public String getParent_name() {- return parent_name;- }-- public void setParent_name(String parentName) {- this.parent_name = parentName;- }-public String getParent_schema() {return parent_schema;}@@ -87,6 +80,22 @@ public final class ObjectInfo {this.parent_schema = parentSchema;}+ public TriggerInfo getTrigger() {+ return trigger;+ }++ public void setTrigger(TriggerInfo trigger) {+ this.trigger = trigger;+ }++ public String getParent_name() {+ return parent_name;+ }++ public void setParent_name(String parentName) {+ this.parent_name = parentName;+ }+@Overridepublic boolean equals(Object other) {if (this == other) return true;@@ -97,13 +106,14 @@ public final class ObjectInfo {&& Objects.equals(schema, that.schema)&& Objects.equals(comment, that.comment)&& Objects.equals(parent_name, that.parent_name)+ && Objects.equals(valid, that.valid)&& Objects.equals(parent_schema, that.parent_schema)- && Objects.equals(valid, that.valid);+ && Objects.equals(trigger, that.trigger);}@Overridepublic int hashCode() {- return Objects.hash(name, object_type, schema, comment, valid, parent_name, parent_schema);+ return Objects.hash(name, object_type, schema, comment, valid, parent_name, parent_schema, trigger);}@Overridediff --git a/agents/common/src/main/java/com/dbx/agent/ObjectSource.java b/agents/common/src/main/java/com/dbx/agent/ObjectSource.javaindex 3aaba3a05d..e22ae076ff 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 TriggerInfo trigger;private transient String sourceOrigin;public ObjectSource() {@@ -78,6 +79,14 @@ public final class ObjectSource {this.editable = editable;}+ public TriggerInfo getTrigger() {+ return trigger;+ }++ public void setTrigger(TriggerInfo trigger) {+ this.trigger = trigger;+ }+@Overridepublic boolean equals(Object other) {if (this == other) return true;@@ -87,12 +96,13 @@ public final class ObjectSource {&& Objects.equals(object_type, that.object_type)&& Objects.equals(schema, that.schema)&& Objects.equals(source, that.source)- && editable == that.editable;+ && editable == that.editable+ && Objects.equals(trigger, that.trigger);}@Overridepublic int hashCode() {- return Objects.hash(name, object_type, schema, source, editable);+ return Objects.hash(name, object_type, schema, source, editable, trigger);}@Overridediff --git a/agents/common/src/main/java/com/dbx/agent/OracleTriggerMetadata.java b/agents/common/src/main/java/com/dbx/agent/OracleTriggerMetadata.javanew file mode 100644index 0000000000..ec85c19cc4--- /dev/null+++ b/agents/common/src/main/java/com/dbx/agent/OracleTriggerMetadata.java@@ -0,0 +1,17 @@+package com.dbx.agent;++import java.util.List;+import java.util.Map;++/** Raw dictionary identity. Missing fields remain unknown, not false or empty. */+public record OracleTriggerMetadata(+ int contractVersion, String identityMode, String engine, String engineVersion,+ String owner, String name, String scope, String scopeType, String scopeOwner,+ Parent parent, String objectId, String lastDdlTime, Definition definition,+ List<CompilationError> errors, Map<String, ReadState> reads+) {+ public record Parent(String owner, String name, String objectType, String objectId) {}+ public record Definition(String origin, String format, boolean complete) {}+ public record CompilationError(long sequence, long line, long position, String text, String severity) {}+ public record ReadState(String state, String message) {}+}diff --git a/agents/common/src/main/java/com/dbx/agent/OracleTriggerReader.java b/agents/common/src/main/java/com/dbx/agent/OracleTriggerReader.javanew file mode 100644index 0000000000..53ad52f1d8--- /dev/null+++ b/agents/common/src/main/java/com/dbx/agent/OracleTriggerReader.java@@ -0,0 +1,319 @@+package com.dbx.agent;++import java.io.IOException;+import java.io.Reader;+import java.sql.Clob;+import java.sql.Connection;+import java.sql.PreparedStatement;+import java.sql.ResultSet;+import java.sql.ResultSetMetaData;+import java.sql.SQLException;+import java.sql.SQLFeatureNotSupportedException;+import java.util.ArrayList;+import java.util.LinkedHashMap;+import java.util.List;+import java.util.Locale;+import java.util.Map;++/** Exact Oracle-family trigger reads, shared by the JDBC-based native agents. */+public final class OracleTriggerReader {+ private static final int NAME_BATCH_SIZE = 500;+ private static final String OBJECT_MARKER = "DBX_TRIGGER_OBJECT_MARKER";+ private static final String ORACLE_SUMMARY_COLUMNS = "t.OWNER, t.TRIGGER_NAME, t.TRIGGERING_EVENT, t.TRIGGER_TYPE, "+ + "t.STATUS, t.TABLE_OWNER, t.TABLE_NAME, t.BASE_OBJECT_TYPE, t.WHEN_CLAUSE, t.REFERENCING_NAMES, t.DESCRIPTION";+ private final Connection connection;+ private final String engine;+ private final String version;++ public OracleTriggerReader(Connection connection, String engine) throws SQLException {+ this.connection = connection;+ this.engine = engine;+ String productVersion;+ try {+ productVersion = connection.getMetaData().getDatabaseProductVersion();+ } catch (SQLException error) {+ productVersion = null;+ }+ this.version = productVersion;+ }++ public List<TriggerInfo> listTriggers(String parentOwner, String parentName) throws SQLException {+ requireIdentity(parentOwner, parentName);+ return summaries("t.TABLE_OWNER = ? AND t.TABLE_NAME = ?", List.of(parentOwner, parentName), true);+ }++ /** Enrich only the already filtered/paged trigger rows, never one source query per row. */+ public void enrichObjects(List<ObjectInfo> objects, String owner) throws SQLException {+ List<ObjectInfo> triggers = objects.stream().filter(object -> "TRIGGER".equals(object.getObject_type())).toList();+ for (int start = 0; start < triggers.size(); start += NAME_BATCH_SIZE) {+ List<ObjectInfo> batch = triggers.subList(start, Math.min(start + NAME_BATCH_SIZE, triggers.size()));+ List<String> args = new ArrayList<>();+ args.add(owner);+ for (ObjectInfo object : batch) args.add(object.getName());+ String names = String.join(",", java.util.Collections.nCopies(batch.size(), "?"));+ Map<Identity, TriggerInfo> byIdentity = new LinkedHashMap<>();+ try {+ for (TriggerInfo trigger : summaries("t.OWNER = ? AND t.TRIGGER_NAME IN (" + names + ")", args, false)) {+ OracleTriggerMetadata metadata = trigger.getOracle_metadata();+ Identity identity = new Identity(metadata.owner(), metadata.name());+ if (byIdentity.put(identity, trigger) != null) throw new SQLException("Trigger identity is not unique");+ }+ for (ObjectInfo object : batch) {+ TriggerInfo trigger = byIdentity.get(new Identity(owner, object.getName()));+ if (trigger == null) trigger = unavailable(object, owner, new OracleTriggerMetadata.ReadState("incomplete", "Trigger changed or is no longer visible; reload"));+ attach(object, trigger);+ }+ } catch (SQLException error) {+ for (ObjectInfo object : batch) attach(object, unavailable(object, owner, readFailure(error)));+ }+ }+ }++ private static void attach(ObjectInfo object, TriggerInfo trigger) {+ object.setTrigger(trigger);+ object.setValid(trigger.getValid());+ OracleTriggerMetadata.Parent parent = trigger.getOracle_metadata().parent();+ object.setParent_schema(parent == null ? null : parent.owner());+ object.setParent_name(parent == null ? null : parent.name());+ }++ private TriggerInfo unavailable(ObjectInfo object, String owner, OracleTriggerMetadata.ReadState failure) {+ TriggerInfo trigger = new TriggerInfo(object.getName(), "", "");+ Map<String, OracleTriggerMetadata.ReadState> reads = new LinkedHashMap<>();+ reads.put("identity", new OracleTriggerMetadata.ReadState("incomplete", "Object version could not be verified"));+ for (String field : List.of("scope", "parent", "enabled", "validity")) reads.put(field, failure);+ trigger.setOracle_metadata(new OracleTriggerMetadata(1, "exact", engine, version, owner, object.getName(),+ "UNKNOWN", null, null, null, null, null, null, null, reads));+ return trigger;+ }++ public ObjectSource getObjectSource(String owner, String name) throws SQLException {+ requireIdentity(owner, name);+ List<TriggerInfo> beforeRows = summaries("t.OWNER = ? AND t.TRIGGER_NAME = ?", List.of(owner, name), true);+ if (beforeRows.size() > 1) throw new SQLException("Trigger identity is not unique");+ if (beforeRows.isEmpty()) {+ ObjectSource result = new ObjectSource(name, "TRIGGER", owner, "", false);+ TriggerInfo trigger = unavailable(new ObjectInfo(name, "TRIGGER", owner, null), owner, missing("Visible trigger"));+ trigger.getOracle_metadata().reads().put("identity", new OracleTriggerMetadata.ReadState("empty", "No visible trigger with this exact owner/name"));+ result.setTrigger(trigger);+ return result;+ }+ TriggerInfo before = beforeRows.get(0);+ if (!owner.equals(before.getOracle_metadata().owner()) || !name.equals(before.getName())) {+ throw new SQLException("Trigger identity does not match the exact request");+ }+ SourceText source = source(owner, name, before.getStatement());+ List<OracleTriggerMetadata.CompilationError> errors = null;+ OracleTriggerMetadata.ReadState errorState;+ try {+ errors = errors(owner, name);+ errorState = available();+ } catch (SQLException error) {+ errorState = readFailure(error);+ }+ List<TriggerInfo> afterRows = summaries("t.OWNER = ? AND t.TRIGGER_NAME = ?", List.of(owner, name), true);+ boolean stable = afterRows.size() == 1 && before.equals(afterRows.get(0));+ TriggerInfo current = afterRows.size() == 1 ? afterRows.get(0) : before;+ OracleTriggerMetadata metadata = current.getOracle_metadata();+ Map<String, OracleTriggerMetadata.ReadState> reads = new LinkedHashMap<>(metadata.reads());+ reads.put("definition", stable ? source.state() : new OracleTriggerMetadata.ReadState("incomplete", "Trigger changed while loading; reload"));+ reads.put("errors", errorState);+ if (!stable) reads.put("identity", new OracleTriggerMetadata.ReadState("incomplete", "Trigger changed while loading; reload"));+ current.setOracle_metadata(new OracleTriggerMetadata(1, "exact", engine, version, metadata.owner(), metadata.name(),+ metadata.scope(), metadata.scopeType(), metadata.scopeOwner(), metadata.parent(), metadata.objectId(), metadata.lastDdlTime(),+ new OracleTriggerMetadata.Definition(source.origin(), source.format(), stable && source.complete()), errors, reads));+ ObjectSource result = new ObjectSource(name, "TRIGGER", owner, source.text());+ result.setTrigger(current);+ return result;+ }++ private List<TriggerInfo> summaries(String predicate, List<String> args, boolean includeBody) throws SQLException {+ // DM releases differ in optional trigger/object columns. SELECT * keeps a+ // missing column distinguishable from an error reading a present column.+ String projection = "dm".equals(engine) || includeBody ? "t.*" : ORACLE_SUMMARY_COLUMNS;+ String sql = "SELECT " + projection + ", o.OBJECT_NAME AS " + OBJECT_MARKER + ", o.* FROM ALL_TRIGGERS t "+ + "LEFT JOIN ALL_OBJECTS o ON o.OWNER = t.OWNER AND o.OBJECT_NAME = t.TRIGGER_NAME AND o.OBJECT_TYPE = 'TRIGGER' "+ + "WHERE " + predicate + " ORDER BY t.TRIGGER_NAME, t.OWNER";+ List<TriggerInfo> result = new ArrayList<>();+ try (PreparedStatement statement = connection.prepareStatement(sql)) {+ for (int i = 0; i < args.size(); i++) statement.setString(i + 1, args.get(i));+ try (ResultSet rows = statement.executeQuery()) {+ Columns columns = new Columns(rows.getMetaData());+ while (rows.next()) result.add(summary(rows, columns, includeBody));+ }+ }+ return result;+ }++ private TriggerInfo summary(ResultSet row, Columns columns, boolean includeBody) throws SQLException {+ String owner = columns.trigger(row, "OWNER");+ String name = columns.trigger(row, "TRIGGER_NAME");+ requireIdentity(owner, name);+ String event = columns.trigger(row, "TRIGGERING_EVENT");+ String timing = columns.trigger(row, "TRIGGER_TYPE");+ TriggerInfo trigger = new TriggerInfo(name, event == null ? "" : event, timing == null ? "" : timing);+ trigger.setEnabled(enabled(columns.trigger(row, "STATUS")));+ trigger.setValid(validity(columns.object(row, "STATUS")));+ trigger.setCondition(columns.trigger(row, "WHEN_CLAUSE"));+ if (includeBody) trigger.setStatement(columns.trigger(row, "TRIGGER_BODY"));+ String scopeType = columns.trigger(row, "BASE_OBJECT_TYPE");+ String scope = scopeType == null ? "UNKNOWN" : switch (scopeType.toUpperCase(Locale.ROOT)) {+ case "TABLE", "VIEW", "SCHEMA", "DATABASE", "TIMER" -> scopeType.toUpperCase(Locale.ROOT);+ default -> "OTHER";+ };+ if ("dm".equals(engine) && "DATABASE".equals(scope) && "TIMER".equalsIgnoreCase(event)) scope = "TIMER";+ String parentOwner = columns.trigger(row, "TABLE_OWNER");+ String parentName = columns.trigger(row, "TABLE_NAME");+ OracleTriggerMetadata.Parent parent = ("TABLE".equals(scope) || "VIEW".equals(scope)) && parentOwner != null && parentName != null+ ? new OracleTriggerMetadata.Parent(parentOwner, parentName, scope, null) : null;+ String objectId = columns.object(row, "OBJECT_ID");+ Map<String, OracleTriggerMetadata.ReadState> reads = new LinkedHashMap<>();+ reads.put("identity", objectId == null ? missing("Object ID") : available());+ reads.put("scope", "UNKNOWN".equals(scope) ? missing("Trigger scope") : available());+ reads.put("parent", "UNKNOWN".equals(scope) || "OTHER".equals(scope)+ || ("TABLE".equals(scope) || "VIEW".equals(scope)) && parent == null ? missing("Owning object") : available());+ if ("SCHEMA".equals(scope) && parentOwner == null) reads.put("scope", missing("Scope owner"));+ reads.put("enabled", trigger.getEnabled() == null ? missing("Enabled state") : available());+ reads.put("validity", trigger.getValid() == null ? missing("Object validity") : available());+ trigger.setOracle_metadata(new OracleTriggerMetadata(1, "exact", engine, version, owner, name, scope, scopeType,+ "SCHEMA".equals(scope) ? parentOwner : null, parent, objectId, columns.object(row, "LAST_DDL_TIME"), null, null, reads));+ return trigger;+ }++ private SourceText source(String owner, String name, String body) throws SQLException {+ SQLException firstError = null;+ boolean metadataFirst = "dm".equals(engine);+ for (boolean metadata : new boolean[]{metadataFirst, !metadataFirst}) {+ try {+ String text = metadata ? metadataSource(owner, name) : dictionarySource(owner, name);+ if (text != null && !text.isBlank()) return new SourceText(text, metadata ? "DBMS_METADATA" : "ALL_SOURCE",+ metadata ? "ddl" : "declaration", true, available());+ } catch (SQLException error) {+ if (firstError == null) firstError = error;+ }+ }+ return new SourceText(body == null ? "" : body, "catalog-body", "body", false,+ firstError == null ? missing("Complete trigger definition") : readFailure(firstError));+ }++ private String dictionarySource(String owner, String name) throws SQLException {+ try (PreparedStatement statement = connection.prepareStatement("SELECT LINE, TEXT FROM ALL_SOURCE WHERE OWNER = ? AND NAME = ? AND TYPE = 'TRIGGER' ORDER BY LINE")) {+ statement.setString(1, owner);+ statement.setString(2, name);+ StringBuilder text = new StringBuilder();+ long expectedLine = 1;+ try (ResultSet rows = statement.executeQuery()) {+ while (rows.next()) {+ if (rows.getLong(1) != expectedLine++ || rows.wasNull()) throw new SQLException("Trigger source dictionary lines are incomplete");+ String line = text(rows, 2);+ if (line == null) throw new SQLException("Trigger source contains an unreadable line");+ text.append(line);+ }+ }+ return text.toString();+ }+ }++ private String metadataSource(String owner, String name) throws SQLException {+ try (PreparedStatement statement = connection.prepareStatement("SELECT DBMS_METADATA.GET_DDL(?, ?, ?) FROM DUAL")) {+ statement.setString(1, "TRIGGER");+ statement.setString(2, name);+ statement.setString(3, owner);+ try (ResultSet rows = statement.executeQuery()) {+ return rows.next() ? text(rows, 1) : null;+ }+ }+ }++ private List<OracleTriggerMetadata.CompilationError> errors(String owner, String name) throws SQLException {+ List<OracleTriggerMetadata.CompilationError> result = new ArrayList<>();+ try (PreparedStatement statement = connection.prepareStatement("SELECT SEQUENCE, LINE, POSITION, TEXT, ATTRIBUTE FROM ALL_ERRORS WHERE OWNER = ? AND NAME = ? AND TYPE = 'TRIGGER' ORDER BY SEQUENCE")) {+ statement.setString(1, owner);+ statement.setString(2, name);+ try (ResultSet rows = statement.executeQuery()) {+ while (rows.next()) {+ String text = text(rows, 4);+ if (text == null) throw new SQLException("Trigger compilation error text is unreadable");+ result.add(new OracleTriggerMetadata.CompilationError(rows.getLong(1), rows.getLong(2), rows.getLong(3), text, rows.getString(5)));+ }+ }+ }+ return result;+ }++ private static String text(ResultSet rows, int column) throws SQLException {+ Reader stream;+ try {+ stream = rows.getCharacterStream(column);+ } catch (SQLFeatureNotSupportedException | AbstractMethodError unsupported) {+ stream = null;+ }+ if (stream == null) {+ Object value = rows.getObject(column);+ if (!(value instanceof Clob clob)) return rows.getString(column);+ stream = clob.getCharacterStream();+ }+ // Once a stream has started, a failed read must not fall back to a+ // potentially truncated getString() and claim a complete definition.+ try (Reader reader = stream) {+ StringBuilder text = new StringBuilder();+ char[] buffer = new char[8192];+ for (int count; (count = reader.read(buffer)) != -1;) text.append(buffer, 0, count);+ return text.toString();+ } catch (IOException error) {+ throw new SQLException("Trigger text could not be read completely", error);+ }+ }++ private static void requireIdentity(String owner, String name) throws SQLException {+ if (owner == null || owner.isEmpty() || name == null || name.isEmpty()) throw new SQLException("Exact trigger metadata requires owner and name");+ }++ private static Boolean enabled(String status) {+ if (status == null) return null;+ return switch (status.trim().toUpperCase(Locale.ROOT)) {+ case "ENABLED", "ENABLE", "Y" -> true;+ case "DISABLED", "DISABLE", "N" -> false;+ default -> null;+ };+ }++ private static Boolean validity(String status) {+ if (status == null) return null;+ return switch (status.trim().toUpperCase(Locale.ROOT)) { case "VALID" -> true; case "INVALID" -> false; default -> null; };+ }++ private static OracleTriggerMetadata.ReadState available() { return new OracleTriggerMetadata.ReadState("available", null); }+ private static OracleTriggerMetadata.ReadState missing(String field) { return new OracleTriggerMetadata.ReadState("unavailable", field + " is not exposed by this dictionary"); }+ private static OracleTriggerMetadata.ReadState readFailure(SQLException error) {+ int code = error.getErrorCode();+ String state = error.getSQLState();+ String category = code == 1031 || "42501".equals(state) ? "denied"+ : code == 942 || code == 904 || "42S02".equals(state) || "42S22".equals(state) ? "unavailable" : "error";+ return new OracleTriggerMetadata.ReadState(category, "Metadata read failed (SQLState " + state + ", code " + code + ")");+ }++ private record Identity(String owner, String name) {}+ private record SourceText(String text, String origin, String format, boolean complete, OracleTriggerMetadata.ReadState state) {}++ private static final class Columns {+ private final Map<String, Integer> trigger = new LinkedHashMap<>();+ private final Map<String, Integer> object = new LinkedHashMap<>();++ Columns(ResultSetMetaData metadata) throws SQLException {+ boolean objectColumns = false;+ for (int i = 1; i <= metadata.getColumnCount(); i++) {+ String label = metadata.getColumnLabel(i).toUpperCase(Locale.ROOT);+ if (OBJECT_MARKER.equals(label)) { objectColumns = true; continue; }+ (objectColumns ? object : trigger).putIfAbsent(label, i);+ }+ }++ String trigger(ResultSet row, String name) throws SQLException { return value(row, trigger, name); }+ String object(ResultSet row, String name) throws SQLException { return value(row, object, name); }+ private static String value(ResultSet row, Map<String, Integer> columns, String name) throws SQLException {+ Integer index = columns.get(name);+ return index == null ? null : "TRIGGER_BODY".equals(name) ? text(row, index) : row.getString(index);+ }+ }+}diff --git a/agents/common/src/main/java/com/dbx/agent/TriggerInfo.java b/agents/common/src/main/java/com/dbx/agent/TriggerInfo.javaindex 876a003b52..8da634a12c 100644--- a/agents/common/src/main/java/com/dbx/agent/TriggerInfo.java+++ b/agents/common/src/main/java/com/dbx/agent/TriggerInfo.java@@ -9,6 +9,8 @@ public final class TriggerInfo {private String statement;private String condition;private Boolean enabled;+ private Boolean valid;+ private OracleTriggerMetadata oracle_metadata;public TriggerInfo() {this("", "", "");@@ -76,6 +78,22 @@ public final class TriggerInfo {this.enabled = enabled;}+ public Boolean getValid() {+ return valid;+ }++ public void setValid(Boolean valid) {+ this.valid = valid;+ }++ public OracleTriggerMetadata getOracle_metadata() {+ return oracle_metadata;+ }++ public void setOracle_metadata(OracleTriggerMetadata metadata) {+ this.oracle_metadata = metadata;+ }+@Overridepublic boolean equals(Object other) {if (this == other) return true;@@ -86,12 +104,14 @@ public final class TriggerInfo {&& Objects.equals(timing, that.timing)&& Objects.equals(statement, that.statement)&& Objects.equals(condition, that.condition)- && Objects.equals(enabled, that.enabled);+ && Objects.equals(enabled, that.enabled)+ && Objects.equals(valid, that.valid)+ && Objects.equals(oracle_metadata, that.oracle_metadata);}@Overridepublic int hashCode() {- return Objects.hash(name, event, timing, statement, condition, enabled);+ return Objects.hash(name, event, timing, statement, condition, enabled, valid, oracle_metadata);}@Overridediff --git a/agents/common/src/main/resources/agent-protocol-v1.json b/agents/common/src/main/resources/agent-protocol-v1.jsonindex c7713e1aa7..1c1f12d33d 100644--- a/agents/common/src/main/resources/agent-protocol-v1.json+++ b/agents/common/src/main/resources/agent-protocol-v1.json@@ -2,9 +2,11 @@"protocolVersion": 1,"handshakeMethod": "handshake","handshakeResponseFields": ["protocolVersion", "agentProtocolVersion", "capabilities"],- "allCapabilities": ["connect", "test_connection", "metadata", "query", "paged_query", "transaction", "ddl", "kv", "kv_ttl", "kv_cas", "kv_list_values", "kv_status", "kv_history", "etcd_compaction", "etcd_defrag", "etcd_watch", "etcd_lease", "etcd_auth", "mongo_drop_database", "mongo_clone_collection", "mongo_run_command", "mongo_insert_documents", "mongo_replace_document", "mongo_bulk_write", "mongo_rename_collection", "mongo_find_cursor", "exact_metadata_identity_v1"],+ "allCapabilities": ["connect", "test_connection", "metadata", "query", "paged_query", "transaction", "ddl", "kv", "kv_ttl", "kv_cas", "kv_list_values", "kv_status", "kv_history", "etcd_compaction", "etcd_defrag", "etcd_watch", "etcd_lease", "etcd_auth", "mongo_drop_database", "mongo_clone_collection", "mongo_run_command", "mongo_insert_documents", "mongo_replace_document", "mongo_bulk_write", "mongo_rename_collection", "mongo_find_cursor", "native_job_legacy_v1", "native_job_session_v1", "exact_metadata_identity_v1"],"capabilities": ["connect", "test_connection", "metadata", "query", "paged_query", "transaction", "ddl"],"defaultSqlCapabilities": ["connect", "test_connection", "metadata", "query", "paged_query", "transaction", "ddl"],+ "nativeJobLegacyMethods": ["prepare_legacy_job", "commit_legacy_job", "rollback_legacy_job", "legacy_job_status"],+ "nativeJobSessionMethods": ["open_native_job_session", "close_native_job_session"],"commonMethods": ["handshake","connect",diff --git a/agents/common/src/main/resources/agent-protocol-v2.json b/agents/common/src/main/resources/agent-protocol-v2.jsonindex 3b472f8a5b..1528b78844 100644--- a/agents/common/src/main/resources/agent-protocol-v2.json+++ b/agents/common/src/main/resources/agent-protocol-v2.json@@ -2,9 +2,52 @@"protocolVersion": 2,"handshakeMethod": "handshake","handshakeResponseFields": ["protocolVersion", "agentProtocolVersion", "capabilities"],- "allCapabilities": ["connect", "test_connection", "metadata", "query", "paged_query", "transaction", "ddl", "kv", "kv_ttl", "kv_cas", "kv_list_values", "kv_status", "kv_history", "etcd_compaction", "etcd_defrag", "etcd_watch", "etcd_lease", "etcd_auth", "mongo_drop_database", "mongo_clone_collection", "mongo_run_command", "mongo_insert_documents", "mongo_replace_document", "mongo_bulk_write", "mongo_rename_collection", "mongo_find_cursor", "exact_metadata_identity_v1", "multi_session", "structured_error_v1", "blob_bind_statements_v1"],+ "allCapabilities": ["connect", "test_connection", "metadata", "query", "paged_query", "transaction", "ddl", "kv", "kv_ttl", "kv_cas", "kv_list_values", "kv_status", "kv_history", "etcd_compaction", "etcd_defrag", "etcd_watch", "etcd_lease", "etcd_auth", "mongo_drop_database", "mongo_clone_collection", "mongo_run_command", "mongo_insert_documents", "mongo_replace_document", "mongo_bulk_write", "mongo_rename_collection", "mongo_find_cursor", "native_job_legacy_v1", "native_job_session_v1", "exact_metadata_identity_v1", "multi_session", "structured_error_v1", "blob_bind_statements_v1", "native_job_legacy_ob_v1"],"capabilities": ["connect", "test_connection", "metadata", "query", "paged_query", "transaction", "ddl", "multi_session"],"defaultSqlCapabilities": ["connect", "test_connection", "metadata", "query", "paged_query", "transaction", "ddl", "multi_session", "structured_error_v1"],+ "nativeJobLegacyMethods": ["prepare_legacy_job", "commit_legacy_job", "rollback_legacy_job", "legacy_job_status"],+ "nativeJobSessionMethods": ["open_native_job_session", "close_native_job_session"],+ "nativeJobSessionV1": {+ "capability": "native_job_session_v1",+ "calledDuring": "confirmed Core apply on an operation-owned metadata logical session",+ "openFields": ["operationId"],+ "queryFields": ["nativeJobOperationId", "nativeJobSessionToken"],+ "queryMethods": ["execute_query", "connection_info"],+ "closeFields": ["operationId", "sessionToken?"],+ "resultFields": ["operationId", "sessionToken", "phase", "reason?", "vendorCode?"],+ "phases": ["not_started", "opened", "closed", "unknown"],+ "ownership": "independent non-pooled physical connection; autoCommit false; existing runtime physical budget and watchdogs apply",+ "guardRule": "same operation and opaque lease token required before every query; no editor transaction, cursor, reconnect, connection replacement or configuration change",+ "lostOpenRule": "the exact operationId may close only its owned connection without knowing the lost token; a replacement logical session cannot confirm old ownership",+ "cleanupRule": "close physical connection once; cache confirmed or unknown disposal; never commit, CONFIG_COMMIT, enable or return unfinished configuration to a pool",+ "configurationRule": "Core owns native SQL, configuration phases and dispatch deduplication; connection close does not prove native configuration rollback or completion"+ },+ "nativeJobLegacyV1": {+ "capability": "native_job_legacy_v1",+ "calledDuring": "confirmed Core apply only; never during SQL preview",+ "prepareFields": ["operationId", "what", "nextDate", "interval", "enabled", "instance", "schema", "timeoutSecs"],+ "finishFields": ["operationId", "jobId"],+ "resultFields": ["operationId", "jobId", "phase", "reason", "vendorCode"],+ "phases": ["not_started", "submitting", "configuring", "prepared", "commit_sent", "committed", "rolled_back", "unknown"],+ "prepareRule": "one owned physical transaction; SUBMIT returns an exact OUT ID, BROKEN sets the final state with explicit nextDate, then same-session readback; no commit",+ "commitRule": "Core records the returned ID before commit; the exact operationId and jobId must match; repeated requests return existing facts without dispatch",+ "rollbackRule": "operationId identifies this operation's owned transaction; jobId may be absent only for rollback after a lost prepare response; commit still requires the exact returned ID",+ "unknownRule": "lost commit response stays unknown; read the exact ID, never replay SUBMIT, commit or BROKEN",+ "cleanupRule": "before commit, confirm rollback or report unknown; discard the physical connection, never activate during cleanup",+ "scope": "native Oracle DBMS_JOB; independent of the editor transaction; nextDate is YYYY-MM-DD HH:mm:ss"+ },+ "nativeJobLegacyObV1": {+ "capability": "native_job_legacy_ob_v1",+ "calledDuring": "confirmed Core apply on its own metadata session; control dispatch precedes pool checkout and reconnect",+ "prepareFields": ["operationId", "dialect", "what", "nextDate", "interval", "enabled", "instance", "zone", "schema", "timeoutSecs"],+ "dialect": "oceanbase-oracle",+ "zoneRule": "zone is a nullable string, instance must be zero; native INSTANCE readback remains VARCHAR2 or SQL NULL",+ "prepareRule": "owned physical transaction; local BINARY_INTEGER to VARCHAR OUT; BROKEN and complete initial readback before first commit",+ "finishRule": "reuse nativeJobLegacyV1 operation/ID binding and no-replay rules; the Oracle legacy capability and requests remain unchanged",+ "resultFields": ["operationId", "jobId?", "phase", "reason?", "vendorCode?", "disposalConfirmed?"],+ "disposalRule": "terminal receipt or same-operation status must explicitly confirm original physical disposal; false is permanent, prepared is not disposed; logical close_session ok does not confirm it",+ "lostTerminalRule": "query original status only; never send another commit or rollback after a terminal dispatch"+ },"commonMethods": ["handshake","connect",diff --git a/agents/common/src/test/java/com/dbx/agent/CommonJavaCompatibilityTest.java b/agents/common/src/test/java/com/dbx/agent/CommonJavaCompatibilityTest.javaindex 955927bd76..aecd1474c5 100644--- a/agents/common/src/test/java/com/dbx/agent/CommonJavaCompatibilityTest.java+++ b/agents/common/src/test/java/com/dbx/agent/CommonJavaCompatibilityTest.java@@ -88,6 +88,8 @@ class CommonJavaCompatibilityTest {assertEquals(AgentProtocol.CAPABILITIES, strings(contract.getAsJsonArray("capabilities")));assertEquals(AgentProtocol.CAPABILITIES, strings(contract.getAsJsonArray("defaultSqlCapabilities")));assertEquals(AgentProtocol.COMMON_METHODS, strings(contract.getAsJsonArray("commonMethods")));+ assertEquals(AgentProtocol.NATIVE_JOB_LEGACY_METHODS, strings(contract.getAsJsonArray("nativeJobLegacyMethods")));+ assertEquals(AgentProtocol.NATIVE_JOB_SESSION_METHODS, strings(contract.getAsJsonArray("nativeJobSessionMethods")));assertEquals(AgentProtocol.MONGO_LEGACY_METHODS, strings(contract.getAsJsonArray("mongoLegacyMethods")));assertEquals(AgentProtocol.KV_METHODS, strings(contract.getAsJsonArray("kvMethods")));}@@ -115,6 +117,8 @@ class CommonJavaCompatibilityTest {strings(contract.getAsJsonArray("defaultSqlCapabilities")));assertEquals(AgentProtocol.MULTI_SESSION_METHODS, strings(contract.getAsJsonArray("commonMethods")));+ assertEquals(AgentProtocol.NATIVE_JOB_LEGACY_METHODS, strings(contract.getAsJsonArray("nativeJobLegacyMethods")));+ assertEquals(AgentProtocol.NATIVE_JOB_SESSION_METHODS, strings(contract.getAsJsonArray("nativeJobSessionMethods")));assertEquals(AgentProtocol.MONGO_LEGACY_METHODS, strings(contract.getAsJsonArray("mongoLegacyMethods")));assertEquals(AgentProtocol.KV_METHODS, strings(contract.getAsJsonArray("kvMethods")));}diff --git a/agents/common/src/test/java/com/dbx/agent/NativeJobSessionTest.java b/agents/common/src/test/java/com/dbx/agent/NativeJobSessionTest.javanew file mode 100644index 0000000000..f153ab3e8c--- /dev/null+++ b/agents/common/src/test/java/com/dbx/agent/NativeJobSessionTest.java@@ -0,0 +1,287 @@+package com.dbx.agent;++import com.google.gson.Gson;+import com.google.gson.JsonObject;+import com.google.gson.JsonParser;+import org.junit.jupiter.api.Test;++import java.lang.reflect.InvocationTargetException;+import java.lang.reflect.Proxy;+import java.sql.Connection;+import java.sql.DriverManager;+import java.sql.SQLException;+import java.util.ArrayList;+import java.util.Collections;+import java.util.List;+import java.util.UUID;++import static org.junit.jupiter.api.Assertions.*;++class NativeJobSessionTest {+ private static final Gson GSON = new Gson();++ @Test+ void capabilityIsExplicitAndDoesNotChangeOrdinaryOrLegacyHandshakes() {+ java.util.concurrent.atomic.AtomicInteger factories = new java.util.concurrent.atomic.AtomicInteger();+ java.util.function.Supplier<DatabaseAgent> factory = () -> {+ factories.incrementAndGet();+ return new H2Agent();+ };+ try (MultiSessionJsonRpcServer ordinary = new MultiSessionJsonRpcServer(factory);+ MultiSessionJsonRpcServer nativeJobs = MultiSessionJsonRpcServer.withNativeJobSessions(factory)) {+ String request = "{\"id\":1,\"method\":\"handshake\",\"params\":{}}";+ assertFalse(ordinary.handleRequest(request).contains("native_job_session_v1"));+ assertTrue(nativeJobs.handleRequest(request).contains("native_job_session_v1"));+ assertFalse(new JsonRpcServer(new H2Agent()).handleRequest(request).contains("native_job_session_v1"));+ assertEquals(0, factories.get(), "handshake must not create a sample database agent");+ }+ }++ @Test+ void workloadSessionsRemainOrdinaryAndCannotBePromotedToNativeJobOwnership() throws Exception {+ try (Environment env = new Environment(true, 3)) {+ JsonObject workload = env.connection.deepCopy();+ workload.addProperty("sessionRole", "workload");+ env.server.dispatchForRuntime("connect", workload);+ assertThrows(Exception.class, () -> env.open("operation"));+ assertNotNull(env.server.dispatchForRuntime("execute_query", json("{\"sql\":\"SELECT 1\"}")));+ }+ }++ @Test+ void internalCommitDoesNotReleaseOrReplaceTheOwnedPhysicalConnection() throws Exception {+ for (boolean pooled : List.of(false, true)) {+ try (Environment env = new Environment(pooled, 3)) {+ int initialPhysical = env.registry.activePhysicalConnectionCount();+ JsonObject opened = env.open("operation");+ assertEquals("opened", opened.get("phase").getAsString());+ Connection owned = env.agent.getConnection();+ assertFalse(owned.getAutoCommit());+ assertEquals(initialPhysical + (pooled ? 1 : 0), env.registry.activePhysicalConnectionCount());+ assertEquals(opened, env.open("operation"), "lost open receipts must not open another connection");+ int opens = env.agent.physical.size();+ env.query(opened, "CREATE TABLE job_session_probe (id INT)");+ env.query(opened, "INSERT INTO job_session_probe VALUES (1)");+ env.query(opened, "COMMIT");+ QueryResult rows = env.query(opened, "SELECT COUNT(*) FROM job_session_probe");+ assertEquals(1L, ((Number) rows.getRows().get(0).get(0)).longValue());+ assertSame(owned, env.agent.getConnection());+ assertFalse(owned.getAutoCommit());+ assertEquals(opens, env.agent.physical.size());+ int commits = env.agent.commits;+ int rollbacks = env.agent.rollbacks;+ JsonObject closed = env.close(opened);+ assertEquals("closed", closed.get("phase").getAsString());+ assertTrue(owned.isClosed());+ assertEquals(initialPhysical, env.registry.activePhysicalConnectionCount());+ assertEquals(closed, env.close(opened));+ assertEquals(commits, env.agent.commits, "lease cleanup must not commit job configuration");+ assertEquals(rollbacks, env.agent.rollbacks, "lease cleanup is not a configuration rollback");+ assertThrows(Exception.class, () -> env.query(opened, "SELECT 1"));+ }+ }+ }++ @Test+ void reservedSessionRejectsOrdinaryCallsChangedIdentityAndForeignTokensBeforeSql() throws Exception {+ try (Environment env = new Environment(true, 3)) {+ JsonObject opened = env.open("operation");+ int opens = env.agent.physical.size();+ for (String method : List.of("connect", "test_connection", "begin_manual_transaction", "execute_query_page")) {+ assertThrows(Exception.class, () -> env.server.dispatchForRuntime(method, env.connection.deepCopy()), method);+ }+ assertThrows(Exception.class, () -> env.server.dispatchForRuntime("execute_query", json("{\"sql\":\"SELECT 1\"}")));+ for (String field : List.of("nativeJobOperationId", "nativeJobSessionToken")) {+ JsonObject invalid = env.authorized(opened);+ invalid.addProperty(field, "foreign");+ invalid.addProperty("sql", "SELECT 1");+ assertThrows(Exception.class, () -> env.server.dispatchForRuntime("execute_query", invalid));+ }+ assertThrows(Exception.class, () -> env.open("other-operation"));+ assertEquals(opens, env.agent.physical.size());+ assertEquals(1L, ((Number) env.query(opened, "SELECT 1").getRows().get(0).get(0)).longValue());+ }+ }++ @Test+ void disconnectedPhysicalSessionCannotReconnectOrReuseItsTokenInAnotherLogicalSession() throws Exception {+ try (Environment original = new Environment(true, 3); Environment replacement = new Environment(true, 3)) {+ JsonObject opened = original.open("operation");+ int opens = original.agent.physical.size();+ original.agent.getConnection().close();+ assertThrows(Exception.class, () -> original.query(opened, "SELECT 1"));+ assertThrows(Exception.class, () -> replacement.query(opened, "SELECT 1"));+ assertEquals(opens, original.agent.physical.size());+ JsonObject own = replacement.open("operation");+ assertNotEquals(opened.get("sessionToken"), own.get("sessionToken"));+ assertThrows(Exception.class, () -> replacement.query(opened, "SELECT 1"));+ replacement.query(own, "SELECT 1");+ }+ }++ @Test+ void failedPhysicalCloseRemainsUnknownOnRepeatedCloseAndLogicalCleanup() throws Exception {+ try (Environment env = new Environment(true, 3)) {+ JsonObject opened = env.open("operation");+ env.agent.failClose = env.agent.physical.get(env.agent.physical.size() - 1);+ JsonObject closed = env.close(opened);+ assertEquals("unknown", closed.get("phase").getAsString());+ int closes = env.agent.closes;+ assertEquals(closed, env.close(opened));+ assertEquals(closes, env.agent.closes, "unknown close must not be retried and relabeled confirmed");+ assertThrows(Exception.class, () -> env.server.dispatchForRuntime("disconnect", new JsonObject()));+ assertEquals(closes, env.agent.closes);+ }+ }++ @Test+ void aLostOpenReceiptCanCloseOnlyThatOperationsConnectionWithoutKnowingItsToken() throws Exception {+ try (Environment env = new Environment(true, 3)) {+ env.open("operation");+ assertThrows(Exception.class, () -> env.server.dispatchForRuntime("close_native_job_session", json("{\"operationId\":\"foreign\"}")));+ JsonObject closed = result(env.server.dispatchForRuntime("close_native_job_session", json("{\"operationId\":\"operation\"}")));+ assertEquals("closed", closed.get("phase").getAsString());+ assertEquals(closed, env.open("operation"));+ }+ }++ @Test+ void anExistingManualTransactionIsNotBorrowedOrClosedByOpeningANativeJobLease() throws Exception {+ try (Environment env = new Environment(true, 3)) {+ env.server.dispatchForRuntime("begin_manual_transaction", new JsonObject());+ Connection editor = env.agent.getConnection();+ int opens = env.agent.physical.size();+ assertThrows(Exception.class, () -> env.open("operation"));+ assertSame(editor, env.agent.getConnection());+ assertFalse(editor.isClosed());+ assertFalse(editor.getAutoCommit());+ assertEquals(opens, env.agent.physical.size());+ env.server.dispatchForRuntime("rollback_manual_transaction", new JsonObject());+ assertEquals("opened", env.open("operation").get("phase").getAsString());+ }+ }++ @Test+ void anExistingCursorSurvivesRejectedReservationAndCanFinishBeforeANewLease() throws Exception {+ try (Environment env = new Environment(true, 3)) {+ QueryPageResult page = (QueryPageResult) env.server.dispatchForRuntime("execute_query_page",+ json("{\"sql\":\"SELECT X FROM SYSTEM_RANGE(1, 3)\",\"pageSize\":1}"));+ assertNotNull(page.getSession_id());+ Connection cursor = env.agent.getConnection();+ assertThrows(Exception.class, () -> env.open("operation"));+ assertSame(cursor, env.agent.getConnection());+ JsonObject fetch = new JsonObject();+ fetch.addProperty("sessionId", page.getSession_id());+ fetch.addProperty("pageSize", 1);+ assertNotNull(env.server.dispatchForRuntime("fetch_query_page", fetch));+ env.server.dispatchForRuntime("close_query_session", fetch);+ assertEquals("opened", env.open("operation").get("phase").getAsString());+ }+ }++ @Test+ void independentNativeConnectionStillHonorsTheExistingRuntimePhysicalBudget() throws Exception {+ try (Environment env = new Environment(true, 1)) {+ assertEquals(1, env.registry.activePhysicalConnectionCount());+ Exception exhausted = assertThrows(Exception.class, () -> env.open("operation"));+ JsonObject diagnostics = AgentRpcError.toJson(exhausted, "open_native_job_session", null).getAsJsonObject("data");+ assertEquals("resource", diagnostics.get("category").getAsString());+ assertTrue(diagnostics.get("retryable").getAsBoolean());+ assertEquals(1, env.agent.physical.size());+ assertEquals(1, env.registry.activePhysicalConnectionCount());+ assertNotNull(env.server.dispatchForRuntime("execute_query", json("{\"sql\":\"SELECT 1\"}")));+ }+ }++ private static JsonObject json(String value) {+ return JsonParser.parseString(value).getAsJsonObject();+ }++ private static JsonObject result(Object value) {+ return GSON.toJsonTree(value).getAsJsonObject();+ }++ private static final class Environment implements AutoCloseable {+ final JdbcConnectionPoolRegistry registry;+ final H2Agent agent = new H2Agent();+ final JsonRpcServer server = new JsonRpcServer(agent);+ final JsonObject connection = json("{\"database\":\"jobs\",\"username\":\"sa\",\"password\":\"\",\"sessionRole\":\"metadata\"}");++ Environment(boolean pooled, int budget) throws Exception {+ registry = new JdbcConnectionPoolRegistry(new JdbcConnectionPoolRegistry.PoolSettings(+ true, 1, 0, 2_000L, 1_000L, 10_000L, 30_000L, 60_000L, 0, budget, 1));+ if (pooled) agent.attachConnectionPoolRegistry(registry);+ server.dispatchForRuntime("connect", connection.deepCopy());+ }++ JsonObject open(String id) throws Exception {+ JsonObject params = new JsonObject();+ params.addProperty("operationId", id);+ return result(server.dispatchForRuntime("open_native_job_session", params));+ }++ JsonObject authorized(JsonObject opened) {+ JsonObject params = new JsonObject();+ params.add("nativeJobOperationId", opened.get("operationId"));+ params.add("nativeJobSessionToken", opened.get("sessionToken"));+ return params;+ }++ QueryResult query(JsonObject opened, String sql) throws Exception {+ JsonObject params = authorized(opened);+ params.addProperty("sql", sql);+ return (QueryResult) server.dispatchForRuntime("execute_query", params);+ }++ JsonObject close(JsonObject opened) throws Exception {+ JsonObject params = new JsonObject();+ params.add("operationId", opened.get("operationId"));+ params.add("sessionToken", opened.get("sessionToken"));+ return result(server.dispatchForRuntime("close_native_job_session", params));+ }++ @Override public void close() {+ try { server.dispatchForRuntime("disconnect", new JsonObject()); }+ catch (Exception ignored) { }+ registry.close();+ }+ }++ private static final class H2Agent extends AbstractJdbcAgent {+ final String url = "jdbc:h2:mem:job_" + UUID.randomUUID() + ";DB_CLOSE_DELAY=-1";+ final List<Connection> physical = new ArrayList<>();+ Connection failClose;+ int commits;+ int rollbacks;+ int closes;++ @Override public boolean supportsNativeJobSessions() { return true; }+ @Override protected String driverClass() { return "org.h2.Driver"; }+ @Override protected String buildJdbcUrl(ConnectParams params) { return url; }+ @Override protected Connection openConnection(ConnectParams params) throws Exception {+ Connection real = DriverManager.getConnection(url, "sa", "");+ Connection tracked = (Connection) Proxy.newProxyInstance(getClass().getClassLoader(),+ new Class<?>[]{Connection.class}, (proxy, method, arguments) -> {+ if ("commit".equals(method.getName())) commits++;+ if ("rollback".equals(method.getName())) rollbacks++;+ if ("close".equals(method.getName())) closes++;+ try {+ Object value = method.invoke(real, arguments);+ if ("close".equals(method.getName()) && proxy == failClose) {+ throw new SQLException("physical close acknowledgement lost", "08006");+ }+ return value;+ } catch (InvocationTargetException error) { throw error.getCause(); }+ });+ physical.add(tracked);+ return tracked;+ }+ @Override public List<DatabaseInfo> listDatabases() { return Collections.emptyList(); }+ @Override public List<String> listSchemas() { return Collections.emptyList(); }+ @Override public List<TableInfo> listTables(String schema) { return Collections.emptyList(); }+ @Override public List<ColumnInfo> getColumns(String schema, String table) { return Collections.emptyList(); }+ @Override public List<IndexInfo> listIndexes(String schema, String table) { return Collections.emptyList(); }+ @Override public List<ForeignKeyInfo> listForeignKeys(String schema, String table) { return Collections.emptyList(); }+ @Override public List<TriggerInfo> listTriggers(String schema, String table) { return Collections.emptyList(); }+ }+}diff --git a/agents/common/src/test/java/com/dbx/agent/NativeLegacyJobTest.java b/agents/common/src/test/java/com/dbx/agent/NativeLegacyJobTest.javanew file mode 100644index 0000000000..f87ef5f320--- /dev/null+++ b/agents/common/src/test/java/com/dbx/agent/NativeLegacyJobTest.java@@ -0,0 +1,364 @@+package com.dbx.agent;++import com.google.gson.Gson;+import com.google.gson.JsonNull;+import com.google.gson.JsonObject;+import com.google.gson.JsonParser;+import org.junit.jupiter.api.Test;++import java.lang.reflect.InvocationTargetException;+import java.lang.reflect.Proxy;+import java.sql.CallableStatement;+import java.sql.Connection;+import java.sql.DatabaseMetaData;+import java.sql.DriverManager;+import java.sql.PreparedStatement;+import java.sql.ResultSet;+import java.sql.SQLException;+import java.sql.Statement;+import java.sql.Types;+import java.util.ArrayList;+import java.util.Collections;+import java.util.HashMap;+import java.util.List;+import java.util.Map;+import java.util.UUID;++import static org.junit.jupiter.api.Assertions.*;++class NativeLegacyJobTest {+ private static final Gson GSON = new Gson();++ @Test+ void pooledAndDedicatedRpcUseOnePhysicalConnectionAndNoCommitBeforeInitialReadback() throws Exception {+ for (boolean pooled : List.of(false, true)) {+ for (String zone : new String[]{null, "zone1"}) {+ try (Environment env = new Environment(pooled)) {+ JsonObject request = prepare();+ request.add("zone", zone == null ? JsonNull.INSTANCE : GSON.toJsonTree(zone));+ JsonObject prepared = env.call("prepare_legacy_job", request);+ assertEquals("prepared", text(prepared, "phase"));+ Physical physical = env.agent.physical.getLast();+ assertEquals("41", text(prepared, "jobId"));+ assertEquals(zone, physical.zone);+ assertFalse(physical.real.getAutoCommit());+ assertEquals(0, physical.commits);+ assertTrue(physical.events.indexOf("submit") < physical.events.indexOf("broken"));+ assertTrue(physical.events.indexOf("broken") < physical.events.indexOf("read"));+ assertTrue(physical.events.indexOf("broken") < physical.events.indexOf("next-date"));+ assertTrue(physical.events.indexOf("next-date") < physical.events.indexOf("read"));+ assertEquals(Types.VARCHAR, physical.outType);+ assertFalse(prepared.has("disposalConfirmed"));+ assertEquals(prepared, env.call("prepare_legacy_job", request));+ JsonObject committed = env.call("commit_legacy_job", finish("41"));+ assertEquals("committed", text(committed, "phase"));+ assertTrue(committed.get("disposalConfirmed").getAsBoolean());+ assertEquals(1, physical.commits);+ assertEquals(0, physical.rollbacks);+ assertEquals(1, physical.closes);+ }+ }+ }+ }++ @Test+ void changedOperationDefinitionOrZoneCannotResubmitAndOrdinaryCallsCannotBorrowTheTransaction() throws Exception {+ try (Environment env = new Environment(true)) {+ JsonObject original = prepare();+ JsonObject prepared = env.call("prepare_legacy_job", original);+ Physical physical = env.agent.physical.getLast();+ for (String field : List.of("zone", "dialect", "what", "operationId")) {+ JsonObject changed = original.deepCopy();+ changed.addProperty(field, "different");+ assertNotEquals("prepared", text(env.call("prepare_legacy_job", changed), "phase"));+ }+ for (String method : List.of("execute_query", "connect", "connection_info", "begin_manual_transaction", "open_native_job_session")) {+ assertThrows(Exception.class, () -> env.server.dispatchForRuntime(method, new JsonObject()), method);+ }+ assertEquals(prepared, env.call("legacy_job_status", finish(null)));+ assertEquals(1, Collections.frequency(physical.events, "submit"));+ assertEquals("native_job_identity_mismatch", text(env.call("commit_legacy_job", finish(null)), "reason"));+ assertEquals("rolled_back", text(env.call("rollback_legacy_job", finish(null)), "phase"));+ assertEquals(1, physical.rollbacks);+ assertEquals(0, physical.commits);+ }+ }++ @Test+ void outGetterAndInitialReadFailuresRollBackAndDoNotLeakBodies() throws Exception {+ for (String failure : List.of("out-read", "broken", "next-date", "mismatch", "zone-mismatch")) {+ try (Environment env = new Environment(false)) {+ Physical physical = env.agent.physical.getLast();+ physical.failure = failure;+ JsonObject failed = env.call("prepare_legacy_job", prepare());+ assertEquals("rolled_back", text(failed, "phase"));+ if (failure.equals("out-read")) assertEquals("native_job_out_read_failed", text(failed, "reason"));+ assertTrue(failed.get("disposalConfirmed").getAsBoolean());+ assertEquals(1, physical.rollbacks);+ assertEquals(0, physical.commits);+ assertFalse(failed.toString().contains("private"));+ }+ }+ }++ @Test+ void unknownCommitIsNeverReplayedOrRolledBackAndCloseFailureCannotBeErased() throws Exception {+ for (String failure : List.of("commit", "close")) {+ try (Environment env = new Environment(false)) {+ env.call("prepare_legacy_job", prepare());+ Physical physical = env.agent.physical.getLast();+ physical.failure = failure;+ JsonObject terminal = env.call("commit_legacy_job", finish("41"));+ assertEquals(failure.equals("commit") ? "unknown" : "committed", text(terminal, "phase"));+ assertEquals(!failure.equals("close"), terminal.get("disposalConfirmed").getAsBoolean());+ assertEquals(terminal, env.call("legacy_job_status", finish(null)));+ assertEquals(terminal, env.call("commit_legacy_job", finish("41")));+ assertEquals(terminal, env.call("rollback_legacy_job", finish(null)));+ assertEquals(1, physical.commits);+ assertEquals(0, physical.rollbacks);+ assertEquals(1, physical.closes);+ }+ }+ }++ @Test+ void editorTransactionSurvivesRejectedPreparationAndAnotherDriverCannotOptInImplicitly() throws Exception {+ try (Environment env = new Environment(true)) {+ env.server.dispatchForRuntime("begin_manual_transaction", new JsonObject());+ Connection editor = env.agent.getConnection();+ assertThrows(Exception.class, () -> env.server.dispatchForRuntime("prepare_legacy_job", prepare()));+ assertSame(editor, env.agent.getConnection());+ assertFalse(editor.isClosed());+ assertFalse(editor.getAutoCommit());+ env.server.dispatchForRuntime("rollback_manual_transaction", new JsonObject());+ }+ JsonRpcServer ordinary = new JsonRpcServer(new FakeAgent() {+ public boolean supportsNativeLegacyJobs() { return false; }+ });+ assertThrows(Exception.class, () -> ordinary.dispatchForRuntime("prepare_legacy_job", prepare()));+ }++ @Test+ void actualMultiSessionEntryPreservesBlobCapabilityAndDoesNotConfuseLogicalCloseWithDisposal() throws Exception {+ List<FakeAgent> agents = new java.util.concurrent.CopyOnWriteArrayList<>();+ java.util.function.Supplier<DatabaseAgent> factory = () -> {+ FakeAgent agent = new FakeAgent();+ agents.add(agent);+ return agent;+ };+ try (MultiSessionJsonRpcServer server = MultiSessionJsonRpcServer.withNativeLegacyJobs(factory, true);+ MultiSessionJsonRpcServer ordinary = MultiSessionJsonRpcServer.withBlobBindings(factory)) {+ JsonObject handshake = rpc(server, "handshake", new JsonObject());+ assertTrue(handshake.toString().contains("native_job_legacy_ob_v1"));+ assertTrue(handshake.toString().contains("blob_bind_statements_v1"));+ assertFalse(rpc(ordinary, "handshake", new JsonObject()).toString().contains("native_job_legacy_ob_v1"));+ assertTrue(agents.isEmpty(), "handshake must not instantiate or connect a sample agent");+ JsonObject connection = JsonParser.parseString("{\"agentSessionId\":\"original\",\"database\":\"jobs\",\"username\":\"Owner\",\"password\":\"\",\"sessionRole\":\"metadata\"}").getAsJsonObject();+ rpc(server, "open_session", connection);+ JsonObject request = prepare();+ request.addProperty("agentSessionId", "original");+ assertEquals("prepared", text(rpc(server, "prepare_legacy_job", request), "phase"));+ Physical physical = agents.getFirst().physical.getLast();+ physical.failure = "close";+ JsonObject finish = finish("41");+ finish.addProperty("agentSessionId", "original");+ JsonObject committed = rpc(server, "commit_legacy_job", finish);+ assertEquals("committed", text(committed, "phase"));+ assertFalse(committed.get("disposalConfirmed").getAsBoolean());+ assertEquals(committed, rpc(server, "legacy_job_status", finish));+ assertTrue(rpc(server, "close_session", connection).get("ok").getAsBoolean());+ connection.addProperty("agentSessionId", "replacement");+ rpc(server, "open_session", connection);+ finish.addProperty("agentSessionId", "replacement");+ JsonObject missing = rpc(server, "commit_legacy_job", finish);+ assertEquals("unknown", text(missing, "phase"));+ assertFalse(missing.has("jobId"));+ assertEquals(1, physical.commits);+ assertEquals(0, physical.rollbacks);+ assertEquals(1, physical.closes);+ } finally {+ for (FakeAgent agent : agents) for (Physical physical : agent.physical) physical.real.close();+ }+ }++ private static JsonObject rpc(MultiSessionJsonRpcServer server, String method, JsonObject params) {+ JsonObject request = new JsonObject();+ request.addProperty("id", 1);+ request.addProperty("method", method);+ request.add("params", params);+ JsonObject response = JsonParser.parseString(server.handleRequest(request.toString())).getAsJsonObject();+ assertFalse(response.has("error"), response.toString());+ return response.getAsJsonObject("result");+ }++ private static JsonObject prepare() {+ return JsonParser.parseString("""+ {"operationId":"operation","dialect":"oceanbase-oracle","what":"private_call();","nextDate":"2026-10-21 10:20:30",+ "interval":"SYSDATE+1","enabled":false,"instance":0,"schema":"Owner","timeoutSecs":2}+ """).getAsJsonObject();+ }+ private static JsonObject finish(String id) {+ JsonObject params = new JsonObject();+ params.addProperty("operationId", "operation");+ if (id != null) params.addProperty("jobId", id);+ return params;+ }++ private static String text(JsonObject value, String field) {+ return value.has(field) ? value.get(field).getAsString() : "";+ }++ private static final class Environment implements AutoCloseable {+ final FakeAgent agent = new FakeAgent();+ final JsonRpcServer server = new JsonRpcServer(agent);+ final JdbcConnectionPoolRegistry registry;++ Environment(boolean pooled) throws Exception {+ registry = new JdbcConnectionPoolRegistry(new JdbcConnectionPoolRegistry.PoolSettings(true, 1, 0, 2_000L, 1_000L, 10_000L, 30_000L, 60_000L, 0, 3, 1));+ if (pooled) agent.attachConnectionPoolRegistry(registry);+ server.dispatchForRuntime("connect", JsonParser.parseString("{\"database\":\"jobs\",\"username\":\"Owner\",\"password\":\"\",\"sessionRole\":\"metadata\"}").getAsJsonObject());+ }++ JsonObject call(String method, JsonObject params) throws Exception {+ return GSON.toJsonTree(server.dispatchForRuntime(method, params)).getAsJsonObject();+ }++ public void close() throws Exception {+ try { server.dispatchForRuntime("disconnect", new JsonObject()); } catch (Exception ignored) {}+ registry.close();+ for (Physical physical : agent.physical) physical.real.close();+ }+ }++ private static class FakeAgent extends AbstractJdbcAgent {+ final String url = "jdbc:h2:mem:legacy_" + UUID.randomUUID();+ final List<Physical> physical = new ArrayList<>();++ public boolean supportsNativeLegacyJobs() { return true; }+ protected String driverClass() { return "org.h2.Driver"; }+ protected String buildJdbcUrl(ConnectParams params) { return url; }+ protected Connection openConnection(ConnectParams params) throws Exception {+ Physical connection = new Physical(DriverManager.getConnection(url, "sa", ""));+ physical.add(connection);+ return connection.connection();+ }+ public List<DatabaseInfo> listDatabases() { return List.of(); }+ public List<String> listSchemas() { return List.of(); }+ public List<TableInfo> listTables(String schema) { return List.of(); }+ public List<ColumnInfo> getColumns(String schema, String table) { return List.of(); }+ public List<IndexInfo> listIndexes(String schema, String table) { return List.of(); }+ public List<ForeignKeyInfo> listForeignKeys(String schema, String table) { return List.of(); }+ public List<TriggerInfo> listTriggers(String schema, String table) { return List.of(); }+ }+ private static final class Physical {+ final Connection real;+ final List<String> events = new ArrayList<>();+ String failure = "", what, nextDate, interval, zone, broken;+ int commits, rollbacks, closes, outType;++ Physical(Connection real) { this.real = real; }++ void stage(String name) throws SQLException {+ events.add(name);+ if (failure.equals(name)) throw new SQLException("private body must not escape", "08006", 4007);+ }++ Connection connection() {+ return proxy(Connection.class, (p, m, a) -> {+ switch (m.getName()) {+ case "getMetaData": {+ DatabaseMetaData metadata = real.getMetaData();+ return proxy(DatabaseMetaData.class, (mp, mm, ma) ->+ mm.getName().equals("getDatabaseProductName") ? "OceanBase" : invoke(mm, metadata, ma));+ }+ case "commit": commits++; stage("commit"); break;+ case "rollback": rollbacks++; stage("rollback"); break;+ case "close": closes++; stage("close"); break;+ case "prepareCall": return statement((String) a[0], CallableStatement.class);+ case "prepareStatement":+ if (((String) a[0]).contains("USER_JOBS") || ((String) a[0]).equals("SELECT USER AS DBX_SESSION_USER FROM DUAL")) {+ return statement((String) a[0], PreparedStatement.class);+ }+ break;+ case "createStatement": {+ Statement actual = real.createStatement();+ return proxy(Statement.class, (sp, sm, sa) -> {+ if (sm.getName().equals("execute") && ((String) sa[0]).startsWith("ALTER SESSION SET CURRENT_SCHEMA")) {+ stage("schema");+ return false;+ }+ return invoke(sm, actual, sa);+ });+ }+ }+ return invoke(m, real, a);+ });+ }++ <T> T statement(String sql, Class<T> type) {+ Map<Integer, Object> bindings = new HashMap<>();+ return proxy(type, (p, m, a) -> switch (m.getName()) {+ case "setString", "setLong", "setInt" -> { bindings.put((int) a[0], a[1]); yield null; }+ case "setNull" -> { bindings.put((int) a[0], null); yield null; }+ case "registerOutParameter" -> { assertEquals(5, a[0]); outType = (int) a[1]; yield null; }+ case "getString" -> { stage("out-read"); yield "41"; }+ case "execute" -> {+ if (sql.contains("DBMS_JOB.SUBMIT")) {+ assertTrue(sql.contains("zone => ?"));+ assertFalse(sql.contains("instance => ?"));+ stage("submit");+ what = (String) bindings.get(1);+ nextDate = (String) bindings.get(2);+ interval = (String) bindings.get(3);+ zone = (String) bindings.get(4);+ } else if (sql.contains("DBMS_JOB.NEXT_DATE")) {+ stage("next-date");+ assertEquals("41", bindings.get(1));+ nextDate = (String) bindings.get(2);+ } else {+ assertTrue(sql.contains("DBMS_JOB.BROKEN"));+ stage("broken");+ assertEquals("41", bindings.get(1));+ broken = (int) bindings.get(2) == 1 ? "Y" : "N";+ assertEquals(nextDate, bindings.get(3));+ if ("Y".equals(broken)) nextDate = "4000-01-01 00:00:00";+ }+ yield false;+ }+ case "executeQuery" -> {+ if (sql.equals("SELECT USER AS DBX_SESSION_USER FROM DUAL")) yield rows(new String[]{"Owner"});+ assertFalse(sql.contains("TO_CHAR(INSTANCE)"));+ stage("read");+ yield rows(new String[]{"41", failure.equals("mismatch") ? "different;" : what, nextDate, interval,+ broken, failure.equals("zone-mismatch") ? "other-zone" : zone, "Owner", "Owner", "Owner"});+ }+ default -> defaultValue(m.getReturnType());+ });+ }++ ResultSet rows(String[] values) {+ int[] row = {0};+ return proxy(ResultSet.class, (p, m, a) -> switch (m.getName()) {+ case "next" -> ++row[0] == 1;+ case "getString" -> values[(int) a[0] - 1];+ default -> defaultValue(m.getReturnType());+ });+ }+ }++ private static Object invoke(java.lang.reflect.Method method, Object receiver, Object[] args) throws Throwable {+ try { return method.invoke(receiver, args); }+ catch (InvocationTargetException error) { throw error.getCause(); }+ }++ private static <T> T proxy(Class<T> type, java.lang.reflect.InvocationHandler handler) {+ return type.cast(Proxy.newProxyInstance(NativeLegacyJobTest.class.getClassLoader(), new Class<?>[]{type}, handler));+ }++ private static Object defaultValue(Class<?> type) {+ if (type == boolean.class) return false;+ if (type == int.class) return 0;+ if (type == long.class) return 0L;+ return null;+ }+}diff --git a/agents/common/src/test/java/com/dbx/agent/OracleTriggerContractTest.java b/agents/common/src/test/java/com/dbx/agent/OracleTriggerContractTest.javanew file mode 100644index 0000000000..1096a6a75c--- /dev/null+++ b/agents/common/src/test/java/com/dbx/agent/OracleTriggerContractTest.java@@ -0,0 +1,83 @@+package com.dbx.agent;++import com.google.gson.Gson;+import com.google.gson.JsonObject;+import com.google.gson.JsonParser;+import java.lang.reflect.Proxy;+import java.util.ArrayList;+import java.util.List;+import org.junit.jupiter.api.Test;+import static org.junit.jupiter.api.Assertions.*;++class OracleTriggerContractTest {+ private final Gson gson = new Gson();+ private static final String TRIGGER = """+ {"name":" Trigger ","event":"INSERT","timing":"BEFORE EACH ROW","enabled":true,"valid":false,+ "oracle_metadata":{"contractVersion":1,"identityMode":"exact","engine":"oceanbase-oracle",+ "engineVersion":"4.2.5.7_107","owner":" Owner ","name":" Trigger ","scope":"VIEW",+ "parent":{"owner":" Other Owner ","name":" View ","objectType":"VIEW","objectId":"42"},+ "objectId":"9007199254740993","reads":{"identity":{"state":"available"}}}}+ """;++ @Test+ void retainsExactMetadataAndIndependentValidity() {+ JsonObject value = gson.toJsonTree(gson.fromJson(TRIGGER, TriggerInfo.class)).getAsJsonObject();+ assertTrue(value.get("enabled").getAsBoolean());+ assertFalse(value.get("valid").getAsBoolean());+ JsonObject metadata = value.getAsJsonObject("oracle_metadata");+ assertEquals(" Owner ", metadata.get("owner").getAsString());+ assertEquals(" Other Owner ", metadata.getAsJsonObject("parent").get("owner").getAsString());+ assertEquals("9007199254740993", metadata.get("objectId").getAsString());+ }++ @Test+ void summaryAndSourceKeepTheSameTriggerWithoutInventingAParent() {+ JsonObject trigger = JsonParser.parseString(TRIGGER).getAsJsonObject();+ JsonObject metadata = trigger.getAsJsonObject("oracle_metadata");+ metadata.addProperty("scope", "SCHEMA");+ metadata.remove("parent");+ JsonObject input = JsonParser.parseString("{\"name\":\" Trigger \",\"object_type\":\"TRIGGER\",\"schema\":\" Owner \",\"source\":\"TRIGGER declaration\"}").getAsJsonObject();+ input.add("trigger", trigger);+ JsonObject source = gson.toJsonTree(gson.fromJson(input, ObjectSource.class)).getAsJsonObject();+ JsonObject summary = gson.toJsonTree(gson.fromJson(input, ObjectInfo.class)).getAsJsonObject();+ assertEquals(trigger, source.get("trigger"));+ assertEquals(trigger, summary.get("trigger"));+ assertFalse(source.getAsJsonObject("trigger").getAsJsonObject("oracle_metadata").has("parent"));+ }++ @Test+ void legacyThreeColumnPayloadDoesNotClaimExactSupportOrDefaultState() {+ TriggerInfo trigger = gson.fromJson("{\"name\":\"T\",\"event\":\"INSERT\",\"timing\":\"BEFORE\"}", TriggerInfo.class);+ JsonObject value = gson.toJsonTree(trigger).getAsJsonObject();+ assertFalse(value.has("enabled"));+ assertFalse(value.has("valid"));+ assertFalse(value.has("oracle_metadata"));+ }++ @Test+ void rpcSelectsExactOverloadsWithoutChangingLegacyArityOrRawArguments() throws Exception {+ List<Object[]> calls = new ArrayList<>();+ DatabaseAgent agent = (DatabaseAgent) Proxy.newProxyInstance(DatabaseAgent.class.getClassLoader(),+ new Class<?>[]{DatabaseAgent.class}, (object, method, args) -> {+ if (method.getName().equals("supportsQueryTiming") || method.getName().equals("permitsAutomaticReconnect")) return false;+ if (List.of("listObjects", "getObjectSource", "listTriggers").contains(method.getName())) {+ calls.add(args);+ return method.getName().equals("getObjectSource") ? new ObjectSource() : List.of();+ }+ return null;+ });+ JsonRpcServer server = new JsonRpcServer(agent);+ for (String method : List.of(AgentProtocol.METHOD_LIST_OBJECTS, AgentProtocol.METHOD_GET_OBJECT_SOURCE, AgentProtocol.METHOD_LIST_TRIGGERS)) {+ JsonObject params = JsonParser.parseString("{\"schema\":\" Owner \",\"table\":\" Parent \",\"name\":\" Trigger \",\"object_type\":\"TRIGGER\"}").getAsJsonObject();+ server.dispatchForRuntime(method, params);+ params.addProperty("identity_mode", "exact");+ server.dispatchForRuntime(method, params);+ Object[] legacy = calls.get(calls.size() - 2);+ Object[] exact = calls.get(calls.size() - 1);+ assertEquals(legacy.length + 1, exact.length, method);+ assertEquals(" Owner ", exact[0]);+ if (method.equals(AgentProtocol.METHOD_LIST_TRIGGERS)) assertEquals(" Parent ", exact[1]);+ if (method.equals(AgentProtocol.METHOD_GET_OBJECT_SOURCE)) assertEquals(" Trigger ", exact[1]);+ }+ }+}diff --git a/agents/common/src/test/java/com/dbx/agent/OracleTriggerReaderTest.java b/agents/common/src/test/java/com/dbx/agent/OracleTriggerReaderTest.javanew file mode 100644index 0000000000..3a7a4375ad--- /dev/null+++ b/agents/common/src/test/java/com/dbx/agent/OracleTriggerReaderTest.java@@ -0,0 +1,234 @@+package com.dbx.agent;++import java.lang.reflect.InvocationTargetException;+import java.lang.reflect.Proxy;+import java.sql.Connection;+import java.sql.DriverManager;+import java.sql.PreparedStatement;+import java.util.List;+import java.util.UUID;+import org.junit.jupiter.api.Test;+import static org.junit.jupiter.api.Assertions.*;++class OracleTriggerReaderTest {+ private static final String OWNER = " Owner ";+ private static final String PARENT_OWNER = " Parent Owner ";+ private static final String NAME = " Trigger A ";+ private static final String SOURCE = "TRIGGER \" Trigger A \" BEFORE INSERT ON \" Parent Owner \".\" Parent \"\nFOR EACH ROW DISABLE\nBEGIN\n/* " + "中文😀".repeat(12_000) + " */\nNULL; END;";++ @Test+ void readsRawCrossOwnerIdentityAndIndependentStatesAndFullClob() throws Exception {+ try (Connection connection = fixture()) {+ OracleTriggerReader reader = new OracleTriggerReader(connection, "oceanbase-oracle");+ List<TriggerInfo> triggers = reader.listTriggers(PARENT_OWNER, " Parent ");+ assertEquals(1, triggers.size());+ TriggerInfo trigger = triggers.get(0);+ assertFalse(trigger.getEnabled());+ assertFalse(trigger.getValid());+ assertEquals(OWNER, trigger.getOracle_metadata().owner());+ assertEquals(NAME, trigger.getName());+ assertEquals(PARENT_OWNER, trigger.getOracle_metadata().parent().owner());+ assertEquals("9007199254740993", trigger.getOracle_metadata().objectId());+ assertTrue(reader.listTriggers(PARENT_OWNER.trim(), " Parent ").isEmpty());+ assertTrue(reader.listTriggers(PARENT_OWNER, "Parent").isEmpty());++ ObjectSource source = reader.getObjectSource(OWNER, NAME);+ assertEquals(SOURCE, source.getSource());+ assertTrue(source.getTrigger().getOracle_metadata().definition().complete());+ assertEquals("ALL_SOURCE", source.getTrigger().getOracle_metadata().definition().origin());+ assertEquals(List.of(new OracleTriggerMetadata.CompilationError(1, 5, 7, "Missing procedure", "ERROR")), source.getTrigger().getOracle_metadata().errors());+ assertFalse(source.getTrigger().getValid());+ }+ }++ @Test+ void enrichesOnlyTheSelectedPageWithoutLoadingSourceOrRewritingOtherRows() throws Exception {+ try (Connection connection = fixture()) {+ connection.createStatement().execute("DROP TABLE ALL_SOURCE");+ ObjectInfo table = new ObjectInfo("unchanged", "TABLE", OWNER, "comment", true);+ ObjectInfo trigger = new ObjectInfo(NAME, "TRIGGER", OWNER, null);+ new OracleTriggerReader(connection, "oceanbase-oracle").enrichObjects(List.of(table, trigger), OWNER);+ assertEquals("comment", table.getComment());+ assertTrue(table.getValid());+ assertNull(table.getTrigger());+ assertNull(trigger.getTrigger().getStatement());+ assertNull(trigger.getTrigger().getOracle_metadata().definition());+ assertEquals(PARENT_OWNER, trigger.getParent_schema());+ assertEquals(" Parent ", trigger.getParent_name());+ assertFalse(trigger.getValid());+ }+ }++ @Test+ void missingColumnsStayUnknownRatherThanDisabledOrValid() throws Exception {+ try (Connection connection = fixture()) {+ connection.createStatement().execute("ALTER TABLE ALL_TRIGGERS DROP COLUMN STATUS");+ connection.createStatement().execute("ALTER TABLE ALL_TRIGGERS DROP COLUMN BASE_OBJECT_TYPE");+ TriggerInfo trigger = new OracleTriggerReader(connection, "dm").listTriggers(PARENT_OWNER, " Parent ").get(0);+ assertNull(trigger.getEnabled());+ assertFalse(trigger.getValid());+ assertEquals("UNKNOWN", trigger.getOracle_metadata().scope());+ assertEquals("unavailable", trigger.getOracle_metadata().reads().get("enabled").state());+ assertEquals("unavailable", trigger.getOracle_metadata().reads().get("scope").state());+ assertEquals("unavailable", trigger.getOracle_metadata().reads().get("parent").state());+ assertNull(trigger.getOracle_metadata().parent());+ }+ }++ @Test+ void bodyOnlyFallbackRetainsTextButCannotAuthorizeReplacement() throws Exception {+ try (Connection connection = fixture()) {+ connection.createStatement().execute("DROP TABLE ALL_SOURCE");+ ObjectSource source = new OracleTriggerReader(connection, "dm").getObjectSource(OWNER, NAME);+ assertEquals("BEGIN NULL; END;", source.getSource());+ assertFalse(source.getTrigger().getOracle_metadata().definition().complete());+ assertEquals("body", source.getTrigger().getOracle_metadata().definition().format());+ assertNotEquals("available", source.getTrigger().getOracle_metadata().reads().get("definition").state());+ }+ }++ @Test+ void schemaScopeHasNoInventedTableAndUnreadableErrorsAreNotEmpty() throws Exception {+ try (Connection connection = fixture()) {+ connection.createStatement().execute("UPDATE ALL_TRIGGERS SET BASE_OBJECT_TYPE='SCHEMA', TABLE_NAME=NULL");+ connection.createStatement().execute("DROP TABLE ALL_ERRORS");+ ObjectSource source = new OracleTriggerReader(connection, "oceanbase-oracle").getObjectSource(OWNER, NAME);+ OracleTriggerMetadata metadata = source.getTrigger().getOracle_metadata();+ assertEquals("SCHEMA", metadata.scope());+ assertEquals(PARENT_OWNER, metadata.scopeOwner());+ assertNull(metadata.parent());+ assertNull(metadata.errors());+ assertNotEquals("available", metadata.reads().get("errors").state());+ }+ }++ @Test+ void dmTimerUsesTheDatabaseBaseScopeWithoutInventingAParent() throws Exception {+ try (Connection connection = fixture()) {+ connection.createStatement().execute("UPDATE ALL_TRIGGERS SET BASE_OBJECT_TYPE='DATABASE', TRIGGERING_EVENT='TIMER', TABLE_NAME=NULL");+ OracleTriggerMetadata metadata = new OracleTriggerReader(connection, "dm").getObjectSource(OWNER, NAME).getTrigger().getOracle_metadata();+ assertEquals("TIMER", metadata.scope());+ assertEquals("DATABASE", metadata.scopeType());+ assertNull(metadata.parent());+ assertNull(metadata.scopeOwner());+ // Oracle's event text must not be reinterpreted as a DM capability.+ assertEquals("DATABASE", new OracleTriggerReader(connection, "oracle").getObjectSource(OWNER, NAME).getTrigger().getOracle_metadata().scope());+ }+ }++ @Test+ void successfulVisibleEmptyIdentityIsNotAnOldProviderOrAnUnreadableDictionary() throws Exception {+ try (Connection connection = fixture()) {+ connection.createStatement().execute("DELETE FROM ALL_TRIGGERS");+ ObjectSource source = new OracleTriggerReader(connection, "oceanbase-oracle").getObjectSource(OWNER, NAME);+ assertEquals("", source.getSource());+ assertEquals("empty", source.getTrigger().getOracle_metadata().reads().get("identity").state());+ assertNull(source.getTrigger().getOracle_metadata().objectId());+ assertNull(source.getTrigger().getOracle_metadata().definition());+ assertEquals(OWNER, source.getTrigger().getOracle_metadata().owner());+ connection.createStatement().execute("DROP TABLE ALL_TRIGGERS");+ assertThrows(java.sql.SQLException.class, () -> new OracleTriggerReader(connection, "oceanbase-oracle").getObjectSource(OWNER, NAME));+ }+ }++ @Test+ void dictionaryLineGapCannotBecomeACompleteReplacementBaseline() throws Exception {+ try (Connection connection = fixture()) {+ connection.createStatement().execute("INSERT INTO ALL_SOURCE SELECT OWNER,NAME,TYPE,3,' -- lost dictionary line' FROM ALL_SOURCE WHERE LINE=1");+ ObjectSource source = new OracleTriggerReader(connection, "oceanbase-oracle").getObjectSource(OWNER, NAME);+ assertFalse(source.getTrigger().getOracle_metadata().definition().complete());+ assertEquals("BEGIN NULL; END;", source.getSource());+ }+ }++ @Test+ void nullCompilationErrorTextRemainsAnExplicitReadFailure() throws Exception {+ try (Connection connection = fixture()) {+ connection.createStatement().execute("UPDATE ALL_ERRORS SET TEXT=NULL");+ ObjectSource source = new OracleTriggerReader(connection, "oceanbase-oracle").getObjectSource(OWNER, NAME);+ assertTrue(source.getTrigger().getOracle_metadata().definition().complete());+ assertNull(source.getTrigger().getOracle_metadata().errors());+ assertEquals("error", source.getTrigger().getOracle_metadata().reads().get("errors").state());+ }+ }++ @Test+ void interruptedCharacterStreamCannotBecomeACompleteDefinition() throws Exception {+ try (Connection connection = fixture()) {+ Connection interrupted = (Connection) Proxy.newProxyInstance(Connection.class.getClassLoader(), new Class<?>[]{Connection.class}, (proxy, method, args) -> {+ try {+ Object value = method.invoke(connection, args);+ if (method.getName().equals("prepareStatement") && ((String) args[0]).contains("FROM ALL_SOURCE")) {+ return Proxy.newProxyInstance(PreparedStatement.class.getClassLoader(), new Class<?>[]{PreparedStatement.class}, (p, m, a) -> {+ try {+ Object result = m.invoke(value, a);+ if (!m.getName().equals("executeQuery")) return result;+ return Proxy.newProxyInstance(java.sql.ResultSet.class.getClassLoader(), new Class<?>[]{java.sql.ResultSet.class}, (r, read, column) -> {+ if (read.getName().equals("getCharacterStream")) return new java.io.Reader() {+ @Override public int read(char[] buffer, int offset, int length) throws java.io.IOException { throw new java.io.IOException("Stream interrupted"); }+ @Override public void close() {}+ };+ try { return read.invoke(result, column); }+ catch (InvocationTargetException error) { throw error.getCause(); }+ });+ } catch (InvocationTargetException error) { throw error.getCause(); }+ });+ }+ return value;+ } catch (InvocationTargetException error) { throw error.getCause(); }+ });+ ObjectSource source = new OracleTriggerReader(interrupted, "oceanbase-oracle").getObjectSource(OWNER, NAME);+ assertEquals("BEGIN NULL; END;", source.getSource());+ assertFalse(source.getTrigger().getOracle_metadata().definition().complete());+ }+ }++ @Test+ void concurrentSameNameRecreationCannotProduceAWritableSnapshot() throws Exception {+ try (Connection connection = fixture()) {+ Connection racing = (Connection) Proxy.newProxyInstance(Connection.class.getClassLoader(), new Class<?>[]{Connection.class}, (proxy, method, args) -> {+ try {+ Object value = method.invoke(connection, args);+ if (method.getName().equals("prepareStatement") && ((String) args[0]).contains("FROM ALL_SOURCE")) {+ PreparedStatement statement = (PreparedStatement) value;+ return Proxy.newProxyInstance(PreparedStatement.class.getClassLoader(), new Class<?>[]{PreparedStatement.class}, (p, m, a) -> {+ try {+ Object result = m.invoke(statement, a);+ if (m.getName().equals("executeQuery")) connection.createStatement().execute("UPDATE ALL_OBJECTS SET OBJECT_ID=99");+ return result;+ } catch (InvocationTargetException error) { throw error.getCause(); }+ });+ }+ return value;+ } catch (InvocationTargetException error) { throw error.getCause(); }+ });+ ObjectSource source = new OracleTriggerReader(racing, "oceanbase-oracle").getObjectSource(OWNER, NAME);+ assertEquals(SOURCE, source.getSource());+ assertFalse(source.getTrigger().getOracle_metadata().definition().complete());+ assertEquals("incomplete", source.getTrigger().getOracle_metadata().reads().get("identity").state());+ }+ }++ private static Connection fixture() throws Exception {+ Connection connection = DriverManager.getConnection("jdbc:h2:mem:" + UUID.randomUUID() + ";MODE=Oracle;NON_KEYWORDS=SEQUENCE,POSITION,LINE");+ try (var statement = connection.createStatement()) {+ statement.execute("CREATE TABLE ALL_TRIGGERS (OWNER VARCHAR, TRIGGER_NAME VARCHAR, TRIGGERING_EVENT VARCHAR, TRIGGER_TYPE VARCHAR, STATUS VARCHAR, TABLE_OWNER VARCHAR, TABLE_NAME VARCHAR, BASE_OBJECT_TYPE VARCHAR, WHEN_CLAUSE VARCHAR, REFERENCING_NAMES VARCHAR, DESCRIPTION VARCHAR, TRIGGER_BODY CLOB)");+ statement.execute("CREATE TABLE ALL_OBJECTS (OWNER VARCHAR, OBJECT_NAME VARCHAR, OBJECT_TYPE VARCHAR, OBJECT_ID BIGINT, LAST_DDL_TIME TIMESTAMP, STATUS VARCHAR)");+ statement.execute("CREATE TABLE ALL_SOURCE (OWNER VARCHAR, NAME VARCHAR, TYPE VARCHAR, LINE INT, TEXT CLOB)");+ statement.execute("CREATE TABLE ALL_ERRORS (OWNER VARCHAR, NAME VARCHAR, TYPE VARCHAR, SEQUENCE INT, LINE INT, POSITION INT, TEXT VARCHAR, ATTRIBUTE VARCHAR)");+ }+ try (PreparedStatement statement = connection.prepareStatement("INSERT INTO ALL_TRIGGERS VALUES (?, ?, 'INSERT', 'BEFORE EACH ROW', 'DISABLED', ?, ' Parent ', 'TABLE', NULL, NULL, NULL, 'BEGIN NULL; END;')")) {+ statement.setString(1, OWNER); statement.setString(2, NAME); statement.setString(3, PARENT_OWNER); statement.executeUpdate();+ }+ try (PreparedStatement statement = connection.prepareStatement("INSERT INTO ALL_OBJECTS VALUES (?, ?, 'TRIGGER', 9007199254740993, CURRENT_TIMESTAMP, 'INVALID')")) {+ statement.setString(1, OWNER); statement.setString(2, NAME); statement.executeUpdate();+ }+ try (PreparedStatement statement = connection.prepareStatement("INSERT INTO ALL_SOURCE VALUES (?, ?, 'TRIGGER', 1, ?)")) {+ statement.setString(1, OWNER); statement.setString(2, NAME); statement.setString(3, SOURCE); statement.executeUpdate();+ }+ try (PreparedStatement statement = connection.prepareStatement("INSERT INTO ALL_ERRORS VALUES (?, ?, 'TRIGGER', 1, 5, 7, 'Missing procedure', 'ERROR')")) {+ statement.setString(1, OWNER); statement.setString(2, NAME); statement.executeUpdate();+ }+ return connection;+ }+}diff --git a/agents/docs/agent-protocol-v2.md b/agents/docs/agent-protocol-v2.mdindex d022130444..a7a9a21091 100644--- a/agents/docs/agent-protocol-v2.md+++ b/agents/docs/agent-protocol-v2.md@@ -23,7 +23,19 @@ This is separate from one-shot `execute_transaction`, which begins, runs a state`agentSessionId` identifies a logical database connection. Existing `sessionId` fields remain pagination cursor identifiers and must not be used as logical connection identifiers.-`sessionRole` is `workload` by default. DBX sends `metadata` for object-tree, completion, and other read-only metadata sessions. New runtimes use this role to preserve metadata checkout capacity; older runtimes may ignore the field.+`sessionRole` is `workload` by default. DBX sends `metadata` for object-tree, completion, and isolated background tasks, including an operation-owned native Job session. The role selects resource isolation, not database write authorization; Core checks write protection before native Job mutations. New runtimes use this role to preserve metadata checkout capacity; older runtimes may ignore the field.++## Native Job physical sessions++Drivers that opt in to `native_job_session_v1` may use `MultiSessionJsonRpcServer.withNativeJobSessions(YourAgent::new)` and implement `supportsNativeJobSessions()`. The default JDBC and legacy v1 handshakes do not advertise this capability.++During confirmed apply, Core opens a private metadata logical session, then calls `open_native_job_session` with its `operationId`. The result contains the same `operationId`, an opaque `sessionToken`, and `phase: opened`. This reserves one non-pooled physical connection with automatic commit disabled. Existing runtime physical-connection limits and opening/closing watchdogs still apply. An editor transaction, pinned connection, cursor, or retained result prevents reservation without altering that existing state.++All subsequent `execute_query` and `connection_info` requests on the reservation carry `nativeJobOperationId` and `nativeJobSessionToken`. Other operations, changed configuration, automatic reconnect, and foreign or stale tokens are rejected before SQL. Native procedures may commit internally without releasing or replacing this physical connection. Core continues to own SQL plans, job-configuration phases, cancellation of remaining steps, and dispatch deduplication.++After the operation, Core calls `close_native_job_session` with `operationId` and `sessionToken` before retiring the metadata route. If the open response was lost, the exact operation may omit the token to close only its own connection; a replacement logical session cannot claim that ownership. Closing returns `phase: closed` only after the physical close is acknowledged. A failed close returns and retains `phase: unknown`, including on duplicate close and outer logical cleanup. Cleanup never submits a commit, native configuration commit, or activation. Closing the connection does not prove that already committed configuration changes were rolled back or that native configuration completed.++The Generic JDBC plugin advertises the same capability through `jdbcSessionProtocol` and accepts both `openNativeJobSession` / `closeNativeJobSession` and the snake-case method names. It supports the private default process and existing logical sessions. The connection and selected driver remain immutable during ownership, and native SQL bypasses ordinary SQL trimming, rewriting, automatic-commit restoration, and result-query retries. Ordinary JDBC requests retain their existing behavior.## Concurrencydiff --git a/agents/drivers/dameng/build.gradle b/agents/drivers/dameng/build.gradleindex 6a80eb99a5..e14d4ca879 100644--- a/agents/drivers/dameng/build.gradle+++ b/agents/drivers/dameng/build.gradle@@ -4,6 +4,7 @@ dependencies {implementation fileTree(dir: 'libs', include: ['*.jar'])// DmJdbcDriver8 supports JDK 8+ (compatible with JRE 21 used by DAMENG agent).implementation 'com.dameng:DmJdbcDriver8:8.1.5.45'+ testImplementation 'com.google.code.gson:gson:2.14.0'}tasks.named('shadowJar') {diff --git a/agents/drivers/dameng/src/main/java/com/dbx/agent/dameng/DamengAgent.java b/agents/drivers/dameng/src/main/java/com/dbx/agent/dameng/DamengAgent.javaindex 3fce6645c9..358c5bad81 100644--- a/agents/drivers/dameng/src/main/java/com/dbx/agent/dameng/DamengAgent.java+++ b/agents/drivers/dameng/src/main/java/com/dbx/agent/dameng/DamengAgent.java@@ -12,8 +12,10 @@ import com.dbx.agent.JdbcExecutor;import com.dbx.agent.JdbcIdentifiers;import com.dbx.agent.MultiSessionJsonRpcServer;import com.dbx.agent.MetadataListConstraints;+import com.dbx.agent.MetadataReadOptions;import com.dbx.agent.ObjectInfo;import com.dbx.agent.ObjectSource;+import com.dbx.agent.OracleTriggerReader;import com.dbx.agent.QueryPageOptions;import com.dbx.agent.QueryPageResult;import com.dbx.agent.QueryResult;@@ -998,6 +1000,7 @@ public final class DamengAgent extends AbstractJdbcAgent {|| constraints.objectTypeAllowed("SEQUENCE")|| constraints.objectTypeAllowed("PACKAGE")|| constraints.objectTypeAllowed("PACKAGE_BODY")+ || constraints.hasObjectTypes() && constraints.objectTypeAllowed("TRIGGER")|| constraints.objectTypeAllowed("TYPE")|| constraints.objectTypeAllowed("TYPE_BODY");}@@ -1050,6 +1053,7 @@ public final class DamengAgent extends AbstractJdbcAgent {if (constraints.objectTypeAllowed("PACKAGE_BODY")) {result.add("PACKAGE BODY");}+ if (constraints.hasObjectTypes() && constraints.objectTypeAllowed("TRIGGER")) result.add("TRIGGER");if (constraints.objectTypeAllowed("TYPE")) {result.add("TYPE");}@@ -1090,6 +1094,7 @@ public final class DamengAgent extends AbstractJdbcAgent {if (constraints.objectTypeAllowed("PACKAGE_BODY")) {result.add("PACKAGE BODY");}+ if (constraints.hasObjectTypes() && constraints.objectTypeAllowed("TRIGGER")) result.add("TRIGGER");if (constraints.objectTypeAllowed("TYPE")) {result.add("TYPE");}@@ -1195,6 +1200,24 @@ public final class DamengAgent extends AbstractJdbcAgent {return queryConstrainedObjects(schema, MetadataListConstraints.orNone(constraints));}+ @Override+ public List<ObjectInfo> listObjects(String schema, MetadataListConstraints constraints, MetadataReadOptions options) {+ if (options == null || !options.exact() || legacyJdbcMetadata) return listObjects(schema, constraints);+ if (schema == null || schema.isEmpty()) throw new IllegalArgumentException("Exact metadata requires an owner");+ MetadataListConstraints requested = MetadataListConstraints.orNone(constraints);+ if (!requested.hasObjectTypes()) {+ List<String> kinds = damengObjectTypes(MetadataListConstraints.NONE);+ kinds.add("TRIGGER");+ requested = new MetadataListConstraints(requested.getFilter(), requested.getLimit(), requested.getOffset(), kinds);+ }+ List<ObjectInfo> objects = queryConstrainedObjectsWithoutValidity(schema, requested, true);+ applyViewValidity(objects, schema);+ if (objects.stream().anyMatch(object -> "TRIGGER".equals(object.getObject_type()))) {+ uncheckedVoid(() -> new OracleTriggerReader(requireConnected(), "dm").enrichObjects(objects, schema));+ }+ return objects;+ }+private List<ObjectInfo> queryConstrainedObjects(String rawSchema, MetadataListConstraints constraints) {final String schema = normalizeSchema(rawSchema);List<ObjectInfo> objects;@@ -1240,6 +1263,10 @@ public final class DamengAgent extends AbstractJdbcAgent {}private List<ObjectInfo> queryConstrainedObjectsWithoutValidity(String schema, MetadataListConstraints constraints) {+ return queryConstrainedObjectsWithoutValidity(schema, constraints, false);+ }++ private List<ObjectInfo> queryConstrainedObjectsWithoutValidity(String schema, MetadataListConstraints constraints, boolean requireDictionary) {if (constraints.isExactIdentity()) {if (legacyJdbcMetadata) throw new UnsupportedOperationException("Legacy DM metadata does not support exact_metadata_identity_v1");return executeConstrainedObjects(schema, buildAccessibleConstrainedObjectsQuery(schema, constraints), constraints);@@ -1295,6 +1322,7 @@ public final class DamengAgent extends AbstractJdbcAgent {}permissionError.addSuppressed(e);}+ if (requireDictionary) throw permissionError;try {return executeJdbcMetadataObjects(schema, constraints);} catch (RuntimeException e) {@@ -1527,6 +1555,14 @@ public final class DamengAgent extends AbstractJdbcAgent {});}+ @Override+ public ObjectSource getObjectSource(String schema, String name, String objectType, MetadataReadOptions options) {+ if (options == null || !options.exact() || legacyJdbcMetadata || !"TRIGGER".equalsIgnoreCase(objectType)) {+ return getObjectSource(schema, name, objectType);+ }+ return unchecked(() -> new OracleTriggerReader(requireConnected(), "dm").getObjectSource(schema, name));+ }+private static boolean isOracleFamilyType(String objectType) {String normalized = normalizeObjectSourceType(objectType);return "TYPE".equals(normalized) || "TYPE_BODY".equals(normalized);@@ -2675,6 +2711,12 @@ public final class DamengAgent extends AbstractJdbcAgent {});}+ @Override+ public List<TriggerInfo> listTriggers(String schema, String table, MetadataReadOptions options) {+ if (options == null || !options.exact() || legacyJdbcMetadata) return listTriggers(schema, table);+ return unchecked(() -> new OracleTriggerReader(requireConnected(), "dm").listTriggers(schema, table));+ }+/*** 读取表上触发器的完整字典信息,供表结构编辑器的触发器页签展示与编辑。*@@ -3567,7 +3609,10 @@ public final class DamengAgent extends AbstractJdbcAgent {});}+ @Override+ public boolean supportsNativeJobSessions() { return true; }+public static void main(String[] args) {- new MultiSessionJsonRpcServer(DamengAgent::new).withExactMetadataIdentity().run();+ MultiSessionJsonRpcServer.withNativeJobSessions(DamengAgent::new).withExactMetadataIdentity().run();}}diff --git a/agents/drivers/dameng/src/test/java/com/dbx/agent/dameng/DamengAgentMetadataTest.java b/agents/drivers/dameng/src/test/java/com/dbx/agent/dameng/DamengAgentMetadataTest.javaindex 0ca3fdf125..081daf9244 100644--- a/agents/drivers/dameng/src/test/java/com/dbx/agent/dameng/DamengAgentMetadataTest.java+++ b/agents/drivers/dameng/src/test/java/com/dbx/agent/dameng/DamengAgentMetadataTest.java@@ -5,6 +5,12 @@ import com.dbx.agent.DatabaseInfo;import com.dbx.agent.ForeignKeyInfo;import com.dbx.agent.IndexInfo;import com.dbx.agent.MetadataListConstraints;+import com.dbx.agent.MetadataReadOptions;+import com.dbx.agent.AgentRpcTestSupport;+import com.dbx.agent.AgentProtocol;+import com.google.gson.Gson;+import com.google.gson.JsonObject;+import com.google.gson.JsonParser;import com.dbx.agent.ObjectInfo;import com.dbx.agent.ObjectSource;import com.dbx.agent.TableInfo;@@ -23,6 +29,7 @@ import java.sql.Connection;import java.sql.DatabaseMetaData;import java.sql.PreparedStatement;import java.sql.ResultSet;+import java.sql.ResultSetMetaData;import java.sql.SQLNonTransientConnectionException;import java.sql.SQLException;import java.sql.Statement;@@ -32,6 +39,69 @@ import java.util.Collections;import java.util.List;class DamengAgentMetadataTest {+ @Test+ void exactTriggerSourceRpcRetainsLongDdlAndIndependentErrors() {+ DamengAgent agent = new DamengAgent();+ List<String> calls = new ArrayList<>();+ String ddl = "CREATE TRIGGER \" Owner \".\" Trigger \" BEFORE INSERT ON \" Parent Owner \".\" Parent \" FOR EACH ROW BEGIN /* " + "中文😀".repeat(12_000) + " */ NULL; END;";+ TestSupport.setPrivateConnection(agent, exactTriggerConnection(calls, "TABLE", ddl, null));+ JsonObject request = new JsonObject();+ request.addProperty("id", 1);+ request.addProperty("method", AgentProtocol.METHOD_GET_OBJECT_SOURCE);+ request.add("params", JsonParser.parseString("{\"schema\":\" Owner \",\"name\":\" Trigger \",\"object_type\":\"TRIGGER\",\"identity_mode\":\"exact\"}"));+ JsonObject response = JsonParser.parseString(AgentRpcTestSupport.handleRequest(agent, request.toString())).getAsJsonObject();+ Assertions.assertFalse(response.has("error"), response.toString());+ ObjectSource source = new Gson().fromJson(response.get("result"), ObjectSource.class);+ Assertions.assertEquals(ddl, source.getSource());+ Assertions.assertEquals("dm", source.getTrigger().getOracle_metadata().engine());+ Assertions.assertEquals("9007199254740993", source.getTrigger().getOracle_metadata().objectId());+ Assertions.assertFalse(source.getTrigger().getEnabled());+ Assertions.assertFalse(source.getTrigger().getValid());+ Assertions.assertTrue(source.getTrigger().getOracle_metadata().definition().complete());+ Assertions.assertEquals("Missing procedure", source.getTrigger().getOracle_metadata().errors().get(0).text());+ Assertions.assertTrue(calls.contains("bind:1= Owner "), calls.toString());+ Assertions.assertTrue(calls.contains("bind:2= Trigger "), calls.toString());+ }++ @Test+ void exactTriggerDiscoveryPreservesNonTableScopesAndPagesBeforeEnrichment() {+ for (String scope : List.of("TABLE", "VIEW", "SCHEMA", "DATABASE", "TIMER")) {+ DamengAgent agent = new DamengAgent();+ List<String> calls = new ArrayList<>();+ TestSupport.setPrivateConnection(agent, exactTriggerConnection(calls, scope, "", null));+ ObjectInfo object = agent.listObjects(" Owner ", new MetadataListConstraints("trig", 1, 2, List.of("TRIGGER")), MetadataReadOptions.EXACT).get(0);+ Assertions.assertEquals(scope, object.getTrigger().getOracle_metadata().scope());+ if (List.of("TABLE", "VIEW").contains(scope)) Assertions.assertEquals(" Parent Owner ", object.getParent_schema());+ else {+ Assertions.assertNull(object.getParent_name());+ Assertions.assertNull(object.getParent_schema());+ Assertions.assertNull(object.getTrigger().getOracle_metadata().parent());+ }+ Assertions.assertTrue(calls.get(0).contains("UPPER(o.OBJECT_NAME)"), calls.toString());+ Assertions.assertTrue(calls.get(0).contains("o.OBJECT_TYPE IN"), calls.toString());+ Assertions.assertTrue(calls.contains("bind:1= Owner "), calls.toString());+ Assertions.assertNull(object.getTrigger().getStatement());+ }+ }++ @Test+ void exactBodyOnlyAndDeniedSourceRemainVisibleButIncomplete() {+ DamengAgent agent = new DamengAgent();+ TestSupport.setPrivateConnection(agent, exactTriggerConnection(new ArrayList<>(), "TABLE", "", new SQLException("ORA-01031: insufficient privileges", "42501", 1031)));+ ObjectSource source = agent.getObjectSource(" Owner ", " Trigger ", "TRIGGER", MetadataReadOptions.EXACT);+ Assertions.assertEquals("BEGIN NULL; END;", source.getSource());+ Assertions.assertFalse(source.getTrigger().getOracle_metadata().definition().complete());+ Assertions.assertEquals("denied", source.getTrigger().getOracle_metadata().reads().get("definition").state());+ }++ @Test+ void exactRequestDoesNotTurnLegacyDm6MetadataIntoANewContract() {+ DamengAgent agent = new DamengAgent();+ TestSupport.setPrivateConnection(agent, legacyMetadataConnection(new ArrayList<>()));+ setLegacyJdbcMetadata(agent, true);+ Assertions.assertTrue(agent.listTriggers("APP", "USERS", MetadataReadOptions.EXACT).isEmpty());+ }+@Testvoid detectsLegacyDamengMetadataFromDatabaseVersion() {Assertions.assertTrue(DamengAgent.usesLegacyJdbcMetadata(versionConnection(6, "6.0.2.79")));@@ -3528,10 +3598,16 @@ class DamengAgentMetadataTest {}return column + 1;}- if ("getString".equals(name) && args[0] instanceof Integer columnIndex) {+ if (("getString".equals(name) || "getObject".equals(name)) && args[0] instanceof Integer columnIndex) {List<String> row = rows.get(index[0]);return columnIndex - 1 < row.size() ? row.get(columnIndex - 1) : null;}+ if ("getLong".equals(name)) return Long.parseLong(rows.get(index[0]).get((Integer) args[0] - 1));+ if ("getMetaData".equals(name)) return proxy(ResultSetMetaData.class, (metadataMethod, values) -> switch (metadataMethod.getName()) {+ case "getColumnCount" -> columns.size();+ case "getColumnLabel" -> columns.get((Integer) values[0] - 1);+ default -> defaultValue(metadataMethod.getReturnType());+ });if ("close".equals(name)) {return null;}@@ -3539,6 +3615,35 @@ class DamengAgentMetadataTest {});}+ private static Connection exactTriggerConnection(List<String> calls, String scope, String ddl, SQLException sourceError) {+ List<String> columns = List.of("OWNER", "TRIGGER_NAME", "TRIGGERING_EVENT", "TRIGGER_TYPE", "STATUS", "TABLE_OWNER", "TABLE_NAME", "BASE_OBJECT_TYPE", "TRIGGER_BODY", "DBX_TRIGGER_OBJECT_MARKER", "OWNER", "OBJECT_NAME", "OBJECT_ID", "LAST_DDL_TIME", "STATUS");+ List<List<String>> rows = List.of(Arrays.asList(" Owner ", " Trigger ", scope.equals("TIMER") ? "TIMER" : "INSERT", "BEFORE EACH ROW", "DISABLED", " Parent Owner ",+ List.of("TABLE", "VIEW").contains(scope) ? " Parent " : null, scope.equals("TIMER") ? "DATABASE" : scope, "BEGIN NULL; END;", " Trigger ", " Owner ", " Trigger ", "9007199254740993", "2026-10-21 08:00:00", "INVALID"));+ return proxy(Connection.class, (method, args) -> {+ if (method.getName().equals("getMetaData")) return proxy(DatabaseMetaData.class, (metadataMethod, values) ->+ metadataMethod.getName().equals("getDatabaseProductVersion") ? "8.1.5" : defaultValue(metadataMethod.getReturnType()));+ if (method.getName().equals("prepareStatement")) {+ String sql = (String) args[0]; calls.add(sql);+ return proxy(PreparedStatement.class, (statementMethod, values) -> {+ if (statementMethod.getName().equals("setString")) { calls.add("bind:" + values[0] + "=" + values[1]); return null; }+ if (statementMethod.getName().equals("executeQuery")) {+ if (sql.contains("FROM ALL_TRIGGERS")) return triggerMetadataResultSet(columns, rows);+ if (sql.contains("DBMS_METADATA.GET_DDL")) {+ if (sourceError != null) throw sourceError;+ return metadataResultSet(List.of(List.of(new LongText(ddl, ddl.substring(0, Math.min(64, ddl.length()))))));+ }+ if (sql.contains("FROM ALL_ERRORS")) return triggerMetadataResultSet(List.of("SEQUENCE", "LINE", "POSITION", "TEXT", "ATTRIBUTE"), List.of(List.of("1", "4", "7", "Missing procedure", "ERROR")));+ if (sql.contains("FROM ALL_SOURCE")) return metadataResultSet(List.of());+ if (sql.contains("FROM ALL_OBJECTS o")) return metadataResultSet(List.of(List.of(" Trigger ", "TRIGGER", "")));+ throw new AssertionError("Unexpected exact trigger query: " + sql);+ }+ return defaultValue(statementMethod.getReturnType());+ });+ }+ return defaultValue(method.getReturnType());+ });+ }+// Serves the session-schema probe, records every first bound parameter (the OWNER of the// metadata queries under test) and answers the column/table queries these tests assert on.private static Connection sessionSchemaConnection(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 a4c8f92d7d..9b42767237 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@@ -23,9 +23,11 @@ import com.dbx.agent.JdbcExecutor;import com.dbx.agent.JdbcIdentifiers;import com.dbx.agent.MultiSessionJsonRpcServer;import com.dbx.agent.MetadataListConstraints;+import com.dbx.agent.MetadataReadOptions;import com.dbx.agent.ObjectInfo;import com.dbx.agent.ObjectSource;import com.dbx.agent.OracleObjectPrivilege;+import com.dbx.agent.OracleTriggerReader;import com.dbx.agent.PartitionInfo;import com.dbx.agent.QueryPageOptions;import com.dbx.agent.QueryPageResult;@@ -104,6 +106,9 @@ public final class OceanBaseOracleAgent extends ConfiguredJdbcAgent {@Overridepublic boolean supportsBlobBindStatements() { return true; }+ @Override+ public boolean supportsNativeLegacyJobs() { return true; }+@Overridepublic QueryResult executeBlobBoundStatements(List<String> previews, List<BlobBoundStatement> statements,String schema, int timeoutSecs, boolean transaction) {@@ -678,10 +683,20 @@ public final class OceanBaseOracleAgent extends ConfiguredJdbcAgent {return queryObjects(schema, MetadataListConstraints.orNone(constraints));}+ @Override+ public List<ObjectInfo> listObjects(String schema, MetadataListConstraints constraints, MetadataReadOptions options) {+ return queryObjects(schema, MetadataListConstraints.orNone(constraints), options != null && options.exact());+ }+private List<ObjectInfo> queryObjects(String schema, MetadataListConstraints constraints) {+ return queryObjects(schema, constraints, false);+ }++ private List<ObjectInfo> queryObjects(String schema, MetadataListConstraints constraints, boolean exact) {return unchecked(() -> {- String owner = normalizeSchema(schema);- List<String> objectTypes = oceanBaseObjectTypes(constraints);+ if (exact && (schema == null || schema.isEmpty())) throw new IllegalArgumentException("Exact metadata requires an owner");+ String owner = exact ? schema : normalizeSchema(schema);+ List<String> objectTypes = oceanBaseObjectTypes(constraints, exact);if (objectTypes.isEmpty()) {return List.of();}@@ -732,7 +747,11 @@ public final class OceanBaseOracleAgent extends ConfiguredJdbcAgent {}}}- return constraints.withoutPaging().filterObjects(result);+ List<ObjectInfo> objects = constraints.withoutPaging().filterObjects(result);+ if (exact && objects.stream().anyMatch(object -> "TRIGGER".equals(object.getObject_type()))) {+ new OracleTriggerReader(requireConnection(), "oceanbase-oracle").enrichObjects(objects, owner);+ }+ return objects;});}@@ -1302,8 +1321,9 @@ public final class OceanBaseOracleAgent extends ConfiguredJdbcAgent {return result;}- private static List<String> oceanBaseObjectTypes(MetadataListConstraints constraints) {- List<String> supported = List.of("TABLE", "VIEW", "PROCEDURE", "FUNCTION", "PACKAGE", "PACKAGE BODY", "SEQUENCE", "SYNONYM", "TYPE", "TYPE BODY", "INDEX");+ private static List<String> oceanBaseObjectTypes(MetadataListConstraints constraints, boolean exact) {+ List<String> supported = new ArrayList<>(List.of("TABLE", "VIEW", "PROCEDURE", "FUNCTION", "PACKAGE", "PACKAGE BODY", "SEQUENCE", "SYNONYM", "TYPE", "TYPE BODY", "INDEX"));+ if (exact) supported.add("TRIGGER");if (!constraints.hasObjectTypes()) {return supported;}@@ -1363,6 +1383,14 @@ public final class OceanBaseOracleAgent extends ConfiguredJdbcAgent {});}+ @Override+ public ObjectSource getObjectSource(String schema, String name, String objectType, MetadataReadOptions options) {+ if (options == null || !options.exact() || !"TRIGGER".equals(normalizeObjectSourceType(objectType))) {+ return getObjectSource(schema, name, objectType);+ }+ return unchecked(() -> new OracleTriggerReader(requireConnection(), "oceanbase-oracle").getObjectSource(schema, name));+ }+private ObjectSource getDictionaryFirstObjectSource(String owner, String name, String objectType, boolean exactMetadataKind) throws SQLException {String source;String origin = "oceanbase-dictionary";@@ -2324,6 +2352,12 @@ public final class OceanBaseOracleAgent extends ConfiguredJdbcAgent {});}+ @Override+ public List<TriggerInfo> listTriggers(String schema, String table, MetadataReadOptions options) {+ if (options == null || !options.exact()) return listTriggers(schema, table);+ return unchecked(() -> new OracleTriggerReader(requireConnection(), "oceanbase-oracle").listTriggers(schema, table));+ }+@Overridepublic String setSchemaSQL(String schema) {if (schema == null || schema.isBlank()) {@@ -2468,6 +2502,6 @@ public final class OceanBaseOracleAgent extends ConfiguredJdbcAgent {}public static void main(String[] args) {- MultiSessionJsonRpcServer.withBlobBindings(OceanBaseOracleAgent::new).withExactMetadataIdentity().run();+ MultiSessionJsonRpcServer.withNativeLegacyJobs(OceanBaseOracleAgent::new, true).withExactMetadataIdentity().run();}}diff --git a/agents/drivers/oceanbase-oracle/src/test/java/com/dbx/agent/oceanbaseoracle/OceanBaseOracleObjectListTest.java b/agents/drivers/oceanbase-oracle/src/test/java/com/dbx/agent/oceanbaseoracle/OceanBaseOracleObjectListTest.javaindex 5b59ea9b61..cda3733e0c 100644--- a/agents/drivers/oceanbase-oracle/src/test/java/com/dbx/agent/oceanbaseoracle/OceanBaseOracleObjectListTest.java+++ b/agents/drivers/oceanbase-oracle/src/test/java/com/dbx/agent/oceanbaseoracle/OceanBaseOracleObjectListTest.java@@ -1,6 +1,14 @@package com.dbx.agent.oceanbaseoracle;import com.dbx.agent.MetadataListConstraints;+import com.dbx.agent.MetadataReadOptions;+import com.dbx.agent.AgentRpcTestSupport;+import com.dbx.agent.AgentProtocol;+import com.dbx.agent.TriggerInfo;+import com.google.gson.JsonParser;+import com.google.gson.Gson;+import com.google.gson.JsonObject;+import com.google.gson.JsonElement;import com.dbx.agent.ObjectInfo;import com.dbx.agent.ObjectSource;import com.dbx.agent.test.TestSupport;@@ -11,8 +19,10 @@ import org.junit.jupiter.params.provider.ValueSource;import java.lang.reflect.InvocationHandler;import java.lang.reflect.Proxy;import java.sql.Connection;+import java.sql.DatabaseMetaData;import java.sql.PreparedStatement;import java.sql.ResultSet;+import java.sql.ResultSetMetaData;import java.sql.SQLException;import java.util.ArrayDeque;import java.util.ArrayList;@@ -23,6 +33,97 @@ import java.util.List;import static org.junit.jupiter.api.Assertions.*;class OceanBaseOracleObjectListTest {+ private static final String[] TRIGGER_COLUMNS = {"OWNER", "TRIGGER_NAME", "TRIGGERING_EVENT", "TRIGGER_TYPE", "STATUS", "TABLE_OWNER", "TABLE_NAME", "BASE_OBJECT_TYPE", "WHEN_CLAUSE", "TRIGGER_BODY", "DBX_TRIGGER_OBJECT_MARKER", "OWNER", "OBJECT_NAME", "OBJECT_ID", "LAST_DDL_TIME", "STATUS"};++ private static String[] triggerRow() {+ return row(" Owner ", " Trigger ", "INSERT", "INSTEAD OF", "DISABLED", " Parent Owner ", " View ", "VIEW", null,+ "BEGIN NULL; END;", " Trigger ", " Owner ", " Trigger ", "9007199254740993", "2026-10-21 08:00:00", "INVALID");+ }++ @Test+ void exactSchemaRpcFiltersBeforePagingThenEnrichesOnlyThatPage() throws Exception {+ JdbcFixture jdbc = new JdbcFixture();+ JdbcCall page = jdbc.rows(row(" Trigger ", "TRIGGER", null));+ JdbcCall metadata = jdbc.rows(triggerRow()).columns(TRIGGER_COLUMNS);+ ObjectInfo object = new Gson().fromJson(rpc(jdbc, AgentProtocol.METHOD_LIST_OBJECTS,+ "{\"schema\":\" Owner \",\"object_types\":[\"TRIGGER\"],\"filter\":\"trig\",\"limit\":1,\"offset\":2,\"identity_mode\":\"exact\"}"), ObjectInfo[].class)[0];+ assertEquals(" Trigger ", object.getName());+ assertEquals(" Parent Owner ", object.getParent_schema());+ assertEquals("VIEW", object.getTrigger().getOracle_metadata().scope());+ assertFalse(object.getValid());+ assertFalse(object.getTrigger().getEnabled());+ assertTrue(page.sql.indexOf("UPPER(o.OBJECT_NAME)") < page.sql.indexOf("WHERE ROWNUM <= ?"));+ assertEquals(List.of(" Owner ", "TRIGGER", "%T%R%I%G%", "%T%R%I%G%", 3L, 2), page.args);+ assertEquals(List.of(" Owner ", " Trigger "), metadata.args);+ assertFalse(metadata.sql.contains("ALL_SOURCE"));+ assertNull(object.getTrigger().getStatement());+ page.assertClosed(); metadata.assertClosed();+ }++ @Test+ void exactOwningObjectRpcUsesParentOwnerNotTriggerOwner() throws Exception {+ JdbcFixture jdbc = new JdbcFixture();+ JdbcCall metadata = jdbc.rows(triggerRow()).columns(TRIGGER_COLUMNS);+ TriggerInfo trigger = new Gson().fromJson(rpc(jdbc, AgentProtocol.METHOD_LIST_TRIGGERS,+ "{\"schema\":\" Parent Owner \",\"table\":\" View \",\"identity_mode\":\"exact\"}"), TriggerInfo[].class)[0];+ assertEquals(" Owner ", trigger.getOracle_metadata().owner());+ assertEquals(" Parent Owner ", trigger.getOracle_metadata().parent().owner());+ assertEquals(List.of(" Parent Owner ", " View "), metadata.args);+ assertTrue(metadata.sql.contains("t.TABLE_OWNER = ? AND t.TABLE_NAME = ?"));+ metadata.assertClosed();+ }++ @Test+ void exactSourceRpcReadsFullDefinitionErrorsAndChecksIdentityAgain() throws Exception {+ JdbcFixture jdbc = new JdbcFixture();+ JdbcCall before = jdbc.rows(triggerRow()).columns(TRIGGER_COLUMNS);+ String definition = "TRIGGER \" Trigger \" INSTEAD OF INSERT ON \" Parent Owner \".\" View \"\nFOR EACH ROW DISABLE BEGIN NULL; END;";+ JdbcCall source = jdbc.rows(row("1", definition));+ JdbcCall errors = jdbc.rows(row("1", "3", "7", "Missing procedure", "ERROR"));+ JdbcCall after = jdbc.rows(triggerRow()).columns(TRIGGER_COLUMNS);+ ObjectSource result = new Gson().fromJson(rpc(jdbc, AgentProtocol.METHOD_GET_OBJECT_SOURCE,+ "{\"schema\":\" Owner \",\"name\":\" Trigger \",\"object_type\":\"TRIGGER\",\"identity_mode\":\"exact\"}"), ObjectSource.class);+ assertEquals(definition, result.getSource());+ assertTrue(result.getTrigger().getOracle_metadata().definition().complete());+ assertFalse(result.getTrigger().getValid());+ assertEquals("Missing procedure", result.getTrigger().getOracle_metadata().errors().get(0).text());+ for (JdbcCall call : List.of(before, source, errors, after)) {+ assertEquals(List.of(" Owner ", " Trigger "), call.args);+ call.assertClosed();+ }+ }++ @Test+ void aDeniedSummaryReadRetainsThePageAndUnknownStates() {+ JdbcFixture jdbc = new JdbcFixture();+ jdbc.rows(row(" Trigger ", "TRIGGER", null));+ JdbcCall denied = jdbc.rows();+ denied.executeFailure = new SQLException("ORA-01031: insufficient privileges", "42000", 1031);+ ObjectInfo result = jdbc.agent.listObjects(" Owner ", constraints(null, 1, 0, "TRIGGER"), MetadataReadOptions.EXACT).get(0);+ assertEquals(" Trigger ", result.getName());+ assertNull(result.getTrigger().getEnabled());+ assertNull(result.getTrigger().getValid());+ assertEquals("denied", result.getTrigger().getOracle_metadata().reads().get("enabled").state());+ assertTrue(denied.statementClosed);+ }++ @Test+ void exactMetadataFallbackRetainsTheExportedStateAppendix() {+ JdbcFixture jdbc = new JdbcFixture();+ jdbc.rows(triggerRow()).columns(TRIGGER_COLUMNS);+ jdbc.rows();+ String exported = "CREATE TRIGGER \" Owner \".\" Trigger \" INSTEAD OF INSERT ON \" Parent Owner \".\" View \" FOR EACH ROW BEGIN NULL; END;\nALTER TRIGGER \" Owner \".\" Trigger \" DISABLE;";+ JdbcCall metadata = jdbc.rows(row(exported));+ jdbc.rows();+ jdbc.rows(triggerRow()).columns(TRIGGER_COLUMNS);+ ObjectSource result = jdbc.agent.getObjectSource(" Owner ", " Trigger ", "TRIGGER", MetadataReadOptions.EXACT);+ assertEquals(exported, result.getSource());+ assertEquals("DBMS_METADATA", result.getTrigger().getOracle_metadata().definition().origin());+ assertTrue(result.getTrigger().getOracle_metadata().definition().complete());+ assertEquals(List.of("TRIGGER", " Trigger ", " Owner "), metadata.args);+ assertFalse(result.getTrigger().getEnabled());+ }+@Testvoid schemaIndexPagesPreserveBothOwnersAndRawNames() {JdbcFixture jdbc = new JdbcFixture();@@ -396,6 +497,16 @@ class OceanBaseOracleObjectListTest {return new MetadataListConstraints(filter, limit, offset, Arrays.asList(types));}+ private static JsonElement rpc(JdbcFixture jdbc, String method, String params) {+ JsonObject request = new JsonObject();+ request.addProperty("id", 1);+ request.addProperty("method", method);+ request.add("params", JsonParser.parseString(params));+ JsonObject response = JsonParser.parseString(AgentRpcTestSupport.handleRequest(jdbc.agent, request.toString())).getAsJsonObject();+ assertFalse(response.has("error"), response.toString());+ return response.get("result");+ }+private static String[] row(String... columns) {return columns;}@@ -424,6 +535,12 @@ class OceanBaseOracleObjectListTest {if (method.getName().equals("isClosed")) {return false;}+ if (method.getName().equals("getMetaData")) {+ return proxy(DatabaseMetaData.class, (metadata, metadataMethod, values) -> {+ if (metadataMethod.getName().equals("getDatabaseProductVersion")) return "4.2.5.7_107";+ throw new AssertionError("Unexpected database metadata method: " + metadataMethod.getName());+ });+ }throw new AssertionError("Unexpected connection method: " + method.getName());}));}@@ -443,11 +560,17 @@ class OceanBaseOracleObjectListTest {SQLException readFailure;boolean statementClosed;boolean resultClosed;+ String[] columns;JdbcCall(String[][] rows) {this.rows = rows;}+ JdbcCall columns(String... labels) {+ columns = labels;+ return this;+ }+PreparedStatement statement() {return proxy(PreparedStatement.class, (statement, method, values) -> switch (method.getName()) {case "setString", "setInt", "setLong", "setObject" -> {@@ -480,8 +603,16 @@ class OceanBaseOracleObjectListTest {}yield cursor[0] < rows.length;}- case "getString" -> (Integer) values[0] <= rows[cursor[0]].length+ case "getString", "getObject" -> (Integer) values[0] <= rows[cursor[0]].length? rows[cursor[0]][(Integer) values[0] - 1] : null;+ case "getLong" -> Long.parseLong(rows[cursor[0]][(Integer) values[0] - 1]);+ case "wasNull" -> false;+ case "getCharacterStream" -> null;+ case "getMetaData" -> proxy(ResultSetMetaData.class, (metadata, metadataMethod, args) -> switch (metadataMethod.getName()) {+ case "getColumnCount" -> columns.length;+ case "getColumnLabel" -> columns[(Integer) args[0] - 1];+ default -> throw new AssertionError("Unexpected result metadata method: " + metadataMethod.getName());+ });case "close" -> {resultClosed = true;yield null;diff --git a/agents/drivers/oracle-go/main.go b/agents/drivers/oracle-go/main.goindex e21ba9aba9..e1f6cd2c01 100644--- a/agents/drivers/oracle-go/main.go+++ b/agents/drivers/oracle-go/main.go@@ -281,8 +281,9 @@ type response struct {}type rpcError struct {- Code int `json:"code"`- Message string `json:"message"`+ Code int `json:"code"`+ Message string `json:"message"`+ Data *rpcErrorData `json:"data,omitempty"`}// oracleDriverPanicError keeps a third-party driver panic on the request path@@ -483,16 +484,19 @@ type metadataListConstraints struct {Limit intOffset intObjectTypes []string+ Exact boolExactIdentity bool}type objectInfo struct {- Name string `json:"name"`- ObjectType string `json:"object_type"`- Schema string `json:"schema"`- Comment *string `json:"comment"`- ParentSchema *string `json:"parent_schema,omitempty"`- ParentName *string `json:"parent_name,omitempty"`+ Name string `json:"name"`+ ObjectType string `json:"object_type"`+ Schema string `json:"schema"`+ Comment *string `json:"comment"`+ Valid *bool `json:"valid,omitempty"`+ ParentSchema *string `json:"parent_schema,omitempty"`+ ParentName *string `json:"parent_name,omitempty"`+ Trigger *triggerInfo `json:"trigger,omitempty"`}type columnInfo struct {@@ -554,11 +558,14 @@ type foreignKeyInfo struct {}type triggerInfo struct {- Name string `json:"name"`- Event string `json:"event"`- Timing string `json:"timing"`- Statement *string `json:"statement,omitempty"`- Enabled *bool `json:"enabled,omitempty"`+ Name string `json:"name"`+ Event string `json:"event"`+ Timing string `json:"timing"`+ Statement *string `json:"statement,omitempty"`+ Enabled *bool `json:"enabled,omitempty"`+ Valid *bool `json:"valid,omitempty"`+ Condition *string `json:"condition,omitempty"`+ OracleMetadata *oracleTriggerMetadata `json:"oracle_metadata,omitempty"`}// constraintInfo represents primary key, unique, and check constraints for a@@ -634,6 +641,7 @@ type server struct {// commit/rollback control across multiple execute_query RPCs.manualConn *sql.ConnmanualTx *sql.Tx+ legacyJob *legacyJobSessionsessions map[string]*querySessiontableReadSessions map[string]*querySessionnextSessionID int64@@ -723,19 +731,19 @@ func (r *runtimeServer) handleLine(line string) (resp response, shutdown bool) {// error response instead of an end-of-stream failure.defer func() {if recovered := recover(); recovered != nil {- resp = errorResponse(req.ID, fmt.Errorf("agent request panic: %v", recovered))+ resp = errorResponse(req.ID, fmt.Errorf("agent request panic: %v", recovered), req.Method, stringParam(req.Params, "agentSessionId"))shutdown = false}}()if err := json.Unmarshal([]byte(line), &req); err != nil {- return errorResponse(nil, err), false+ return errorResponse(nil, err, "", ""), false}if len(req.ID) == 0 {req.ID = json.RawMessage("1")}result, shouldShutdown, err := r.dispatch(req.Method, req.Params)if err != nil {- return errorResponse(req.ID, err), false+ return errorResponse(req.ID, err, req.Method, stringParam(req.Params, "agentSessionId")), false}return response{JSONRPC: "2.0", ID: req.ID, Result: result}, shouldShutdown}@@ -746,7 +754,7 @@ func (r *runtimeServer) dispatch(method string, params map[string]json.RawMessagreturn map[string]any{"protocolVersion": multiSessionProtocolVersion,"agentProtocolVersion": multiSessionProtocolVersion,- "capabilities": []string{"connect", "test_connection", "metadata", "query", "transaction", "ddl", "multi_session", "exact_metadata_identity_v1"},+ "capabilities": []string{"connect", "test_connection", "metadata", "query", "transaction", "ddl", "multi_session", "native_job_legacy_v1", "structured_error_v1", "exact_metadata_identity_v1"},}, false, nilcase "open_session":agentSessionID := stringParam(params, "agentSessionId")@@ -909,14 +917,14 @@ func newServer() *server {func (s *server) handleLine(line string) (response, bool) {var req requestif err := json.Unmarshal([]byte(line), &req); err != nil {- return errorResponse(nil, err), false+ return errorResponse(nil, err, "", ""), false}if len(req.ID) == 0 {req.ID = json.RawMessage("1")}result, shutdown, err := s.dispatch(req.Method, req.Params)if err != nil {- return errorResponse(req.ID, err), false+ return errorResponse(req.ID, err, req.Method, ""), false}return response{JSONRPC: "2.0", ID: req.ID, Result: result}, shutdown}@@ -932,7 +940,7 @@ func (s *server) dispatch(method string, params map[string]json.RawMessage) (anyreturn map[string]any{"protocolVersion": protocolVersion,"agentProtocolVersion": protocolVersion,- "capabilities": []string{"connect", "test_connection", "metadata", "query", "transaction", "ddl", "exact_metadata_identity_v1"},+ "capabilities": []string{"connect", "test_connection", "metadata", "query", "transaction", "ddl", "native_job_legacy_v1", "exact_metadata_identity_v1"},}, false, nilcase "connect":var cp connectParams@@ -968,7 +976,13 @@ func (s *server) dispatch(method string, params map[string]json.RawMessage) (anyreturn result, false, errcase "list_objects":schema := stringParam(params, "schema")- result, err := s.listObjects(schema, metadataListConstraintsFromParams(params))+ exact, err := exactMetadataReadParam(params)+ if err != nil {+ return nil, false, err+ }+ constraints := metadataListConstraintsFromParams(params)+ constraints.Exact = exact+ result, err := s.listObjects(schema, constraints)return result, false, errcase "completion_assistant_search_v1":var request completionAssistantRequest@@ -991,6 +1005,14 @@ func (s *server) dispatch(method string, params map[string]json.RawMessage) (anyschema := stringParam(params, "schema")name := stringParam(params, "name")objectType := stringParam(params, "object_type")+ exact, err := exactMetadataReadParam(params)+ if err != nil {+ return nil, false, err+ }+ if exact && strings.EqualFold(objectType, "TRIGGER") {+ source, err := s.getExactTriggerSource(schema, name)+ return source, false, err+ }source, err := s.getObjectSource(schema, name, objectType)if err == nil && boolParam(params, "include_source_origin") {switch strings.ToUpper(objectType) {@@ -1054,6 +1076,14 @@ func (s *server) dispatch(method string, params map[string]json.RawMessage) (anycase "list_triggers":schema := stringParam(params, "schema")table := stringParam(params, "table")+ exact, err := exactMetadataReadParam(params)+ if err != nil {+ return nil, false, err+ }+ if exact {+ result, err := s.listExactTriggers(schema, table)+ return result, false, err+ }result, err := s.listTriggersWithIdentity(schema, table, boolParam(params, "exact_identity"))return result, false, errcase "get_explain_info":@@ -1070,6 +1100,16 @@ func (s *server) dispatch(method string, params map[string]json.RawMessage) (anyreturn result, false, errcase "begin_manual_transaction":return map[string]bool{"ok": true}, false, s.beginManualTransaction(stringParam(params, "schema"))+ case "prepare_legacy_job":+ var request legacyJobPrepareRequest+ if err := decodeParams(params, &request); err != nil {+ return legacyJobResult{Phase: "not_started", Reason: "native_job_request_invalid"}, false, nil+ }+ return s.prepareLegacyJob(request), false, nil+ case "commit_legacy_job", "rollback_legacy_job":+ return s.finishLegacyJob(stringParam(params, "operationId"), stringParam(params, "jobId"), method == "commit_legacy_job"), false, nil+ case "legacy_job_status":+ return s.legacyJobStatus(stringParam(params, "operationId")), false, nilcase "commit_manual_transaction":return map[string]bool{"ok": true}, false, s.commitManualTransaction()case "rollback_manual_transaction":@@ -1258,12 +1298,16 @@ func withOracleLOBFetchPost(params connectParams) connectParams {func (s *server) disconnect() error {s.closeAllQuerySessions()_ = s.rollbackManualTransactionQuiet()+ jobErr := s.closeLegacyJob()s.legacyLOBFetchDeferred = falseif s.db == nil {- return nil+ return jobErr}err := s.db.Close()s.db = nil+ if jobErr != nil {+ return jobErr+ }return err}@@ -1912,6 +1956,9 @@ SELECT o.OBJECT_NAME,CAST(NULL AS VARCHAR2(128)) AS PARENT_NAMEFROM ALL_OBJECTS oWHERE o.OWNER = :4 AND o.OBJECT_TYPE IN ('TYPE', 'TYPE BODY')`+ if constraints.Exact {+ baseSQL = strings.Replace(baseSQL, "'PACKAGE BODY', 'INDEX')", "'PACKAGE BODY', 'INDEX', 'TRIGGER')", 1)+ }return oracleConstrainedMetadataListQuery(baseSQL,"OBJECT_NAME, OBJECT_TYPE, COMMENTS, PARENT_SCHEMA, PARENT_NAME",@@ -1923,8 +1970,12 @@ WHERE o.OWNER = :4 AND o.OBJECT_TYPE IN ('TYPE', 'TYPE BODY')`}func oracleListSessionUserObjectsQuery(constraints metadataListConstraints) oracleMetadataListQuery {+ baseSQL := oracleListObjectsSessionUserBaseSQL+ if constraints.Exact {+ baseSQL = strings.Replace(baseSQL, "'PACKAGE BODY', 'INDEX', 'TYPE', 'TYPE BODY')", "'PACKAGE BODY', 'INDEX', 'TYPE', 'TYPE BODY', 'TRIGGER')", 1)+ }return oracleConstrainedMetadataListQuery(- oracleListObjectsSessionUserBaseSQL,+ baseSQL,"OBJECT_NAME, OBJECT_TYPE, COMMENTS, PARENT_SCHEMA, PARENT_NAME","OBJECT_TYPE",oracleListObjectsOrderSQL,@@ -2047,7 +2098,7 @@ func (s *server) listTables(schema string, constraints metadataListConstraints)func (s *server) listObjects(schema string, constraints metadataListConstraints) ([]objectInfo, error) {rawTypeOwner := schema- schema, err := s.metadataSchema(schema, constraints.ExactIdentity)+ schema, err := s.metadataSchema(schema, constraints.Exact || constraints.ExactIdentity)if err != nil {return nil, err}@@ -2055,13 +2106,13 @@ func (s *server) listObjects(schema string, constraints metadataListConstraints)rawTypeOwner = schema}query := oracleListObjectsQueryWithTypeOwner(schema, rawTypeOwner, constraints)- useSessionUser := rawTypeOwner == schema && s.metadataSchemaIsSessionUser(schema, constraints.ExactIdentity)+ useSessionUser := !constraints.Exact && rawTypeOwner == schema && s.metadataSchemaIsSessionUser(schema, constraints.ExactIdentity)if useSessionUser {query = oracleListSessionUserObjectsQuery(constraints)}rows, err := s.queryRows(query.SQL, query.Args)if err != nil {- if isOraclePGALimitError(err) && !constraints.ExactIdentity && !metadataIncludesIndexes(constraints.ObjectTypes) {+ if isOraclePGALimitError(err) && !constraints.Exact && !constraints.ExactIdentity && !metadataIncludesIndexes(constraints.ObjectTypes) {return []objectInfo{}, nil}return nil, err@@ -2079,7 +2130,14 @@ func (s *server) listObjects(schema string, constraints metadataListConstraints)}result = append(result, item)}- return emptyIfNil(result), rows.Err()+ if err := rows.Err(); err != nil {+ return nil, err+ }+ s.closeRows(rows)+ if constraints.Exact {+ s.enrichExactTriggerObjects(result, schema)+ }+ return emptyIfNil(result), nil}func metadataIncludesIndexes(objectTypes []string) bool {@@ -5989,10 +6047,6 @@ func boolParam(params map[string]json.RawMessage, key string) bool {return value}-func errorResponse(id json.RawMessage, err error) response {- return response{JSONRPC: "2.0", ID: id, Error: &rpcError{Code: -1, Message: err.Error()}}-}-func parseURLParams(raw string) map[string]string {result := map[string]string{}values, err := url.ParseQuery(raw)diff --git a/agents/drivers/oracle-go/main_test.go b/agents/drivers/oracle-go/main_test.goindex b1d2ba601d..879bc03a83 100644--- a/agents/drivers/oracle-go/main_test.go+++ b/agents/drivers/oracle-go/main_test.go@@ -3870,6 +3870,7 @@ type oracleViewSourceQueryStep struct {nextPanicText stringcolumnsPanicText stringcolumnsPanicCall int+ nextError error}type oracleViewSourceDriver struct {@@ -3937,6 +3938,7 @@ func (c *oracleViewSourceConn) QueryContext(nextPanicText: step.nextPanicText,columnsPanicText: step.columnsPanicText,columnsPanicCall: step.columnsPanicCall,+ nextError: step.nextError,}, nil}@@ -3975,6 +3977,7 @@ type oracleViewSourceRows struct {columnsPanicText stringcolumnsPanicCall intcolumnsCalls int+ nextError error}func (r *oracleViewSourceRows) Columns() []string {@@ -3997,6 +4000,9 @@ func (r *oracleViewSourceRows) Next(dest []driver.Value) error {return r.nextErr}if r.next >= len(r.values) {+ if r.nextError != nil {+ return r.nextError+ }return io.EOF}copy(dest, r.values[r.next])diff --git a/agents/drivers/oracle-go/native_jobs.go b/agents/drivers/oracle-go/native_jobs.gonew file mode 100644index 0000000000..2f1a7960fd--- /dev/null+++ b/agents/drivers/oracle-go/native_jobs.go@@ -0,0 +1,228 @@+package main++import (+ "context"+ "database/sql"+ "database/sql/driver"+ "errors"+ "strconv"+ "strings"+ "time"++ go_ora "github.com/sijms/go-ora/v2"+)++type legacyJobPrepareRequest struct {+ OperationID string `json:"operationId"`+ What string `json:"what"`+ NextDate string `json:"nextDate"`+ Interval string `json:"interval"`+ Enabled bool `json:"enabled"`+ Instance int64 `json:"instance"`+ Schema string `json:"schema"`+ TimeoutSecs int `json:"timeoutSecs"`+}++type legacyJobResult struct {+ OperationID string `json:"operationId"`+ JobID string `json:"jobId,omitempty"`+ Phase string `json:"phase"`+ Reason string `json:"reason,omitempty"`+ VendorCode *int `json:"vendorCode,omitempty"`+}++// This is separate from the editor transaction and stays on one physical connection.+type legacyJobSession struct {+ request legacyJobPrepareRequest+ result legacyJobResult+ conn *sql.Conn+ tx *sql.Tx+}++func legacyJobNumericID(id string) bool {+ if id == "" || id[0] == '0' {+ return false+ }+ for _, b := range []byte(id) {+ if b < '0' || b > '9' {+ return false+ }+ }+ return true+}++func (job *legacyJobSession) discardConnection() {+ if job.conn != nil {+ // Raw's ErrBadConn discards this connection; it does not replay a statement.+ _ = job.conn.Raw(func(any) error { return driver.ErrBadConn })+ _ = job.conn.Close()+ job.conn = nil+ }+}++func (job *legacyJobSession) rollback(reason string, cause error) legacyJobResult {+ job.result.Reason = reason+ job.result.VendorCode = oracleVendorCode(cause)+ if job.tx == nil {+ job.discardConnection()+ return job.result+ }+ err := job.tx.Rollback()+ job.tx = nil+ if err == nil {+ job.result.Phase = "rolled_back"+ } else {+ job.result.Phase = "unknown"+ job.result.Reason = "native_job_rollback_unknown"+ if code := oracleVendorCode(err); code != nil {+ job.result.VendorCode = code+ }+ }+ job.discardConnection()+ return job.result+}++func (s *server) prepareLegacyJob(request legacyJobPrepareRequest) legacyJobResult {+ if s.legacyJob != nil {+ if s.legacyJob.request != request {+ return legacyJobResult{OperationID: request.OperationID, Phase: "unknown", Reason: "native_job_operation_mismatch"}+ }+ return s.legacyJob.result+ }+ invalid := func(reason string) legacyJobResult {+ return legacyJobResult{OperationID: request.OperationID, Phase: "not_started", Reason: reason}+ }+ if request.OperationID == "" || len(request.OperationID) > 128 || strings.ContainsRune(request.OperationID, '\x00') || request.Instance < 0 || request.TimeoutSecs < 0 || strings.ContainsRune(request.Schema, '\x00') {+ return invalid("native_job_request_invalid")+ }+ if _, err := time.Parse("2006-01-02 15:04:05", request.NextDate); err != nil {+ return invalid("native_job_date_invalid")+ }+ if strings.TrimSpace(request.What) == "" {+ return invalid("native_job_action_required")+ }+ db, err := s.requireDB()+ if err != nil {+ return invalid("native_job_connection_missing")+ }+ job := &legacyJobSession{request: request, result: legacyJobResult{OperationID: request.OperationID, Phase: "not_started"}}+ s.legacyJob = job+ ctx := context.Background()+ var cancel context.CancelFunc+ if request.TimeoutSecs > 0 {+ ctx, cancel = context.WithTimeout(ctx, time.Duration(request.TimeoutSecs)*time.Second)+ defer cancel()+ }+ job.conn, err = db.Conn(ctx)+ if err != nil {+ job.result.Reason = "native_job_session_open_failed"+ job.result.VendorCode = oracleVendorCode(err)+ return job.result+ }+ if request.Schema != "" {+ if _, err = job.conn.ExecContext(ctx, "ALTER SESSION SET CURRENT_SCHEMA = "+quoteIdentifier(request.Schema)); err != nil {+ job.result.Reason = "native_job_schema_not_selected"+ job.result.VendorCode = oracleVendorCode(err)+ job.discardConnection()+ return job.result+ }+ }+ // A statement deadline must not become the transaction lifetime: preparation+ // returns before Core records the OUT ID and authorizes the first commit.+ job.tx, err = job.conn.BeginTx(context.Background(), nil)+ if err != nil {+ job.result.Reason = "native_job_transaction_not_started"+ job.result.VendorCode = oracleVendorCode(err)+ job.discardConnection()+ return job.result+ }+ job.result.Phase = "submitting"+ var id string+ var out any = go_ora.Out{Dest: &id, Size: 64}+ if usesOCIProfile(s.params) {+ out = sql.Out{Dest: &id}+ }+ _, err = job.tx.ExecContext(ctx, `DECLARE native_id BINARY_INTEGER;+BEGIN+ SYS.DBMS_JOB.SUBMIT(job => native_id, what => :what, next_date => TO_DATE(:next_date, 'YYYY-MM-DD HH24:MI:SS'), interval => :repeat_interval, no_parse => FALSE, instance => :instance, force => FALSE);+ :job_id := TO_CHAR(native_id);+END;`, sql.Named("what", request.What), sql.Named("next_date", request.NextDate), sql.Named("repeat_interval", request.Interval), sql.Named("instance", request.Instance), sql.Named("job_id", out))+ if legacyJobNumericID(id) {+ job.result.JobID = id+ }+ if err != nil {+ return job.rollback("native_job_submit_failed", err)+ }+ if job.result.JobID == "" {+ return job.rollback("native_job_out_id_unverified", nil)+ }+ broken := 0+ if !request.Enabled {+ broken = 1+ }+ job.result.Phase = "configuring"+ _, err = job.tx.ExecContext(ctx, `BEGIN SYS.DBMS_JOB.BROKEN(TO_NUMBER(:job_id), :broken = 1, TO_DATE(:next_date, 'YYYY-MM-DD HH24:MI:SS')); END;`, sql.Named("job_id", id), sql.Named("broken", broken), sql.Named("next_date", request.NextDate))+ if err != nil {+ return job.rollback("native_job_initial_state_failed", err)+ }+ var gotID, what, nextDate, brokenFlag, instance, logUser, privUser, schemaUser string+ var interval sql.NullString+ err = job.tx.QueryRowContext(ctx, `SELECT TO_CHAR(JOB), WHAT, TO_CHAR(NEXT_DATE, 'YYYY-MM-DD HH24:MI:SS'), INTERVAL, BROKEN, TO_CHAR(INSTANCE), LOG_USER, PRIV_USER, SCHEMA_USER FROM SYS.USER_JOBS WHERE JOB = TO_NUMBER(:job_id)`, sql.Named("job_id", id)).Scan(&gotID, &what, &nextDate, &interval, &brokenFlag, &instance, &logUser, &privUser, &schemaUser)+ if err != nil {+ return job.rollback("native_job_initial_read_failed", err)+ }+ expectedBroken := "N"+ if !request.Enabled {+ expectedBroken = "Y"+ }+ if gotID != id || what != request.What || nextDate != request.NextDate || interval.String != request.Interval || brokenFlag != expectedBroken || instance != strconv.FormatInt(request.Instance, 10) || (request.Schema != "" && schemaUser != request.Schema) {+ return job.rollback("native_job_initial_state_unverified", nil)+ }+ job.result.Phase = "prepared"+ return job.result+}++func (s *server) finishLegacyJob(operationID, jobID string, commit bool) legacyJobResult {+ job := s.legacyJob+ if job == nil || job.result.OperationID != operationID {+ return legacyJobResult{OperationID: operationID, Phase: "unknown", Reason: "native_job_session_unavailable"}+ }+ if job.result.Phase != "prepared" {+ return job.result+ }+ if (commit || jobID != "") && (jobID != job.result.JobID || !legacyJobNumericID(jobID)) {+ return legacyJobResult{OperationID: operationID, Phase: "unknown", Reason: "native_job_identity_mismatch"}+ }+ if !commit {+ return job.rollback("native_job_canceled_before_commit", nil)+ }+ job.result.Phase = "commit_sent"+ err := job.tx.Commit()+ job.tx = nil+ if err != nil {+ job.result.Phase = "unknown"+ job.result.Reason = "native_job_commit_unknown"+ job.result.VendorCode = oracleVendorCode(err)+ } else {+ job.result.Phase = "committed"+ }+ job.discardConnection()+ return job.result+}++func (s *server) legacyJobStatus(operationID string) legacyJobResult {+ if s.legacyJob == nil || s.legacyJob.result.OperationID != operationID {+ return legacyJobResult{OperationID: operationID, Phase: "unknown", Reason: "native_job_session_unavailable"}+ }+ return s.legacyJob.result+}++func (s *server) closeLegacyJob() error {+ if s.legacyJob != nil && s.legacyJob.tx != nil {+ result := s.legacyJob.rollback("native_job_session_closed_before_commit", nil)+ if result.Phase != "rolled_back" {+ return errors.New("native_job_rollback_unknown")+ }+ }+ return nil+}diff --git a/agents/drivers/oracle-go/native_jobs_test.go b/agents/drivers/oracle-go/native_jobs_test.gonew file mode 100644index 0000000000..fd8ddce557--- /dev/null+++ b/agents/drivers/oracle-go/native_jobs_test.go@@ -0,0 +1,335 @@+package main++import (+ "context"+ "database/sql"+ "database/sql/driver"+ "encoding/json"+ "errors"+ "fmt"+ "strings"+ "testing"++ go_ora "github.com/sijms/go-ora/v2"+ "github.com/sijms/go-ora/v2/network"+)++type legacyJobTestDriver struct {+ nativeError error+ events []string+ opens, commits, rollbacks, closed int+ id string+ fail string+ commitError, rollbackError bool+ what, nextDate, interval, instance, broken string+}++func (d *legacyJobTestDriver) Open(string) (driver.Conn, error) {+ d.opens+++ return &legacyJobTestConn{d: d, id: d.opens}, nil+}++type legacyJobTestConn struct {+ d *legacyJobTestDriver+ id int+}++func (*legacyJobTestConn) Prepare(string) (driver.Stmt, error) {+ return nil, errors.New("context APIs required")+}+func (c *legacyJobTestConn) Close() error { c.d.closed++; return nil }+func (c *legacyJobTestConn) Begin() (driver.Tx, error) {+ return c.BeginTx(context.Background(), driver.TxOptions{})+}+func (c *legacyJobTestConn) BeginTx(context.Context, driver.TxOptions) (driver.Tx, error) {+ c.d.events = append(c.d.events, fmt.Sprintf("%d:begin", c.id))+ return &legacyJobTestTx{c}, nil+}+func (*legacyJobTestConn) CheckNamedValue(*driver.NamedValue) error { return nil }+func (c *legacyJobTestConn) ExecContext(_ context.Context, query string, args []driver.NamedValue) (driver.Result, error) {+ stage := "schema"+ if strings.Contains(query, "DBMS_JOB.SUBMIT") {+ stage = "submit"+ }+ if strings.Contains(query, "DBMS_JOB.BROKEN") {+ stage = "broken"+ }+ c.d.events = append(c.d.events, fmt.Sprintf("%d:%s", c.id, stage))+ if c.d.fail == stage {+ if c.d.nativeError != nil {+ return nil, c.d.nativeError+ }+ return nil, errors.New("native body/argument must not escape in diagnostics")+ }+ if stage == "submit" {+ if strings.Contains(query, "private") {+ return nil, errors.New("body interpolated instead of bound")+ }+ for _, arg := range args {+ switch arg.Name {+ case "what":+ c.d.what = arg.Value.(string)+ case "next_date":+ c.d.nextDate = arg.Value.(string)+ case "repeat_interval":+ c.d.interval = arg.Value.(string)+ case "instance":+ c.d.instance = fmt.Sprint(arg.Value)+ }+ switch out := arg.Value.(type) {+ case sql.Out:+ *out.Dest.(*string) = c.d.id+ case go_ora.Out:+ *out.Dest.(*string) = c.d.id+ }+ }+ }+ if stage == "broken" {+ for _, arg := range args {+ if arg.Name == "broken" {+ c.d.broken = "N"+ if fmt.Sprint(arg.Value) == "1" {+ c.d.broken = "Y"+ }+ }+ }+ }+ return driver.RowsAffected(1), nil+}+func (c *legacyJobTestConn) QueryContext(_ context.Context, query string, _ []driver.NamedValue) (driver.Rows, error) {+ c.d.events = append(c.d.events, fmt.Sprintf("%d:read", c.id))+ if c.d.fail == "read" {+ return nil, errors.New("read failed with sensitive body")+ }+ if c.d.fail == "mismatch" {+ c.d.what += "changed"+ }+ return &oracleManualTxRows{columns: []string{"JOB", "WHAT", "NEXT_DATE", "INTERVAL", "BROKEN", "INSTANCE", "LOG_USER", "PRIV_USER", "SCHEMA_USER"}, values: [][]driver.Value{{c.d.id, c.d.what, c.d.nextDate, c.d.interval, c.d.broken, c.d.instance, "Owner", "Owner", "Owner"}}}, nil+}++type legacyJobTestTx struct{ c *legacyJobTestConn }++func (t *legacyJobTestTx) Commit() error {+ t.c.d.commits+++ t.c.d.events = append(t.c.d.events, fmt.Sprintf("%d:commit", t.c.id))+ if t.c.d.commitError {+ return errors.New("commit acknowledgement lost")+ }+ return nil+}+func (t *legacyJobTestTx) Rollback() error {+ t.c.d.rollbacks+++ t.c.d.events = append(t.c.d.events, fmt.Sprintf("%d:rollback", t.c.id))+ if t.c.d.rollbackError {+ return errors.New("rollback acknowledgement lost")+ }+ return nil+}+func legacyJobServer(t *testing.T) (*server, *legacyJobTestDriver) {+ t.Helper()+ d := &legacyJobTestDriver{id: "9007199254740993"}+ db := sql.OpenDB(legacyJobTestConnector{d})+ db.SetMaxOpenConns(4)+ s := newServer()+ s.db = db+ t.Cleanup(func() { _ = s.disconnect() })+ return s, d+}++type legacyJobTestConnector struct{ d *legacyJobTestDriver }++func (c legacyJobTestConnector) Driver() driver.Driver { return c.d }+func (c legacyJobTestConnector) Connect(context.Context) (driver.Conn, error) { return c.d.Open("") }++const legacyJobPrepareParams = `{"operationId":"operation-a","what":"BEGIN p('private'); END;","nextDate":"2030-01-02 03:04:05","interval":"SYSDATE+1","enabled":false,"instance":0,"timeoutSecs":1}`++func legacyJobRPC(t *testing.T, s *server, method, params string) map[string]any {+ t.Helper()+ response, _ := s.handleLine(`{"jsonrpc":"2.0","id":1,"method":"` + method + `","params":` + params + `}`)+ if response.Error != nil {+ t.Fatalf("%s RPC rejected: %v", method, response.Error)+ }+ wire, err := json.Marshal(response.Result)+ if err != nil {+ t.Fatal(err)+ }+ if strings.Contains(string(wire), "private") || strings.Contains(string(wire), "sensitive") {+ t.Fatal("job inputs escaped through operation diagnostics")+ }+ var result map[string]any+ if err = json.Unmarshal(wire, &result); err != nil {+ t.Fatal(err)+ }+ return result+}+func TestLegacyJobRPCPinsOnePhysicalTransactionBeforeFirstCommit(t *testing.T) {+ for _, profile := range []string{"thin", "oci"} {+ t.Run(profile, func(t *testing.T) {+ s, d := legacyJobServer(t)+ s.params.DriverProfile = profile+ prepared := legacyJobRPC(t, s, "prepare_legacy_job", legacyJobPrepareParams)+ if prepared["phase"] != "prepared" || prepared["jobId"] != d.id {+ t.Fatalf("unexpected preparation: %v", prepared)+ }+ if got := strings.Join(d.events, ","); got != "1:begin,1:submit,1:broken,1:read" {+ t.Fatalf("unsafe initial sequence: %s", got)+ }+ if d.commits != 0 || d.closed != 0 {+ t.Fatal("prepared job was committed or its physical session was released")+ }+ legacyJobRPC(t, s, "prepare_legacy_job", legacyJobPrepareParams)+ if len(d.events) != 4 {+ t.Fatal("duplicate prepare resubmitted the job")+ }+ params := `{"operationId":"operation-a","jobId":"` + d.id + `"}`+ if legacyJobRPC(t, s, "commit_legacy_job", params)["phase"] != "committed" {+ t.Fatal("commit not confirmed")+ }+ legacyJobRPC(t, s, "commit_legacy_job", params)+ if d.commits != 1 || d.closed != 1 {+ t.Fatalf("commit replay or unreleased connection: %v", d.events)+ }+ })+ }+}+func TestLegacyJobRPCUnknownIDCannotCommitAndDoesNotGuessFromTheCatalog(t *testing.T) {+ s, d := legacyJobServer(t)+ d.id = ""+ result := legacyJobRPC(t, s, "prepare_legacy_job", legacyJobPrepareParams)+ if result["phase"] != "rolled_back" || d.commits != 0 || d.rollbacks != 1 {+ t.Fatalf("unsafe unknown ID: %v / %v", result, d.events)+ }+ if got := strings.Join(d.events, ","); got != "1:begin,1:submit,1:rollback" {+ t.Fatalf("guessed or configured an unknown ID: %s", got)+ }+ legacyJobRPC(t, s, "commit_legacy_job", `{"operationId":"operation-a","jobId":"41"}`)+ if d.commits != 0 {+ t.Fatal("committed after missing OUT ID")+ }+}++func TestLegacyJobRPCEnabledCreationStillAppliesTheChosenStateBeforeTheFirstCommit(t *testing.T) {+ s, d := legacyJobServer(t)+ params := strings.Replace(legacyJobPrepareParams, `"enabled":false`, `"enabled":true`, 1)+ result := legacyJobRPC(t, s, "prepare_legacy_job", params)+ if result["phase"] != "prepared" || d.broken != "N" || d.commits != 0 {+ t.Fatalf("initial enabled state was not prepared atomically: %v / %v", result, d.events)+ }+ found := false+ for _, capability := range legacyJobRPC(t, s, "handshake", `{}`)["capabilities"].([]any) {+ if capability == "native_job_legacy_v1" {+ found = true+ }+ }+ if !found {+ t.Fatal("legacy session protocol capability missing")+ }+}+func TestLegacyJobRPCBeforeCommitFailuresRollbackAndCleanupNeverActivates(t *testing.T) {+ for _, stage := range []string{"submit", "broken", "read", "mismatch"} {+ t.Run(stage, func(t *testing.T) {+ s, d := legacyJobServer(t)+ d.fail = stage+ result := legacyJobRPC(t, s, "prepare_legacy_job", legacyJobPrepareParams)+ if result["phase"] != "rolled_back" || d.commits != 0 || d.rollbacks != 1 || d.closed != 1 {+ t.Fatalf("unsafe failure cleanup: %v / %v", result, d.events)+ }+ })+ }+}++type legacyJobCodedError struct{}++func (legacyJobCodedError) Error() string { return "private native input" }+func (legacyJobCodedError) Code() int { return 27486 }++func TestLegacyJobRPCPreservesTypedNativeCodesWithoutReturningTheNativeMessage(t *testing.T) {+ for _, cause := range []error{network.NewOracleError(27486), legacyJobCodedError{}} {+ s, d := legacyJobServer(t)+ d.fail = "submit"+ d.nativeError = cause+ result := legacyJobRPC(t, s, "prepare_legacy_job", legacyJobPrepareParams)+ if result["vendorCode"] != float64(27486) || result["phase"] != "rolled_back" {+ t.Fatalf("typed diagnostic lost: %v", result)+ }+ }+}++func TestLegacyJobRPCInvalidPreparationIsRejectedBeforeOpeningItsTransaction(t *testing.T) {+ for _, params := range []string{strings.Replace(legacyJobPrepareParams, "2030-01-02 03:04:05", "SYSDATE", 1), strings.Replace(legacyJobPrepareParams, `"instance":0`, `"instance":-1`, 1)} {+ s, d := legacyJobServer(t)+ if legacyJobRPC(t, s, "prepare_legacy_job", params)["phase"] != "not_started" || len(d.events) != 0 {+ t.Fatal("invalid preparation reached the database")+ }+ }+}++func TestLegacyJobRPCCommitLostResponseIsUnknownAndNeverReplayed(t *testing.T) {+ s, d := legacyJobServer(t)+ legacyJobRPC(t, s, "prepare_legacy_job", legacyJobPrepareParams)+ d.commitError = true+ params := `{"operationId":"operation-a","jobId":"` + d.id + `"}`+ result := legacyJobRPC(t, s, "commit_legacy_job", params)+ if result["phase"] != "unknown" || result["jobId"] != d.id {+ t.Fatalf("lost commit was not preserved: %v", result)+ }+ legacyJobRPC(t, s, "commit_legacy_job", params)+ legacyJobRPC(t, s, "rollback_legacy_job", params)+ if d.commits != 1 || d.rollbacks != 0 || d.closed != 1 {+ t.Fatalf("commit/rollback was replayed after uncertainty: %v", d.events)+ }+}+func TestLegacyJobRPCCancelRollsBackItsOwnConnectionNotTheEditorTransaction(t *testing.T) {+ s, d := legacyJobServer(t)+ if err := s.beginManualTransaction(""); err != nil {+ t.Fatal(err)+ }+ legacyJobRPC(t, s, "prepare_legacy_job", legacyJobPrepareParams)+ result := legacyJobRPC(t, s, "rollback_legacy_job", `{"operationId":"operation-a","jobId":"`+d.id+`"}`)+ if result["phase"] != "rolled_back" || !s.hasManualTransaction() {+ t.Fatalf("cancel touched editor transaction: %v", result)+ }+ if got := strings.Join(d.events, ","); got != "1:begin,2:begin,2:submit,2:broken,2:read,2:rollback" {+ t.Fatalf("physical sessions were mixed: %s", got)+ }+}+func TestLegacyJobRPCFailedRollbackIsUnknownAndTheConnectionIsDiscarded(t *testing.T) {+ s, d := legacyJobServer(t)+ legacyJobRPC(t, s, "prepare_legacy_job", legacyJobPrepareParams)+ d.rollbackError = true+ result := legacyJobRPC(t, s, "rollback_legacy_job", `{"operationId":"operation-a","jobId":"`+d.id+`"}`)+ if result["phase"] != "unknown" || d.closed != 1 || d.commits != 0 {+ t.Fatalf("unconfirmed rollback was reported as safe: %v / %v", result, d.events)+ }+}++func TestLegacyJobRPCALostPrepareResponseCanRollbackByItsOwnedOperationWithoutGuessingAnID(t *testing.T) {+ s, d := legacyJobServer(t)+ legacyJobRPC(t, s, "prepare_legacy_job", legacyJobPrepareParams)+ if legacyJobRPC(t, s, "commit_legacy_job", `{"operationId":"operation-a"}`)["phase"] != "unknown" || d.commits != 0 {+ t.Fatal("a missing OUT ID authorized a commit")+ }+ result := legacyJobRPC(t, s, "rollback_legacy_job", `{"operationId":"operation-a"}`)+ if result["phase"] != "rolled_back" || d.rollbacks != 1 || d.commits != 0 {+ t.Fatalf("lost OUT response prevented rollback of the owned transaction: %v / %v", result, d.events)+ }+}+func TestLegacyJobRPCMismatchedOperationCannotCommitOrReplaceThePreparedJob(t *testing.T) {+ s, d := legacyJobServer(t)+ legacyJobRPC(t, s, "prepare_legacy_job", legacyJobPrepareParams)+ result := legacyJobRPC(t, s, "commit_legacy_job", `{"operationId":"different-operation","jobId":"`+d.id+`"}`)+ if result["phase"] != "unknown" || d.commits != 0 {+ t.Fatal("foreign operation committed a prepared job")+ }+ changed := strings.Replace(legacyJobPrepareParams, "SYSDATE+1", "SYSDATE+7", 1)+ result = legacyJobRPC(t, s, "prepare_legacy_job", changed)+ if result["reason"] != "native_job_operation_mismatch" || d.commits != 0 || d.opens != 1 {+ t.Fatal("immutable preparation was replaced")+ }+ if err := s.disconnect(); err != nil {+ t.Fatal(err)+ }+ if d.commits != 0 || d.rollbacks != 1 || d.closed != 1 {+ t.Fatalf("disconnect activated or leaked a job: %v", d.events)+ }+}diff --git a/agents/drivers/oracle-go/rpc_errors.go b/agents/drivers/oracle-go/rpc_errors.gonew file mode 100644index 0000000000..56985f1bfc--- /dev/null+++ b/agents/drivers/oracle-go/rpc_errors.go@@ -0,0 +1,96 @@+package main++import (+ "context"+ "database/sql"+ "database/sql/driver"+ "encoding/json"+ "errors"+ "fmt"+ "io"+ "net"++ "github.com/sijms/go-ora/v2/network"+)++// The shared structured_error_v1 contract, also consumed by ordinary query callers.+type rpcErrorData struct {+ ContractVersion int `json:"contractVersion"`+ Category string `json:"category"`+ Retryable bool `json:"retryable"`+ SessionDisposition string `json:"sessionDisposition"`+ Stage string `json:"stage"`+ OperationOutcome string `json:"operationOutcome"`+ VendorCode *int `json:"vendorCode,omitempty"`+ ExceptionClass string `json:"exceptionClass,omitempty"`+ AgentSessionID string `json:"agentSessionId,omitempty"`+}++func oracleVendorCode(err error) *int {+ var thin *network.OracleError+ if errors.As(err, &thin) {+ code := thin.ErrCode+ return &code+ }+ var coded interface{ Code() int }+ if errors.As(err, &coded) {+ code := coded.Code()+ return &code+ }+ return nil+}++func oracleRPCStage(method string) string {+ switch method {+ case "", "handshake":+ return "request"+ case "connect", "open_session", "test_connection":+ return "connect"+ case "validate_connection", "validate_session":+ return "validate"+ case "cancel_session":+ return "cancel"+ case "close_session", "disconnect", "shutdown", "close_query_session", "close_table_read_session":+ return "close"+ case "fetch_query_page", "fetch_table_read_page":+ return "fetch"+ default:+ return "execute"+ }+}++func oracleConnectionCode(code int) bool {+ switch code {+ case 28, 1012, 3113, 3114, 3135:+ return true+ default:+ return code >= 12500 && code <= 12699+ }+}++func errorResponse(id json.RawMessage, err error, method, sessionID string) response {+ stage := oracleRPCStage(method)+ data := &rpcErrorData{ContractVersion: 1, Category: "protocol", SessionDisposition: "keep", Stage: stage,+ OperationOutcome: "unknown", VendorCode: oracleVendorCode(err), ExceptionClass: fmt.Sprintf("%T", err), AgentSessionID: sessionID}+ if stage == "request" || stage == "connect" || stage == "validate" {+ data.OperationOutcome = "not_started"+ }+ var netError net.Error+ switch {+ case errors.Is(err, context.Canceled) || data.VendorCode != nil && *data.VendorCode == 1013:+ data.Category, data.SessionDisposition = "canceled", "quarantine"+ case errors.Is(err, context.DeadlineExceeded) || errors.As(err, &netError) && netError.Timeout():+ data.Category, data.SessionDisposition = "timeout", "quarantine"+ case errors.Is(err, driver.ErrBadConn) || errors.Is(err, sql.ErrConnDone) || errors.Is(err, net.ErrClosed) ||+ errors.Is(err, io.EOF) || errors.Is(err, io.ErrUnexpectedEOF) || errors.As(err, &netError) ||+ data.VendorCode != nil && (oracleConnectionCode(*data.VendorCode) || stage == "connect" || stage == "validate"):+ data.Category = "connection"+ if stage != "connect" {+ data.SessionDisposition = "quarantine"+ }+ data.Retryable = stage == "connect" || stage == "validate"+ case data.VendorCode != nil && stage != "request":+ data.Category = "sql"+ }+ return response{JSONRPC: "2.0", ID: id, Error: &rpcError{Code: -1, Message: err.Error(), Data: data}}+}diff --git a/agents/drivers/oracle-go/rpc_errors_test.go b/agents/drivers/oracle-go/rpc_errors_test.gonew file mode 100644index 0000000000..d2d94e59b7--- /dev/null+++ b/agents/drivers/oracle-go/rpc_errors_test.go@@ -0,0 +1,125 @@+package main++import (+ "context"+ "database/sql/driver"+ "encoding/json"+ "errors"+ "fmt"+ "net"+ "strings"+ "testing"++ "github.com/sijms/go-ora/v2/network"+)++type oracleRPCCodedError int++func (e oracleRPCCodedError) Error() string { return "native diagnostic without a number or SQL text" }+func (e oracleRPCCodedError) Code() int { return int(e) }++func rpcDiagnostics(t *testing.T, resp response) map[string]any {+ t.Helper()+ encoded, err := json.Marshal(resp)+ if err != nil {+ t.Fatal(err)+ }+ var decoded map[string]any+ if err = json.Unmarshal(encoded, &decoded); err != nil {+ t.Fatal(err)+ }+ rpc, ok := decoded["error"].(map[string]any)+ if !ok {+ t.Fatal("expected RPC failure")+ }+ data, ok := rpc["data"].(map[string]any)+ if !ok {+ t.Fatal("native diagnostic is lost at the real RPC boundary")+ }+ if data["contractVersion"] != float64(1) {+ t.Fatalf("wrong diagnostic contract: %v", data)+ }+ return data+}++func TestQueryRPCPreservesTypedOracleCodesWithoutParsingTheMessage(t *testing.T) {+ for _, cause := range []error{network.NewOracleError(942), oracleRPCCodedError(1031), fmt.Errorf("wrapped: %w", oracleRPCCodedError(1422))} {+ t.Run(fmt.Sprintf("%T", cause), func(t *testing.T) {+ db, scripted := openOracleViewSourceTestDB(t, []oracleViewSourceQueryStep{+ {queryContains: "DBA_JOBS", args: []driver.Value{}, err: cause},+ {queryContains: "USER_JOBS", args: []driver.Value{}, columns: []string{"JOB"}, rows: [][]driver.Value{{"41"}}},+ })+ s := newServer()+ s.db = db+ runtime := newRuntimeServer()+ runtime.sessions["job-metadata"] = &agentSession{server: s}+ resp, shutdown := runtime.handleLine(`{"id":1,"method":"execute_query","params":{"agentSessionId":"job-metadata","sql":"SELECT JOB FROM DBA_JOBS"}}`)+ if shutdown || resp.Error == nil {+ t.Fatal("catalog failure must not shut down or become a successful empty result")+ }+ data := rpcDiagnostics(t, resp)+ want := map[string]any{"category": "sql", "retryable": false, "sessionDisposition": "keep", "stage": "execute", "operationOutcome": "unknown", "agentSessionId": "job-metadata"}+ for key, value := range want {+ if data[key] != value {+ t.Errorf("%s: got %v, want %v", key, data[key], value)+ }+ }+ if data["vendorCode"] != float64(*oracleVendorCode(cause)) {+ t.Errorf("native code lost: %v", data)+ }+ followUp, _ := runtime.handleLine(`{"id":2,"method":"execute_query","params":{"agentSessionId":"job-metadata","sql":"SELECT JOB FROM USER_JOBS"}}`)+ if followUp.Error != nil || scripted.next != 2 {+ t.Fatal("a dictionary visibility error must keep the same session usable")+ }+ })+ }+}++func TestRPCDoesNotInferNativeCodesFromErrorText(t *testing.T) {+ s := newServer()+ db, _ := openOracleViewSourceTestDB(t, []oracleViewSourceQueryStep{{queryContains: "DBA_JOBS", args: []driver.Value{}, err: errors.New("ORA-00942 is only untrusted text")}})+ s.db = db+ resp, _ := s.handleLine(`{"id":1,"method":"execute_query","params":{"sql":"SELECT JOB FROM DBA_JOBS"}}`)+ data := rpcDiagnostics(t, resp)+ if _, exists := data["vendorCode"]; exists || data["category"] != "protocol" {+ t.Fatalf("uncoded failure must not authorize catalog fallback: %v", data)+ }+}++func TestRPCErrorContractPreservesStageAndNeverAuthorizesExecutionRetry(t *testing.T) {+ for _, scenario := range []struct {+ method, category, disposition, outcome string+ cause error+ }{+ {"open_session", "connection", "keep", "not_started", oracleRPCCodedError(1017)},+ {"validate_session", "connection", "quarantine", "not_started", net.ErrClosed},+ {"execute_query", "timeout", "quarantine", "unknown", context.DeadlineExceeded},+ {"execute_query", "canceled", "quarantine", "unknown", context.Canceled},+ {"commit_manual_transaction", "connection", "quarantine", "unknown", oracleRPCCodedError(3113)},+ {"fetch_query_page", "sql", "keep", "unknown", oracleRPCCodedError(942)},+ {"close_session", "protocol", "keep", "unknown", errors.New("close failure")},+ } {+ t.Run(scenario.method, func(t *testing.T) {+ data := rpcDiagnostics(t, errorResponse(json.RawMessage("1"), scenario.cause, scenario.method, "session"))+ if data["category"] != scenario.category || data["sessionDisposition"] != scenario.disposition || data["operationOutcome"] != scenario.outcome {+ t.Fatalf("incorrect recovery facts: %v", data)+ }+ if data["retryable"] == true && scenario.outcome != "not_started" {+ t.Fatal("a sent operation must never be labeled safe to retry")+ }+ })+ }+}++func TestRuntimeNegotiatesStructuredErrorsAndLegacyHandshakeStaysCompatible(t *testing.T) {+ legacy, _ := newServer().handleLine(`{"id":1,"method":"handshake","params":{}}`)+ runtime, _ := newRuntimeServer().handleLine(`{"id":1,"method":"handshake","params":{}}`)+ encodedLegacy, _ := json.Marshal(legacy.Result)+ encodedRuntime, _ := json.Marshal(runtime.Result)+ if strings.Contains(string(encodedLegacy), `"structured_error_v1"`) {+ t.Fatal("the legacy handshake must stay within its v1 capability contract")+ }+ if !strings.Contains(string(encodedRuntime), `"structured_error_v1"`) {+ t.Fatal("typed errors must be negotiated before the Core consumes their native codes")+ }+}diff --git a/agents/drivers/oracle-go/trigger_metadata.go b/agents/drivers/oracle-go/trigger_metadata.gonew file mode 100644index 0000000000..0fc158b080--- /dev/null+++ b/agents/drivers/oracle-go/trigger_metadata.go@@ -0,0 +1,423 @@+package main++import (+ "database/sql"+ "encoding/json"+ "errors"+ "fmt"+ "reflect"+ "regexp"+ "strings"+)++type oracleTriggerParent struct {+ Owner string `json:"owner"`+ Name string `json:"name"`+ ObjectType string `json:"objectType"`+ ObjectID *string `json:"objectId,omitempty"`+}++type oracleTriggerDefinition struct {+ Origin string `json:"origin"`+ Format string `json:"format"`+ Complete bool `json:"complete"`+}++type oracleTriggerCompilationError struct {+ Sequence int64 `json:"sequence"`+ Line int64 `json:"line"`+ Position int64 `json:"position"`+ Text string `json:"text"`+ Severity *string `json:"severity,omitempty"`+}++type oracleTriggerReadState struct {+ State string `json:"state"`+ Message string `json:"message,omitempty"`+}++type oracleTriggerMetadata struct {+ ContractVersion int `json:"contractVersion"`+ IdentityMode string `json:"identityMode"`+ Engine string `json:"engine"`+ EngineVersion *string `json:"engineVersion"`+ Owner string `json:"owner"`+ Name string `json:"name"`+ Scope string `json:"scope"`+ ScopeType *string `json:"scopeType,omitempty"`+ ScopeOwner *string `json:"scopeOwner"`+ Parent *oracleTriggerParent `json:"parent"`+ ObjectID *string `json:"objectId"`+ LastDDLTime *string `json:"lastDdlTime"`+ Definition *oracleTriggerDefinition `json:"definition"`+ Errors []oracleTriggerCompilationError `json:"errors"`+ Reads map[string]oracleTriggerReadState `json:"reads"`+ description string+ referencing string+}++func exactMetadataReadParam(params map[string]json.RawMessage) (bool, error) {+ var mode, alias *string+ if value, ok := params["identity_mode"]; ok {+ if err := json.Unmarshal(value, &mode); err != nil {+ return false, err+ }+ }+ if value, ok := params["identityMode"]; ok {+ if err := json.Unmarshal(value, &alias); err != nil {+ return false, err+ }+ }+ if mode != nil && alias != nil && *mode != *alias {+ return false, errors.New("conflicting metadata identity modes")+ }+ if mode == nil {+ mode = alias+ }+ if mode == nil {+ return false, nil+ }+ if *mode != "exact" {+ return false, errors.New("unsupported metadata identity mode")+ }+ return true, nil+}++func oracleTriggerAvailable() oracleTriggerReadState {+ return oracleTriggerReadState{State: "available"}+}+func oracleTriggerMissing(field string) oracleTriggerReadState {+ return oracleTriggerReadState{State: "unavailable", Message: field + " is not exposed by this dictionary"}+}++var oracleTriggerErrorCode = regexp.MustCompile(`ORA-[0-9]{5}`)++func oracleTriggerReadFailure(err error) oracleTriggerReadState {+ code := oracleTriggerErrorCode.FindString(err.Error())+ state := "error"+ switch code {+ case "ORA-01031":+ state = "denied"+ case "ORA-00942", "ORA-00904":+ state = "unavailable"+ }+ message := "Trigger metadata could not be read"+ if code != "" {+ message += " (" + code + ")"+ }+ return oracleTriggerReadState{State: state, Message: message}+}++func triggerText(value sql.NullString) *string {+ if !value.Valid {+ return nil+ }+ text := value.String+ return &text+}++func newOracleTriggerMetadata(owner, name string) *oracleTriggerMetadata {+ return &oracleTriggerMetadata{ContractVersion: 1, IdentityMode: "exact", Engine: "oracle", Owner: owner, Name: name,+ Scope: "UNKNOWN", Reads: make(map[string]oracleTriggerReadState)}+}++func oracleTriggerStatement(source, description, condition, referencing string) string {+ if oracleTriggerIsStructured(description, condition, referencing) {+ if body, ok := oracleTriggerBody(source, description); ok {+ return body+ }+ }+ return source+}++func (s *server) readExactTriggerRows(predicate string, args []any, includeSource bool) ([]triggerInfo, error) {+ projection := `t.OWNER, t.TRIGGER_NAME, t.TRIGGERING_EVENT, t.TRIGGER_TYPE, t.STATUS,+t.TABLE_OWNER, t.TABLE_NAME, t.BASE_OBJECT_TYPE, t.DESCRIPTION, t.WHEN_CLAUSE, t.REFERENCING_NAMES,+TO_CHAR(o.OBJECT_ID), TO_CHAR(o.LAST_DDL_TIME, 'YYYY-MM-DD HH24:MI:SS'), o.STATUS`+ join := ""+ if includeSource {+ projection += ", s.LINE, s.TEXT"+ join = " LEFT JOIN ALL_SOURCE s ON s.OWNER=t.OWNER AND s.NAME=t.TRIGGER_NAME AND s.TYPE='TRIGGER'"+ }+ query := "SELECT " + projection + " FROM ALL_TRIGGERS t LEFT JOIN ALL_OBJECTS o " ++ "ON o.OWNER=t.OWNER AND o.OBJECT_NAME=t.TRIGGER_NAME AND o.OBJECT_TYPE='TRIGGER'" + join ++ " WHERE " + predicate + " ORDER BY t.TRIGGER_NAME, t.OWNER"+ if includeSource {+ query += ", s.LINE"+ }+ rows, err := s.queryRows(query, args)+ if err != nil {+ return nil, err+ }+ defer s.closeRows(rows)+ result := []triggerInfo{}+ type identity struct{ owner, name string }+ type sourceGroup struct {+ index int+ description, condition, referencing string+ source strings.Builder+ lastLine int64+ }+ groups := map[identity]*sourceGroup{}+ for rows.Next() {+ var owner, name string+ var event, timing, status, parentOwner, parentName, scopeType, description, condition, referencing, objectID, ddlTime, validity sql.NullString+ var line sql.NullInt64+ var lineText sql.NullString+ values := []any{&owner, &name, &event, &timing, &status, &parentOwner, &parentName, &scopeType, &description,+ &condition, &referencing, &objectID, &ddlTime, &validity}+ if includeSource {+ values = append(values, &line, &lineText)+ }+ if err := rows.Scan(values...); err != nil {+ return nil, err+ }+ if owner == "" || name == "" {+ return nil, errors.New("trigger dictionary identity is incomplete")+ }+ key := identity{owner, name}+ group := groups[key]+ if group == nil {+ metadata := newOracleTriggerMetadata(owner, name)+ metadata.description, metadata.referencing = description.String, referencing.String+ metadata.ObjectID, metadata.LastDDLTime, metadata.ScopeType = triggerText(objectID), triggerText(ddlTime), triggerText(scopeType)+ if scopeType.Valid {+ switch strings.ToUpper(scopeType.String) {+ case "TABLE", "VIEW", "SCHEMA", "DATABASE", "TIMER":+ metadata.Scope = strings.ToUpper(scopeType.String)+ default:+ metadata.Scope = "OTHER"+ }+ }+ if (metadata.Scope == "TABLE" || metadata.Scope == "VIEW") && parentOwner.Valid && parentName.Valid {+ metadata.Parent = &oracleTriggerParent{Owner: parentOwner.String, Name: parentName.String, ObjectType: metadata.Scope}+ }+ if metadata.Scope == "SCHEMA" {+ metadata.ScopeOwner = triggerText(parentOwner)+ }+ trigger := triggerInfo{Name: name, Event: event.String, Timing: timing.String, Condition: triggerText(condition),+ Enabled: oracleTriggerEnabled(status), OracleMetadata: metadata}+ if validity.Valid && (strings.EqualFold(validity.String, "VALID") || strings.EqualFold(validity.String, "INVALID")) {+ valid := strings.EqualFold(validity.String, "VALID")+ trigger.Valid = &valid+ }+ metadata.Reads["identity"] = oracleTriggerAvailable()+ if metadata.ObjectID == nil {+ metadata.Reads["identity"] = oracleTriggerMissing("Object ID")+ }+ metadata.Reads["scope"] = oracleTriggerAvailable()+ if metadata.Scope == "UNKNOWN" {+ metadata.Reads["scope"] = oracleTriggerMissing("Trigger scope")+ }+ metadata.Reads["parent"] = oracleTriggerAvailable()+ if metadata.Scope == "UNKNOWN" || metadata.Scope == "OTHER" || (metadata.Scope == "TABLE" || metadata.Scope == "VIEW") && metadata.Parent == nil {+ metadata.Reads["parent"] = oracleTriggerMissing("Owning object")+ }+ if metadata.Scope == "SCHEMA" && metadata.ScopeOwner == nil {+ metadata.Reads["scope"] = oracleTriggerMissing("Scope owner")+ }+ metadata.Reads["enabled"] = oracleTriggerAvailable()+ if trigger.Enabled == nil {+ metadata.Reads["enabled"] = oracleTriggerMissing("Enabled state")+ }+ metadata.Reads["validity"] = oracleTriggerAvailable()+ if trigger.Valid == nil {+ metadata.Reads["validity"] = oracleTriggerMissing("Object validity")+ }+ group = &sourceGroup{index: len(result), description: description.String, condition: condition.String, referencing: referencing.String}+ groups[key] = group+ result = append(result, trigger)+ } else if !includeSource {+ return nil, errors.New("exact trigger identity is not unique")+ }+ if includeSource && line.Valid {+ if !lineText.Valid || line.Int64 != group.lastLine+1 {+ return nil, errors.New("trigger source rows are incomplete or duplicated")+ }+ group.source.WriteString(lineText.String)+ group.lastLine = line.Int64+ }+ }+ if err := rows.Err(); err != nil {+ return nil, err+ }+ if includeSource {+ for _, group := range groups {+ source := group.source.String()+ if source == "" {+ continue+ }+ source = oracleTriggerStatement(source, group.description, group.condition, group.referencing)+ result[group.index].Statement = &source+ }+ }+ return result, nil+}++func (s *server) listExactTriggers(parentOwner, parentName string) ([]triggerInfo, error) {+ if parentOwner == "" || parentName == "" {+ return nil, errors.New("exact trigger metadata requires a parent owner and name")+ }+ triggers, err := s.readExactTriggerRows("t.TABLE_OWNER=:1 AND t.TABLE_NAME=:2 AND t.BASE_OBJECT_TYPE IN ('TABLE','VIEW')", []any{parentOwner, parentName}, true)+ if err != nil {+ return nil, err+ }+ for _, trigger := range triggers {+ parent := trigger.OracleMetadata.Parent+ if parent == nil || parent.Owner != parentOwner || parent.Name != parentName {+ return nil, errors.New("owning object identity does not match the exact request")+ }+ }+ return triggers, nil+}++func (s *server) enrichExactTriggerObjects(objects []objectInfo, owner string) {+ indices := []int{}+ for index := range objects {+ if objects[index].ObjectType == "TRIGGER" {+ indices = append(indices, index)+ }+ }+ for start := 0; start < len(indices); start += 500 {+ end := start + 500+ if end > len(indices) {+ end = len(indices)+ }+ batch := indices[start:end]+ args := []any{owner}+ binds := []string{}+ for _, index := range batch {+ args = append(args, objects[index].Name)+ binds = append(binds, fmt.Sprintf(":%d", len(args)))+ }+ triggers, err := s.readExactTriggerRows("t.OWNER=:1 AND t.TRIGGER_NAME IN ("+strings.Join(binds, ",")+")", args, false)+ byName := map[string]triggerInfo{}+ for _, trigger := range triggers {+ if trigger.OracleMetadata.Owner == owner {+ byName[trigger.Name] = trigger+ }+ }+ for _, index := range batch {+ trigger, found := byName[objects[index].Name]+ if err != nil || !found {+ metadata := newOracleTriggerMetadata(owner, objects[index].Name)+ state := oracleTriggerReadState{State: "incomplete", Message: "Trigger changed or is no longer visible; reload"}+ if err != nil {+ state = oracleTriggerReadFailure(err)+ }+ for _, field := range []string{"identity", "scope", "parent", "enabled", "validity"} {+ metadata.Reads[field] = state+ }+ trigger = triggerInfo{Name: objects[index].Name, OracleMetadata: metadata}+ }+ objects[index].Trigger, objects[index].Valid = &trigger, trigger.Valid+ if parent := trigger.OracleMetadata.Parent; parent != nil {+ parentOwner, parentName := parent.Owner, parent.Name+ objects[index].ParentSchema, objects[index].ParentName = &parentOwner, &parentName+ }+ }+ }+}++func (s *server) getExactTriggerSource(owner, name string) (map[string]any, error) {+ if owner == "" || name == "" {+ return nil, errors.New("exact trigger metadata requires owner and name")+ }+ read := func() ([]triggerInfo, error) {+ return s.readExactTriggerRows("t.OWNER=:1 AND t.TRIGGER_NAME=:2", []any{owner, name}, false)+ }+ before, err := read()+ if err != nil {+ return nil, err+ }+ if len(before) == 0 {+ metadata := newOracleTriggerMetadata(owner, name)+ metadata.Reads["identity"] = oracleTriggerReadState{State: "empty", Message: "No visible trigger with this exact owner/name"}+ return map[string]any{"name": name, "object_type": "TRIGGER", "schema": owner, "source": "", "editable": false,+ "trigger": triggerInfo{Name: name, OracleMetadata: metadata}}, nil+ }+ if len(before) != 1 || before[0].OracleMetadata.Owner != owner || before[0].Name != name {+ return nil, errors.New("trigger identity does not match the exact request")+ }+ source, found, sourceErr := s.loadObjectSourceText(owner, name, "TRIGGER")+ origin, format := "ALL_SOURCE", "declaration"+ if sourceErr != nil || !found || source == "" {+ if ddl, ddlErr := s.exactTriggerDDL(owner, name); ddlErr == nil && ddl != "" {+ source, found, sourceErr, origin, format = ddl, true, nil, "DBMS_METADATA", "ddl"+ } else if sourceErr == nil {+ sourceErr = ddlErr+ }+ }+ compilationErrors, errorsErr := s.exactTriggerErrors(owner, name)+ after, err := read()+ if err != nil {+ return nil, err+ }+ stable := len(after) == 1 && reflect.DeepEqual(before[0], after[0])+ trigger := before[0]+ if len(after) == 1 {+ trigger = after[0]+ }+ metadata := trigger.OracleMetadata+ if origin == "ALL_SOURCE" && found && sourceErr == nil && source != "" {+ condition := ""+ if trigger.Condition != nil {+ condition = *trigger.Condition+ }+ statement := oracleTriggerStatement(source, metadata.description, condition, metadata.referencing)+ trigger.Statement = &statement+ }+ metadata.Definition = &oracleTriggerDefinition{Origin: origin, Format: format, Complete: stable && found && sourceErr == nil && source != ""}+ metadata.Reads["definition"] = oracleTriggerAvailable()+ if !metadata.Definition.Complete {+ metadata.Reads["definition"] = oracleTriggerMissing("Complete trigger definition")+ }+ if sourceErr != nil {+ metadata.Reads["definition"] = oracleTriggerReadFailure(sourceErr)+ }+ if !stable {+ state := oracleTriggerReadState{State: "incomplete", Message: "Trigger changed while loading; reload"}+ metadata.Reads["identity"], metadata.Reads["definition"] = state, state+ }+ metadata.Errors, metadata.Reads["errors"] = compilationErrors, oracleTriggerAvailable()+ if errorsErr != nil {+ metadata.Errors = nil+ metadata.Reads["errors"] = oracleTriggerReadFailure(errorsErr)+ }+ return map[string]any{"name": name, "object_type": "TRIGGER", "schema": owner, "source": source, "trigger": trigger}, nil+}++func (s *server) exactTriggerDDL(owner, name string) (string, error) {+ rows, err := s.queryRows("SELECT DBMS_METADATA.GET_DDL(:1, :2, :3) FROM DUAL", []any{"TRIGGER", name, owner})+ if err != nil {+ return "", err+ }+ defer s.closeRows(rows)+ if !rows.Next() {+ return "", rows.Err()+ }+ var source sql.NullString+ if err := rows.Scan(&source); err != nil {+ return "", err+ }+ return source.String, rows.Err()+}++func (s *server) exactTriggerErrors(owner, name string) ([]oracleTriggerCompilationError, error) {+ rows, err := s.queryRows("SELECT SEQUENCE, LINE, POSITION, TEXT, ATTRIBUTE FROM ALL_ERRORS WHERE OWNER=:1 AND NAME=:2 AND TYPE='TRIGGER' ORDER BY SEQUENCE", []any{owner, name})+ if err != nil {+ return nil, err+ }+ defer s.closeRows(rows)+ result := []oracleTriggerCompilationError{}+ for rows.Next() {+ var item oracleTriggerCompilationError+ var severity sql.NullString+ if err := rows.Scan(&item.Sequence, &item.Line, &item.Position, &item.Text, &severity); err != nil {+ return nil, err+ }+ item.Severity = triggerText(severity)+ result = append(result, item)+ }+ return result, rows.Err()+}diff --git a/agents/drivers/oracle-go/trigger_metadata_test.go b/agents/drivers/oracle-go/trigger_metadata_test.gonew file mode 100644index 0000000000..e43445bb6b--- /dev/null+++ b/agents/drivers/oracle-go/trigger_metadata_test.go@@ -0,0 +1,296 @@+package main++import (+ "database/sql/driver"+ "encoding/json"+ "errors"+ "strings"+ "testing"+)++var exactTriggerColumns = []string{"OWNER", "TRIGGER_NAME", "EVENT", "TIMING", "ENABLED", "PARENT_OWNER", "PARENT_NAME", "SCOPE", "DESCRIPTION", "CONDITION", "REFERENCING", "OBJECT_ID", "DDL_TIME", "VALIDITY"}++func exactTriggerRow(owner, name, id string) []driver.Value {+ return []driver.Value{owner, name, "INSERT", "INSTEAD OF", "DISABLED", " Parent Owner ", " View ", "VIEW", nil, nil, nil, id, "2026-10-21 08:00:00", "INVALID"}+}++func exactTriggerStep(owner, name, id string) oracleViewSourceQueryStep {+ return oracleViewSourceQueryStep{queryContains: "FROM ALL_TRIGGERS", args: []driver.Value{owner, name}, columns: exactTriggerColumns, rows: [][]driver.Value{exactTriggerRow(owner, name, id)}}+}++func exactTriggerParams(text string) map[string]json.RawMessage {+ var params map[string]json.RawMessage+ if err := json.Unmarshal([]byte(text), ¶ms); err != nil {+ panic(err)+ }+ return params+}++func TestExactTriggerSchemaRPCPreservesPagedIdentity(t *testing.T) {+ owner, name := " Owner ", " Trigger "+ metadata := exactTriggerStep(owner, name, "9007199254740993")+ db, scripted := openOracleViewSourceTestDB(t, []oracleViewSourceQueryStep{+ {queryContains: "'PACKAGE BODY', 'INDEX', 'TRIGGER'", args: []driver.Value{owner, owner, owner, owner, "%T%R%I%G%", "TRIGGER", int64(3), int64(2)},+ columns: []string{"OBJECT_NAME", "OBJECT_TYPE", "COMMENTS", "PARENT_SCHEMA", "PARENT_NAME"}, rows: [][]driver.Value{{name, "TRIGGER", nil, nil, nil}}},+ metadata,+ })+ s := newServer()+ s.db = db+ value, _, err := s.dispatch("list_objects", exactTriggerParams(`{"schema":" Owner ","object_types":["TRIGGER"],"filter":"trig","limit":1,"offset":2,"identity_mode":"exact"}`))+ if err != nil {+ t.Fatal(err)+ }+ objects := value.([]objectInfo)+ if len(objects) != 1 || objects[0].Name != name || objects[0].Trigger == nil {+ t.Fatalf("missing exact trigger: %#v", objects)+ }+ trigger := objects[0].Trigger+ if trigger.OracleMetadata.Owner != owner || trigger.OracleMetadata.Parent.Owner != " Parent Owner " {+ t.Fatalf("owners collapsed: %#v", trigger.OracleMetadata)+ }+ if trigger.Enabled == nil || *trigger.Enabled || trigger.Valid == nil || *trigger.Valid {+ t.Fatalf("independent states missing: %#v", trigger)+ }+ if *trigger.OracleMetadata.ObjectID != "9007199254740993" || trigger.Statement != nil {+ t.Fatalf("summary must retain ID without loading source: %#v", trigger)+ }+ if scripted.next != 2 {+ t.Fatalf("unexpected source or approximate lookup: %d", scripted.next)+ }+}++func TestExactTriggerParentRPCKeepsComplexDefinition(t *testing.T) {+ definition := "TRIGGER \" Trigger \" INSTEAD OF INSERT ON \" Parent Owner \".\" View \"\nREFERENCING NEW AS N OLD AS O\nFOR EACH ROW\nBEGIN NULL; END;"+ row := append(exactTriggerRow(" Owner ", " Trigger ", "42"), int64(1), definition)+ row[10] = "REFERENCING NEW AS N OLD AS O"+ db, _ := openOracleViewSourceTestDB(t, []oracleViewSourceQueryStep{{queryContains: "t.TABLE_OWNER=:1 AND t.TABLE_NAME=:2", args: []driver.Value{" Parent Owner ", " View "},+ columns: append(append([]string{}, exactTriggerColumns...), "LINE", "TEXT"), rows: [][]driver.Value{row}}})+ s := newServer()+ s.db = db+ value, _, err := s.dispatch("list_triggers", exactTriggerParams(`{"schema":" Parent Owner ","table":" View ","identity_mode":"exact"}`))+ if err != nil {+ t.Fatal(err)+ }+ trigger := value.([]triggerInfo)[0]+ if trigger.OracleMetadata.Owner != " Owner " || trigger.Statement == nil || *trigger.Statement != definition {+ t.Fatalf("complex source or independent owner lost: %#v", trigger)+ }+}++func TestExactTriggerSourceRPCReadsInvalidErrorsAndRetainsLongSource(t *testing.T) {+ owner, name := " Owner ", " Trigger "+ definition := "TRIGGER \" Trigger \" INSTEAD OF INSERT ON \" Parent Owner \".\" View \"\nBEGIN /* " + strings.Repeat("中文😀", 12_000) + " */ NULL; END;"+ db, _ := openOracleViewSourceTestDB(t, []oracleViewSourceQueryStep{+ exactTriggerStep(owner, name, "42"),+ {queryContains: "XMLAGG", args: []driver.Value{owner, name, "TRIGGER"}, rows: [][]driver.Value{{definition}}},+ {queryContains: "FROM ALL_ERRORS", args: []driver.Value{owner, name}, columns: []string{"SEQUENCE", "LINE", "POSITION", "TEXT", "ATTRIBUTE"}, rows: [][]driver.Value{{int64(1), int64(4), int64(7), "Missing procedure", "ERROR"}}},+ exactTriggerStep(owner, name, "42"),+ })+ s := newServer()+ s.db = db+ value, _, err := s.dispatch("get_object_source", exactTriggerParams(`{"schema":" Owner ","name":" Trigger ","object_type":"TRIGGER","identity_mode":"exact"}`))+ if err != nil {+ t.Fatal(err)+ }+ source := value.(map[string]any)+ trigger := source["trigger"].(triggerInfo)+ if source["source"] != definition || !trigger.OracleMetadata.Definition.Complete {+ t.Fatal("full source was lost or not verified")+ }+ if trigger.Valid == nil || *trigger.Valid || len(trigger.OracleMetadata.Errors) != 1 || trigger.OracleMetadata.Errors[0].Position != 7 {+ t.Fatalf("INVALID/errors lost: %#v", trigger)+ }+}++func TestExactTriggerListAndSourceUseTheSameStatement(t *testing.T) {+ owner, name := " Owner ", " Trigger "+ description := "\" Trigger \" INSTEAD OF INSERT ON \" Parent Owner \".\" View \""+ for _, referencing := range []string{"REFERENCING NEW AS NEW OLD AS OLD", "REFERENCING NEW AS N OLD AS O"} {+ t.Run(referencing, func(t *testing.T) {+ definition := "TRIGGER " + description + "\nBEGIN NULL; END;"+ before, after := exactTriggerStep(owner, name, "42"), exactTriggerStep(owner, name, "42")+ for _, step := range []*oracleViewSourceQueryStep{&before, &after} {+ step.rows[0][8], step.rows[0][10] = description, referencing+ }+ row := append(append([]driver.Value{}, before.rows[0]...), int64(1), definition)+ db, _ := openOracleViewSourceTestDB(t, []oracleViewSourceQueryStep{+ {queryContains: "t.TABLE_OWNER=:1 AND t.TABLE_NAME=:2", args: []driver.Value{" Parent Owner ", " View "},+ columns: append(append([]string{}, exactTriggerColumns...), "LINE", "TEXT"), rows: [][]driver.Value{row}},+ before,+ {queryContains: "XMLAGG", args: []driver.Value{owner, name, "TRIGGER"}, rows: [][]driver.Value{{definition}}},+ {queryContains: "FROM ALL_ERRORS", args: []driver.Value{owner, name}},+ after,+ })+ s := newServer()+ s.db = db+ listed, _, err := s.dispatch("list_triggers", exactTriggerParams(`{"schema":" Parent Owner ","table":" View ","identity_mode":"exact"}`))+ if err != nil {+ t.Fatal(err)+ }+ value, _, err := s.dispatch("get_object_source", exactTriggerParams(`{"schema":" Owner ","name":" Trigger ","object_type":"TRIGGER","identity_mode":"exact"}`))+ if err != nil {+ t.Fatal(err)+ }+ trigger := value.(map[string]any)["trigger"].(triggerInfo)+ original := listed.([]triggerInfo)[0]+ if original.Statement == nil || trigger.Statement == nil || *original.Statement != *trigger.Statement {+ t.Fatalf("statement differs between list and source: %#v / %#v", original, trigger)+ }+ want := definition+ if referencing == "REFERENCING NEW AS NEW OLD AS OLD" {+ want = "BEGIN NULL; END;"+ }+ if *trigger.Statement != want || !trigger.OracleMetadata.Definition.Complete {+ t.Fatalf("statement representation or completeness lost: %#v", trigger)+ }+ encoded, err := json.Marshal(trigger.OracleMetadata)+ if err != nil || strings.Contains(string(encoded), "description") || strings.Contains(string(encoded), "referencing") {+ t.Fatalf("internal dictionary fields leaked: %s (%v)", encoded, err)+ }+ })+ }+}++func TestExactTriggerSourceKeepsGetDDLFallbackWithoutInventingAListStatement(t *testing.T) {+ owner, name := " Owner ", " Trigger "+ definition := "CREATE TRIGGER \" Trigger \" INSTEAD OF INSERT ON \" Parent Owner \".\" View \" BEGIN NULL; END;"+ db, _ := openOracleViewSourceTestDB(t, []oracleViewSourceQueryStep{+ exactTriggerStep(owner, name, "42"),+ {queryContains: "XMLAGG", args: []driver.Value{owner, name, "TRIGGER"}, err: errors.New("ORA-01031")},+ {queryContains: "SELECT TEXT", args: []driver.Value{owner, name, "TRIGGER"}, err: errors.New("ORA-01031")},+ {queryContains: "DBMS_METADATA.GET_DDL", args: []driver.Value{"TRIGGER", name, owner}, rows: [][]driver.Value{{definition}}},+ {queryContains: "FROM ALL_ERRORS", args: []driver.Value{owner, name}},+ exactTriggerStep(owner, name, "42"),+ })+ s := newServer()+ s.db = db+ value, err := s.getExactTriggerSource(owner, name)+ if err != nil {+ t.Fatal(err)+ }+ trigger := value["trigger"].(triggerInfo)+ if value["source"] != definition || trigger.Statement != nil || !trigger.OracleMetadata.Definition.Complete || trigger.OracleMetadata.Definition.Origin != "DBMS_METADATA" {+ t.Fatalf("GET_DDL fallback changed: %#v", value)+ }+}++func TestExactTriggerSourceRejectsConcurrentReplacementAndDoesNotHideErrorReadFailure(t *testing.T) {+ owner, name := " Owner ", " Trigger "+ db, _ := openOracleViewSourceTestDB(t, []oracleViewSourceQueryStep{+ exactTriggerStep(owner, name, "42"),+ {queryContains: "XMLAGG", args: []driver.Value{owner, name, "TRIGGER"}, rows: [][]driver.Value{{"TRIGGER draft"}}},+ {queryContains: "FROM ALL_ERRORS", args: []driver.Value{owner, name}, err: errors.New("ORA-01031: insufficient privileges")},+ exactTriggerStep(owner, name, "43"),+ })+ s := newServer()+ s.db = db+ value, err := s.getExactTriggerSource(owner, name)+ if err != nil {+ t.Fatal(err)+ }+ trigger := value["trigger"].(triggerInfo)+ if value["source"] != "TRIGGER draft" || trigger.OracleMetadata.Definition.Complete {+ t.Fatal("racing source must remain visible but not writable")+ }+ if trigger.OracleMetadata.Reads["identity"].State != "incomplete" || trigger.OracleMetadata.Reads["errors"].State != "denied" || trigger.OracleMetadata.Errors != nil {+ t.Fatalf("unknown was converted to complete/empty: %#v", trigger.OracleMetadata)+ }+}++func TestExactTriggerSourceKeepsNonTableScopeAndNoFakeParent(t *testing.T) {+ owner, name := " Owner ", " Trigger "+ before, after := exactTriggerStep(owner, name, "42"), exactTriggerStep(owner, name, "42")+ for _, step := range []*oracleViewSourceQueryStep{&before, &after} {+ step.rows[0][6], step.rows[0][7] = nil, "SCHEMA"+ }+ db, _ := openOracleViewSourceTestDB(t, []oracleViewSourceQueryStep{before,+ {queryContains: "XMLAGG", args: []driver.Value{owner, name, "TRIGGER"}, rows: [][]driver.Value{{"TRIGGER \" Trigger \" AFTER CREATE ON \" Parent Owner \".SCHEMA BEGIN NULL; END;"}}},+ {queryContains: "FROM ALL_ERRORS", args: []driver.Value{owner, name}}, after})+ s := newServer()+ s.db = db+ value, err := s.getExactTriggerSource(owner, name)+ if err != nil {+ t.Fatal(err)+ }+ metadata := value["trigger"].(triggerInfo).OracleMetadata+ if metadata.Scope != "SCHEMA" || metadata.Parent != nil || metadata.ScopeOwner == nil || *metadata.ScopeOwner != " Parent Owner " {+ t.Fatalf("non-table scope lost: %#v", metadata)+ }+}++func TestExactTriggerProtocolRejectsUnknownModesAndLegacyPayloadStaysSmall(t *testing.T) {+ for _, text := range []string{`{"identity_mode":"approximate"}`, `{"identity_mode":"exact","identityMode":"legacy"}`} {+ if _, err := exactMetadataReadParam(exactTriggerParams(text)); err == nil {+ t.Fatalf("accepted unknown mode: %s", text)+ }+ }+ value, err := json.Marshal(triggerInfo{Name: "T", Event: "INSERT", Timing: "BEFORE"})+ if err != nil {+ t.Fatal(err)+ }+ if strings.Contains(string(value), "oracle_metadata") || strings.Contains(string(value), "enabled") || strings.Contains(string(value), "valid") {+ t.Fatalf("legacy gained metadata defaults: %s", value)+ }+}++func TestExactTriggerSourceDoesNotPromoteAPartialReadToACompleteDefinition(t *testing.T) {+ owner, name := " Owner ", " Trigger "+ db, _ := openOracleViewSourceTestDB(t, []oracleViewSourceQueryStep{+ exactTriggerStep(owner, name, "42"),+ {queryContains: "XMLAGG", args: []driver.Value{owner, name, "TRIGGER"}, err: errors.New("aggregate unavailable")},+ {queryContains: "SELECT TEXT", args: []driver.Value{owner, name, "TRIGGER"}, rows: [][]driver.Value{{"TRIGGER partial"}}, nextError: errors.New("source stream ended early")},+ {queryContains: "DBMS_METADATA.GET_DDL", args: []driver.Value{"TRIGGER", name, owner}, err: errors.New("metadata unavailable")},+ {queryContains: "FROM ALL_ERRORS", args: []driver.Value{owner, name}},+ exactTriggerStep(owner, name, "42"),+ })+ s := newServer()+ s.db = db+ value, err := s.getExactTriggerSource(owner, name)+ if err != nil {+ t.Fatal(err)+ }+ metadata := value["trigger"].(triggerInfo).OracleMetadata+ if metadata.Definition.Complete || metadata.Reads["definition"].State == "available" {+ t.Fatalf("partial source became authoritative: %#v", metadata)+ }+}++func TestExactObjectReadDoesNotTurnPGAErrorsIntoAnEmptyTriggerGroup(t *testing.T) {+ db, _ := openOracleViewSourceTestDB(t, []oracleViewSourceQueryStep{{queryContains: "'TRIGGER'", args: []driver.Value{" Owner ", " Owner ", " Owner ", " Owner ", "TRIGGER", int64(1), int64(0)}, err: errors.New("ORA-04036: PGA memory used by the instance exceeds PGA_AGGREGATE_LIMIT")}})+ s := newServer()+ s.db = db+ if _, err := s.listObjects(" Owner ", metadataListConstraints{Exact: true, Limit: 1, ObjectTypes: []string{"TRIGGER"}}); err == nil {+ t.Fatal("catalog failure became an empty result")+ }+}++func TestExactTriggerVisibleEmptyReadIsExplicitAndNotADictionaryError(t *testing.T) {+ owner, name := " Owner ", " Trigger "+ for _, failure := range []error{nil, errors.New("ORA-01031")} {+ label := "empty"+ if failure != nil {+ label = "denied"+ }+ t.Run(label, func(t *testing.T) {+ db, _ := openOracleViewSourceTestDB(t, []oracleViewSourceQueryStep{+ {queryContains: "FROM ALL_TRIGGERS", args: []driver.Value{owner, name}, columns: exactTriggerColumns, err: failure},+ })+ s := newServer()+ s.db = db+ value, err := s.getExactTriggerSource(owner, name)+ if failure != nil {+ if err == nil {+ t.Fatal("dictionary failure became absence")+ }+ return+ }+ if err != nil {+ t.Fatal(err)+ }+ metadata := value["trigger"].(triggerInfo).OracleMetadata+ if metadata.Reads["identity"].State != "empty" || metadata.Owner != owner || metadata.Name != name || metadata.ObjectID != nil || metadata.Definition != nil {+ t.Fatalf("visible empty read lost its exact provenance: %#v", metadata)+ }+ })+ }+}diff --git a/agents/test-support/src/main/java/com/dbx/agent/AgentRpcTestSupport.java b/agents/test-support/src/main/java/com/dbx/agent/AgentRpcTestSupport.javanew file mode 100644index 0000000000..6aac136e9c--- /dev/null+++ b/agents/test-support/src/main/java/com/dbx/agent/AgentRpcTestSupport.java@@ -0,0 +1,10 @@+package com.dbx.agent;++/** Exercises the production wire codec without exposing it as an agent API. */+public final class AgentRpcTestSupport {+ private AgentRpcTestSupport() {}++ public static String handleRequest(DatabaseAgent agent, String request) {+ return new JsonRpcServer(agent).handleRequest(request);+ }+}diff --git a/apps/desktop/src/components/admin/DamengJobAdmin.vue b/apps/desktop/src/components/admin/DamengJobAdmin.vueindex 66a134a59b..06cf983b29 100644--- a/apps/desktop/src/components/admin/DamengJobAdmin.vue+++ b/apps/desktop/src/components/admin/DamengJobAdmin.vue@@ -1,484 +1,8 @@<script setup lang="ts">-import { computed, onMounted, ref, watch } from "vue";-import { useI18n } from "vue-i18n";-import { AlertTriangle, CalendarClock, DatabaseZap, Loader2, Play, Plus, Power, RefreshCcw, Square, Trash2, XCircle } from "@lucide/vue";-import { Button } from "@/components/ui/button";-import { Badge } from "@/components/ui/badge";-import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog";-import { Input } from "@/components/ui/input";-import { useConnectionStore } from "@/stores/connectionStore";-import { useToast } from "@/composables/useToast";+import DatabaseJobAdmin from "@/components/admin/DatabaseJobAdmin.vue";import type { ConnectionConfig } from "@/types/database";-import * as api from "@/lib/backend/api";-import { executeWithProductionSqlGuard } from "@/lib/database/productionExecutionGuard";-import {- DAMENG_JOB_ENVIRONMENT_SQL,- damengClearJobHistoriesSql,- damengCreateJobSql,- damengDropJobSql,- damengEnableJobSql,- damengInitJobSystemSql,- damengJobHistoriesSql,- damengJobListSql,- damengJobSchedulesSql,- damengJobStepsSql,- damengRunJobSql,- damengStopJobSql,- isDamengJobEnvironmentMissingError,- parseDamengJobEnvironmentReady,- parseDamengJobs,- queryResultToObjects,- type DamengJob,-} from "@/lib/database/damengJobAdmin";-import { useTabUiState } from "@/lib/tabs/tabUiState";--const props = defineProps<{- connection: ConnectionConfig;-}>();--type DetailTab = "steps" | "schedules" | "histories";--const { t } = useI18n();-const { toast } = useToast();-const connectionStore = useConnectionStore();-const { initialState: restoredUiState, track: trackUiState } = useTabUiState<{ selectedJobName?: string; search?: string; detailTab?: DetailTab }>({}, "DamengJobAdmin");--const jobs = ref<DamengJob[]>([]);-const selectedJobName = ref(restoredUiState.selectedJobName ?? "");-const search = ref(restoredUiState.search ?? "");-const loadingJobs = ref(false);-const loadingDetails = ref(false);-const applying = ref(false);-const jobEnvironmentReady = ref(true);-const loadError = ref("");-const detailError = ref("");-const detailTab = ref<DetailTab>(["steps", "schedules", "histories"].includes(restoredUiState.detailTab ?? "") ? restoredUiState.detailTab! : "steps");-const detailRows = ref<Record<string, unknown>[]>([]);--const createDialogOpen = ref(false);-const previewDialogOpen = ref(false);-const pendingSql = ref("");-const pendingAfterApply = ref<(() => Promise<void>) | undefined>();-const pendingDanger = ref(false);-const pendingUseTransaction = ref(false);--const createName = ref("JOB_TEST");-const createEnabled = ref(true);-const createDescription = ref("");-const createStepName = ref("STEP1");-const createCommand = ref("SELECT 1;");-const createScheduleName = ref("SCHEDULE1");-const createScheduleMode = ref<"once" | "daily">("daily");-const createStartDate = ref("CURDATE");-const createStartTime = ref("00:00:00");-const createEndTime = ref("");-const createMinuteInterval = ref(0);--trackUiState(() => ({ selectedJobName: selectedJobName.value, search: search.value, detailTab: detailTab.value }));--const supported = computed(() => props.connection.db_type === "dameng");-const executionDatabase = computed(() => (props.connection.db_type === "dameng" ? "" : props.connection.database || ""));-const useSystemJobTables = computed(() => props.connection.username?.trim().toUpperCase() === "SYSDBA");-const selectedJob = computed(() => jobs.value.find((job) => job.name === selectedJobName.value));-const filteredJobs = computed(() => {- const query = search.value.trim().toLowerCase();- if (!query) return jobs.value;- return jobs.value.filter((job) => `${job.name} ${job.owner || ""} ${job.description || ""}`.toLowerCase().includes(query));-});-const detailColumns = computed(() => {- const set = new Set<string>();- for (const row of detailRows.value) {- Object.keys(row).forEach((key) => set.add(key));- }- return Array.from(set);-});-const canCreateJob = computed(() => createName.value.trim() && createStepName.value.trim() && createScheduleName.value.trim() && createCommand.value.trim());--async function ensureConnection() {- await connectionStore.ensureConnected(props.connection.id, { skipIfClosedByUser: true });-}--async function loadJobs() {- if (!supported.value) return;- loadingJobs.value = true;- loadError.value = "";- try {- await ensureConnection();- const environment = await api.executeQuery(props.connection.id, executionDatabase.value, DAMENG_JOB_ENVIRONMENT_SQL, undefined, undefined, {- maxRows: 1,- });- jobEnvironmentReady.value = parseDamengJobEnvironmentReady(environment);- if (!jobEnvironmentReady.value) {- jobs.value = [];- detailRows.value = [];- selectedJobName.value = "";- return;- }- const result = await api.executeQuery(props.connection.id, executionDatabase.value, damengJobListSql(useSystemJobTables.value), undefined, undefined, {- maxRows: 5000,- });- jobs.value = parseDamengJobs(result);- if (!selectedJob.value) selectedJobName.value = jobs.value[0]?.name || "";- await loadDetails();- } catch (error: any) {- const message = error?.message || String(error);- if (isDamengJobEnvironmentMissingError(message)) {- jobEnvironmentReady.value = false;- loadError.value = "";- } else {- loadError.value = message;- }- jobs.value = [];- detailRows.value = [];- } finally {- loadingJobs.value = false;- }-}--async function loadDetails() {- const job = selectedJob.value;- if (!job) {- detailRows.value = [];- return;- }- loadingDetails.value = true;- detailError.value = "";- try {- const sql = detailTab.value === "steps" ? damengJobStepsSql(job.id, useSystemJobTables.value) : detailTab.value === "schedules" ? damengJobSchedulesSql(job.id, useSystemJobTables.value) : damengJobHistoriesSql(job, useSystemJobTables.value);- const result = await api.executeQuery(props.connection.id, executionDatabase.value, sql, undefined, undefined, {- maxRows: 1000,- });- detailRows.value = queryResultToObjects(result);- } catch (error: any) {- detailError.value = error?.message || String(error);- detailRows.value = [];- } finally {- loadingDetails.value = false;- }-}--function selectJob(job: DamengJob) {- selectedJobName.value = job.name;-}--function previewSql(sql: string, options: { danger?: boolean; afterApply?: () => Promise<void>; useTransaction?: boolean } = {}) {- pendingSql.value = sql;- pendingDanger.value = !!options.danger;- pendingUseTransaction.value = !!options.useTransaction;- pendingAfterApply.value = options.afterApply;- previewDialogOpen.value = true;-}--async function applyPendingSql() {- if (!pendingSql.value.trim()) return;- applying.value = true;- try {- await ensureConnection();- const result = await executeWithProductionSqlGuard({- connection: props.connection,- database: executionDatabase.value,- sql: pendingSql.value,- source: t("production.sourceAdmin"),- execute: () =>- api.executeMulti(props.connection.id, executionDatabase.value, pendingSql.value, undefined, undefined, {- maxRows: 1000,- useTransaction: pendingUseTransaction.value,- }),- });- if (!result) return;- toast(t("damengJobAdmin.applySuccess"), 2500);- previewDialogOpen.value = false;- await (pendingAfterApply.value?.() ?? Promise.resolve());- await loadJobs();- } catch (error: any) {- toast(t("damengJobAdmin.applyFailed", { message: error?.message || String(error) }), 5000);- } finally {- applying.value = false;- }-}--function previewCreateEnvironment() {- previewSql(damengInitJobSystemSql());-}--function previewCreateJob() {- if (!canCreateJob.value) return;- previewSql(- damengCreateJobSql({- name: createName.value,- enabled: createEnabled.value,- description: createDescription.value,- stepName: createStepName.value,- command: createCommand.value,- scheduleName: createScheduleName.value,- scheduleMode: createScheduleMode.value,- startDate: createStartDate.value,- startTime: createStartTime.value,- endTime: createEndTime.value,- minuteInterval: createMinuteInterval.value,- }),- {- afterApply: async () => {- createDialogOpen.value = false;- },- useTransaction: true,- },- );-}--function previewEnableJob(enabled: boolean) {- const job = selectedJob.value;- if (!job) return;- previewSql(damengEnableJobSql(job.name, enabled));-}--function previewDropJob() {- const job = selectedJob.value;- if (!job) return;- previewSql(damengDropJobSql(job.name), { danger: true });-}--function previewRunJob() {- const job = selectedJob.value;- if (!job) return;- const sql = damengRunJobSql(job.id);- if (sql) previewSql(sql);-}--function previewStopJob() {- const job = selectedJob.value;- if (!job) return;- const sql = damengStopJobSql(job.id);- if (sql) previewSql(sql, { danger: true });-}--function previewClearHistories() {- const job = selectedJob.value;- if (!job) return;- previewSql(damengClearJobHistoriesSql(job.name), { danger: true });-}--function cellText(value: unknown): string {- return value == null ? "" : String(value);-}--watch(selectedJobName, () => void loadDetails());-watch(detailTab, () => void loadDetails());-onMounted(() => void loadJobs());+import type { NativeJobAdminSelection } from "@/lib/database/nativeJobAdmin";+defineProps<{ connection: ConnectionConfig; initialSelection?: NativeJobAdminSelection }>();</script>-<template>- <div class="flex h-full min-h-0 flex-col bg-background">- <div class="flex h-12 shrink-0 items-center gap-2 border-b px-3">- <CalendarClock class="h-4 w-4 text-primary" />- <div class="min-w-0 flex-1">- <div class="truncate text-sm font-semibold">{{ t("damengJobAdmin.title") }}</div>- <div class="truncate text-[11px] text-muted-foreground">{{ connection.name }}</div>- </div>- <Button size="sm" variant="outline" class="h-8 gap-1.5" :disabled="loadingJobs" @click="loadJobs">- <Loader2 v-if="loadingJobs" class="h-3.5 w-3.5 animate-spin" />- <RefreshCcw v-else class="h-3.5 w-3.5" />- {{ t("contextMenu.refreshChildren") }}- </Button>- <Button size="sm" variant="outline" class="h-8 gap-1.5" :disabled="jobEnvironmentReady" :title="jobEnvironmentReady ? t('damengJobAdmin.environmentReady') : t('damengJobAdmin.initEnvironment')" @click="previewCreateEnvironment">- <DatabaseZap class="h-3.5 w-3.5" />- {{ jobEnvironmentReady ? t("damengJobAdmin.environmentReady") : t("damengJobAdmin.initEnvironment") }}- </Button>- <Button size="sm" class="h-8 gap-1.5" @click="createDialogOpen = true">- <Plus class="h-3.5 w-3.5" />- {{ t("damengJobAdmin.newJob") }}- </Button>- </div>-- <div v-if="!supported" class="m-4 rounded border border-dashed p-4 text-sm text-muted-foreground">- {{ t("damengJobAdmin.unsupported") }}- </div>-- <div v-else class="grid min-h-0 flex-1 grid-cols-[300px_minmax(0,1fr)]">- <aside class="flex min-h-0 flex-col border-r">- <div class="border-b p-2">- <Input v-model="search" class="h-8 text-xs" :placeholder="t('damengJobAdmin.searchJob')" />- </div>- <div v-if="loadError" class="m-2 rounded border border-destructive/30 bg-destructive/5 p-2 text-xs text-destructive">- <div class="mb-1 flex items-center gap-1 font-medium"><AlertTriangle class="h-3.5 w-3.5" />{{ t("damengJobAdmin.loadFailed") }}</div>- <div class="break-all">{{ loadError }}</div>- </div>- <div v-else-if="!jobEnvironmentReady" class="m-2 rounded border border-amber-500/30 bg-amber-500/5 p-2 text-xs text-amber-700 dark:text-amber-300">- <div class="mb-1 flex items-center gap-1 font-medium"><AlertTriangle class="h-3.5 w-3.5" />{{ t("damengJobAdmin.environmentMissingTitle") }}</div>- <div>{{ t("damengJobAdmin.environmentMissingHint") }}</div>- </div>- <div class="min-h-0 flex-1 overflow-auto p-2">- <button v-for="job in filteredJobs" :key="job.name" type="button" class="mb-1 w-full rounded border px-2 py-2 text-left text-xs transition hover:bg-accent" :class="selectedJobName === job.name ? 'border-primary bg-primary/10' : 'border-transparent'" @click="selectJob(job)">- <div class="flex items-center gap-2">- <span class="min-w-0 flex-1 truncate font-medium">{{ job.name }}</span>- <Badge v-if="job.running" variant="outline" class="h-5 border-amber-500/50 px-1.5 text-[10px] text-amber-700 dark:text-amber-300">{{ t("damengJobAdmin.running") }}</Badge>- <Badge :variant="job.enabled ? 'default' : 'secondary'" class="h-5 px-1.5 text-[10px]">{{ job.enabled ? t("damengJobAdmin.enabled") : t("damengJobAdmin.disabled") }}</Badge>- </div>- <div class="mt-1 truncate text-[11px] text-muted-foreground">{{ job.owner || "-" }} · {{ job.valid || "-" }}</div>- </button>- <div v-if="!loadingJobs && filteredJobs.length === 0" class="p-6 text-center text-xs text-muted-foreground">- {{ t("damengJobAdmin.emptyJobs") }}- </div>- </div>- </aside>-- <main class="flex min-h-0 flex-col">- <div v-if="selectedJob" class="flex shrink-0 flex-wrap items-center gap-2 border-b p-3">- <div class="min-w-0 flex-1">- <div class="truncate text-sm font-semibold">{{ selectedJob.name }}</div>- <div class="flex min-w-0 items-center gap-2 text-xs text-muted-foreground">- <Badge v-if="selectedJob.running" variant="outline" class="h-5 border-amber-500/50 px-1.5 text-[10px] text-amber-700 dark:text-amber-300">{{ t("damengJobAdmin.running") }}</Badge>- <span class="truncate">{{ selectedJob.description || t("damengJobAdmin.noDescription") }}</span>- </div>- </div>- <Button size="sm" variant="outline" class="h-8 gap-1.5" @click="previewRunJob">- <Play class="h-3.5 w-3.5" />- {{ t("damengJobAdmin.runAsync") }}- </Button>- <Button size="sm" variant="outline" class="h-8 gap-1.5" :disabled="!selectedJob.running" :title="selectedJob.running ? t('damengJobAdmin.stopRunning') : t('damengJobAdmin.stopRunningDisabled')" @click="previewStopJob">- <Square class="h-3.5 w-3.5" />- {{ t("damengJobAdmin.stopRunning") }}- </Button>- <Button size="sm" variant="outline" class="h-8 gap-1.5" @click="previewEnableJob(!selectedJob.enabled)">- <Power class="h-3.5 w-3.5" />- {{ selectedJob.enabled ? t("damengJobAdmin.disable") : t("damengJobAdmin.enable") }}- </Button>- <Button size="sm" variant="outline" class="h-8 gap-1.5" @click="previewClearHistories">- <XCircle class="h-3.5 w-3.5" />- {{ t("damengJobAdmin.clearHistories") }}- </Button>- <Button size="sm" variant="destructive" class="h-8 gap-1.5" @click="previewDropJob">- <Trash2 class="h-3.5 w-3.5" />- {{ t("damengJobAdmin.dropJob") }}- </Button>- </div>-- <div v-if="selectedJob" class="flex h-10 shrink-0 items-center gap-1 border-b px-3">- <Button size="sm" :variant="detailTab === 'steps' ? 'secondary' : 'ghost'" class="h-7 px-2 text-xs" @click="detailTab = 'steps'">{{ t("damengJobAdmin.steps") }}</Button>- <Button size="sm" :variant="detailTab === 'schedules' ? 'secondary' : 'ghost'" class="h-7 px-2 text-xs" @click="detailTab = 'schedules'">{{ t("damengJobAdmin.schedules") }}</Button>- <Button size="sm" :variant="detailTab === 'histories' ? 'secondary' : 'ghost'" class="h-7 px-2 text-xs" @click="detailTab = 'histories'">{{ t("damengJobAdmin.histories") }}</Button>- <Loader2 v-if="loadingDetails" class="ml-auto h-3.5 w-3.5 animate-spin text-muted-foreground" />- </div>-- <div class="min-h-0 flex-1 overflow-auto p-3">- <div v-if="!jobEnvironmentReady" class="flex h-full items-center justify-center">- <div class="max-w-xl rounded-lg border border-dashed p-5 text-sm">- <div class="mb-2 flex items-center gap-2 font-semibold"><DatabaseZap class="h-4 w-4 text-primary" />{{ t("damengJobAdmin.environmentMissingTitle") }}</div>- <p class="mb-4 text-xs leading-5 text-muted-foreground">{{ t("damengJobAdmin.environmentMissingDescription") }}</p>- <Button size="sm" class="gap-1.5" @click="previewCreateEnvironment">- <DatabaseZap class="h-3.5 w-3.5" />- {{ t("damengJobAdmin.initEnvironment") }}- </Button>- </div>- </div>- <div v-else-if="!selectedJob" class="flex h-full items-center justify-center text-sm text-muted-foreground">- {{ t("damengJobAdmin.selectJob") }}- </div>- <div v-else-if="detailError" class="rounded border border-destructive/30 bg-destructive/5 p-3 text-xs text-destructive">- {{ detailError }}- </div>- <table v-else class="w-full min-w-max border-collapse text-xs">- <thead>- <tr class="border-b bg-muted/40">- <th v-for="column in detailColumns" :key="column" class="px-2 py-2 text-left font-medium">{{ column }}</th>- </tr>- </thead>- <tbody>- <tr v-for="(row, index) in detailRows" :key="index" class="border-b hover:bg-muted/30">- <td v-for="column in detailColumns" :key="column" class="max-w-[360px] px-2 py-2 align-top">- <span class="block truncate" :title="cellText(row[column])">{{ cellText(row[column]) || "-" }}</span>- </td>- </tr>- </tbody>- </table>- <div v-if="selectedJob && !loadingDetails && !detailError && detailRows.length === 0" class="p-8 text-center text-xs text-muted-foreground">- {{ t("damengJobAdmin.emptyDetails") }}- </div>- </div>- </main>- </div>-- <Dialog v-model:open="createDialogOpen">- <DialogContent class="max-w-3xl">- <DialogHeader>- <DialogTitle>{{ t("damengJobAdmin.newJob") }}</DialogTitle>- </DialogHeader>- <div class="grid gap-3 text-xs">- <div class="grid grid-cols-2 gap-3">- <label class="grid gap-1">- <span>{{ t("damengJobAdmin.jobName") }}</span>- <Input v-model="createName" class="h-8 text-xs" />- </label>- <label class="grid gap-1">- <span>{{ t("damengJobAdmin.description") }}</span>- <Input v-model="createDescription" class="h-8 text-xs" />- </label>- </div>- <label class="flex items-center gap-2">- <input v-model="createEnabled" type="checkbox" />- <span>{{ t("damengJobAdmin.enabled") }}</span>- </label>- <div class="grid grid-cols-2 gap-3">- <label class="grid gap-1">- <span>{{ t("damengJobAdmin.stepName") }}</span>- <Input v-model="createStepName" class="h-8 text-xs" />- </label>- <label class="grid gap-1">- <span>{{ t("damengJobAdmin.scheduleName") }}</span>- <Input v-model="createScheduleName" class="h-8 text-xs" />- </label>- </div>- <label class="grid gap-1">- <span>{{ t("damengJobAdmin.sqlCommand") }}</span>- <textarea v-model="createCommand" class="min-h-28 rounded-md border bg-background px-3 py-2 font-mono text-xs outline-none focus:ring-2 focus:ring-ring" />- </label>- <div class="grid grid-cols-5 gap-3">- <label class="grid gap-1">- <span>{{ t("damengJobAdmin.scheduleMode") }}</span>- <select v-model="createScheduleMode" class="h-8 rounded-md border bg-background px-2 text-xs">- <option value="daily">{{ t("damengJobAdmin.daily") }}</option>- <option value="once">{{ t("damengJobAdmin.once") }}</option>- </select>- </label>- <label class="grid gap-1">- <span>{{ t("damengJobAdmin.startDate") }}</span>- <Input v-model="createStartDate" class="h-8 text-xs" />- </label>- <label class="grid gap-1">- <span>{{ t("damengJobAdmin.startTime") }}</span>- <Input v-model="createStartTime" class="h-8 text-xs" />- </label>- <label class="grid gap-1">- <span>{{ t("damengJobAdmin.endTime") }}</span>- <Input v-model="createEndTime" class="h-8 text-xs" placeholder="23:59:59" />- </label>- <label class="grid gap-1">- <span>{{ t("damengJobAdmin.minuteInterval") }}</span>- <Input v-model.number="createMinuteInterval" type="number" min="0" max="1439" class="h-8 text-xs" />- </label>- </div>- </div>- <DialogFooter>- <Button variant="outline" @click="createDialogOpen = false">{{ t("common.cancel") }}</Button>- <Button :disabled="!canCreateJob" @click="previewCreateJob">{{ t("damengJobAdmin.previewSql") }}</Button>- </DialogFooter>- </DialogContent>- </Dialog>-- <Dialog v-model:open="previewDialogOpen">- <DialogContent class="max-w-3xl">- <DialogHeader>- <DialogTitle>{{ t("damengJobAdmin.sqlPreview") }}</DialogTitle>- </DialogHeader>- <pre class="max-h-[50vh] overflow-auto rounded-md border bg-muted/30 p-3 text-xs"><code>{{ pendingSql }}</code></pre>- <DialogFooter>- <Button variant="outline" @click="previewDialogOpen = false">{{ t("common.cancel") }}</Button>- <Button :variant="pendingDanger ? 'destructive' : 'default'" :disabled="applying" @click="applyPendingSql">- <Loader2 v-if="applying" class="mr-1 h-3.5 w-3.5 animate-spin" />- {{ t("damengJobAdmin.applySql") }}- </Button>- </DialogFooter>- </DialogContent>- </Dialog>- </div>-</template>+<template><DatabaseJobAdmin :connection="connection" :initial-selection="initialSelection" /></template>diff --git a/apps/desktop/src/components/admin/DatabaseJobAdmin.vue b/apps/desktop/src/components/admin/DatabaseJobAdmin.vuenew file mode 100644index 0000000000..a7ad28e148--- /dev/null+++ b/apps/desktop/src/components/admin/DatabaseJobAdmin.vue@@ -0,0 +1,1118 @@+<script setup lang="ts">+// Shared workspace; the existing Dameng tab keeps its compatibility entry.+import { computed, onMounted, onScopeDispose, ref, shallowRef, watch, type Ref } from "vue";+import { useI18n } from "vue-i18n";+import { AlertTriangle, CalendarClock, DatabaseZap, Loader2, Pencil, Play, Plus, Power, RefreshCcw, Square, Trash2, XCircle } from "@lucide/vue";+import { Button } from "@/components/ui/button";+import { Badge } from "@/components/ui/badge";+import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog";+import { Input } from "@/components/ui/input";+import { useConnectionStore } from "@/stores/connectionStore";+import { useToast } from "@/composables/useToast";+import type { ConnectionConfig } from "@/types/database";+import * as api from "@/lib/backend/api";+import { executeWithProductionSqlGuard } from "@/lib/database/productionExecutionGuard";+import { useNativeJobExecution } from "@/composables/useNativeJobExecution";+import { connectionConfigFingerprint } from "@/lib/connection/connectionDatabaseInfo";+import {+ buildNativeJobDamengCreate,+ buildNativeJobDamengEdit,+ rebaseNativeJobDamengCreation,+ rebaseNativeJobDamengDraft,+ nativeJobRefKey,+ type NativeJobContext,+ type NativeJobDamengEditDraft,+ type NativeJobDetails,+ type NativeJobMetadata,+ type NativeJobMutation,+ type NativeJobKind,+ type NativeJobRef,+ type NativeJobRow,+ type NativeJobSummary,+} from "@/lib/database/nativeJobs";+import NativeJobDamengEditor from "@/components/admin/NativeJobDamengEditor.vue";+import NativeJobDefinitionEditor from "@/components/admin/NativeJobDefinitionEditor.vue";+import {+ buildNativeJobDefinitionCreate,+ buildNativeJobDefinitionEdit,+ initializeNativeJobDefinitionEdit,+ rebaseNativeJobDefinitionCreation,+ nativeJobAdminKinds,+ nativeJobAdminEngine,+ nativeJobAdminSupported,+ nativeJobAdminSelection,+ nativeJobAdminSelectionKey,+ newNativeJobDefinitionDraft,+ type NativeJobAdminSelection,+ type NativeJobDefinitionDraft,+} from "@/lib/database/nativeJobAdmin";+import { DAMENG_JOB_ENVIRONMENT_SQL, damengInitJobSystemSql, isDamengJobEnvironmentMissingError, parseDamengJobEnvironmentReady } from "@/lib/database/damengJobAdmin";+import { useTabUiState } from "@/lib/tabs/tabUiState";++const props = defineProps<{+ connection: ConnectionConfig;+ initialSelection?: NativeJobAdminSelection;+}>();++type DetailTab = "definition" | "arguments" | "steps" | "schedules" | "running" | "histories";+interface RetainedJobDraft {+ dameng: NativeJobDamengEditDraft;+ definition: NativeJobDefinitionDraft;+ anchor?: { engine: NativeJobContext["engine"]; sessionUser: string; actualDatabase: string | null; details: NativeJobDetails };+}++const { t } = useI18n();+const { toast } = useToast();+const connectionStore = useConnectionStore();+const context = shallowRef<NativeJobContext>();+const isDameng = computed(() => (context.value?.engine ?? nativeJobAdminEngine(props.connection)) === "dameng");+const { initialState: restoredUiState, track: trackUiState } = useTabUiState<{ selectedJobName?: string; selectedJob?: NativeJobAdminSelection; kind?: NativeJobKind; ownerFilter?: string; search?: string; detailTab?: DetailTab; listOffset?: number }>(+ {},+ isDameng.value ? "DamengJobAdmin" : "DatabaseJobAdmin",+);++const jobs = shallowRef<NativeJobSummary[]>([]);+const selectedExtra = shallowRef<NativeJobSummary>();+const details = shallowRef<NativeJobDetails>();+const editDialogOpen = ref(false);+const editDraft = ref<NativeJobDamengEditDraft>({});+const definitionEditDraft = ref({}) as Ref<NativeJobDefinitionDraft>;+const selectedIdentity = shallowRef<NativeJobAdminSelection | undefined>(props.initialSelection ?? restoredUiState.selectedJob);+const kind = ref<NativeJobKind>(selectedIdentity.value?.kind ?? restoredUiState.kind ?? (isDameng.value ? "dameng-native" : "scheduler"));+const ownerFilter = ref(restoredUiState.ownerFilter ?? "");+const retainedDrafts = new Map<string, RetainedJobDraft>();+const detachedDraft = shallowRef<RetainedJobDraft>();+const viewingDetachedDraft = ref(false);+const refreshingContext = ref(false);+let contextRefreshGeneration = 0;+let installingContext = false;+let disposed = false;+const listTruncated = ref(false);+const listOffset = ref(Number.isSafeInteger(restoredUiState.listOffset) && restoredUiState.listOffset! >= 0 ? restoredUiState.listOffset! : 0);+const pageSize = 100;+let jobsRequest = 0;+let detailsRequest = 0;+let selectedRead = Promise.resolve();+let selectionChanges = 0;+let renameSource: { operationId: string; before: NativeJobDetails; handled: boolean } | undefined;+let searchTimer: ReturnType<typeof setTimeout> | undefined;+const selectedJobName = ref(restoredUiState.selectedJobName ?? "");+const search = ref(restoredUiState.search ?? "");+const loadingJobs = ref(false);+const loadingDetails = ref(false);+const applying = ref(false);+const jobEnvironmentReady = ref(true);+const loadError = ref("");+const detailError = ref("");+const detailTab = ref<DetailTab>(["definition", "arguments", "steps", "schedules", "running", "histories"].includes(restoredUiState.detailTab ?? "") ? restoredUiState.detailTab! : isDameng.value ? "steps" : "definition");++const createDialogOpen = ref(false);+const previewDialogOpen = ref(false);+const pendingSql = ref("");+const pendingAfterApply = ref<(() => Promise<void>) | undefined>();+const pendingDanger = ref(false);+const pendingUseTransaction = ref(false);+const pendingNative = ref(false);+const pendingNativeSlot = ref<"main" | "stop">("main");+const pendingConfirmation = shallowRef<{ slot: "main" | "stop"; planId: string; operationId: string }>();++const createName = ref("JOB_TEST");+const createOwner = ref("");+const createKind = ref<NativeJobKind>(kind.value);+// Keep the recursive JSON contract stable instead of expanding Vue's deep-unwrapped type.+const schedulerCreateDraft = ref(newNativeJobDefinitionDraft("scheduler")) as Ref<NativeJobDefinitionDraft>;+const legacyCreateDraft = ref(newNativeJobDefinitionDraft("legacy")) as Ref<NativeJobDefinitionDraft>;+const definitionCreateDraft = computed({+ get: () => (createKind.value === "legacy" ? legacyCreateDraft.value : schedulerCreateDraft.value),+ set: (value: NativeJobDefinitionDraft) => {+ if (createKind.value === "legacy") legacyCreateDraft.value = value;+ else schedulerCreateDraft.value = value;+ },+});+const createDraft = ref<NativeJobDamengEditDraft>({+ attributes: { ENABLE: { kind: "set", value: true } },+ steps: [{ kind: "add", name: "STEP1", attributes: { TYPE: { kind: "set", value: 0 }, COMMAND_INPUT: { kind: "set", value: "SELECT 1;" } } }],+ schedules: [{ kind: "add", name: "SCHEDULE1", attributes: { TYPE: { kind: "set", value: 1 } } }],+});+const creationPending = ref(false);++trackUiState(() => ({ selectedJobName: selectedJobName.value, selectedJob: selectedIdentity.value, kind: kind.value, ownerFilter: ownerFilter.value, search: search.value, detailTab: detailTab.value, listOffset: listOffset.value }));++const supported = computed(() => nativeJobAdminSupported(props.connection));+const executionDatabase = computed(() => "");+const engine = computed(() => context.value?.engine ?? nativeJobAdminEngine(props.connection) ?? "oracle");+const kinds = computed(() => nativeJobAdminKinds(engine.value));+const connectionIdentity = computed(() => connectionConfigFingerprint(props.connection));+const selectedJob = computed(() =>+ selectedIdentity.value+ ? (jobs.value.find((job) => nativeJobAdminSelectionKey(job.ref) === nativeJobAdminSelectionKey(selectedIdentity.value!)) ?? (selectedExtra.value && nativeJobAdminSelectionKey(selectedExtra.value.ref) === nativeJobAdminSelectionKey(selectedIdentity.value) ? selectedExtra.value : undefined))+ : jobs.value.find((job) => job.name === selectedJobName.value),+);+const selectedTarget = computed(() => selectedJob.value?.ref);+const selectedTargetKey = computed(() => (selectedTarget.value ? nativeJobRefKey(selectedTarget.value) : ""));+const damengCatalogSelection = computed(() => engine.value === "dameng" && (selectedTarget.value?.kind === "dameng-native" || selectedTarget.value?.kind === "legacy"));+const detailTabs = computed<DetailTab[]>(() => ["definition", ...(damengCatalogSelection.value ? (["steps", "schedules"] as const) : selectedTarget.value?.kind === "scheduler" ? (["arguments"] as const) : []), "running", "histories"]);+const usableBaseline = computed(() => supported.value && !refreshingContext.value && !!details.value?.snapshot.revision && details.value.snapshot.definition.status === "available" && details.value.consistency.status === "available" && details.value.nativeIdentity.status === "available");+const stopAvailable = computed(() => selectedTarget.value?.kind === "scheduler" || engine.value === "dameng");+const selectedRunning = computed(() => (details.value?.running.status === "available" ? details.value.running.value.length > 0 : details.value?.running.status === "empty" ? false : undefined));+const detailMetadata = computed<NativeJobMetadata<NativeJobRow[]> | undefined>(() => {+ if (!details.value) return undefined;+ if (detailTab.value === "definition") {+ const definition = details.value.snapshot.definition;+ return definition.status === "available" ? { status: "available", value: [definition.value] } : definition.status === "truncated" ? { ...definition, value: [definition.value] } : definition;+ }+ return details.value[detailTab.value === "histories" ? "history" : detailTab.value === "arguments" ? "parameterMetadata" : detailTab.value];+});+const detailRows = computed(() => (detailMetadata.value?.status === "available" || detailMetadata.value?.status === "truncated" ? detailMetadata.value.value : []));+const metadataWarning = computed(() => (detailMetadata.value && !["available", "empty"].includes(detailMetadata.value.status) ? t("nativeJobs.partitionUnavailable", { status: detailMetadata.value.status }) : ""));+const native = useNativeJobExecution({+ connection: () => props.connection,+ database: () => executionDatabase.value,+ scope: () => context.value?.scope,+ selected: () => selectedTarget.value,+ source: () => t("production.sourceAdmin"),+ onTargetObserved: async (status, original) => {+ if (refreshingContext.value || disposed) return;+ const refresh = contextRefreshGeneration;+ const source = renameSource;+ const target = status.target;+ const observed = status.observedIdentity;+ if (!source || source.operationId !== status.operationId || engine.value !== "dameng" || original.kind === "scheduler" || !target || target.kind === "scheduler" || target.kind !== original.kind || target.jobId !== original.jobId || typeof observed?.NAME !== "string" || !observed.NAME) return;+ if (target.kind === "dameng-native" && target.name !== observed.NAME) return;+ const identity = source.before.nativeIdentity;+ if (identity.status !== "available" || ["DBX_JOB_ID", "DBX_CREATED_AT"].some((key) => identity.value[key] !== observed[key])) return;+ const previous = selectedTargetKey.value;+ const next = nativeJobRefKey(target);+ if (previous !== nativeJobRefKey(original) && previous !== next) return;+ const selection = selectionChanges;+ const connection = connectionIdentity.value;+ const retained = { dameng: editDraft.value, definition: definitionEditDraft.value };+ retainedDrafts.set(next, retained);+ selectedExtra.value = { ...(selectedJob.value ?? extraSummary(target)), ref: target, name: observed.NAME };+ if (target.kind === "legacy") jobs.value = jobs.value.map((job) => (nativeJobRefKey(job.ref) === next ? { ...job, name: observed.NAME as string } : job));+ selectedIdentity.value = nativeJobAdminSelection(target);+ selectedJobName.value = observed.NAME;+ if (previous !== next) {+ retainedDrafts.delete(previous);+ await selectedRead;+ } else await loadDetails();+ if (refresh !== contextRefreshGeneration || disposed || source !== renameSource || connection !== connectionIdentity.value || selection !== selectionChanges || next !== selectedTargetKey.value) return;+ await loadJobs(false);+ if (refresh !== contextRefreshGeneration || disposed || source !== renameSource || connection !== connectionIdentity.value || selection !== selectionChanges || next !== selectedTargetKey.value || !details.value) return;+ const current = details.value.nativeIdentity;+ if (current.status !== "available" || ["DBX_JOB_ID", "DBX_CREATED_AT"].some((key) => identity.value[key] !== current.value[key])) {+ details.value = undefined;+ detailError.value = "native_job_identity_mismatch";+ return;+ }+ if (target.kind === "dameng-native") editDraft.value = rebaseNativeJobDamengDraft(source.before, details.value, editDraft.value, status, context.value?.sessionUser ?? "");+ else if (status.outcome !== "unknown" && details.value.snapshot.definition.status === "available") {+ const remaining = buildNativeJobDefinitionEdit(details.value, "dameng", definitionEditDraft.value).attributes;+ definitionEditDraft.value = { ...definitionEditDraft.value, attributes: Object.fromEntries(remaining.map(({ name, change }) => [name, change])) };+ }+ retainedDrafts.set(next, currentDraft(next));+ source.handled = true;+ },+ onFinished: async (status) => {+ if (refreshingContext.value || disposed) return;+ const refresh = contextRefreshGeneration;+ const creating = creationPending.value;+ const selection = selectionChanges;+ if (status.outcome === "verified") {+ editDraft.value = {};+ definitionEditDraft.value = {};+ toast(t("damengJobAdmin.applySuccess"), 2500);+ }+ if (!creating && renameSource?.operationId === status.operationId) {+ if (!renameSource.handled) await loadDetails();+ return;+ }+ if (creating && status.target && selection === selectionChanges) kind.value = status.target.kind;+ await loadJobs();+ if (refresh !== contextRefreshGeneration || disposed) return;+ if (creating && selection === selectionChanges && status.target && status.target.scope.contextId === context.value?.scope.contextId) {+ const previous = selectedTargetKey.value;+ if (!jobs.value.some((job) => nativeJobRefKey(job.ref) === nativeJobRefKey(status.target!))) {+ selectedExtra.value = extraSummary(status.target);+ }+ selectedIdentity.value = nativeJobAdminSelection(status.target);+ selectedJobName.value = status.target.kind === "legacy" ? status.target.jobId : status.target.name;+ if (previous === selectedTargetKey.value) await loadDetails();+ else await selectedRead;+ if (details.value && nativeJobRefKey(details.value.snapshot.ref) === nativeJobRefKey(status.target)) {+ if (status.outcome !== "verified") {+ if (status.target.kind === "dameng-native") editDraft.value = rebaseNativeJobDamengCreation(details.value, createDraft.value, status);+ else definitionEditDraft.value = rebaseNativeJobDefinitionCreation(details.value, definitionCreateDraft.value, status);+ }+ creationPending.value = false;+ createDialogOpen.value = false;+ }+ }+ },+});+const stopping = useNativeJobExecution({+ connection: () => props.connection,+ database: () => executionDatabase.value,+ scope: () => context.value?.scope,+ selected: () => selectedTarget.value,+ source: () => t("production.sourceAdmin"),+ onFinished: async () => {+ if (!refreshingContext.value && !disposed) await loadDetails();+ },+});+const previewExecution = computed(() => (pendingNativeSlot.value === "stop" ? stopping : native));+const nativePreview = computed(() => previewExecution.value.preview.value);+const nativeError = computed(() => {+ const error = previewExecution.value.error.value;+ return error?.includes("native_job_timestamp_precision_microseconds") ? t("nativeJobs.datePrecisionMicroseconds") : error;+});+const legacyRunRestoresScheduling = computed(() => engine.value === "oceanbase-oracle" && nativePreview.value?.target?.kind === "legacy" && nativePreview.value.steps.some((step) => step.id === "run"));+const nativeResult = computed(() => native.execution.value ?? native.previousExecution.value);+const dispatchedRun = computed(() => !native.previousExecution.value && native.execution.value?.status.state === "running" && native.execution.value.status.steps.some((step) => step.id === "run" && step.state === "dispatching"));+const nativeBusy = computed(() => native.busy.value || native.preparing.value || stopping.busy.value || stopping.preparing.value || refreshingContext.value || !supported.value);+const stopBusy = computed(() => stopping.busy.value || stopping.preparing.value || native.preparing.value || refreshingContext.value || !supported.value || (native.busy.value && !dispatchedRun.value));+const confirmationBusy = computed(() => (pendingNativeSlot.value === "stop" ? stopBusy.value : nativeBusy.value));+const nativeResults = computed(() =>+ [native, stopping].flatMap((owner) => {+ const result = owner.execution.value ?? owner.previousExecution.value;+ return result ? [{ owner, result, previous: owner.previousExecution.value?.status.operationId === result.status.operationId, target: result.prepared.plan.target ?? result.status.target }] : [];+ }),+);+watch(+ [() => native.execution.value?.status.operationId, () => stopping.execution.value?.status.operationId],+ () => {+ const confirmation = pendingConfirmation.value;+ if (!confirmation) return;+ const owner = confirmation.slot === "stop" ? stopping : native;+ const execution = owner.execution.value;+ if (execution?.prepared.plan.planId === confirmation.planId && execution.status.operationId === confirmation.operationId) previewDialogOpen.value = false;+ },+ { flush: "sync" },+);+const previewText = computed(() => (pendingNative.value ? (nativePreview.value?.steps.map((step) => step.sql).join("\n\n") ?? "") : pendingSql.value));+const filteredJobs = computed(() => jobs.value);+const detailColumns = computed(() => {+ const set = new Set<string>();+ for (const row of detailRows.value) {+ Object.keys(row).forEach((key) => set.add(key));+ }+ return Array.from(set);+});+const canCreateJob = computed(() => !!context.value && (createKind.value === "legacy" || !!createName.value) && (createKind.value === "dameng-native" || !!createOwner.value) && !nativeBusy.value);++function extraSummary(target: NativeJobRef): NativeJobSummary {+ return { ref: target, name: target.kind === "legacy" ? target.jobId : target.name, owner: target.kind === "scheduler" ? target.owner : null, enabled: null, jobType: null, state: null, nextRun: null, comments: null, aliases: [], logUser: null, privUser: null, schemaUser: null };+}++function draftAnchor(value = details.value): RetainedJobDraft["anchor"] {+ const current = context.value;+ return current && value && value.snapshot.ref.scope.contextId === current.scope.contextId ? { engine: current.engine, sessionUser: current.sessionUser, actualDatabase: current.actualDatabase, details: value } : undefined;+}++function currentDraft(key = selectedTargetKey.value): RetainedJobDraft {+ return { dameng: editDraft.value, definition: definitionEditDraft.value, anchor: retainedDrafts.get(key)?.anchor ?? (details.value && nativeJobRefKey(details.value.snapshot.ref) === key ? draftAnchor() : undefined) };+}++function draftBelongsToCurrentObject(draft: RetainedJobDraft): boolean {+ const old = draft.anchor;+ const current = context.value;+ const value = details.value;+ if (+ !old ||+ !current ||+ !value ||+ old.engine !== current.engine ||+ old.sessionUser !== current.sessionUser ||+ old.actualDatabase !== current.actualDatabase ||+ nativeJobAdminSelectionKey(old.details.snapshot.ref) !== nativeJobAdminSelectionKey(value.snapshot.ref) ||+ old.details.consistency.status !== "available" ||+ value.consistency.status !== "available" ||+ old.details.nativeIdentity.status !== "available" ||+ value.nativeIdentity.status !== "available"+ )+ return false;+ const before = old.details.nativeIdentity.value;+ const after = value.nativeIdentity.value;+ return Object.keys(before).length > 0 && Object.keys(before).length === Object.keys(after).length && Object.keys(before).every((key) => JSON.stringify(before[key]) === JSON.stringify(after[key]));+}++async function refreshContext() {+ if (!supported.value && !context.value) return;+ const key = selectedTargetKey.value;+ const saved = currentDraft(key);+ if (key) retainedDrafts.set(key, saved);+ const selection = selectedIdentity.value ?? (selectedTarget.value ? nativeJobAdminSelection(selectedTarget.value) : undefined);+ const expectedSelection = selection ? nativeJobAdminSelectionKey(selection) : "";+ const identity = connectionIdentity.value;+ const refresh = ++contextRefreshGeneration;+ const request = ++jobsRequest;+ const selected = ++selectionChanges;+ detailsRequest++;+ loadingJobs.value = false;+ loadingDetails.value = false;+ if (searchTimer) clearTimeout(searchTimer);+ searchTimer = undefined;+ native.invalidateContext();+ stopping.invalidateContext();+ pendingConfirmation.value = undefined;+ previewDialogOpen.value = false;+ editDialogOpen.value = false;+ createDialogOpen.value = false;+ creationPending.value = false;+ renameSource = undefined;+ viewingDetachedDraft.value = false;+ refreshingContext.value = true;+ installingContext = true;+ selectedIdentity.value = selection;+ details.value = undefined;+ context.value = undefined;+ jobs.value = [];+ selectedExtra.value = undefined;+ installingContext = false;+ detailError.value = "";+ loadError.value = "";+ const stillCurrent = () => !disposed && refresh === contextRefreshGeneration && identity === connectionIdentity.value && selected === selectionChanges && (selectedIdentity.value ? nativeJobAdminSelectionKey(selectedIdentity.value) : "") === expectedSelection;+ try {+ await ensureConnection();+ if (!stillCurrent() || request !== jobsRequest) return;+ if (isDameng.value) {+ const environment = await api.executeQuery(props.connection.id, executionDatabase.value, DAMENG_JOB_ENVIRONMENT_SQL, undefined, undefined, { maxRows: 1 });+ if (!stillCurrent() || request !== jobsRequest) return;+ jobEnvironmentReady.value = parseDamengJobEnvironmentReady(environment);+ if (!jobEnvironmentReady.value) return;+ }+ const opened = await api.nativeJobOpenContext(props.connection.id, executionDatabase.value);+ if (!stillCurrent() || request !== jobsRequest) return;+ installingContext = true;+ context.value = opened;+ if (selection) {+ const target = { ...selection, scope: opened.scope } as NativeJobRef;+ nativeJobRefKey(target);+ selectedExtra.value = extraSummary(target);+ selectedIdentity.value = selection;+ }+ installingContext = false;+ await loadJobs(false);+ if (!stillCurrent()) return;+ await loadDetails();+ if (!stillCurrent()) return;+ if (key && draftBelongsToCurrentObject(saved)) {+ editDraft.value = saved.dameng;+ definitionEditDraft.value = saved.definition;+ retainedDrafts.set(selectedTargetKey.value, { ...saved, anchor: draftAnchor() });+ if (key !== selectedTargetKey.value) retainedDrafts.delete(key);+ } else if (key) {+ if (Object.keys(saved.dameng).length || Object.keys(saved.definition).length) detachedDraft.value = saved;+ editDraft.value = {};+ definitionEditDraft.value = {};+ if (selectedTargetKey.value) retainedDrafts.set(selectedTargetKey.value, { dameng: editDraft.value, definition: definitionEditDraft.value, anchor: draftAnchor() });+ }+ } catch (error) {+ if (stillCurrent()) {+ loadError.value = error instanceof Error ? error.message : String(error);+ if (key && (Object.keys(saved.dameng).length || Object.keys(saved.definition).length)) detachedDraft.value = saved;+ }+ } finally {+ installingContext = false;+ if (refresh === contextRefreshGeneration) refreshingContext.value = false;+ }+}++async function ensureConnection() {+ await connectionStore.ensureConnected(props.connection.id, { skipIfClosedByUser: true });+}++async function loadJobs(refreshDetails = true) {+ if (disposed || !supported.value) return;+ const request = ++jobsRequest;+ const identity = connectionIdentity.value;+ loadingJobs.value = true;+ loadError.value = "";+ try {+ await ensureConnection();+ if (isDameng.value) {+ const environment = await api.executeQuery(props.connection.id, executionDatabase.value, DAMENG_JOB_ENVIRONMENT_SQL, undefined, undefined, {+ maxRows: 1,+ });+ if (disposed || request !== jobsRequest || identity !== connectionIdentity.value) return;+ jobEnvironmentReady.value = parseDamengJobEnvironmentReady(environment);+ if (!jobEnvironmentReady.value) {+ jobs.value = [];+ details.value = undefined;+ selectedJobName.value = "";+ return;+ }+ } else jobEnvironmentReady.value = true;+ const currentContext = context.value ?? (await api.nativeJobOpenContext(props.connection.id, executionDatabase.value));+ if (disposed || request !== jobsRequest || identity !== connectionIdentity.value) return;+ context.value = currentContext;+ if (!kinds.value.includes(kind.value)) kind.value = kinds.value[0]!;+ if (!createOwner.value) createOwner.value = currentContext.sessionUser;+ const result = await api.nativeJobList({ scope: currentContext.scope, kind: kind.value, ...(ownerFilter.value ? { schema: ownerFilter.value } : {}), filter: search.value.trim(), offset: listOffset.value, limit: pageSize });+ if (disposed || request !== jobsRequest || identity !== connectionIdentity.value) return;+ if (result.jobs.status !== "available" && result.jobs.status !== "empty" && result.jobs.status !== "truncated") throw new Error(t("nativeJobs.partitionUnavailable", { status: result.jobs.status }));+ const previous = selectedTargetKey.value;+ jobs.value = result.jobs.status === "empty" ? [] : result.jobs.value;+ listTruncated.value = result.jobs.status === "truncated";+ if (!selectedJob.value && selectedIdentity.value && selectedIdentity.value.kind === kind.value) {+ const target = { ...selectedIdentity.value, scope: currentContext.scope } as NativeJobRef;+ try {+ nativeJobRefKey(target);+ selectedExtra.value = extraSummary(target);+ } catch {+ selectedIdentity.value = undefined;+ }+ }+ if (!selectedJob.value) {+ selectedIdentity.value = jobs.value[0] ? nativeJobAdminSelection(jobs.value[0].ref) : undefined;+ selectedJobName.value = jobs.value[0]?.name || "";+ }+ if (refreshDetails && previous === selectedTargetKey.value) await loadDetails();+ } catch (error: any) {+ if (disposed || request !== jobsRequest || identity !== connectionIdentity.value) return;+ const message = error?.message || String(error);+ if (isDameng.value && isDamengJobEnvironmentMissingError(message)) {+ jobEnvironmentReady.value = false;+ loadError.value = "";+ } else {+ loadError.value = message;+ }+ jobs.value = [];+ details.value = undefined;+ } finally {+ if (request === jobsRequest) loadingJobs.value = false;+ }+}++async function loadDetails() {+ const target = selectedTarget.value;+ const request = ++detailsRequest;+ if (!target) {+ details.value = undefined;+ loadingDetails.value = false;+ return;+ }+ loadingDetails.value = true;+ detailError.value = "";+ try {+ const result = await api.nativeJobRead(target);+ if (disposed || request !== detailsRequest || nativeJobRefKey(target) !== selectedTargetKey.value) return;+ if (nativeJobRefKey(result.snapshot.ref) !== nativeJobRefKey(target)) throw new Error("native_job_identity_mismatch");+ details.value = result;+ if (!retainedDrafts.get(selectedTargetKey.value)?.anchor) retainedDrafts.set(selectedTargetKey.value, currentDraft());+ if (selectedExtra.value && nativeJobRefKey(selectedExtra.value.ref) === nativeJobRefKey(target) && result.snapshot.definition.status === "available") {+ const row = result.snapshot.definition.value;+ const enabled = row.ENABLED ?? row.ENABLE;+ selectedExtra.value = {+ ...selectedExtra.value,+ owner: target.kind === "scheduler" ? target.owner : typeof row.USERNAME === "string" ? row.USERNAME : null,+ enabled: enabled == null ? (row.BROKEN === "N" ? true : row.BROKEN === "Y" ? false : null) : enabled === true || enabled === 1 || enabled === "1" || enabled === "TRUE",+ comments: typeof row.COMMENTS === "string" ? row.COMMENTS : typeof row.DESCRIBE === "string" ? row.DESCRIBE : null,+ logUser: typeof row.LOG_USER === "string" ? row.LOG_USER : null,+ privUser: typeof row.PRIV_USER === "string" ? row.PRIV_USER : null,+ schemaUser: typeof row.SCHEMA_USER === "string" ? row.SCHEMA_USER : null,+ };+ }+ } catch (error: any) {+ if (disposed || request !== detailsRequest) return;+ detailError.value = error?.message || String(error);+ details.value = undefined;+ } finally {+ if (request === detailsRequest) loadingDetails.value = false;+ }+}++function selectJob(job: NativeJobSummary) {+ selectionChanges++;+ selectedIdentity.value = nativeJobAdminSelection(job.ref);+ selectedJobName.value = job.name;+}++function changeKind() {+ selectionChanges++;+ jobsRequest++;+ selectedIdentity.value = undefined;+ selectedJobName.value = "";+ selectedExtra.value = undefined;+ jobs.value = [];+ listOffset.value = 0;+ detailTab.value = kind.value === "dameng-native" ? "steps" : "definition";+ void loadJobs();+}++function openCreate() {+ createKind.value = kind.value;+ createDialogOpen.value = true;+}++function previewSql(sql: string, options: { danger?: boolean; afterApply?: () => Promise<void>; useTransaction?: boolean } = {}) {+ pendingNative.value = false;+ pendingConfirmation.value = undefined;+ pendingSql.value = sql;+ pendingDanger.value = !!options.danger;+ pendingUseTransaction.value = !!options.useTransaction;+ pendingAfterApply.value = options.afterApply;+ previewDialogOpen.value = true;+}++async function applyPendingSql() {+ if (pendingNative.value) {+ const refresh = contextRefreshGeneration;+ const confirmation = pendingConfirmation.value;+ if (!confirmation) return;+ const owner = confirmation.slot === "stop" ? stopping : native;+ if (owner.preview.value?.planId !== confirmation.planId || owner.preview.value.operationId !== confirmation.operationId) return;+ const status = await owner.apply();+ if (!disposed && refresh === contextRefreshGeneration && status && pendingConfirmation.value === confirmation && status.operationId === confirmation.operationId) previewDialogOpen.value = false;+ return;+ }+ if (!pendingSql.value.trim()) return;+ applying.value = true;+ try {+ await ensureConnection();+ const result = await executeWithProductionSqlGuard({+ connection: props.connection,+ database: executionDatabase.value,+ sql: pendingSql.value,+ source: t("production.sourceAdmin"),+ execute: () =>+ api.executeMulti(props.connection.id, executionDatabase.value, pendingSql.value, undefined, undefined, {+ maxRows: 1000,+ useTransaction: pendingUseTransaction.value,+ }),+ });+ if (!result) return;+ toast(t("damengJobAdmin.applySuccess"), 2500);+ previewDialogOpen.value = false;+ await (pendingAfterApply.value?.() ?? Promise.resolve());+ await loadJobs();+ } catch (error: any) {+ toast(t("damengJobAdmin.applyFailed", { message: error?.message || String(error) }), 5000);+ } finally {+ applying.value = false;+ }+}++function previewCreateEnvironment() {+ previewSql(damengInitJobSystemSql());+}++async function previewCreateJob() {+ if (!canCreateJob.value || !context.value) return;+ try {+ pendingNative.value = true;+ pendingNativeSlot.value = "main";+ pendingDanger.value = false;+ const request =+ createKind.value === "dameng-native" ? buildNativeJobDamengCreate(context.value.scope, createName.value.trim(), createDraft.value) : buildNativeJobDefinitionCreate(context.value.scope, engine.value, createKind.value, createOwner.value, createName.value, definitionCreateDraft.value);+ const plan = await native.prepare(request);+ if (plan) {+ pendingConfirmation.value = { slot: "main", planId: plan.planId, operationId: plan.operationId };+ creationPending.value = true;+ createDialogOpen.value = false;+ previewDialogOpen.value = true;+ }+ } catch (error) {+ toast(error instanceof Error ? error.message : String(error), 5000);+ }+}++async function previewNative(change: NativeJobMutation, danger = false) {+ creationPending.value = false;+ pendingNative.value = true;+ const slot = change.action === "stop" ? "stop" : "main";+ pendingNativeSlot.value = slot;+ pendingDanger.value = danger;+ const before = details.value;+ const plan = await (slot === "stop" ? stopping : native).prepare(change);+ if (plan) {+ pendingConfirmation.value = { slot, planId: plan.planId, operationId: plan.operationId };+ renameSource = before && plan.steps.some((step) => step.id === "rename") ? { operationId: plan.operationId, before, handled: false } : undefined;+ previewDialogOpen.value = true;+ }+}++function correctDraft() {+ const status = nativeResult.value?.status;+ if (+ !creationPending.value &&+ status?.target?.kind === "scheduler" &&+ status.steps.some((step) => step.id === "create" && step.state === "applied") &&+ status.steps.some((step) => step.id === "enable" && step.state !== "applied") &&+ status.steps.every((step) => step.id === "enable" || step.state === "applied")+ ) {+ previewControl("enable");+ return;+ }+ if (creationPending.value) createDialogOpen.value = true;+ else editJob();+}++function previewControl(action: "enable" | "disable" | "run" | "stop" | "drop" | "clear-history", force = false) {+ if (!details.value || !selectedTarget.value) return;+ void previewNative({ action, target: selectedTarget.value, baseline: details.value.snapshot.revision, ...(force && (action === "stop" || action === "drop") ? { force: true } : {}) }, action === "drop" || action === "stop" || action === "clear-history");+}++function editJob() {+ if (!details.value) return;+ viewingDetachedDraft.value = false;+ if (selectedTarget.value?.kind === "dameng-native" && !Object.keys(editDraft.value).length) editDraft.value = { attributes: { ENABLE: { kind: "set", value: selectedJob.value?.enabled === true } } };+ initializeNativeJobDefinitionEdit(details.value, definitionEditDraft.value);+ retainedDrafts.set(selectedTargetKey.value, currentDraft());+ editDialogOpen.value = true;+}++async function previewEdit() {+ if (!details.value) return;+ try {+ await previewNative(selectedTarget.value?.kind === "dameng-native" ? buildNativeJobDamengEdit(details.value, editDraft.value) : buildNativeJobDefinitionEdit(details.value, engine.value, definitionEditDraft.value));+ if (nativePreview.value) editDialogOpen.value = false;+ } catch (error) {+ toast(error instanceof Error ? error.message : String(error), 5000);+ }+}++function cellText(value: unknown): string {+ return value == null ? "" : typeof value === "object" ? JSON.stringify(value) : String(value);+}++watch(+ selectedTargetKey,+ (_next, previous) => {+ if (installingContext) return;+ if (previous) retainedDrafts.set(previous, currentDraft(previous));+ details.value = undefined;+ const retained = retainedDrafts.get(selectedTargetKey.value);+ editDraft.value = retained?.dameng ?? {};+ definitionEditDraft.value = retained?.definition ?? {};+ editDialogOpen.value = false;+ if (!detailTabs.value.includes(detailTab.value)) detailTab.value = "definition";+ selectedRead = loadDetails();+ },+ { flush: "sync" },+);+watch(connectionIdentity, () => {+ contextRefreshGeneration++;+ refreshingContext.value = false;+ native.invalidateContext();+ stopping.invalidateContext();+ pendingConfirmation.value = undefined;+ selectionChanges++;+ jobsRequest++;+ detailsRequest++;+ context.value = undefined;+ details.value = undefined;+ jobs.value = [];+ selectedExtra.value = undefined;+ selectedIdentity.value = undefined;+ selectedJobName.value = "";+ createOwner.value = "";+ listOffset.value = 0;+ editDraft.value = {};+ definitionEditDraft.value = {};+ retainedDrafts.clear();+ detachedDraft.value = undefined;+ viewingDetachedDraft.value = false;+ renameSource = undefined;+ editDialogOpen.value = false;+ createDialogOpen.value = false;+ creationPending.value = false;+ previewDialogOpen.value = false;+ void loadJobs();+});+watch(+ () => nativeJobAdminEngine(props.connection),+ () => {+ if (context.value) {+ if (!supported.value) {+ native.invalidatePreview();+ stopping.invalidatePreview();+ previewDialogOpen.value = false;+ }+ return;+ }+ if (refreshingContext.value || disposed) return;+ jobsRequest++;+ detailsRequest++;+ details.value = undefined;+ native.invalidatePreview();+ stopping.invalidatePreview();+ void loadJobs();+ },+);+watch(+ () => props.initialSelection,+ (selection) => {+ if (!selection) return;+ kind.value = selection.kind;+ selectedIdentity.value = selection;+ selectedExtra.value = undefined;+ listOffset.value = 0;+ void loadJobs();+ },+);+onMounted(() => void loadJobs());+watch([search, ownerFilter], () => {+ jobsRequest++;+ listOffset.value = 0;+ if (searchTimer) clearTimeout(searchTimer);+ searchTimer = setTimeout(() => {+ searchTimer = undefined;+ void loadJobs();+ }, 200);+});+onScopeDispose(() => {+ disposed = true;+ contextRefreshGeneration++;+ jobsRequest++;+ detailsRequest++;+ if (searchTimer) clearTimeout(searchTimer);+});+</script>++<template>+ <div class="flex h-full min-h-0 flex-col bg-background">+ <div class="flex h-12 shrink-0 items-center gap-2 border-b px-3">+ <CalendarClock class="h-4 w-4 text-primary" />+ <div class="min-w-0 flex-1">+ <div class="truncate text-sm font-semibold">{{ t(isDameng ? "damengJobAdmin.title" : "nativeJobs.title") }}</div>+ <div class="truncate text-[11px] text-muted-foreground">{{ connection.name }}</div>+ </div>+ <Button size="sm" variant="outline" class="h-8 gap-1.5" :disabled="loadingJobs || refreshingContext || applying" @click="refreshContext">+ <Loader2 v-if="loadingJobs || refreshingContext" class="h-3.5 w-3.5 animate-spin" />+ <RefreshCcw v-else class="h-3.5 w-3.5" />+ {{ t("contextMenu.refreshChildren") }}+ </Button>+ <Button v-if="isDameng" size="sm" variant="outline" class="h-8 gap-1.5" :disabled="jobEnvironmentReady || !supported || refreshingContext" :title="jobEnvironmentReady ? t('damengJobAdmin.environmentReady') : t('damengJobAdmin.initEnvironment')" @click="previewCreateEnvironment">+ <DatabaseZap class="h-3.5 w-3.5" />+ {{ jobEnvironmentReady ? t("damengJobAdmin.environmentReady") : t("damengJobAdmin.initEnvironment") }}+ </Button>+ <Button size="sm" class="h-8 gap-1.5" :disabled="nativeBusy || !jobEnvironmentReady || !context" @click="openCreate">+ <Plus class="h-3.5 w-3.5" />+ {{ t("damengJobAdmin.newJob") }}+ </Button>+ </div>++ <div v-if="!supported" class="m-4 rounded border border-dashed p-4 text-sm text-muted-foreground">+ {{ t("nativeJobs.unsupported") }}+ </div>++ <div v-else class="grid min-h-0 flex-1 grid-cols-[300px_minmax(0,1fr)]">+ <aside class="flex min-h-0 flex-col border-r">+ <div class="grid gap-2 border-b p-2">+ <select v-model="kind" :disabled="refreshingContext" :aria-label="t('nativeJobs.kind')" class="h-9 rounded border bg-background px-2 text-sm" @change="changeKind">+ <option v-for="value in kinds" :key="value" :value="value">{{ t(`nativeJobs.kinds.${value}`) }}</option>+ </select>+ <Input v-if="!isDameng" v-model="ownerFilter" :disabled="refreshingContext" class="h-8 text-xs" :aria-label="t('nativeJobs.ownerFilter')" :placeholder="t('nativeJobs.ownerFilter')" />+ <Input v-model="search" :disabled="refreshingContext" class="h-8 text-xs" :placeholder="t('damengJobAdmin.searchJob')" />+ </div>+ <div v-if="loadError" class="m-2 rounded border border-destructive/30 bg-destructive/5 p-2 text-xs text-destructive">+ <div class="mb-1 flex items-center gap-1 font-medium"><AlertTriangle class="h-3.5 w-3.5" />{{ t("damengJobAdmin.loadFailed") }}</div>+ <div class="break-all">{{ loadError }}</div>+ </div>+ <div v-else-if="!jobEnvironmentReady" class="m-2 rounded border border-amber-500/30 bg-amber-500/5 p-2 text-xs text-amber-700 dark:text-amber-300">+ <div class="mb-1 flex items-center gap-1 font-medium"><AlertTriangle class="h-3.5 w-3.5" />{{ t("damengJobAdmin.environmentMissingTitle") }}</div>+ <div>{{ t("damengJobAdmin.environmentMissingHint") }}</div>+ </div>+ <div class="min-h-0 flex-1 overflow-auto p-2">+ <button+ v-for="job in filteredJobs"+ :key="nativeJobRefKey(job.ref)"+ type="button"+ class="mb-1 w-full rounded border px-2 py-2 text-left text-xs transition hover:bg-accent"+ :class="selectedTargetKey === nativeJobRefKey(job.ref) ? 'border-primary bg-primary/10' : 'border-transparent'"+ @click="selectJob(job)"+ >+ <div class="flex items-center gap-2">+ <span class="min-w-0 flex-1 truncate font-medium">{{ job.name }}</span>+ <Badge :variant="job.enabled ? 'default' : 'secondary'" class="h-5 px-1.5 text-[10px]">{{ job.enabled === null ? t("nativeJobs.unknown") : job.enabled ? t("damengJobAdmin.enabled") : t("damengJobAdmin.disabled") }}</Badge>+ </div>+ <div class="mt-1 truncate text-[11px] text-muted-foreground">{{ job.owner || "-" }} · {{ job.state || t("nativeJobs.unknown") }}</div>+ </button>+ <div v-if="!loadingJobs && !loadError && jobEnvironmentReady && filteredJobs.length === 0" class="p-6 text-center text-xs text-muted-foreground">+ {{ t(search.trim() ? "nativeJobs.noMatches" : "nativeJobs.emptyJobs") }}+ </div>+ </div>+ <div class="flex shrink-0 items-center justify-between border-t p-2 text-xs">+ <Button+ size="sm"+ variant="ghost"+ :disabled="loadingJobs || listOffset === 0"+ @click="+ listOffset = Math.max(0, listOffset - pageSize);+ loadJobs();+ "+ >{{ t("nativeJobs.previousPage") }}</Button+ >+ <span>{{ jobs.length ? listOffset + 1 : 0 }}–{{ listOffset + jobs.length }}</span>+ <Button+ size="sm"+ variant="ghost"+ :disabled="loadingJobs || !listTruncated"+ @click="+ listOffset += pageSize;+ loadJobs();+ "+ >{{ t("nativeJobs.nextPage") }}</Button+ >+ </div>+ </aside>++ <main class="flex min-h-0 flex-col">+ <div v-if="detachedDraft" class="flex flex-wrap items-center gap-2 border-b border-amber-500/40 p-3 text-sm">+ <span>{{ t("nativeJobs.detachedDraft") }}</span>+ <Button+ size="sm"+ variant="outline"+ @click="+ viewingDetachedDraft = true;+ editDialogOpen = true;+ "+ >{{ t("nativeJobs.viewRetainedDraft") }}</Button+ >+ </div>+ <div v-if="selectedJob" class="flex shrink-0 flex-wrap items-center gap-2 border-b p-3">+ <div class="min-w-0 flex-1">+ <div class="truncate text-sm font-semibold">{{ selectedJob.owner ? `${selectedJob.owner} · ` : "" }}{{ selectedJob.name }}</div>+ <div class="flex min-w-0 items-center gap-2 text-xs text-muted-foreground">+ <Badge v-if="selectedRunning" variant="outline" class="h-5 border-amber-500/50 px-1.5 text-[10px] text-amber-700 dark:text-amber-300">{{ t("damengJobAdmin.running") }}</Badge>+ <span class="truncate">{{ selectedJob.comments || t("damengJobAdmin.noDescription") }}</span>+ </div>+ </div>+ <Button size="sm" variant="outline" class="h-8 gap-1.5" :disabled="!usableBaseline || nativeBusy" @click="editJob"> <Pencil class="h-3.5 w-3.5" />{{ t("nativeJobs.editJob") }} </Button>+ <Button size="sm" variant="outline" class="h-8 gap-1.5" :disabled="!usableBaseline || nativeBusy" @click="previewControl('run')">+ <Play class="h-3.5 w-3.5" />+ {{ t(selectedTarget?.kind === "legacy" && engine !== "dameng" ? "nativeJobs.runForeground" : "damengJobAdmin.runAsync") }}+ </Button>+ <Button+ v-if="stopAvailable"+ size="sm"+ variant="outline"+ class="h-8 gap-1.5"+ :disabled="!usableBaseline || stopBusy || (selectedRunning === false && !dispatchedRun)"+ :title="selectedRunning === undefined ? t('nativeJobs.runningUnknownHint') : selectedRunning ? t('damengJobAdmin.stopRunning') : t('damengJobAdmin.stopRunningDisabled')"+ @click="previewControl('stop')"+ >+ <Square class="h-3.5 w-3.5" />+ {{ t("damengJobAdmin.stopRunning") }}+ </Button>+ <Button v-if="engine === 'oracle' && selectedTarget?.kind === 'scheduler'" size="sm" variant="outline" class="h-8" :disabled="!usableBaseline || stopBusy || (selectedRunning === false && !dispatchedRun)" @click="previewControl('stop', true)">{{ t("nativeJobs.forceStop") }}</Button>+ <Button size="sm" variant="outline" class="h-8 gap-1.5" :disabled="!usableBaseline || nativeBusy" @click="previewControl(selectedJob.enabled ? 'disable' : 'enable')">+ <Power class="h-3.5 w-3.5" />+ {{ selectedJob.enabled ? t("damengJobAdmin.disable") : t("damengJobAdmin.enable") }}+ </Button>+ <Button v-if="damengCatalogSelection" size="sm" variant="outline" class="h-8 gap-1.5" :disabled="!usableBaseline || nativeBusy" @click="previewControl('clear-history')">+ <XCircle class="h-3.5 w-3.5" />+ {{ t("damengJobAdmin.clearHistories") }}+ </Button>+ <Button size="sm" variant="destructive" class="h-8 gap-1.5" :disabled="!usableBaseline || nativeBusy" @click="previewControl('drop')">+ <Trash2 class="h-3.5 w-3.5" />+ {{ t("damengJobAdmin.dropJob") }}+ </Button>+ </div>+ <p v-if="selectedJob && !stopAvailable" class="border-b px-3 py-2 text-xs text-muted-foreground">{{ t("nativeJobs.legacyNoStop") }}</p>+ <p v-if="selectedJob && details && !usableBaseline" role="status" class="border-b border-amber-500/40 p-3 text-sm">{{ t("nativeJobs.baselineUnavailable") }}</p>++ <div v-if="nativeError" role="alert" class="border-b border-destructive/30 bg-destructive/5 p-3 text-sm text-destructive">{{ nativeError }}</div>+ <section v-for="{ owner: execution, result: nativeResult, previous: previousContextResult, target: resultTarget } in nativeResults" :key="nativeResult.status.operationId" aria-live="polite" class="grid shrink-0 gap-2 border-b p-3 text-sm">+ <p v-if="execution === stopping" class="font-medium">{{ t("damengJobAdmin.stopRunning") }}</p>+ <p v-if="previousContextResult" class="text-muted-foreground">{{ t("nativeJobs.previousContext") }} · {{ resultTarget?.kind === "scheduler" ? `${resultTarget.owner} · ${resultTarget.name}` : resultTarget?.kind === "legacy" ? resultTarget.jobId : resultTarget?.name }}</p>+ <div class="flex flex-wrap items-center gap-2">+ <Loader2 v-if="nativeResult.status.state !== 'finished'" class="h-4 w-4 animate-spin" />+ <strong>{{+ t(+ nativeResult.status.state === "finished" && nativeResult.status.outcome === "accepted" && nativeResult.status.reason === "native_job_legacy_interval_expression_not_readable"+ ? "nativeJobs.damengIntervalAccepted"+ : `nativeJobs.outcomes.${nativeResult.status.state === "finished" ? nativeResult.status.outcome : "running"}`,+ )+ }}</strong>+ <Button v-if="nativeResult.status.state !== 'finished'" size="sm" variant="outline" @click="execution.cancel">{{ t("nativeJobs.cancelFollowing") }}</Button>+ <Button v-if="!previousContextResult && (nativeResult.status.outcome === 'partial' || nativeResult.status.outcome === 'unknown')" size="sm" variant="outline" :disabled="loadingDetails || refreshingContext" @click="loadDetails">{{ t("nativeJobs.readAgain") }}</Button>+ <Button+ v-if="execution === native && !previousContextResult && nativeResult.status.state === 'finished' && (nativeResult.status.outcome === 'partial' || nativeResult.status.outcome === 'unknown')"+ size="sm"+ variant="outline"+ :disabled="refreshingContext || (!creationPending && !details)"+ @click="correctDraft"+ >{{ t("nativeJobs.correctDraft") }}</Button+ >+ <Button v-if="nativeResult.status.state === 'finished' && ['partial', 'unknown'].includes(nativeResult.status.outcome) && nativeResult.status.steps.some((step) => step.id === 'rename')" size="sm" variant="outline" :disabled="execution.observing.value" @click="execution.observe">{{+ t("nativeJobs.checkResult")+ }}</Button>+ <Button v-else-if="nativeResult.error" size="sm" variant="outline" @click="execution.refresh">{{ t("nativeJobs.checkResult") }}</Button>+ </div>+ <p v-if="nativeResult.error" class="text-muted-foreground">{{ t("nativeJobs.operationStatusUnavailable") }}</p>+ <p v-else-if="nativeResult.status.reason === 'native_job_legacy_runtime_update_required'" class="text-muted-foreground">{{ t("nativeJobs.legacyRuntimeUpdateRequired") }}</p>+ <div v-if="nativeResult.status.executionObservation" class="grid gap-2 border-t pt-3">+ <div class="flex flex-wrap items-center justify-between gap-2">+ <strong>{{ t("nativeJobs.executionObservation") }}</strong>+ <Button size="sm" variant="outline" :disabled="execution.observing.value || nativeResult.status.state !== 'finished'" @click="execution.observe">{{ t("nativeJobs.observeExecution") }}</Button>+ </div>+ <p>{{ t(nativeResult.status.executionObservation.association === "uncertain" ? "nativeJobs.associationUncertain" : "nativeJobs.observationUnavailable") }}</p>+ </div>+ <details v-if="nativeResult.status.executionObservation || nativeResult.error || nativeResult.status.reason || ['partial', 'unknown'].includes(nativeResult.status.outcome)" class="text-xs text-muted-foreground">+ <summary class="cursor-pointer">{{ t("nativeJobs.observationNativeDetails") }}</summary>+ <p v-if="nativeResult.error" class="break-words py-2">{{ nativeResult.error }}</p>+ <p v-if="nativeResult.status.reason" class="break-words py-2">{{ nativeResult.status.reason }}</p>+ <ol v-if="nativeResult.status.outcome === 'partial' || nativeResult.status.outcome === 'unknown'" class="max-h-40 overflow-auto">+ <li v-for="step in nativeResult.status.steps" :key="step.id" class="flex gap-3 py-1">+ <span class="min-w-0 flex-1 break-words">{{ step.id }}</span+ ><span>{{ t(`nativeJobs.stepStates.${step.state}`) }}</span+ ><span v-if="step.reason">{{ step.reason }}</span>+ </li>+ </ol>+ <template v-if="nativeResult.status.executionObservation">+ <p class="py-2">{{ t("nativeJobs.observationReadStatus", { running: nativeResult.status.executionObservation.running.status, history: nativeResult.status.executionObservation.history.status }) }}</p>+ <ul v-if="nativeResult.status.executionObservation.candidates.length" class="grid max-h-40 gap-2 overflow-auto">+ <li v-for="candidate in nativeResult.status.executionObservation.candidates" :key="candidate.nativeKey" class="flex flex-wrap items-baseline gap-x-3 gap-y-1">+ <code>{{ candidate.nativeKey }}</code>+ <span>{{ candidate.phase === "not-observed" ? t("nativeJobs.instanceNotObserved") : candidate.phase === "running" ? t("nativeJobs.running") : t("damengJobAdmin.histories") }}</span>+ <span v-if="candidate.row.STATUS">{{ candidate.row.STATUS }}</span>+ <span class="text-muted-foreground">{{ t(candidate.evidence === "new-history" ? "nativeJobs.newlyObserved" : "nativeJobs.observedInstance") }}</span>+ </li>+ </ul>+ <p v-else>{{ t("nativeJobs.observationEmpty") }}</p>+ <p class="py-2">{{ t("nativeJobs.observationTimestamp", { time: nativeResult.status.executionObservation.observedAt }) }}</p>+ <pre class="max-h-64 overflow-auto whitespace-pre-wrap break-words">{{ JSON.stringify(nativeResult.status.executionObservation, null, 2) }}</pre>+ </template>+ </details>+ </section>++ <div v-if="selectedJob" class="flex h-10 shrink-0 items-center gap-1 border-b px-3">+ <Button v-for="tab in detailTabs" :key="tab" size="sm" :variant="detailTab === tab ? 'secondary' : 'ghost'" class="h-7 px-2 text-xs" @click="detailTab = tab">{{+ t(tab === "definition" ? "nativeJobs.attributes" : tab === "arguments" || tab === "running" ? `nativeJobs.${tab}` : `damengJobAdmin.${tab}`)+ }}</Button>+ <Loader2 v-if="loadingDetails" class="ml-auto h-3.5 w-3.5 animate-spin text-muted-foreground" />+ </div>++ <div class="min-h-0 flex-1 overflow-auto p-3">+ <div v-if="!jobEnvironmentReady" class="flex h-full items-center justify-center">+ <div class="max-w-xl rounded-lg border border-dashed p-5 text-sm">+ <div class="mb-2 flex items-center gap-2 font-semibold"><DatabaseZap class="h-4 w-4 text-primary" />{{ t("damengJobAdmin.environmentMissingTitle") }}</div>+ <p class="mb-4 text-xs leading-5 text-muted-foreground">{{ t("damengJobAdmin.environmentMissingDescription") }}</p>+ <Button size="sm" class="gap-1.5" @click="previewCreateEnvironment">+ <DatabaseZap class="h-3.5 w-3.5" />+ {{ t("damengJobAdmin.initEnvironment") }}+ </Button>+ </div>+ </div>+ <div v-else-if="!selectedJob" class="flex h-full items-center justify-center text-sm text-muted-foreground">+ {{ t("damengJobAdmin.selectJob") }}+ </div>+ <div v-else-if="detailError" class="rounded border border-destructive/30 bg-destructive/5 p-3 text-xs text-destructive">+ {{ detailError }}+ </div>+ <div v-if="metadataWarning" role="status" class="mb-3 rounded border border-amber-500/40 p-3 text-sm">{{ metadataWarning }}</div>+ <dl v-if="!detailError && detailTab === 'definition' && detailRows[0]" class="grid gap-x-8 gap-y-4 sm:grid-cols-2">+ <div v-for="column in detailColumns" :key="column" class="min-w-0 border-b pb-3" :class="['JOB_ACTION', 'WHAT', 'COMMAND'].includes(column) ? 'sm:col-span-2' : ''">+ <dt class="mb-1.5 text-xs font-medium text-muted-foreground">{{ column }}</dt>+ <dd class="max-h-72 overflow-auto whitespace-pre-wrap break-words font-mono text-sm">{{ detailRows[0][column] === null ? "NULL" : cellText(detailRows[0][column]) }}</dd>+ </div>+ </dl>+ <table v-else-if="!detailError && detailRows.length" class="w-full min-w-max border-collapse text-xs">+ <thead>+ <tr class="border-b bg-muted/40">+ <th v-for="column in detailColumns" :key="column" class="px-2 py-2 text-left font-medium">{{ column }}</th>+ </tr>+ </thead>+ <tbody>+ <tr v-for="(row, index) in detailRows" :key="index" class="border-b hover:bg-muted/30">+ <td v-for="column in detailColumns" :key="column" class="max-w-[360px] px-2 py-2 align-top">+ <span class="block truncate" :title="cellText(row[column])">{{ cellText(row[column]) || "-" }}</span>+ </td>+ </tr>+ </tbody>+ </table>+ <section v-if="!detailError && detailTab === 'definition' && details?.legacyDefinition" class="mt-5 grid gap-3 border-t pt-4">+ <h3 class="text-sm font-medium">{{ t("nativeJobs.kinds.legacy") }} · DBMS_JOB</h3>+ <dl v-if="details.legacyDefinition.status === 'available'" class="grid gap-x-8 gap-y-4 sm:grid-cols-2">+ <div v-for="(value, column) in details.legacyDefinition.value" :key="column" class="min-w-0 border-b pb-3" :class="column === 'WHAT' ? 'sm:col-span-2' : ''">+ <dt class="mb-1.5 text-xs font-medium text-muted-foreground">{{ column }}</dt>+ <dd class="max-h-72 overflow-auto whitespace-pre-wrap break-words font-mono text-sm">{{ value === null ? "NULL" : cellText(value) }}</dd>+ </div>+ </dl>+ <p v-else role="status" class="text-sm text-muted-foreground">{{ details.legacyDefinition.status === "empty" ? t("damengJobAdmin.emptyDetails") : t("nativeJobs.partitionUnavailable", { status: details.legacyDefinition.status }) }}</p>+ </section>+ <div v-if="selectedJob && !loadingDetails && !detailError && (detailMetadata?.status === 'empty' || (detailMetadata?.status === 'available' && detailRows.length === 0))" class="p-8 text-center text-xs text-muted-foreground">+ {{ t("damengJobAdmin.emptyDetails") }}+ </div>+ </div>+ </main>+ </div>++ <Dialog v-model:open="editDialogOpen">+ <DialogContent class="flex max-h-[90vh] max-w-4xl flex-col">+ <DialogHeader+ ><DialogTitle+ >{{ viewingDetachedDraft ? t("nativeJobs.viewRetainedDraft") : t("nativeJobs.editJob") }} ·+ {{ viewingDetachedDraft ? (detachedDraft?.anchor?.details.snapshot.ref.kind === "legacy" ? detachedDraft.anchor.details.snapshot.ref.jobId : detachedDraft?.anchor?.details.snapshot.ref.name) : selectedJob?.name }}</DialogTitle+ ></DialogHeader+ >+ <div v-if="viewingDetachedDraft && detachedDraft?.anchor" class="min-h-0 overflow-auto p-1">+ <NativeJobDamengEditor v-if="detachedDraft.anchor.details.snapshot.ref.kind === 'dameng-native'" :model-value="detachedDraft.dameng" :details="detachedDraft.anchor.details" disabled />+ <NativeJobDefinitionEditor v-else :model-value="detachedDraft.definition" :engine="detachedDraft.anchor.engine" :kind="detachedDraft.anchor.details.snapshot.ref.kind" :details="detachedDraft.anchor.details" disabled />+ </div>+ <pre v-else-if="viewingDetachedDraft && detachedDraft" class="max-h-[60vh] overflow-auto whitespace-pre-wrap text-sm">{{ JSON.stringify({ attributes: detachedDraft.definition.attributes, arguments: detachedDraft.definition.arguments, dameng: detachedDraft.dameng }, null, 2) }}</pre>+ <div v-else-if="details" class="min-h-0 overflow-auto p-1">+ <NativeJobDamengEditor v-if="selectedTarget?.kind === 'dameng-native'" v-model="editDraft" :details="details" :disabled="nativeBusy" />+ <NativeJobDefinitionEditor v-else-if="selectedTarget" v-model="definitionEditDraft" :engine="engine" :kind="selectedTarget.kind" :details="details" :scope="context?.scope" :disabled="nativeBusy" />+ </div>+ <p v-if="native.error.value" role="alert" class="text-sm text-destructive">{{ nativeError }}</p>+ <DialogFooter>+ <Button variant="outline" @click="editDialogOpen = false">{{ t("common.cancel") }}</Button>+ <Button v-if="!viewingDetachedDraft" :disabled="!details || nativeBusy" @click="previewEdit"><Loader2 v-if="native.preparing.value" class="mr-1 h-4 w-4 animate-spin" />{{ t("damengJobAdmin.previewSql") }}</Button>+ </DialogFooter>+ </DialogContent>+ </Dialog>++ <Dialog v-model:open="createDialogOpen">+ <DialogContent class="flex max-h-[90vh] max-w-4xl flex-col">+ <DialogHeader>+ <DialogTitle>{{ t("damengJobAdmin.newJob") }}{{ createKind === "legacy" ? "" : ` · ${createName}` }}</DialogTitle>+ </DialogHeader>+ <div class="grid min-h-0 gap-4 overflow-auto p-1 text-sm">+ <label class="grid gap-1.5"+ ><span>{{ t("nativeJobs.kind") }}</span+ ><select v-model="createKind" :aria-label="t('nativeJobs.createKind')" class="h-9 rounded border bg-background px-2" :disabled="nativeBusy">+ <option v-for="value in kinds" :key="value" :value="value">{{ t(`nativeJobs.kinds.${value}`) }}</option>+ </select></label+ >+ <label v-if="createKind !== 'dameng-native'" class="grid gap-1.5"+ ><span>{{ createKind === "legacy" ? "SCHEMA_USER" : t("nativeJobs.owner") }}</span+ ><Input v-model="createOwner" :aria-label="createKind === 'legacy' ? 'SCHEMA_USER' : t('nativeJobs.owner')" class="h-9"+ /></label>+ <label v-if="createKind !== 'legacy'" class="grid gap-1.5">+ <span>{{ t("damengJobAdmin.jobName") }}</span>+ <Input v-model="createName" :aria-label="t('damengJobAdmin.jobName')" class="h-9" />+ </label>+ <NativeJobDamengEditor v-if="createKind === 'dameng-native'" v-model="createDraft" :disabled="nativeBusy" />+ <NativeJobDefinitionEditor v-else :key="createKind" v-model="definitionCreateDraft" :engine="engine" :kind="createKind" :scope="context?.scope" :owner="createOwner" :disabled="nativeBusy" />+ </div>+ <p v-if="native.error.value" role="alert" class="text-sm text-destructive">{{ nativeError }}</p>+ <DialogFooter>+ <Button variant="outline" @click="createDialogOpen = false">{{ t("common.cancel") }}</Button>+ <Button :disabled="!canCreateJob" @click="previewCreateJob">{{ t("damengJobAdmin.previewSql") }}</Button>+ </DialogFooter>+ </DialogContent>+ </Dialog>++ <Dialog v-model:open="previewDialogOpen">+ <DialogContent class="max-w-3xl">+ <DialogHeader>+ <DialogTitle>{{ t("damengJobAdmin.sqlPreview") }}</DialogTitle>+ </DialogHeader>+ <pre class="max-h-[50vh] overflow-auto rounded-md border bg-muted/30 p-3 text-xs"><code>{{ previewText }}</code></pre>+ <p v-if="pendingNative && legacyRunRestoresScheduling" role="note" class="text-sm text-amber-700 dark:text-amber-400">{{ t("nativeJobs.legacyRunRestoresScheduling") }}</p>+ <p v-if="pendingNative && nativePreview?.target?.kind === 'scheduler' && nativePreview.steps.some((step) => step.id === 'pause')" role="note" class="text-sm text-muted-foreground">{{ t("nativeJobs.transitionPreviewHint") }}</p>+ <p v-if="pendingNative && previewExecution.error.value" role="alert" class="text-sm text-destructive">{{ nativeError }}</p>+ <DialogFooter>+ <Button variant="outline" @click="previewDialogOpen = false">{{ t("common.cancel") }}</Button>+ <Button :variant="pendingDanger ? 'destructive' : 'default'" :disabled="applying || confirmationBusy || !previewText" @click="applyPendingSql">+ <Loader2 v-if="applying || confirmationBusy" class="mr-1 h-3.5 w-3.5 animate-spin" />+ {{ t("damengJobAdmin.applySql") }}+ </Button>+ </DialogFooter>+ </DialogContent>+ </Dialog>+ </div>+</template>diff --git a/apps/desktop/src/components/admin/NativeJobArgumentValueEditor.vue b/apps/desktop/src/components/admin/NativeJobArgumentValueEditor.vuenew file mode 100644index 0000000000..925a97d15e--- /dev/null+++ b/apps/desktop/src/components/admin/NativeJobArgumentValueEditor.vue@@ -0,0 +1,108 @@+<script setup lang="ts">+import { computed } from "vue";+import { useI18n } from "vue-i18n";+import type { NativeJobValue } from "@/lib/database/nativeJobs";++const props = defineProps<{ disabled?: boolean; readonly?: boolean; anydata?: boolean; label: string }>();+const model = defineModel<NativeJobValue>({ required: true });+const { t } = useI18n();+const types = ["varchar2", "char", "nvarchar2", "nchar", "number", "date", "timestamp", "timestamp-tz", "timestamp-ltz", "interval-ym", "interval-ds", "raw", "binary-float", "binary-double", "urowid"];+const typeLabels: Record<string, string> = { "timestamp-tz": "TIMESTAMP WITH TIME ZONE", "timestamp-ltz": "TIMESTAMP WITH LOCAL TIME ZONE", "interval-ym": "INTERVAL YEAR TO MONTH", "interval-ds": "INTERVAL DAY TO SECOND", "binary-float": "BINARY_FLOAT", "binary-double": "BINARY_DOUBLE" };+const envelope = computed(() => {+ const value = model.value;+ return value && typeof value === "object" && !Array.isArray(value) && value.$dbx === "oracle-anydata-v1" ? value : undefined;+});+const type = computed(() => (envelope.value?.typeName === "SYS.NUMBER" ? "number" : typeof envelope.value?.scalarType === "string" ? envelope.value.scalarType : "text"));+const payload = computed(() => (envelope.value ? envelope.value.value : model.value));+const temporal = computed(() => ["date", "timestamp", "timestamp-tz", "timestamp-ltz"].includes(type.value));+const fields = computed(() => (payload.value && typeof payload.value === "object" && !Array.isArray(payload.value) ? payload.value : {}));+const clock = computed(() => {+ const seconds = fields.value.seconds;+ if (typeof seconds !== "string") return "";+ const match = /^(\d{1,5})(\.\d{1,9})?$/.exec(seconds);+ if (!match || BigInt(match[1]!) >= 86400n) return seconds;+ const whole = BigInt(match[1]!);+ return [whole / 3600n, (whole % 3600n) / 60n, whole % 60n].map((part) => part.toString().padStart(2, "0")).join(":") + (match[2] ?? "");+});+const locked = computed(() => props.disabled || props.readonly);+function setPayload(value: NativeJobValue) {+ if (locked.value) return;+ model.value = type.value === "text" ? value : { $dbx: "oracle-anydata-v1", scalarType: type.value, value };+}+function selectType(event: Event) {+ if (locked.value) return;+ const kind = (event.target as HTMLSelectElement).value;+ const value: NativeJobValue = ["date", "timestamp", "timestamp-tz", "timestamp-ltz"].includes(kind) ? { civilDate: "", seconds: "0", ...(kind === "timestamp-tz" ? { region: "+00:00", offset: "+00:00", abbreviation: null } : {}) } : "";+ model.value = kind === "text" ? "" : { $dbx: "oracle-anydata-v1", scalarType: kind, value };+}+function updateField(name: string, event: Event) {+ const value = (event.target as HTMLInputElement).value;+ const next = { ...fields.value, [name]: name === "abbreviation" && value === "" ? null : value };+ if (name === "civilDate") delete next.day;+ setPayload(next);+}+function updateClock(event: Event) {+ const value = (event.target as HTMLInputElement).value;+ const match = /^(\d{2}):(\d{2}):(\d{2})(\.\d{1,9})?$/.exec(value);+ const seconds = match && BigInt(match[1]!) < 24n && BigInt(match[2]!) < 60n && BigInt(match[3]!) < 60n ? (BigInt(match[1]!) * 3600n + BigInt(match[2]!) * 60n + BigInt(match[3]!)).toString() + (match[4] ?? "") : value;+ setPayload({ ...fields.value, seconds });+}+function setNull(event: Event) {+ if ((event.target as HTMLInputElement).checked) setPayload(null);+ else setPayload(temporal.value ? { civilDate: "", seconds: "0", ...(type.value === "timestamp-tz" ? { region: "+00:00", offset: "+00:00", abbreviation: null } : {}) } : "");+}+const valueLabel = computed(() => {+ const key = ({ "interval-ym": "scalarMonths", "interval-ds": "scalarNanoseconds", raw: "scalarHex", "binary-float": "scalarFloatHex", "binary-double": "scalarDoubleHex", urowid: "scalarUrowid" } as Record<string, string>)[type.value];+ return key ? t(`nativeJobs.${key}`) : props.label;+});+</script>++<template>+ <div class="grid gap-3">+ <label v-if="anydata || envelope" class="grid gap-1.5">+ <span>{{ t("nativeJobs.scalarStorage") }}</span>+ <select :value="type" class="h-9 rounded border bg-background px-2" :disabled="locked" @change="selectType">+ <option value="text">{{ t("nativeJobs.scalarText") }}</option>+ <option v-for="kind in types" :key="kind" :value="kind">ANYDATA · {{ typeLabels[kind] ?? kind.toUpperCase() }}</option>+ </select>+ </label>+ <label v-if="envelope" class="flex items-center gap-2">+ <input type="checkbox" :checked="payload === null" :disabled="locked" @change="setNull" />+ <span>{{ t("nativeJobs.scalarNull") }}</span>+ </label>+ <template v-if="payload !== null">+ <template v-if="temporal">+ <p v-if="type === 'timestamp-ltz'" class="text-muted-foreground">{{ t("nativeJobs.scalarUtc") }}</p>+ <div class="grid gap-3 sm:grid-cols-2">+ <label class="grid gap-1.5">+ <span>{{ t("nativeJobs.scalarCivilDate") }}</span>+ <input :value="fields.civilDate ?? ''" type="text" placeholder="2026-10-21" class="h-9 rounded border bg-background px-2 font-mono" :disabled="disabled" :readonly="readonly" @input="updateField('civilDate', $event)" />+ <span class="text-muted-foreground">{{ t("nativeJobs.scalarCivilHint") }}</span>+ </label>+ <label class="grid gap-1.5">+ <span>{{ t(type === "date" ? "nativeJobs.scalarDateClock" : "nativeJobs.scalarClock") }}</span>+ <input :value="clock" type="text" :placeholder="type === 'date' ? '12:34:56' : '12:34:56.123456789'" class="h-9 rounded border bg-background px-2 font-mono" :disabled="disabled" :readonly="readonly" @input="updateClock" />+ </label>+ <template v-if="type === 'timestamp-tz'">+ <label+ v-for="field in [+ { name: 'region', key: 'scalarRegion' },+ { name: 'offset', key: 'scalarOffset' },+ { name: 'abbreviation', key: 'scalarAbbreviation' },+ ]"+ :key="field.name"+ class="grid gap-1.5"+ >+ <span>{{ t(`nativeJobs.${field.key}`) }}</span>+ <input :value="fields[field.name] ?? ''" type="text" class="h-9 rounded border bg-background px-2 font-mono" :disabled="disabled" :readonly="readonly" @input="updateField(field.name, $event)" />+ </label>+ </template>+ </div>+ </template>+ <label v-else class="grid gap-1.5">+ <span>{{ valueLabel }}</span>+ <textarea :value="typeof payload === 'string' ? payload : JSON.stringify(payload)" :aria-label="label" class="min-h-20 rounded border bg-background p-2 font-mono text-sm" :disabled="disabled" :readonly="readonly" @input="setPayload(($event.target as HTMLTextAreaElement).value)" />+ </label>+ </template>+ </div>+</template>diff --git a/apps/desktop/src/components/admin/NativeJobDamengEditor.vue b/apps/desktop/src/components/admin/NativeJobDamengEditor.vuenew file mode 100644index 0000000000..07cf8667d9--- /dev/null+++ b/apps/desktop/src/components/admin/NativeJobDamengEditor.vue@@ -0,0 +1,172 @@+<script setup lang="ts">+import { computed, ref } from "vue";+import { useI18n } from "vue-i18n";+import { Button } from "@/components/ui/button";+import type { NativeJobDamengChildDraft, NativeJobDamengEditDraft, NativeJobDetails, NativeJobFieldChange, NativeJobRow, NativeJobValue } from "@/lib/database/nativeJobs";++const props = defineProps<{ details?: NativeJobDetails; disabled?: boolean }>();+const draft = defineModel<NativeJobDamengEditDraft>({ required: true });+const { t } = useI18n();+const section = ref<"attributes" | "steps" | "schedules">("attributes");+const selectedIndex = ref(0);+type Field = { name: string; type: "text" | "number" | "boolean" | "body"; nullable?: boolean };+const text = (name: string, nullable = false): Field => ({ name, type: "text", nullable });+const number = (name: string): Field => ({ name, type: "number" });+const flag = (name: string): Field => ({ name, type: "boolean" });+const fields = computed<Field[]>(() =>+ section.value === "attributes"+ ? [...(props.details ? [text("NAME")] : []), flag("ENABLE"), text("DESCRIBE", true), flag("ENABLE_EMAIL"), text("EMAIL_OPERATOR_NAME", true), number("EMAIL_TYPE"), flag("ENABLE_NETSEND"), text("NETSEND_OPERATOR_NAME", true), number("NETSEND_TYPE"), number("EP_SEQNO"), text("RAFT_NAME", true)]+ : section.value === "steps"+ ? [text("NAME"), number("TYPE"), { name: "COMMAND_INPUT", type: "body" }, number("SUCC_ACTION"), text("SUCC_NEXT_STEP", true), number("FAIL_ACTION"), text("FAIL_NEXT_STEP", true), number("RETRY_ATTEMPTS"), number("RETRY_INTERVAL"), flag("APPEND_FLAG"), text("DESCRIBE", true)]+ : [text("NAME"), flag("ENABLE"), number("TYPE"), number("FREQ_INTERVAL"), number("FREQ_SUB_INTERVAL"), number("FREQ_MINUTE_INTERVAL"), text("STARTTIME"), text("ENDTIME", true), text("DURING_START_DATE"), text("DURING_END_DATE", true), text("DESCRIBE", true)],+);++const metadata = computed(() => (section.value === "attributes" ? undefined : (props.details?.[section.value] ?? { status: "empty" as const })));+const readable = computed(() => (section.value === "attributes" ? !props.details || props.details.snapshot.definition.status === "available" : metadata.value?.status === "available" || metadata.value?.status === "empty"));+const entries = computed(() => {+ if (section.value === "attributes") return [];+ const changes = draft.value[section.value] ?? [];+ const existing = metadata.value?.status === "available" ? metadata.value.value : [];+ return [...existing.map((row) => ({ name: String(row.NAME), row, change: changes.find((change) => change.name === row.NAME && change.kind !== "add") })), ...changes.filter((change) => change.kind === "add").map((change) => ({ name: change.name, row: {} as NativeJobRow, change }))];+});+const selected = computed(() => entries.value[selectedIndex.value]);+const original = computed<NativeJobRow>(() => {+ if (section.value === "attributes") return !props.details ? { ENABLE: true, DESCRIBE: "", ENABLE_EMAIL: false, EMAIL_TYPE: 0, ENABLE_NETSEND: false, NETSEND_TYPE: 0, RAFT_NAME: null } : props.details.snapshot.definition.status === "available" ? props.details.snapshot.definition.value : {};+ if (selected.value?.change?.kind !== "add") return selected.value?.row ?? {};+ return section.value === "steps"+ ? { TYPE: 0, SUCC_ACTION: 1, FAIL_ACTION: 1, RETRY_ATTEMPTS: 0, RETRY_INTERVAL: 0, APPEND_FLAG: 0, DESCRIBE: null, SUCC_NEXT_STEP: null, FAIL_NEXT_STEP: null }+ : { ENABLE: 1, TYPE: 1, FREQ_INTERVAL: 1, FREQ_SUB_INTERVAL: 0, FREQ_MINUTE_INTERVAL: 0, STARTTIME: "00:00:00", ENDTIME: null, DURING_START_DATE: "CURDATE", DURING_END_DATE: null, DESCRIBE: null };+});+const changes = computed(() => (section.value === "attributes" ? (draft.value.attributes ?? {}) : (selected.value?.change?.attributes ?? {})));+const removed = computed(() => selected.value?.change?.kind === "drop");++function choose(value: typeof section.value) {+ section.value = value;+ selectedIndex.value = 0;+}+function childList(): NativeJobDamengChildDraft[] {+ if (section.value === "attributes") throw new Error("native_job_child_missing");+ if (!draft.value[section.value]) draft.value[section.value] = [];+ // Read through the model again so subsequent inserts and edits use Vue's reactive proxy.+ return draft.value[section.value]!;+}+function childDraft(): NativeJobDamengChildDraft {+ if (section.value === "attributes" || !selected.value) throw new Error("native_job_child_missing");+ const selectedEntry = selected.value;+ if (selectedEntry.change) return selectedEntry.change;+ const list = childList();+ list.push({ kind: "update", name: selectedEntry.name, attributes: {} });+ return list[list.length - 1]!;+}+function update(name: string, change: NativeJobFieldChange) {+ if (section.value === "attributes") {+ if (!draft.value.attributes) draft.value.attributes = {};+ draft.value.attributes[name] = change;+ } else {+ const child = childDraft();+ if (name === "NAME" && child.kind === "add" && change.kind === "set") child.name = String(change.value);+ else {+ if (!child.attributes) child.attributes = {};+ child.attributes[name] = change;+ }+ }+}+function value(name: string): NativeJobValue | undefined {+ if (name === "NAME" && selected.value?.change?.kind === "add") return selected.value.change.name;+ const change = changes.value[name];+ if (change?.kind === "clear") return null;+ if (change?.kind === "set") return change.value;+ if (name === "COMMAND_INPUT") return Number(original.value.TYPE) === 0 ? original.value.COMMAND : undefined;+ return original.value[name];+}+function input(field: Field, event: Event) {+ const target = event.target as HTMLInputElement;+ const next = field.type === "boolean" ? target.checked : field.type === "number" && target.value !== "" ? Number(target.value) : target.value;+ update(field.name, { kind: "set", value: typeof next === "number" && !Number.isFinite(next) ? "" : next });+}+function add() {+ if (section.value === "attributes") return;+ const list = childList();+ const stem = section.value === "steps" ? "STEP" : "SCHEDULE";+ let index = entries.value.length + 1;+ while (entries.value.some((entry) => entry.name.toUpperCase() === `${stem}_${index}`)) index++;+ list.push({ kind: "add", name: `${stem}_${index}`, attributes: section.value === "steps" ? { TYPE: { kind: "set", value: 0 } } : {} });+ selectedIndex.value = entries.value.length - 1;+}+function toggleDrop() {+ const child = childDraft();+ if (child.kind === "add" && section.value !== "attributes") {+ const list = draft.value[section.value]!;+ list.splice(list.indexOf(child), 1);+ selectedIndex.value = Math.max(0, selectedIndex.value - 1);+ } else child.kind = child.kind === "drop" ? "update" : "drop";+}+const backupInput = computed(() => section.value === "steps" && selected.value?.change?.kind !== "add" && Number(original.value.TYPE) !== 0);+function label(name: string) {+ return t(`nativeJobs.fields.${name}`);+}+function choices(name: string) {+ const group = name === "TYPE" ? (section.value === "steps" ? "stepTypes" : "scheduleTypes") : name === "SUCC_ACTION" || name === "FAIL_ACTION" ? "actions" : name === "EMAIL_TYPE" || name === "NETSEND_TYPE" ? "notificationTypes" : undefined;+ const count = group === "stepTypes" ? 7 : group === "scheduleTypes" ? 9 : group === "actions" ? 4 : 3;+ return group ? Array.from({ length: count }, (_, value) => ({ value, label: t(`nativeJobs.${group}.${value}`) })) : [];+}+</script>++<template>+ <div class="grid min-h-0 gap-4">+ <nav class="flex gap-1 border-b pb-2" :aria-label="t('nativeJobs.editSections')">+ <Button v-for="item in ['attributes', 'steps', 'schedules'] as const" :key="item" size="sm" :variant="section === item ? 'secondary' : 'ghost'" @click="choose(item)">{{ t(`nativeJobs.${item}`) }}</Button>+ </nav>+ <p v-if="!readable" role="status" class="rounded border border-amber-500/40 p-3 text-sm">{{ t("nativeJobs.partitionUnavailable", { status: metadata?.status ?? details?.snapshot.definition.status }) }}</p>+ <div v-if="section !== 'attributes'" class="flex flex-wrap items-center gap-2">+ <label class="grid min-w-48 flex-1 gap-1 text-sm">+ <span>{{ t(`nativeJobs.${section}`) }}</span>+ <select v-model.number="selectedIndex" :aria-label="t(`nativeJobs.${section}`)" class="h-9 rounded-md border bg-background px-2" :disabled="disabled || !readable">+ <option v-for="(entry, index) in entries" :key="index" :value="index">{{ entry.name }}{{ entry.change?.kind === "drop" ? ` · ${t("nativeJobs.pendingDrop")}` : "" }}{{ entry.change?.kind === "add" ? ` · ${t("nativeJobs.pendingAdd")}` : "" }}</option>+ </select>+ </label>+ <Button size="sm" variant="outline" :disabled="disabled || !readable" @click="add">{{ t("nativeJobs.add") }}</Button>+ <Button v-if="selected" size="sm" variant="outline" :disabled="disabled" @click="toggleDrop">{{ removed ? t("nativeJobs.undoDrop") : t("common.delete") }}</Button>+ </div>+ <div v-if="readable && (section === 'attributes' || selected)" class="grid gap-4 sm:grid-cols-2">+ <label v-for="field in fields" :key="field.name" class="grid content-start gap-1.5 text-sm" :class="field.type === 'body' ? 'sm:col-span-2' : ''">+ <span class="flex items-center gap-2">+ <span>{{ label(field.name) }}</span>+ <button v-if="changes[field.name] && changes[field.name]?.kind !== 'keep'" type="button" class="ml-auto text-xs text-primary hover:underline" :disabled="disabled || removed" @click.prevent="update(field.name, { kind: 'keep' })">{{ t("nativeJobs.keepOriginal") }}</button>+ <button v-if="field.nullable" type="button" class="text-xs text-muted-foreground hover:text-foreground" :disabled="disabled || removed" @click.prevent="update(field.name, { kind: 'clear' })">NULL</button>+ </span>+ <textarea+ v-if="field.type === 'body'"+ :value="String(value(field.name) ?? '')"+ :aria-label="label(field.name)"+ class="min-h-36 rounded-md border bg-background p-2 font-mono text-sm focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"+ :disabled="disabled || removed"+ @input="input(field, $event)"+ />+ <select v-else-if="choices(field.name).length" :value="value(field.name)" :aria-label="label(field.name)" class="h-9 rounded-md border bg-background px-2" :disabled="disabled || removed" @change="input(field, $event)">+ <option v-for="option in choices(field.name)" :key="option.value" :value="option.value">{{ option.label }}</option>+ </select>+ <input v-else-if="field.type === 'boolean'" type="checkbox" class="h-4 w-4" :aria-label="label(field.name)" :checked="value(field.name) === true || value(field.name) === 1 || value(field.name) === '1'" :disabled="disabled || removed" @change="input(field, $event)" />+ <input+ v-else+ :type="field.type"+ :value="value(field.name) ?? ''"+ :aria-label="label(field.name)"+ :placeholder="value(field.name) === null ? 'NULL' : ''"+ class="h-9 rounded-md border bg-background px-2 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"+ :disabled="disabled || removed"+ @input="input(field, $event)"+ />+ <span v-if="changes[field.name]?.kind === 'clear'" class="text-xs text-muted-foreground">{{ t("nativeJobs.explicitNull") }}</span>+ <span v-if="(field.name === 'EMAIL_OPERATOR_NAME' || field.name === 'NETSEND_OPERATOR_NAME') && !changes[field.name] && Number(original[field.name === 'EMAIL_OPERATOR_NAME' ? 'EMAIL_OPERID' : 'NETSEND_OPERID']) > 0" class="text-xs text-muted-foreground">{{+ t("nativeJobs.keepOperator", { id: original[field.name === "EMAIL_OPERATOR_NAME" ? "EMAIL_OPERID" : "NETSEND_OPERID"] })+ }}</span>+ <span v-if="field.name === 'SUCC_NEXT_STEP' || field.name === 'FAIL_NEXT_STEP'" class="text-xs text-muted-foreground">{{ t("nativeJobs.nextStepHint") }}</span>+ </label>+ <div v-if="backupInput" class="grid gap-2 sm:col-span-2">+ <p class="text-sm text-muted-foreground">{{ t("nativeJobs.generatedCommandHint") }}</p>+ <pre class="max-h-32 overflow-auto rounded border bg-muted/30 p-2 text-xs"><code>{{ original.COMMAND }}</code></pre>+ </div>+ </div>+ </div>+</template>diff --git a/apps/desktop/src/components/admin/NativeJobDefinitionEditor.vue b/apps/desktop/src/components/admin/NativeJobDefinitionEditor.vuenew file mode 100644index 0000000000..d6cf9cf493--- /dev/null+++ b/apps/desktop/src/components/admin/NativeJobDefinitionEditor.vue@@ -0,0 +1,569 @@+<script setup lang="ts">+import { computed, ref, shallowRef, watch } from "vue";+import { useI18n } from "vue-i18n";+import { Button } from "@/components/ui/button";+import type { NativeJobArgument, NativeJobArgumentValue, NativeJobDetails, NativeJobEngine, NativeJobFieldChange, NativeJobMetadata, NativeJobReferenceKind, NativeJobRow, NativeJobScope, NativeJobValue } from "@/lib/database/nativeJobs";+import { nativeJobReferences } from "@/lib/backend/api";+import {+ nativeJobArgumentBaseline,+ nativeJobDefinitionForEdit,+ nativeJobDestinationMode,+ nativeJobEventDraft,+ nativeJobProgramArgumentLayout,+ nativeJobScheduleMode,+ restoreNativeJobDefinitionDraft,+ selectNativeJobArgumentContext,+ type NativeJobDefinitionDraft,+ type NativeJobDestinationMode,+ type NativeJobEventDraft,+ type NativeJobScheduleMode,+} from "@/lib/database/nativeJobAdmin";+import NativeJobReferencePicker from "./NativeJobReferencePicker.vue";+import NativeJobArgumentValueEditor from "./NativeJobArgumentValueEditor.vue";++const props = defineProps<{ engine: NativeJobEngine; kind: "scheduler" | "legacy"; details?: NativeJobDetails; scope?: NativeJobScope; owner?: string; disabled?: boolean }>();+const draft = defineModel<NativeJobDefinitionDraft>({ required: true });+const { t } = useI18n();+const translatedFields = new Set([+ "ENABLED",+ "WHAT",+ "NEXT_DATE",+ "INTERVAL",+ "INSTANCE",+ "ZONE",+ "JOB_TYPE",+ "JOB_ACTION",+ "NUMBER_OF_ARGUMENTS",+ "PROGRAM_OWNER",+ "PROGRAM_NAME",+ "SCHEDULE_OWNER",+ "SCHEDULE_NAME",+ "START_DATE",+ "END_DATE",+ "REPEAT_INTERVAL",+ "AUTO_DROP",+ "COMMENTS",+ "LOG_USER",+ "PRIV_USER",+ "SCHEMA_USER",+ "JOB_CLASS",+ "JOB_PRIORITY",+ "MAX_RUNS",+ "MAX_FAILURES",+ "MAX_RUN_DURATION",+ "SCHEDULE_LIMIT",+ "RESTARTABLE",+ "STOP_ON_WINDOW_CLOSE",+ "STORE_OUTPUT",+ "ALLOW_RUNS_IN_RESTRICTED_MODE",+ "INSTANCE_STICKINESS",+ "FOLLOW_DEFAULT_TIMEZONE",+ "INSTANCE_ID",+ "JOB_WEIGHT",+ "RAISE_EVENTS",+ "CONNECT_CREDENTIAL_NAME",+ "CREDENTIAL_NAME",+ "DESTINATION_NAME",+ "DESTINATION",+ "JOB_STYLE",+ "LOGGING_LEVEL",+]);+function fieldLabel(name: string) {+ if (props.engine === "dameng" && name === "NAME") return t("nativeJobs.fields.NAME");+ if (props.engine === "dameng" && props.kind === "legacy" && name === "INTERVAL") return t("nativeJobs.damengInterval");+ if (props.engine === "oceanbase-oracle" && name === "INSTANCE_ID") return t("nativeJobs.definitionFields.ZONE");+ return translatedFields.has(name) ? t(`nativeJobs.definitionFields.${name}`) : name;+}+type EditorSection = "definition" | "arguments" | "advanced";+const section = ref<EditorSection>("definition");+const sections = computed<EditorSection[]>(() => (props.kind === "scheduler" ? ["definition", "arguments", "advanced"] : ["definition", "advanced"]));+type Field = { name: string; type: "text" | "body" | "number" | "boolean"; nullable?: boolean; readonly?: boolean };+const text = (name: string, nullable = false): Field => ({ name, type: "text", nullable });+const number = (name: string): Field => ({ name, type: "number" });+const flag = (name: string): Field => ({ name, type: "boolean" });+const original = computed<NativeJobRow>(() => {+ const definition = props.details && nativeJobDefinitionForEdit(props.engine, props.kind, props.details.snapshot.definition, props.details.legacyDefinition);+ return definition?.status === "available" ? definition.value : {};+});+const readable = computed(() => !props.details || props.details.snapshot.definition.status === "available");+const damengLegacyBodyReadable = computed(() => props.details?.legacyDefinition?.status === "available" && typeof props.details.legacyDefinition.value.WHAT === "string");+const damengLegacyDateReadable = computed(() => props.details?.legacyDefinition?.status === "available" && typeof props.details.legacyDefinition.value.NEXT_DATE === "string" && Object.prototype.hasOwnProperty.call(props.details.legacyDefinition.value, "NEXT_SEC"));+const canSwitchReferences = computed(() => props.engine === "oracle" && props.kind === "scheduler");+function canReplaceNamedReference(name: string): boolean {+ if (canSwitchReferences.value) return true;+ if (props.engine !== "dameng" || props.kind !== "scheduler" || !props.details) return false;+ const prefix = name.startsWith("PROGRAM_") ? "PROGRAM" : name.startsWith("SCHEDULE_") ? "SCHEDULE" : undefined;+ return !!prefix && ["OWNER", "NAME"].every((part) => typeof original.value[`${prefix}_${part}`] === "string" && !!original.value[`${prefix}_${part}`]);+}+const destinationMode = computed(() => nativeJobDestinationMode(draft.value, original.value));+function changeDestinationMode(event: Event) {+ draft.value.destinationMode = (event.target as HTMLSelectElement).value as NativeJobDestinationMode;+ draft.value.transitionRetained = true;+}+const triggerMode = computed(() => nativeJobScheduleMode(draft.value, original.value));+const eventInputs = computed(() => draft.value.eventDraft ?? nativeJobEventDraft(original.value));+const eventFields = computed<Array<{ name: keyof NativeJobEventDraft; label: string }>>(() => [+ { name: "condition", label: "eventCondition" },+ ...(triggerMode.value === "file-watcher"+ ? [+ { name: "watcherOwner" as const, label: "fileWatcherOwner" },+ { name: "watcherName" as const, label: "fileWatcherName" },+ ]+ : [+ { name: "queueOwner" as const, label: "eventQueueOwner" },+ { name: "queueName" as const, label: "eventQueueName" },+ { name: "agent" as const, label: "eventQueueAgent" },+ ]),+]);+function changeTriggerMode(event: Event) {+ draft.value.eventDraft ??= { ...eventInputs.value };+ draft.value.scheduleMode = (event.target as HTMLSelectElement).value as NativeJobScheduleMode;+ if (props.details) draft.value.transitionRetained = true;+}+function updateEvent(name: keyof NativeJobEventDraft, event: Event) {+ draft.value.eventDraft = { ...eventInputs.value, [name]: (event.target as HTMLInputElement).value };+ draft.value.scheduleMode = triggerMode.value;+ if (props.details) draft.value.transitionRetained = true;+}+function selectFileWatcher(reference: { owner: string; name: string }) {+ draft.value.eventDraft = { ...eventInputs.value, watcherOwner: reference.owner, watcherName: reference.name };+ draft.value.scheduleMode = "file-watcher";+ if (props.details) draft.value.transitionRetained = true;+}+const fields = computed<Field[]>(() => {+ if (props.kind === "legacy")+ return section.value === "definition"+ ? [+ ...(props.details && props.engine === "dameng" ? [text("NAME")] : []),+ ...(!props.details ? [flag("ENABLED")] : []),+ { name: "WHAT", type: "body", readonly: props.engine === "dameng" && !damengLegacyBodyReadable.value },+ { ...text("NEXT_DATE"), readonly: props.engine === "dameng" && !damengLegacyDateReadable.value },+ text("INTERVAL"),+ ...(props.engine === "oceanbase-oracle" ? [text("ZONE", true)] : [{ ...number("INSTANCE"), readonly: props.engine === "dameng" }]),+ ]+ : ["LOG_USER", "PRIV_USER", "SCHEMA_USER"].map((name) => ({ ...text(name), readonly: true }));+ if (section.value === "definition") {+ const definition: Field[] = [+ ...(!props.details || canSwitchReferences.value ? [flag("ENABLED")] : []),+ text("JOB_TYPE"),+ number("NUMBER_OF_ARGUMENTS"),+ { name: "JOB_ACTION", type: "body" },+ ...["PROGRAM_OWNER", "PROGRAM_NAME", "SCHEDULE_OWNER", "SCHEDULE_NAME"].map((name) => ({ ...text(name, props.engine !== "dameng" || !props.details), readonly: !!props.details && !canReplaceNamedReference(name) })),+ text("START_DATE", true),+ text("END_DATE", true),+ text("REPEAT_INTERVAL", true),+ flag("AUTO_DROP"),+ text("COMMENTS", true),+ ];+ return definition+ .filter((field) => !(props.engine === "oceanbase-oracle" && !props.details && ["SCHEDULE_OWNER", "SCHEDULE_NAME"].includes(field.name)) && !(canSwitchReferences.value && ["queue", "file-watcher"].includes(triggerMode.value) && ["SCHEDULE_OWNER", "SCHEDULE_NAME"].includes(field.name)))+ .map((field) => ({ ...field, readonly: field.readonly || (props.engine === "oceanbase-oracle" && !!props.details), nullable: field.nullable && !(props.engine === "oceanbase-oracle" && !!props.details) }));+ }+ const advanced = [+ text("JOB_CLASS"),+ number("JOB_PRIORITY"),+ number("MAX_RUNS"),+ number("MAX_FAILURES"),+ text("MAX_RUN_DURATION", props.engine !== "oceanbase-oracle"),+ text("SCHEDULE_LIMIT", true),+ flag("RESTARTABLE"),+ flag("STOP_ON_WINDOW_CLOSE"),+ flag("STORE_OUTPUT"),+ flag("ALLOW_RUNS_IN_RESTRICTED_MODE"),+ flag("INSTANCE_STICKINESS"),+ flag("FOLLOW_DEFAULT_TIMEZONE"),+ props.engine === "oceanbase-oracle" ? text("INSTANCE_ID") : number("INSTANCE_ID"),+ number("JOB_WEIGHT"),+ number("RAISE_EVENTS"),+ text("CONNECT_CREDENTIAL_NAME", true),+ ...(!props.details || canSwitchReferences.value ? [text("CREDENTIAL_NAME", true), text("DESTINATION_NAME", true)] : []),+ ...(props.details && canSwitchReferences.value && destinationMode.value === "legacy" ? [text("DESTINATION", true)] : []),+ ...(!props.details ? [text("JOB_STYLE")] : []),+ ];+ if (props.engine === "oracle") advanced.push(text("LOGGING_LEVEL"));+ return advanced+ .filter((field) => !(props.details && canSwitchReferences.value && destinationMode.value !== "named" && field.name === "DESTINATION_NAME") && (props.engine !== "oceanbase-oracle" || ["JOB_CLASS", "MAX_FAILURES", "MAX_RUN_DURATION", "INSTANCE_ID", "JOB_STYLE"].includes(field.name)))+ .map((field) => ({ ...field, readonly: props.engine === "dameng" && !!props.details && field.name !== "MAX_RUN_DURATION" }));+});+function value(name: string): NativeJobValue | undefined {+ if (name === "ENABLED" && props.details && props.kind === "scheduler" && draft.value.finalEnabled !== undefined) return draft.value.finalEnabled;+ const change = draft.value.attributes?.[name];+ if (change?.kind === "set") return change.value;+ if (change?.kind === "clear") return null;+ if (name === "DESTINATION" && props.details && original.value.DESTINATION_OWNER !== null) return null;+ if ((name === "PROGRAM_OWNER" || name === "SCHEDULE_OWNER") && !props.details) return props.owner;+ return original.value[name];+}+function editable(field: Field): boolean {+ if (props.kind === "scheduler") {+ if (value("PROGRAM_NAME") && ["JOB_TYPE", "JOB_ACTION", "NUMBER_OF_ARGUMENTS"].includes(field.name)) return false;+ if ((canSwitchReferences.value ? triggerMode.value === "named" : value("SCHEDULE_NAME")) && ["START_DATE", "END_DATE", "REPEAT_INTERVAL"].includes(field.name)) return false;+ if (canSwitchReferences.value && ["queue", "file-watcher"].includes(triggerMode.value) && field.name === "REPEAT_INTERVAL") return false;+ }+ return !props.disabled && readable.value && !field.readonly && (!props.details || Object.prototype.hasOwnProperty.call(original.value, field.name) || (canSwitchReferences.value && field.name === "DESTINATION_NAME" && Object.prototype.hasOwnProperty.call(original.value, "DESTINATION")));+}+function update(name: string, change: NativeJobFieldChange) {+ if (props.details && canSwitchReferences.value && ["DESTINATION", "DESTINATION_NAME"].includes(name)) {+ draft.value.destinationMode = change.kind === "clear" ? "local" : change.kind === "keep" ? nativeJobDestinationMode({}, original.value) : name === "DESTINATION" ? "legacy" : "named";+ draft.value.transitionRetained = true;+ if (change.kind === "clear") return;+ }+ if (props.details && props.kind === "scheduler" && name === "ENABLED" && change.kind === "set" && typeof change.value === "boolean") {+ draft.value.finalEnabled = change.value;+ return;+ }+ if (!draft.value.attributes) draft.value.attributes = {};+ draft.value.attributes[name] = change;+ if (canSwitchReferences.value && name === "SCHEDULE_NAME" && change.kind !== "keep") draft.value.scheduleMode = change.kind === "set" && change.value ? "named" : "inline";+ if (props.details && props.kind === "scheduler" && ["JOB_TYPE", "NUMBER_OF_ARGUMENTS"].includes(name) && change.kind !== "keep") {+ const changed = name === "NUMBER_OF_ARGUMENTS" && change.kind === "set" ? Number(change.value) !== Number(original.value[name]) : change.kind === "clear" ? original.value[name] !== null : change.value !== original.value[name];+ if (changed) draft.value.reconcileArguments = true;+ }+ if (+ props.details &&+ props.kind === "scheduler" &&+ (["PROGRAM_OWNER", "PROGRAM_NAME", "SCHEDULE_OWNER", "SCHEDULE_NAME", "CREDENTIAL_NAME", "CONNECT_CREDENTIAL_NAME", "DESTINATION", "DESTINATION_NAME"].includes(name) || (name === "JOB_ACTION" && value("JOB_TYPE") === "CHAIN")) &&+ change.kind !== "keep"+ )+ draft.value.transitionRetained = true;+}+function selectReference(prefix: "PROGRAM" | "SCHEDULE", reference: { owner: string; name: string }) {+ update(`${prefix}_OWNER`, { kind: "set", value: reference.owner });+ update(`${prefix}_NAME`, { kind: "set", value: reference.name });+}+const scheduleKind = computed<"schedule" | "window" | "window-group">(() => {+ const kind = draft.value.referenceKinds?.SCHEDULE_NAME ?? (original.value.SCHEDULE_TYPE === "WINDOW" ? "window" : original.value.SCHEDULE_TYPE === "WINDOW_GROUP" ? "window-group" : "schedule");+ return kind === "window" || kind === "window-group" ? kind : "schedule";+});+function changeScheduleKind(event: Event) {+ draft.value.referenceKinds ??= {};+ draft.value.referenceKinds.SCHEDULE_NAME = (event.target as HTMLSelectElement).value as NativeJobReferenceKind;+ const name = value("SCHEDULE_NAME");+ if (typeof name === "string" && name) update("SCHEDULE_NAME", { kind: "set", value: name });+}+function qualifiedReference(reference: { owner: string; name: string }) {+ const quoted = (value: string) => `"${value.replace(/"/g, '""')}"`;+ return `${quoted(reference.owner)}.${quoted(reference.name)}`;+}+function selectChain(reference: { owner: string; name: string }) {+ update("JOB_TYPE", { kind: "set", value: "CHAIN" });+ update("NUMBER_OF_ARGUMENTS", { kind: "set", value: 0 });+ update("JOB_ACTION", { kind: "set", value: qualifiedReference(reference) });+}+function referenceDisplay(value: NativeJobValue | undefined): string {+ if (value && typeof value === "object" && !Array.isArray(value) && typeof value.owner === "string" && typeof value.name === "string") return qualifiedReference({ owner: value.owner, name: value.name });+ return value === undefined || value === null ? "" : String(value);+}+function selectAdvancedReference(name: string, reference: { owner: string; name: string }, kind?: "destination-group") {+ update(name, { kind: "set", value: props.details ? { ...reference, ...(kind ? { kind } : {}) } : qualifiedReference(reference) });+}+function input(field: Field, event: Event) {+ const element = event.target as HTMLInputElement;+ const next = field.type === "boolean" ? element.checked : field.type === "number" && element.value !== "" ? Number(element.value) : element.value;+ update(field.name, { kind: "set", value: next });+}+const argumentMetadata = computed(() => props.details?.snapshot.arguments);+const creationProgram = shallowRef<NativeJobMetadata<NativeJobRow>>();+const creationProgramArguments = shallowRef<NativeJobMetadata<NativeJobRow[]>>();+const currentProgram = computed(() => !!props.details && value("PROGRAM_OWNER") === original.value.PROGRAM_OWNER && value("PROGRAM_NAME") === original.value.PROGRAM_NAME);+const program = computed(() => (currentProgram.value ? props.details?.program : creationProgram.value));+const programArguments = computed(() => (currentProgram.value ? props.details?.programArguments : creationProgramArguments.value));+function rememberProgramLayout() {+ if (!draft.value.argumentContext) return;+ const layout = nativeJobProgramArgumentLayout(program.value, programArguments.value);+ draft.value.argumentLayouts ??= {};+ if (layout.status === "available" || !draft.value.argumentLayouts[draft.value.argumentContext]) draft.value.argumentLayouts[draft.value.argumentContext] = layout;+}+watch(+ () => JSON.stringify([props.scope, props.details?.snapshot.revision, props.kind, value("PROGRAM_OWNER"), value("PROGRAM_NAME")]),+ async (_, __, onCleanup) => {+ let current = true;+ onCleanup(() => {+ current = false;+ });+ creationProgram.value = undefined;+ creationProgramArguments.value = undefined;+ const owner = value("PROGRAM_OWNER"),+ name = value("PROGRAM_NAME");+ if (props.kind === "scheduler") selectNativeJobArgumentContext(draft.value, typeof owner === "string" ? owner : "", typeof name === "string" ? name : undefined);+ if (props.kind !== "scheduler" || !props.scope || typeof owner !== "string" || !owner || typeof name !== "string" || !name) return;+ if (currentProgram.value) {+ rememberProgramLayout();+ return;+ }+ creationProgram.value = { status: "unknown", reason: "loading" };+ creationProgramArguments.value = { status: "unknown", reason: "loading" };+ const request = { scope: { ...props.scope }, schema: owner, name };+ await Promise.all([+ nativeJobReferences({ ...request, kind: "program", limit: 1 })+ .then((catalog) => {+ if (!current) return;+ creationProgram.value =+ catalog.objects.status === "available" && catalog.objects.value.length === 1+ ? { status: "available", value: catalog.objects.value[0]! }+ : catalog.objects.status === "available" || catalog.objects.status === "truncated"+ ? { status: "unknown", reason: "native_job_program_identity_unavailable" }+ : catalog.objects;+ })+ .catch(() => {+ if (current) creationProgram.value = { status: "error", reason: "native_job_reference_read_failed" };+ }),+ nativeJobReferences({ ...request, kind: "program-arguments", limit: 10_000 })+ .then((catalog) => {+ if (current) creationProgramArguments.value = catalog.objects;+ })+ .catch(() => {+ if (current) creationProgramArguments.value = { status: "error", reason: "native_job_reference_read_failed" };+ }),+ ]);+ if (current) rememberProgramLayout();+ },+ { immediate: true },+);+const programDefinition = computed(() => (program.value?.status === "available" ? program.value.value : undefined));+const creationProgramRows = computed<NativeJobArgument[]>(() => {+ if (!value("PROGRAM_NAME")) return [];+ const layout = draft.value.argumentLayouts?.[draft.value.argumentContext ?? ""] ?? nativeJobProgramArgumentLayout(program.value, programArguments.value);+ return layout.status === "available" ? layout.value : [];+});+const controlledArguments = computed(() => !!props.details && !!draft.value.reconcileArguments);+const argumentRows = computed<NativeJobArgument[]>(() => {+ if (props.details && !controlledArguments.value) return argumentMetadata.value?.status === "available" ? argumentMetadata.value.value : [];+ if (controlledArguments.value) {+ const count = Number(value("NUMBER_OF_ARGUMENTS"));+ const saved = draft.value.argumentLayouts?.inline;+ const inline =+ Number.isSafeInteger(count) && count >= 0 && count <= 255+ ? Array.from(+ { length: count },+ (_, index) => (saved?.status === "available" && saved.value.find((argument) => argument.position === index + 1)) || { position: index + 1, dataType: draft.value.argumentTypes?.[index + 1] ?? "VARCHAR2", value: { kind: "unset" } as NativeJobArgumentValue, editable: true },+ )+ : [];+ return nativeJobArgumentBaseline(draft.value, draft.value.argumentContext ?? "inline", value("PROGRAM_NAME") ? creationProgramRows.value : inline);+ }+ return [+ ...creationProgramRows.value,+ ...(draft.value.arguments ?? []).filter((argument) => !creationProgramRows.value.some((row) => row.position === argument.position)).map((argument) => ({ position: argument.position, dataType: draft.value.argumentTypes?.[argument.position] ?? "VARCHAR2", value: argument.value, editable: true })),+ ].sort((a, b) => a.position - b.position);+});+function argumentChange(argument: NativeJobArgument) {+ return draft.value.arguments?.find((change) => change.position === argument.position);+}+function argumentState(argument: NativeJobArgument) {+ return argumentChange(argument)?.value.kind ?? (props.details && !controlledArguments.value ? "keep" : argument.value.kind);+}+function argumentValue(argument: NativeJobArgument) {+ const changed = argumentChange(argument)?.value ?? argument.value;+ if (changed.kind !== "value") return "";+ const value = changed.value;+ if (value && typeof value === "object" && !Array.isArray(value) && value.$dbx === "oracle-anydata-v1") return value;+ return typeof value === "string" ? value : JSON.stringify(value);+}+function changeArgument(argument: NativeJobArgument, value: NativeJobArgumentValue | undefined) {+ if ((!props.details || controlledArguments.value) && value !== undefined && !draft.value.argumentTypes?.[argument.position]) {+ if (!draft.value.argumentTypes) draft.value.argumentTypes = {};+ draft.value.argumentTypes[argument.position] = argument.dataType;+ }+ if (!draft.value.arguments) draft.value.arguments = [];+ const index = draft.value.arguments.findIndex((change) => change.position === argument.position);+ if (value === undefined) {+ if (index >= 0) draft.value.arguments.splice(index, 1);+ } else if (index >= 0) draft.value.arguments[index] = { position: argument.position, value };+ else draft.value.arguments.push({ position: argument.position, value });+}+function changeArgumentState(argument: NativeJobArgument, event: Event) {+ const state = (event.target as HTMLSelectElement).value;+ if (state === "keep") changeArgument(argument, undefined);+ else if (state === "value") changeArgument(argument, { kind: "value", value: argumentValue(argument) });+ else if (state === "unset" || state === "inherit" || state === "null") changeArgument(argument, { kind: state });+}+function addArgument() {+ const positions = new Set(argumentRows.value.map((argument) => argument.position));+ let position = 1;+ while (positions.has(position)) position++;+ changeArgument({ position, dataType: "VARCHAR2", value: { kind: "unset" }, editable: true }, { kind: "unset" });+ if (!value("PROGRAM_NAME") && Number(value("NUMBER_OF_ARGUMENTS") ?? 0) < position) update("NUMBER_OF_ARGUMENTS", { kind: "set", value: position });+}+function displayArgument(value: NativeJobArgumentValue) {+ return value.kind === "value" || value.kind === "opaque" ? (typeof value.value === "string" ? value.value : JSON.stringify(value.value, null, 2)) : value.kind === "null" ? "NULL" : t(`nativeJobs.argumentStates.${value.kind}`);+}+function argumentType(argument: NativeJobArgument, event: Event) {+ if (!draft.value.argumentTypes) draft.value.argumentTypes = {};+ draft.value.argumentTypes[argument.position] = (event.target as HTMLInputElement).value;+}+function choices(name: string) {+ return name === "JOB_TYPE" ? (props.engine !== "oracle" ? ["PLSQL_BLOCK", "STORED_PROCEDURE"] : ["PLSQL_BLOCK", "STORED_PROCEDURE", "CHAIN", "EXECUTABLE", "EXTERNAL_SCRIPT", "SQL_SCRIPT", "BACKUP_SCRIPT"]) : name === "LOGGING_LEVEL" ? ["OFF", "RUNS", "FAILED RUNS", "FULL"] : [];+}+function choiceLabel(name: string, choice: string) {+ if (name === "JOB_TYPE" && choices(name).includes(choice)) return t(`nativeJobs.jobTypes.${choice}`);+ if (name === "LOGGING_LEVEL" && choices(name).includes(choice)) return t(`nativeJobs.loggingLevels.${choice.replace(/ /g, "_")}`);+ return choice;+}+</script>++<template>+ <div class="grid gap-4">+ <nav class="flex gap-1 border-b pb-2" :aria-label="t('nativeJobs.editSections')">+ <Button v-for="item in sections" :key="item" size="sm" :variant="section === item ? 'secondary' : 'ghost'" @click="section = item">{{ t(`nativeJobs.${item}`) }}</Button>+ </nav>+ <p v-if="!readable" role="status" class="rounded border border-amber-500/40 p-3 text-sm">{{ t("nativeJobs.partitionUnavailable", { status: details?.snapshot.definition.status }) }}</p>+ <p v-if="engine === 'oceanbase-oracle' && kind === 'scheduler' && details && section === 'definition'" role="status" class="text-sm text-muted-foreground">{{ t("nativeJobs.obSchedulerDefinitionReadOnly") }}</p>+ <div v-if="canSwitchReferences && section === 'definition'" class="flex flex-wrap items-end justify-between gap-3">+ <label class="grid gap-1.5 text-sm">+ <span>{{ t("nativeJobs.scheduleMode") }}</span>+ <select :value="triggerMode" :aria-label="t('nativeJobs.scheduleMode')" class="h-9 rounded border bg-background px-2" :disabled="disabled || !readable" @change="changeTriggerMode">+ <option value="inline">{{ t("nativeJobs.scheduleModes.inline") }}</option>+ <option value="named">{{ t("nativeJobs.scheduleModes.named") }}</option>+ <option value="queue">{{ t("nativeJobs.scheduleModes.queue") }}</option>+ <option value="file-watcher">{{ t("nativeJobs.scheduleModes.fileWatcher") }}</option>+ </select>+ </label>+ <Button v-if="details && draft.originalSnapshot" variant="outline" size="sm" :disabled="disabled || !readable" @click="restoreNativeJobDefinitionDraft(draft, details)">{{ t("nativeJobs.restoreDefinitionDraft") }}</Button>+ </div>+ <div v-if="value('PROGRAM_NAME') && section !== 'advanced'" class="grid gap-2 rounded border bg-muted/20 p-3 text-sm">+ <strong>{{ t("nativeJobs.referenceKinds.program") }} · {{ value("PROGRAM_OWNER") }} / {{ value("PROGRAM_NAME") }}</strong>+ <template v-if="programDefinition">+ <span>{{ choiceLabel("JOB_TYPE", String(programDefinition.PROGRAM_TYPE ?? "")) }} · {{ fieldLabel("NUMBER_OF_ARGUMENTS") }}: {{ programDefinition.NUMBER_OF_ARGUMENTS }}</span>+ <pre class="max-h-32 overflow-auto whitespace-pre-wrap break-words font-mono">{{ programDefinition.PROGRAM_ACTION }}</pre>+ </template>+ <p v-else-if="program" role="status" class="text-muted-foreground">{{ t("nativeJobs.partitionUnavailable", { status: program.status }) }}</p>+ </div>+ <template v-if="section === 'arguments'">+ <p v-if="argumentMetadata && argumentMetadata.status !== 'available' && argumentMetadata.status !== 'empty'" role="status" class="rounded border border-amber-500/40 p-3 text-sm">+ {{ engine === "oceanbase-oracle" && argumentMetadata.status === "unsupported" ? t("nativeJobs.argumentCatalogUnavailable") : t("nativeJobs.partitionUnavailable", { status: argumentMetadata.status }) }}+ </p>+ <p v-if="programArguments && programArguments.status !== 'available' && programArguments.status !== 'empty'" role="status" class="text-sm text-muted-foreground">{{ t("nativeJobs.programDefaultUnknown") }}</p>+ <Button v-if="(!details || controlledArguments) && !value('PROGRAM_NAME')" variant="outline" class="justify-self-start" :disabled="disabled" @click="addArgument">{{ t("nativeJobs.addArgument") }}</Button>+ <div v-for="argument in argumentRows" :key="argument.position" class="grid gap-3 rounded border p-3 text-sm">+ <div class="flex flex-wrap items-center gap-2">+ <strong>{{ t("nativeJobs.argumentPosition", { position: argument.position }) }}{{ argument.name ? ` · ${argument.name}` : "" }}</strong>+ <span v-if="!argument.metadataAttribute" class="text-muted-foreground">{{ t(`nativeJobs.argumentStates.${argumentChange(argument)?.value.kind ?? argument.value.kind}`) }}</span>+ <input+ v-if="(!details || controlledArguments) && !value('PROGRAM_NAME')"+ :value="draft.argumentTypes?.[argument.position] ?? argument.dataType"+ :aria-label="t('nativeJobs.argumentType', { position: argument.position })"+ class="ml-auto h-9 rounded border bg-background px-2"+ :disabled="disabled"+ @input="argumentType(argument, $event)"+ />+ <span v-else class="ml-auto text-muted-foreground">{{ argument.dataType }}</span>+ <Button v-if="!details && !value('PROGRAM_NAME')" variant="ghost" size="sm" :disabled="disabled" @click="changeArgument(argument, undefined)">{{ t("common.delete") }}</Button>+ </div>+ <select+ :value="argumentState(argument)"+ :aria-label="t('nativeJobs.argumentState', { position: argument.position })"+ class="h-9 rounded border bg-background px-2"+ :disabled="disabled || (!argument.editable && !(controlledArguments && argument.value.kind === 'opaque' && !argument.metadataAttribute))"+ @change="changeArgumentState(argument, $event)"+ >+ <option v-if="details && !controlledArguments" value="keep">{{ t("nativeJobs.keepOriginal") }}</option>+ <option v-if="argumentState(argument) === 'opaque'" value="opaque" disabled>{{ t("nativeJobs.argumentStates.opaque") }}</option>+ <option v-for="state in argument.editable ? ['unset', 'inherit', 'null', 'value'] : ['unset', 'inherit']" :key="state" :value="state">{{ t(`nativeJobs.argumentStates.${state}`) }}</option>+ </select>+ <NativeJobArgumentValueEditor+ v-if="argumentState(argument) === 'value' || (argumentState(argument) === 'keep' && argument.value.kind === 'value')"+ :model-value="argumentValue(argument)"+ :label="t('nativeJobs.argumentValue', { position: argument.position })"+ :anydata="engine === 'oracle' && String(value('JOB_STYLE') ?? '').toUpperCase() !== 'LIGHTWEIGHT'"+ :disabled="disabled"+ :readonly="!argument.editable || argumentState(argument) !== 'value'"+ @update:model-value="changeArgument(argument, { kind: 'value', value: $event })"+ />+ <pre v-if="argument.value.kind === 'opaque'" class="max-h-40 overflow-auto whitespace-pre-wrap rounded bg-muted/30 p-2 text-xs">{{ JSON.stringify(argument.value.value, null, 2) }}</pre>+ <div v-if="argument.defaultValue" class="grid gap-1 border-t pt-2">+ <span v-if="argument.defaultValue.status !== 'available' || argument.defaultValue.value.kind !== 'value'" class="text-muted-foreground">{{ t("nativeJobs.programDefault") }}</span>+ <NativeJobArgumentValueEditor v-if="argument.defaultValue.status === 'available' && argument.defaultValue.value.kind === 'value'" :model-value="argument.defaultValue.value.value" :label="t('nativeJobs.programDefault')" readonly />+ <pre v-else-if="argument.defaultValue.status === 'available'" class="max-h-32 overflow-auto whitespace-pre-wrap break-words font-mono">{{ displayArgument(argument.defaultValue.value) }}</pre>+ <span v-else class="text-muted-foreground">{{ t("nativeJobs.programDefaultUnknown") }}</span>+ </div>+ <p v-if="argument.metadataAttribute" class="text-muted-foreground">{{ t("nativeJobs.metadataArgument", { attribute: argument.metadataAttribute }) }}</p>+ <p v-else-if="!argument.editable" class="text-muted-foreground">{{ t("nativeJobs.opaqueArgument") }}</p>+ </div>+ </template>+ <div v-else-if="readable" class="grid gap-4 sm:grid-cols-2">+ <template v-for="field in fields" :key="field.name">+ <label v-if="details && canSwitchReferences && section === 'advanced' && field.name === 'CREDENTIAL_NAME'" class="grid justify-self-start gap-1.5 text-sm sm:col-span-2">+ <span>{{ t("nativeJobs.destinationMode") }}</span>+ <select :value="destinationMode" :aria-label="t('nativeJobs.destinationMode')" class="h-9 rounded border bg-background px-2" :disabled="disabled || !readable" @change="changeDestinationMode">+ <option v-for="mode in ['local', 'legacy', 'named']" :key="mode" :value="mode">{{ t(`nativeJobs.destinationModes.${mode}`) }}</option>+ </select>+ </label>+ <div class="grid content-start gap-1.5 text-sm" :class="field.type === 'body' ? 'sm:col-span-2' : ''">+ <span class="flex items-center gap-2">+ <span>{{ fieldLabel(field.name) }}</span>+ <button v-if="details && draft.attributes?.[field.name] && draft.attributes[field.name]?.kind !== 'keep'" type="button" class="ml-auto text-xs text-primary hover:underline" :disabled="!editable(field)" @click.prevent="update(field.name, { kind: 'keep' })">+ {{ t("nativeJobs.keepOriginal") }}+ </button>+ <button v-if="field.nullable" type="button" class="text-xs text-muted-foreground hover:text-foreground" :disabled="!editable(field)" @click.prevent="update(field.name, { kind: 'clear' })">NULL</button>+ </span>+ <textarea+ v-if="field.type === 'body'"+ :value="referenceDisplay(value(field.name))"+ :aria-label="fieldLabel(field.name)"+ class="min-h-36 rounded border bg-background p-2 font-mono text-sm focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"+ :disabled="!editable(field)"+ @input="input(field, $event)"+ />+ <select v-else-if="choices(field.name).length" :value="value(field.name)" :aria-label="fieldLabel(field.name)" class="h-9 rounded border bg-background px-2" :disabled="!editable(field)" @change="input(field, $event)">+ <option v-if="value(field.name) && !choices(field.name).includes(String(value(field.name)))" :value="value(field.name)">{{ value(field.name) }}</option>+ <option v-for="choice in choices(field.name)" :key="choice" :value="choice">{{ choiceLabel(field.name, choice) }}</option>+ </select>+ <input+ v-else-if="field.type === 'boolean'"+ type="checkbox"+ class="h-4 w-4"+ :checked="value(field.name) === true || value(field.name) === 1 || value(field.name) === '1' || value(field.name) === 'TRUE'"+ :aria-label="fieldLabel(field.name)"+ :disabled="!editable(field)"+ @change="input(field, $event)"+ />+ <input+ v-else+ :type="field.type"+ :value="referenceDisplay(value(field.name))"+ :placeholder="value(field.name) === null ? 'NULL' : ''"+ :aria-label="fieldLabel(field.name)"+ class="h-9 rounded border bg-background px-2 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"+ :disabled="!editable(field)"+ @input="input(field, $event)"+ />+ <span v-if="draft.attributes?.[field.name]?.kind === 'clear'" class="text-xs text-muted-foreground">{{ t("nativeJobs.explicitNull") }}</span>+ <span v-if="engine === 'dameng' && kind === 'legacy' && field.name === 'INTERVAL'" class="text-sm text-muted-foreground">{{ t("nativeJobs.damengIntervalHint") }}</span>+ <span v-if="details && field.name === 'ENABLED'" class="text-sm text-muted-foreground">{{ t("nativeJobs.finalEnabledHint") }}</span>+ <span v-if="(!details || canSwitchReferences) && ((field.name === 'PROGRAM_NAME' && value('PROGRAM_NAME')) || (field.name === 'SCHEDULE_NAME' && value('SCHEDULE_NAME') && triggerMode === 'named'))" class="text-xs text-muted-foreground">{{ t("nativeJobs.inactiveInlineDraft") }}</span>+ <NativeJobReferencePicker v-if="(!details || canReplaceNamedReference(field.name)) && field.name === 'PROGRAM_NAME'" :scope="scope" kind="program" :disabled="disabled" @select="selectReference('PROGRAM', $event)" />+ <select+ v-if="details && canSwitchReferences && field.name === 'SCHEDULE_NAME'"+ :value="scheduleKind"+ :aria-label="t('nativeJobs.chooseReference', { kind: t('nativeJobs.referenceKinds.schedule') })"+ class="h-9 rounded border bg-background px-2"+ :disabled="disabled"+ @change="changeScheduleKind"+ >+ <option value="schedule">{{ t("nativeJobs.referenceKinds.schedule") }}</option>+ <option value="window">{{ t("nativeJobs.referenceKinds.window") }}</option>+ <option value="window-group">{{ t("nativeJobs.referenceKinds.window-group") }}</option>+ </select>+ <NativeJobReferencePicker v-if="(!details || canReplaceNamedReference(field.name)) && field.name === 'SCHEDULE_NAME'" :scope="scope" :kind="engine === 'dameng' ? 'schedule' : scheduleKind" :disabled="disabled" @select="selectReference('SCHEDULE', $event)" />+ <NativeJobReferencePicker v-if="(!details || canSwitchReferences) && field.name === 'JOB_ACTION' && value('JOB_TYPE') === 'CHAIN' && engine !== 'dameng'" :scope="scope" kind="chain" :disabled="disabled" @select="selectChain" />+ <NativeJobReferencePicker+ v-if="(!details || canSwitchReferences) && ['CREDENTIAL_NAME', 'CONNECT_CREDENTIAL_NAME', 'DESTINATION_NAME'].includes(field.name) && engine !== 'dameng'"+ :scope="scope"+ :kind="field.name === 'DESTINATION_NAME' ? 'destination' : 'credential'"+ :disabled="disabled"+ @select="selectAdvancedReference(field.name, $event)"+ />+ <NativeJobReferencePicker v-if="details && canSwitchReferences && field.name === 'DESTINATION_NAME'" :scope="scope" kind="destination-group" :disabled="disabled" @select="selectAdvancedReference(field.name, $event, 'destination-group')" />+ </div>+ </template>+ <template v-if="canSwitchReferences && section === 'definition' && (triggerMode === 'queue' || triggerMode === 'file-watcher')">+ <label v-for="field in eventFields" :key="field.name" class="grid content-start gap-1.5 text-sm" :class="field.name === 'condition' ? 'sm:col-span-2' : ''">+ <span>{{ t(`nativeJobs.${field.label}`) }}</span>+ <textarea v-if="field.name === 'condition'" :value="eventInputs[field.name]" :aria-label="t(`nativeJobs.${field.label}`)" class="min-h-24 rounded border bg-background p-2 font-mono text-sm" :disabled="disabled" @input="updateEvent(field.name, $event)" />+ <input v-else :value="eventInputs[field.name]" :aria-label="t(`nativeJobs.${field.label}`)" class="h-9 rounded border bg-background px-2" :disabled="disabled" @input="updateEvent(field.name, $event)" />+ <NativeJobReferencePicker v-if="field.name === 'watcherName'" :scope="scope" kind="file-watcher" :disabled="disabled" @select="selectFileWatcher" />+ </label>+ </template>+ </div>+ </div>+</template>diff --git a/apps/desktop/src/components/admin/NativeJobReferencePicker.vue b/apps/desktop/src/components/admin/NativeJobReferencePicker.vuenew file mode 100644index 0000000000..6e8cf11202--- /dev/null+++ b/apps/desktop/src/components/admin/NativeJobReferencePicker.vue@@ -0,0 +1,111 @@+<script setup lang="ts">+import { computed, ref, shallowRef, watch } from "vue";+import { useI18n } from "vue-i18n";+import { Button } from "@/components/ui/button";+import { Input } from "@/components/ui/input";+import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/components/ui/dialog";+import * as api from "@/lib/backend/api";+import type { NativeJobReferenceCatalog, NativeJobReferenceKind, NativeJobRow, NativeJobScope } from "@/lib/database/nativeJobs";++const props = defineProps<{ scope?: NativeJobScope; kind: Exclude<NativeJobReferenceKind, "program-arguments" | "destination-group-members">; disabled?: boolean }>();+const emit = defineEmits<{ select: [reference: { owner: string; name: string; metadata: NativeJobRow }] }>();+const { t } = useI18n();+const open = ref(false);+const filter = ref("");+const owner = ref("");+const offset = ref(0);+const loading = ref(false);+const failed = ref(false);+const catalog = shallowRef<NativeJobReferenceCatalog>();+const pageSize = 100;+let requestId = 0;+const scopeKey = computed(() => JSON.stringify([props.scope?.connectionId, props.scope?.database, props.scope?.contextId, props.kind]));+const rows = computed(() => (catalog.value?.objects.status === "available" || catalog.value?.objects.status === "truncated" ? catalog.value.objects.value : []));+const title = computed(() => t("nativeJobs.chooseReference", { kind: t(`nativeJobs.referenceKinds.${props.kind}`) }));++async function load(nextOffset = 0) {+ if (!props.scope || props.disabled || !open.value) return;+ const id = ++requestId;+ const key = scopeKey.value;+ loading.value = true;+ failed.value = false;+ catalog.value = undefined;+ offset.value = nextOffset;+ try {+ const result = await api.nativeJobReferences({ scope: { ...props.scope }, kind: props.kind, schema: owner.value || undefined, filter: filter.value, offset: nextOffset, limit: pageSize });+ if (id === requestId && key === scopeKey.value && open.value) catalog.value = result;+ } catch {+ if (id === requestId && key === scopeKey.value && open.value) failed.value = true;+ } finally {+ if (id === requestId) loading.value = false;+ }+}+function select(row: NativeJobRow) {+ if (loading.value || props.disabled || !props.scope || !open.value) return;+ if (typeof row.DBX_OWNER !== "string" || typeof row.DBX_NAME !== "string") return;+ emit("select", { owner: row.DBX_OWNER, name: row.DBX_NAME, metadata: row });+ open.value = false;+}+watch(+ scopeKey,+ () => {+ ++requestId;+ open.value = false;+ catalog.value = undefined;+ filter.value = "";+ owner.value = "";+ loading.value = false;+ failed.value = false;+ },+ { flush: "sync" },+);+watch(open, (value) => {+ if (value) void load();+ else {+ ++requestId;+ loading.value = false;+ catalog.value = undefined;+ }+});+</script>++<template>+ <Button type="button" variant="outline" size="sm" :disabled="disabled || !scope" @click="open = true">{{ title }}</Button>+ <Dialog v-model:open="open">+ <DialogContent class="flex max-h-[80vh] max-w-2xl flex-col gap-4 overflow-hidden">+ <DialogHeader+ ><DialogTitle>{{ title }}</DialogTitle></DialogHeader+ >+ <form class="grid gap-2 sm:grid-cols-[1fr_1fr_auto]" @submit.prevent="load()">+ <Input v-model="owner" :aria-label="t('nativeJobs.ownerFilter')" :placeholder="t('nativeJobs.ownerFilter')" :disabled="loading" />+ <Input v-model="filter" :aria-label="t('nativeJobs.referenceFilter')" :placeholder="t('nativeJobs.referenceFilter')" :disabled="loading" />+ <Button type="submit" variant="secondary" :disabled="loading || disabled">{{ t("common.refresh") }}</Button>+ </form>+ <p v-if="loading" role="status" class="py-6 text-center text-sm text-muted-foreground">{{ t("common.loading") }}</p>+ <p v-else-if="failed" role="alert" class="text-sm text-destructive">{{ t("damengJobAdmin.loadFailed") }}</p>+ <template v-else-if="catalog">+ <p v-if="catalog.source.source" class="text-xs text-muted-foreground">{{ catalog.source.source }} · {{ t(`nativeJobs.catalogCoverage.${catalog.source.coverage ?? "unknown"}`) }}</p>+ <p v-if="catalog.objects.status === 'empty'" role="status" class="py-6 text-center text-sm text-muted-foreground">{{ t("nativeJobs.emptyReferences") }}</p>+ <p v-else-if="catalog.objects.status !== 'available' && catalog.objects.status !== 'truncated'" role="status" class="rounded border border-amber-500/40 p-3 text-sm">{{ t("nativeJobs.referenceCatalogUnavailable", { status: catalog.objects.status }) }}</p>+ <div v-else class="min-h-0 overflow-auto rounded border" role="group" :aria-label="title">+ <button+ v-for="row in rows"+ :key="JSON.stringify([row.DBX_OWNER, row.DBX_NAME])"+ type="button"+ data-native-reference+ class="grid w-full grid-cols-[minmax(6rem,1fr)_minmax(0,2fr)] gap-3 border-b px-3 py-2 text-left text-sm last:border-b-0 hover:bg-accent focus-visible:bg-accent focus-visible:outline-none"+ :disabled="disabled"+ @click="select(row)"+ >+ <span class="break-all text-muted-foreground">{{ row.DBX_OWNER }}</span+ ><span class="break-all font-mono">{{ row.DBX_NAME }}</span>+ </button>+ </div>+ <div class="flex justify-end gap-2">+ <Button type="button" variant="outline" size="sm" :disabled="offset === 0 || loading || disabled" @click="load(Math.max(0, offset - pageSize))">{{ t("nativeJobs.previousPage") }}</Button>+ <Button type="button" variant="outline" size="sm" :disabled="catalog.objects.status !== 'truncated' || loading || disabled" @click="load(offset + pageSize)">{{ t("nativeJobs.nextPage") }}</Button>+ </div>+ </template>+ </DialogContent>+ </Dialog>+</template>diff --git a/apps/desktop/src/components/layout/ContentArea.vue b/apps/desktop/src/components/layout/ContentArea.vueindex 876ec51e99..7d6c13a3b1 100644--- a/apps/desktop/src/components/layout/ContentArea.vue+++ b/apps/desktop/src/components/layout/ContentArea.vue@@ -82,7 +82,10 @@ import ResultSetNavigator from "@/components/layout/ResultSetNavigator.vue";import QueryResultViewSwitcher from "@/components/layout/QueryResultViewSwitcher.vue";import ProductionWatermark from "@/components/common/ProductionWatermark.vue";import ObjectDependenciesPanel from "@/components/objects/ObjectDependenciesPanel.vue";-import { objectDependencyTarget, isObjectDependencySection, type ObjectDependencyTarget, type ObjectDetailsSection } from "@/lib/database/objectDependencyDetails";+import OracleTriggerStatus from "@/components/objects/OracleTriggerStatus.vue";+import type { OracleTriggerSnapshot, OracleTriggerTarget, OracleTriggerExecutionResult } from "@/lib/database/oracleTriggerPlan";+const OracleInvalidObjectsDialog = defineAsyncComponent(() => import("@/components/objects/OracleInvalidObjectsDialog.vue"));+import { objectDependencyTarget, type ObjectDependencyTarget, type ObjectDetailsSection } from "@/lib/database/objectDependencyDetails";import DataGridFreezeFirstColumnControl from "@/components/grid/DataGridFreezeFirstColumnControl.vue";import DataGridStatusSqlControl from "@/components/grid/DataGridStatusSqlControl.vue";import type { DataGridSqlPreview } from "@/components/grid/dataGridSqlPreview";@@ -152,6 +155,7 @@ const MySqlDashboard = defineAsyncComponent(() => import("@/components/admin/MySconst PostgresDashboard = defineAsyncComponent(() => import("@/components/admin/PostgresDashboard.vue"));const XuguServerDashboard = defineAsyncComponent(() => import("@/components/admin/XuguServerDashboard.vue"));const DamengJobAdmin = defineAsyncComponent(() => import("@/components/admin/DamengJobAdmin.vue"));+const DatabaseJobAdmin = defineAsyncComponent(() => import("@/components/admin/DatabaseJobAdmin.vue"));const DamengUserAdmin = defineAsyncComponent(() => import("@/components/admin/DamengUserAdmin.vue"));const DamengRoleAdmin = defineAsyncComponent(() => import("@/components/admin/DamengRoleAdmin.vue"));@@ -217,7 +221,7 @@ import { analyzeEditableQuery } from "@/lib/sql/sqlAnalysis";import { loadQueryResultTransferSourceDdl } from "@/components/transfer/queryResultTransferSource";import { sqlObjectNavigationTypeFromTableType } from "@/lib/sql/sqlNavigation";import type { CustomSaveHandler } from "@/composables/useDataGridEditor";-import type { QueryMessage, QueryResult, QueryTab, RedisResultViewMode, TableInfoTab, TabOutputView, TreeNode, VectorCollectionMeta } from "@/types/database";+import type { QueryMessage, QueryResult, QueryTab, RedisResultViewMode, TableInfoTab, TableStructureEditorDraft, TabOutputView, TreeNode, VectorCollectionMeta } from "@/types/database";import type { SqlObjectNavigationTarget } from "@/lib/sql/sqlNavigation";import { sqlFormatDialectForDbType, type SqlFormatDialect } from "@/lib/sql/sqlFormatter";import { productionContextForDatabase } from "@/lib/database/productionSafety";@@ -293,6 +297,10 @@ const { t } = useI18n();const queryStore = useQueryStore();const connectionStore = useConnectionStore();const productionSafetyStore = useProductionSafetyStore();+function updateStructureDraft(draft: TableStructureEditorDraft | undefined, originTabId?: string) {+ const tab = originTabId === undefined ? props.activeTab : queryStore.tabs.find((item) => item.id === originTabId);+ if (tab?.mode === "structure") tab.structureDraft = draft;+}/** Clear a consumed editor reveal request so a later normal tab re-visit doesn't re-jump. */function clearEditorRevealRequest(tab: { editorRevealRequest?: unknown }): void {if (tab.editorRevealRequest !== undefined) {@@ -448,13 +456,49 @@ const activeObjectDependencyTarget = computed(() => {const tab = props.activeTab;const details = tab.objectDetails;if (!details || details.connectionId !== tab.connectionId || details.database !== tab.database || details.schema !== (tab.schema || tab.database) || (details.catalog || "") !== (tab.catalog || "")) return undefined;- return objectDependencyTarget(details, effectiveDatabaseTypeForConnection(connectionStore.getConfig(details.connectionId)));+ return objectDependencyTarget(details, effectiveDatabaseTypeForConnection(connectionStore.getConfig(details.connectionId)), queryStore.oracleTriggerSourceState(tab.id)?.profile);});const activeObjectSection = computed<ObjectDetailsSection>(() => (activeObjectDependencyTarget.value ? props.activeTab.objectDetails?.section || "source" : "source"));-const sourceSectionActive = computed(() => !isObjectDependencySection(props.activeTab));+const sourceSectionActive = computed(() => activeObjectSection.value === "source");+const retainTriggerSourceEditor = computed(() => props.activeTab.objectSource?.objectType === "TRIGGER" && !!queryStore.oracleTriggerSourceState(props.activeTab.id));+const triggerDiagnosticOpen = ref(false);+const triggerDiagnosticContext = ref<{ target: Readonly<OracleTriggerTarget>; expectedObjectId?: string; originTabId: string; originRevision?: number }>();+const triggerDiagnosticConnection = computed(() => (triggerDiagnosticContext.value ? connectionStore.getConfig(triggerDiagnosticContext.value.target.connectionId) : undefined));+watch(+ () => props.activeTab.id,+ () => {+ triggerDiagnosticOpen.value = false;+ },+);+function openTriggerSourceDiagnostics() {+ const snapshot = queryStore.oracleTriggerSourceState(props.activeTab.id)?.baseline;+ if (!snapshot?.exists) return;+ triggerDiagnosticContext.value = { target: snapshot.target, expectedObjectId: snapshot.metadata.objectId ?? undefined, originTabId: props.activeTab.id, originRevision: queryStore.oracleTriggerSourceState(props.activeTab.id)?.readVersion };+ triggerDiagnosticOpen.value = true;+}+function returnFromTriggerSourceDiagnostics(object: { owner: string; name: string; objectId?: string }, location?: { line: number; position: number }) {+ const context = triggerDiagnosticContext.value;+ if (!context || context.originTabId !== props.activeTab.id || context.target.owner !== object.owner || context.target.name !== object.name) return;+ triggerDiagnosticOpen.value = false;+ setObjectSection("source");+ if (location && !queryStore.revealOracleTriggerSourceError(context.originTabId, location, object.objectId)) toast(t("oracleTrigger.errorPositionUnavailable"), 3000);+}+function acceptTriggerSourceDiagnosticResult(_target: Readonly<OracleTriggerTarget>, result: OracleTriggerExecutionResult, before: OracleTriggerSnapshot, originTabId?: string, originRevision?: number) {+ if (originTabId) queryStore.acceptOracleTriggerDiagnosticResult(originTabId, result, before, originRevision);+}function setObjectSection(section: ObjectDetailsSection) {if (props.activeTab.objectDetails) props.activeTab.objectDetails.section = section;}+function openTriggerSourceParent() {+ const snapshot = queryStore.oracleTriggerSourceState(props.activeTab.id)?.baseline;+ const parent = snapshot?.metadata.parent;+ if (!snapshot || !parent) return;+ emit(+ "openDependencyObject",+ { connectionId: snapshot.target.connectionId, database: snapshot.target.database, schema: snapshot.target.owner, catalog: snapshot.target.catalog, name: snapshot.target.name, objectType: "TRIGGER" },+ { name: parent.name, schema: parent.owner, type: parent.objectType === "VIEW" ? "view" : "table", nameQuoted: true, schemaQuoted: true },+ );+}function viewObjectDependencySql(context: ObjectDependencyTarget, sql: string) {queryStore.createTab(context.connectionId, context.database, t("objectDependencies.viewSql"), "query", context.schema, sql, context.catalog, { forceNew: true });}@@ -2101,6 +2145,17 @@ defineExpose({<template><div class="production-session-shell flex flex-col min-h-0" :class="[resultOnly ? 'h-full' : 'flex-1', { 'production-session-shell--active': activeProductionContext.active }]">+ <OracleInvalidObjectsDialog+ v-if="!resultOnly && triggerDiagnosticContext && triggerDiagnosticConnection"+ :open="triggerDiagnosticOpen && triggerDiagnosticContext.originRevision === queryStore.oracleTriggerSourceState(triggerDiagnosticContext.originTabId)?.readVersion"+ :connection="triggerDiagnosticConnection"+ :database="triggerDiagnosticContext.target.database"+ :schema="triggerDiagnosticContext.target.owner"+ :trigger-context="triggerDiagnosticContext"+ @update:open="triggerDiagnosticOpen = $event"+ @open-source="returnFromTriggerSourceDiagnostics"+ @trigger-result="acceptTriggerSourceDiagnosticResult"+ /><div v-if="activeProductionContext.active" class="production-session-strip flex h-7 shrink-0 items-center gap-2 border-b border-red-500/35 bg-red-500/10 px-3 text-xs font-semibold text-red-800 shadow-[inset_0_1px_0_rgb(239_68_68_/_0.28)] dark:text-red-200"><ShieldAlert class="h-3.5 w-3.5 shrink-0" aria-hidden="true" /><span class="font-mono uppercase tracking-normal">{{ t("production.title") }}</span>@@ -2131,11 +2186,27 @@ defineExpose({</div><ProductionWatermark v-if="activeProductionContext.active" /><ObjectDependenciesPanel :target="activeObjectDependencyTarget" :section="activeObjectSection" @update:section="setObjectSection" @view-sql="viewObjectDependencySql" @open-object="(context, target) => emit('openDependencyObject', context, target)">+ <OracleTriggerStatus+ v-if="queryStore.oracleTriggerSourceState(activeTab.id)"+ :snapshot="queryStore.oracleTriggerSourceState(activeTab.id)?.baseline"+ :result="queryStore.oracleTriggerSourceState(activeTab.id)?.result"+ :source-issue="queryStore.oracleTriggerSourceState(activeTab.id)?.error"+ :busy="queryStore.oracleTriggerSourceState(activeTab.id)?.busy"+ @action="queryStore.runOracleTriggerSourceAction(activeTab.id, $event)"+ @refresh="queryStore.refreshObjectSourceTab(activeTab.id)"+ @parent="openTriggerSourceParent"+ @diagnostics="openTriggerSourceDiagnostics"+ /><!-- issue #9035:源码 tab 先出现再加载。pending 期间不挂载编辑器(还没有内容可编辑,也省下一次 Monaco 初始化),失败则就地重试。issue #9387:DDL 新标签同样先出 tab 再加载,失败就地显示错误。 -->- <QueryLoadingState v-if="activeTab.sourceLoad && !activeTab.sourceLoad.error" class="relative z-0 flex-1" :elapsed-seconds="sourceLoadElapsedSeconds" />- <div v-else-if="activeTab.sourceLoad?.error" class="relative z-0 flex flex-1 min-h-0 flex-col items-center justify-center gap-3 px-6 text-sm" data-object-source-load-error>+ <div v-if="retainTriggerSourceEditor && activeTab.sourceLoad" class="flex shrink-0 items-center gap-2 px-3 py-2 text-sm" data-object-source-refresh-state>+ <Loader2 v-if="!activeTab.sourceLoad.error" class="h-4 w-4 animate-spin" />+ <p v-if="activeTab.sourceLoad.error" class="min-w-0 flex-1 break-words text-destructive">{{ activeTab.sourceLoad.error }}</p>+ <Button v-if="activeTab.sourceLoad.error" variant="outline" size="sm" @click="queryStore.retryObjectSourceTab(activeTab.id)">{{ t("common.retry") }}</Button>+ </div>+ <QueryLoadingState v-if="activeTab.sourceLoad && !activeTab.sourceLoad.error && !retainTriggerSourceEditor" class="relative z-0 flex-1" :elapsed-seconds="sourceLoadElapsedSeconds" />+ <div v-else-if="activeTab.sourceLoad?.error && !retainTriggerSourceEditor" class="relative z-0 flex flex-1 min-h-0 flex-col items-center justify-center gap-3 px-6 text-sm" data-object-source-load-error><p class="max-w-[80%] text-center break-words text-destructive">{{ activeTab.sourceLoad.error }}</p><Button variant="outline" size="sm" class="gap-1.5" @click="queryStore.retryObjectSourceTab(activeTab.id)"><RotateCcw class="h-4 w-4" />@@ -3743,8 +3814,8 @@ defineExpose({if (activeTab.objectPropertiesRequest?.requestId === id) activeTab.objectPropertiesRequest = undefined;}"- @open-dependency-object="(context, target) => emit('openDependencyObject', context, target)"@open-table="emit('openObjectTable', activeTab.id, $event)"+ @open-dependency-object="(context, target) => emit('openDependencyObject', context, target)"@locate-table="onLocateObjectTable"@schema-change="emit('objectSchemaChange', activeTab.id, $event)"@viewport-change="emit('objectBrowserViewportChange', activeTab.id, $event)"@@ -3766,14 +3837,15 @@ defineExpose({:catalog="activeTab.catalog":schema="activeTab.schema":table-name="activeTab.structureTableName || ''"+ :origin-tab-id="activeTab.id":table-type="activeTab.structureTableType":exact-identity="activeTab.structureExactIdentity":initial-tab="activeTab.structureInitialTab":initial-tab-request-id="activeTab.structureInitialTabRequestId":initial-target="activeTab.structureInitialTarget":draft="activeTab.structureDraft"- @update:draft="(draft) => (activeTab.structureDraft = draft)"- @saved="(commentChanged, createdTableName) => emit('structureEditorSaved', activeTab.id, commentChanged, createdTableName)"+ @update:draft="updateStructureDraft"+ @saved="(commentChanged, createdTableName, originTabId) => emit('structureEditorSaved', originTabId || activeTab.id, commentChanged, createdTableName)"@close="emit('structureEditorClose', activeTab.id)"@open-settings="(initialTab, initialSection) => emit('openSettings', initialTab, initialSection)"@view-data="onHandleStructureViewData"@@ -3834,7 +3906,10 @@ defineExpose({</template><template v-else-if="activeTab.mode === 'dameng-jobs' && activeConnection">- <DamengJobAdmin :key="activeTab.id" :connection="activeConnection" />+ <DamengJobAdmin :key="activeTab.id" :connection="activeConnection" :initial-selection="activeTab.nativeJobAdmin" />+ </template>+ <template v-else-if="activeTab.mode === 'database-jobs' && activeConnection">+ <DatabaseJobAdmin :key="activeTab.id" :connection="activeConnection" :initial-selection="activeTab.nativeJobAdmin" /></template><template v-else-if="activeTab.mode === 'dameng-users' && activeConnection">diff --git a/apps/desktop/src/components/layout/TabModeIcon.vue b/apps/desktop/src/components/layout/TabModeIcon.vueindex 3b8f33743c..ceacbf949a 100644--- a/apps/desktop/src/components/layout/TabModeIcon.vue+++ b/apps/desktop/src/components/layout/TabModeIcon.vue@@ -37,7 +37,7 @@ defineProps<{ tab: QueryTab }>();<FileCode v-else-if="tab.objectSource?.objectType === 'PACKAGE_BODY'" /><Braces v-else-if="tab.objectSource?.objectType === 'TYPE'" /><FileCode v-else-if="tab.objectSource?.objectType === 'TYPE_BODY'" />- <CalendarClock v-else-if="tab.mode === 'dameng-jobs'" />+ <CalendarClock v-else-if="tab.mode === 'dameng-jobs' || tab.mode === 'database-jobs'" /><Activity v-else-if="tab.mode === 'processlist' || tab.mode === 'sqlserver-trace'" /><Gauge v-else-if="tab.mode === 'dolt-version-control'" /><PluginIcon v-else-if="tab.mode === 'plugin-workbench' && tab.pluginWorkbench" :plugin-id="tab.pluginWorkbench.pluginId" :contribution-id="tab.pluginWorkbench.contributionId" />diff --git a/apps/desktop/src/components/layout/__tests__/ContentArea.oracleTriggerDiagnostics.spec.ts b/apps/desktop/src/components/layout/__tests__/ContentArea.oracleTriggerDiagnostics.spec.tsnew file mode 100644index 0000000000..94e0954d98--- /dev/null+++ b/apps/desktop/src/components/layout/__tests__/ContentArea.oracleTriggerDiagnostics.spec.ts@@ -0,0 +1,204 @@+// @vitest-environment happy-dom+import { createApp, h, nextTick, type App } from "vue";+import { createPinia, setActivePinia } from "pinia";+import { EditorView } from "@codemirror/view";+import { afterEach, expect, it, vi } from "vitest";+import i18n from "@/i18n";+import { useConnectionStore } from "@/stores/connectionStore";+import { useQueryStore } from "@/stores/queryStore";+import type { ConnectionConfig, ObjectSource } from "@/types/database";+import ContentArea from "../ContentArea.vue";++const rpc = vi.hoisted(() => ({+ getObjectSource: vi.fn(),+ prepareOracleTriggerSql: vi.fn(),+ executeQuery: vi.fn(),+ listCompletionObjects: vi.fn(async () => []),+ listPlugins: vi.fn(async () => []),+ listInstalledAgents: vi.fn(async () => []),+ loadSchemaCache: vi.fn(async () => null),+ saveSchemaCache: vi.fn(async () => undefined),+ deleteSchemaCachePrefix: vi.fn(async () => undefined),+ checkConnectionHealth: vi.fn(async () => undefined),+ saveOpenTabsState: vi.fn(async () => undefined),+}));+vi.mock("@/lib/backend/api", async (original) => ({ ...(await original<typeof import("@/lib/backend/api")>()), ...rpc }));+let app: App | undefined;+afterEach(() => {+ app?.unmount();+ app = undefined;+ vi.restoreAllMocks();+ document.body.innerHTML = "";+});++it.each(["diagnostics", "failed-refresh", "partial-refresh", "parent"])("keeps the bound trigger source editor through %s", async (scenario) => {+ vi.clearAllMocks();+ rpc.executeQuery.mockReset();+ const pinia = createPinia();+ setActivePinia(pinia);+ i18n.global.locale.value = "en";+ const config = { id: "content-trigger-diagnostic", name: "Trigger source", db_type: "oceanbase-oracle", username: "Execution.Owner", database: "service" } as ConnectionConfig;+ const connection = useConnectionStore();+ connection.connections = [config];+ connection.connectedIds.add(config.id);+ const stored = 'TRIGGER " Trigger.Owner "." Tr""igger " BEFORE INSERT ON "Parent"."T"\nBEGIN\n missing_proc;\nEND;';+ const raw: ObjectSource = {+ name: ' Tr"igger ',+ schema: " Trigger.Owner ",+ object_type: "TRIGGER",+ source: stored,+ editable: false,+ trigger: {+ name: ' Tr"igger ',+ event: "INSERT",+ timing: "BEFORE",+ enabled: false,+ valid: false,+ oracle_metadata: {+ contractVersion: 1,+ identityMode: "exact",+ engine: "oceanbase-oracle",+ engineVersion: "4.2.5.7_107",+ owner: " Trigger.Owner ",+ name: ' Tr"igger ',+ objectId: "9007199254740993",+ scope: "TABLE",+ parent: { owner: "Parent", name: "T", objectType: "TABLE" },+ definition: { origin: "ALL_SOURCE", format: "declaration", complete: true },+ errors: [{ sequence: 1, line: 3, position: 3, text: "Missing procedure" }],+ reads: { identity: { state: "available" }, scope: { state: "available" }, parent: { state: "available" }, enabled: { state: "available" }, validity: { state: "available" }, definition: { state: "available" }, errors: { state: "available" } },+ },+ },+ };+ rpc.getObjectSource.mockImplementation(async () => JSON.parse(JSON.stringify(raw)));+ rpc.prepareOracleTriggerSql.mockImplementation(async (input) => ({+ definition: input.source.startsWith("TRIGGER") ? "CREATE OR REPLACE " + input.source : input.source,+ comparisonSource: input.source,+ header: { scope: "RELATION", owner: "Parent", name: "T", viewOnly: false, pluggable: false },+ requiresStateRestore: false,+ }));+ const query = useQueryStore();+ const id = query.openObjectSourceTabPending({ connectionId: config.id, database: "service", schema: raw.schema!, catalog: " Catalog ", title: "Trigger source", initialEditing: true, request: { name: raw.name, objectType: "TRIGGER" } });+ await vi.waitFor(() => expect(query.oracleTriggerSourceState(id)?.baseline).toBeDefined());+ const tab = query.tabs.find((candidate) => candidate.id === id)!;+ const dependencyOpen = vi.fn();+ const host = document.createElement("div");+ document.body.append(host);+ app = createApp({+ render: () =>+ h(ContentArea, {+ activeTab: tab,+ activeConnection: config,+ activeOutputView: "result",+ executableSql: tab.sql,+ formatSqlRequest: null,+ compressSqlRequest: null,+ selectedSql: "",+ cursorPos: 0,+ blockDangerousRedisCommands: false,+ editorOnly: true,+ onEditorUpdate: (tabId: string, sql: string) => query.updateSql(tabId, sql),+ onOpenDependencyObject: dependencyOpen,+ }),+ });+ app.use(pinia);+ app.use(i18n);+ app.mount(host);+ await vi.waitFor(() => expect(host.querySelector(".cm-editor")).not.toBeNull(), { timeout: 10_000 });+ const view = EditorView.findFromDOM(host.querySelector<HTMLElement>(".cm-editor")!)!;+ const original = view.state.doc.toString();+ view.dispatch({ changes: { from: 0, insert: "-- preserve this draft\n" } });+ await nextTick();+ const draft = tab.sql;+ if (scenario === "parent") {+ const { useNavigationTargets } = await import("@/composables/useNavigationTargets");+ const { sqlObjectNavigationContextTarget } = await import("@/lib/sql/sqlNavigation");+ const { useSettingsStore } = await import("@/stores/settingsStore");+ useSettingsStore().editorSettings.dataTabReuseMode = "same-table";+ const parentId = query.createTab(config.id, "service", "Parent.T", "data", "Parent", undefined, " Catalog ", { forceNew: true });+ query.setTableMeta(parentId, { database: "service", schema: "Parent", catalog: " Catalog ", tableName: "T", tableType: "TABLE", columns: [], primaryKeys: [] });+ query.switchTab(id);+ const navigation = useNavigationTargets({ showFieldLineageDialog: { value: false }, showDatabaseSearchDialog: { value: false }, showDiagramDialog: { value: false } });+ let opened: Promise<void> | undefined;+ dependencyOpen.mockImplementation((context, target) => {+ opened = navigation.openObjectBrowserTableTarget(sqlObjectNavigationContextTarget(target, context));+ });+ [...host.querySelectorAll<HTMLButtonElement>("[data-oracle-trigger-status] button")].find((button) => button.textContent?.includes("Parent.T"))!.click();+ await vi.waitFor(() => expect(dependencyOpen).toHaveBeenCalledOnce());+ await opened;+ expect(dependencyOpen).toHaveBeenCalledWith(expect.objectContaining({ connectionId: config.id, database: "service", catalog: " Catalog ", schema: raw.schema, name: raw.name }), { name: "T", schema: "Parent", type: "table", nameQuoted: true, schemaQuoted: true });+ expect(query.activeTabId).toBe(parentId);+ expect(query.tabs.filter((candidate) => candidate.tableMeta?.tableName === "T")).toHaveLength(1);+ expect(query.tabs.find((candidate) => candidate.id === id)?.sql).toBe(draft);+ expect(query.isTabDirty(tab)).toBe(true);+ expect(EditorView.findFromDOM(host.querySelector<HTMLElement>(".cm-editor")!)).toBe(view);+ expect(rpc.executeQuery).not.toHaveBeenCalled();+ return;+ }+ if (scenario !== "diagnostics") {+ rpc.executeQuery.mockResolvedValue({ columns: ["DIRECTION", "OBJECT_OWNER", "OBJECT_NAME", "OBJECT_TYPE", "REFERENCED_OWNER", "REFERENCED_NAME", "REFERENCED_TYPE", "DEPENDENCY_TYPE", "REFERENCED_LINK_NAME"], rows: [] });+ host.querySelector<HTMLButtonElement>('[data-object-section="dependencies"]')!.click();+ await nextTick();+ const reads = rpc.getObjectSource.mock.calls.length;+ let finish!: (value: ObjectSource) => void;+ let fail!: (error: Error) => void;+ rpc.getObjectSource.mockImplementationOnce(+ () =>+ new Promise<ObjectSource>((resolve, reject) => {+ finish = resolve;+ fail = reject;+ }),+ );+ expect(query.refreshObjectSourceTab(id)).toBe(true);+ await vi.waitFor(() => expect(rpc.getObjectSource.mock.calls.length).toBe(reads + 1));+ await nextTick();+ expect(host.querySelector(".cm-editor")).not.toBeNull();+ expect(EditorView.findFromDOM(host.querySelector<HTMLElement>(".cm-editor")!)).toBe(view);+ view.dispatch({ changes: { from: view.state.doc.length, insert: "\n-- edited during refresh" } });+ await nextTick();+ const latestDraft = tab.sql;+ if (scenario === "failed-refresh") fail(new Error("source permission lost"));+ else {+ const partial = structuredClone(raw);+ partial.trigger!.oracle_metadata!.reads.identity = { state: "denied", message: "identity permission lost" };+ finish(partial);+ }+ await vi.waitFor(() => expect(scenario === "failed-refresh" ? tab.sourceLoad?.error : !tab.sourceLoad).toBeTruthy());+ expect(host.querySelector('[data-object-section="dependencies"]')).not.toBeNull();+ expect(tab.objectDetails?.section).toBe("dependencies");+ host.querySelector<HTMLButtonElement>('[data-object-section="source"]')!.click();+ await nextTick();+ if (scenario === "failed-refresh") expect(host.textContent).toContain("source permission lost");+ else expect(query.oracleTriggerSourceState(id)?.baseline).toBeUndefined();+ expect(EditorView.findFromDOM(host.querySelector<HTMLElement>(".cm-editor")!)).toBe(view);+ expect(tab.sql).toBe(latestDraft);+ expect(view.state.doc.toString()).toBe(latestDraft);+ const { undo } = await import("@codemirror/commands");+ expect(undo(view)).toBe(true);+ expect(undo(view)).toBe(true);+ expect(view.state.doc.toString()).toBe(original);+ view.dispatch({ changes: { from: 0, insert: "-- new correction after failed read\n" } });+ await nextTick();+ const retryDraft = tab.sql;+ rpc.getObjectSource.mockResolvedValueOnce(structuredClone(raw));+ if (scenario === "failed-refresh") query.retryObjectSourceTab(id);+ else query.refreshObjectSourceTab(id);+ await vi.waitFor(() => expect(tab.sourceLoad).toBeUndefined());+ expect(query.oracleTriggerSourceState(id)?.baseline).toBeDefined();+ expect(EditorView.findFromDOM(host.querySelector<HTMLElement>(".cm-editor")!)).toBe(view);+ expect(tab.sql).toBe(retryDraft);+ expect(view.state.doc.toString()).toBe(retryDraft);+ expect(rpc.executeQuery.mock.calls.every((call) => call[2].includes("ALL_DEPENDENCIES"))).toBe(true);+ return;+ }+ [...host.querySelectorAll<HTMLButtonElement>("[data-oracle-trigger-status] button")].find((button) => button.textContent?.trim() === i18n.global.t("processList.oracleInvalidObjects.errorsTitle"))!.click();+ const locate = () => [...document.querySelectorAll<HTMLButtonElement>("button")].find((button) => button.getAttribute("aria-label") === i18n.global.t("editor.locateError", { line: 3, column: 3 }));+ await vi.waitFor(() => expect(locate()).toBeDefined(), { timeout: 10_000 });+ locate()!.click();+ await vi.waitFor(() => expect(view.state.selection.main.head).toBe(draft.indexOf("missing_proc")));+ expect(tab.sql).toBe(draft);+ expect(query.isTabDirty(tab)).toBe(true);+ expect(EditorView.findFromDOM(host.querySelector<HTMLElement>(".cm-editor")!)).toBe(view);+ expect(tab.editorRevealRequest).toBeUndefined();+ expect(rpc.executeQuery).not.toHaveBeenCalled();+});diff --git a/apps/desktop/src/components/objects/ObjectBrowser.vue b/apps/desktop/src/components/objects/ObjectBrowser.vueindex 12c9ba5d36..e9b103dcbd 100644--- a/apps/desktop/src/components/objects/ObjectBrowser.vue+++ b/apps/desktop/src/components/objects/ObjectBrowser.vue@@ -1,4 +1,5 @@<script setup lang="ts">+import { uuid } from "@/lib/common/utils";import { OBJECT_BROWSER_COMPACT_WIDTHS, normalizeObjectBrowserCompactWidth, type ObjectBrowserCompactWidth } from "@/lib/table/objectBrowserCompactWidth";import { applyDdlTextPreferences } from "@/lib/sql/ddlPreferences";import DatabaseActionsMenu from "@/components/objects/DatabaseActionsMenu.vue";@@ -6,7 +7,7 @@ import FirebirdObjectManager from "@/components/objects/FirebirdObjectManager.vuimport { useDatabaseBrowserMutation } from "@/lib/database/databaseBrowserActions";import DdlStorageToggle from "@/components/objects/DdlStorageToggle.vue";-import { computed, createApp, nextTick, onActivated, onBeforeUnmount, ref, watch, type Component } from "vue";+import { computed, createApp, nextTick, onActivated, onBeforeUnmount, onDeactivated, ref, shallowRef, watch, type Component } from "vue";import { RecycleScroller } from "vue-virtual-scroller";import { useSqlHighlighter } from "@/composables/useSqlHighlighter";import {@@ -112,6 +113,22 @@ import { executeOceanbaseTableClone, executeOceanbaseTableCloneData, oceanbaseClimport { useOceanbaseCloneDialog } from "@/composables/useOceanbaseCloneDialog";import { useToast } from "@/composables/useToast";import { buildExecutableObjectSourceStatements, buildRoutineRenameObjectSourceStatements, prepareObjectSourceSave, objectSourceSaveSuccessMessage, formatObjectSourceSaveError, supportsSourceBackedRoutineRename } from "@/lib/table/objectSourceEditor";+import { inspectExactOracleTriggerSource } from "@/lib/table/objectSourceLoad";+import {+ readOracleTriggerSource,+ prepareOracleTriggerPlan,+ prepareOracleTriggerDropBatchPlan,+ executeOracleTriggerDropBatchPlan,+ verifyOracleTriggerDeletion,+ type OracleTriggerDropBatchPlan,+ type OracleTriggerSnapshot,+ type OracleTriggerExecutionResult,+ type OracleTriggerAction,+ type OracleTriggerTarget,+} from "@/lib/database/oracleTriggerPlan";+import { confirmOracleTriggerPlan } from "@/lib/database/oracleTriggerActions";+import OracleTriggerStatus from "@/components/objects/OracleTriggerStatus.vue";+import ObjectSourceDialog from "@/components/objects/ObjectSourceDialog.vue";import { assertSourceIdentity, beginSourceSave, captureSourceIdentity, freezeSourceIdentities, renewSourceIdentity, type SourceIdentitySnapshot } from "@/lib/table/objectSourceIdentity";import { buildRenameObjectSql, supportsObjectRename } from "@/lib/table/objectRenameSql";import { prepareOracleViewRename, executeOracleViewRename, OracleViewRenameFailure, type OracleViewRenamePlan } from "@/lib/table/oracleViewRename";@@ -129,7 +146,7 @@ import { generateDatabaseExportId } from "@/lib/export/databaseExport";import { buildXlsxHeaderOverrides, hasXlsxHeaderComments, xlsxHeaderUsesCommentRows, type XlsxExportOptions, type XlsxHeaderMode } from "@/lib/export/xlsxHeader";import { showSqlInsertModeDialog, type SqlInsertDialect, type SqlInsertMode } from "@/lib/export/sqlInsertMode";import { csvNullLiteralForMode } from "@/lib/export/csvNullMode";-import { copyToClipboard, eventTargetAllowsAppClipboardShortcut } from "@/lib/common/clipboard";+import { copyToClipboard, eventTargetAllowsAppClipboardShortcut, eventTargetUsesNativeClipboard } from "@/lib/common/clipboard";import { encodeSpreadsheetTsvCell } from "@/lib/common/spreadsheetTsv";import {defaultPasteTableMode,@@ -149,6 +166,7 @@ import { useConnectionStore } from "@/stores/connectionStore";import { treeNodePinIdentity, type PinnedTreeNodeIdentity } from "@/lib/app/pinnedItems";import { useExportTracker, type ExportTask } from "@/composables/useExportTracker";import { useSettingsStore } from "@/stores/settingsStore";+import { useProductionSafetyStore } from "@/stores/productionSafetyStore";import { useSidebarMenuPresentation } from "@/composables/useSidebarMenuPresentation";import { formatSidebarTableNamesForCopy, type SidebarTableCopyTarget } from "@/lib/sidebar/sidebarTableNameCopy";import { useQueryStore } from "@/stores/queryStore";@@ -160,6 +178,8 @@ import { applyDdlDatabaseQualifier, omitDdlIdentifierQuotes } from "@/lib/sql/ddimport { isCancelSearchShortcut } from "@/lib/editor/keyboardShortcuts";import { parseSlashDelimitedRegexQuery } from "@/lib/common/searchPattern";import { executeWithProductionSqlGuard } from "@/lib/database/productionExecutionGuard";+import { exactOracleTriggerMetadata, oracleTriggerObjectReadOptions, oracleTriggerReadOptions } from "@/lib/database/oracleTriggerIdentity";+import { tablePageRowAnchorKey } from "@/lib/table/tableTree";import { connectionIsEffectivelyReadOnly } from "@/lib/database/readOnlyWriteAccess";import { buildXuguCompileSql } from "@/lib/database/xuguCompileSql";import { buildDamengCompileViewSql } from "@/lib/database/damengCompileSql";@@ -209,7 +229,7 @@ import { invalidateObjectMetadataCache } from "@/lib/metadata/objectMetadataCachimport { invalidateObjectDdl, invalidateObjectDdlCache } from "@/lib/metadata/objectDdlCache";import { invalidateObjectBrowserRowsCache } from "@/lib/table/objectBrowserRowsCache";import { completeOracleInvalidObjectCompile, type OracleInvalidObjectCompileScope } from "@/lib/database/oracleInvalidObjectCacheRefresh";-import { oracleInvalidObjectSourceKind } from "@/lib/database/oracleInvalidObjects";+import { oracleCompileUnsupportedReason, oracleInvalidObjectSourceKind } from "@/lib/database/oracleInvalidObjects";import { eventEditorInstanceKey, resolveInitialEventEditorRequest } from "@/lib/table/eventEditorRequest";import { createLocateTabMenuItem } from "@/lib/tabs/tabMenu";import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";@@ -267,14 +287,41 @@ const refreshTooltip = computed(() => {const firebirdManagerOpen = ref(false);const schemas = ref<string[]>([]);const selectedSchema = ref<string | undefined>(props.schema);+const triggerCreateOpen = ref(false);+const triggerCreateDialog = ref<InstanceType<typeof ObjectSourceDialog>>();+const triggerCreateContext = ref<{ connectionId: string; database: string; catalog?: string; schema: string; databaseType: ConnectionConfig["db_type"] }>();+const canCreateOracleTrigger = computed(() => !!selectedSchema.value && !!oracleTriggerReadOptions(effectiveDatabaseType.value));+function openCreateOracleTrigger() {+ if (!canCreateOracleTrigger.value || !selectedSchema.value) return;+ const context = { connectionId: props.connection.id, database: props.database, catalog: props.catalog, schema: selectedSchema.value, databaseType: effectiveDatabaseType.value };+ if (JSON.stringify(triggerCreateContext.value) !== JSON.stringify(context)) {+ if (triggerCreateDialog.value?.hasUnsavedDraft() && !window.confirm(t("objects.refreshDiscardConfirm"))) return;+ triggerCreateContext.value = context;+ }+ triggerCreateOpen.value = true;+}+watch([() => props.connection.id, () => props.database, () => props.catalog, selectedSchema], () => {+ triggerCreateOpen.value = false;+});+function refreshCreatedTrigger() {+ const context = triggerCreateContext.value;+ if (context && context.connectionId === props.connection.id && context.database === props.database && context.catalog === props.catalog && context.schema === selectedSchema.value) void reload({ preserveExistingRows: true });+}const oracleInvalidObjectsOpen = ref(false);+const invalidTriggerContext = shallowRef<{ target: Readonly<OracleTriggerTarget>; expectedObjectId?: string; originRevision: number }>();let invalidObjectsDialogGeneration = 0;let invalidObjectSourceRequestGeneration = 0;let objectBrowserUnmounted = false;const rows = ref<ObjectBrowserRow[]>([]);const rootRef = ref<HTMLElement>();const search = ref(props.initialSearchQuery ?? "");-const objectFilter = ref<ObjectFilter>(props.selectedObjectFilter === "indexes" || props.initialObjectFilter === "indexes" ? "indexes" : props.connection.db_type === "oceanbase-oracle" ? (props.selectedObjectFilter ?? props.initialObjectFilter ?? "tables") : "all");+function initialObjectBrowserFilter(): ObjectFilter {+ const preferred = props.selectedObjectFilter ?? props.initialObjectFilter;+ if (preferred === "indexes") return "indexes";+ if (props.connection.db_type === "oceanbase-oracle") return preferred ?? "tables";+ return preferred === "triggers" && oracleTriggerObjectReadOptions(props.connection, ["TRIGGER"], props.catalog) ? "triggers" : "all";+}+const objectFilter = ref<ObjectFilter>(initialObjectBrowserFilter());const userHasSelectedFilter = ref(false);const sortKey = ref<ObjectBrowserSortKey>("name");const sortDirection = ref<ObjectBrowserSortDirection>("asc");@@ -283,7 +330,7 @@ const loadingObjects = ref(false);const loadingMoreObjects = ref(false);const hasMoreObjects = ref(false);let objectPageOffset = 0;-let indexNextPageAnchor: string | undefined;+let objectPageNextAnchor: string | undefined;let objectSearchTimer: ReturnType<typeof setTimeout> | undefined;const refreshingObjects = ref(false);const scaffoldRefreshError = ref("");@@ -392,15 +439,24 @@ function openRelationObject(context: ObjectDependencyTarget, target: SqlObjectNaemit("openDependencyObject", context, target);}const oracleInvalidObjectsSupported = computed(() => effectiveDatabaseType.value === "oracle" || effectiveDatabaseType.value === "oceanbase-oracle");+const supportsExactTriggerDiscovery = computed(() => !!oracleTriggerObjectReadOptions(props.connection, ["TRIGGER"], props.catalog));const supportsSchemaIndexes = computed(() => supportsSchemaIndexManagement(effectiveDatabaseType.value));const exactIndexList = computed(() => supportsSchemaIndexes.value && objectFilter.value === "indexes");-const usesServerObjectPaging = computed(() => props.connection.db_type === "oceanbase-oracle" || exactIndexList.value);+const usesServerObjectPaging = computed(() => props.connection.db_type === "oceanbase-oracle" || exactIndexList.value || (objectFilter.value === "triggers" && supportsExactTriggerDiscovery.value));const objectPageSize = computed(() => Math.max(1, Math.min(10_000, Math.floor(settingsStore.desktopSettings?.sidebar_table_page_size || 500))));const isGaussdbM = computed(() => effectiveDatabaseType.value === "gaussdb" && props.connection.driver_profile?.toLowerCase() === "gaussdb-m");function setOracleInvalidObjectsOpen(open: boolean) {if (oracleInvalidObjectsOpen.value !== open) invalidObjectsDialogGeneration++;oracleInvalidObjectsOpen.value = open;+ if (!open) invalidTriggerContext.value = undefined;+}++function openBrowserTriggerDiagnostics() {+ const snapshot = sourceTriggerSnapshot.value;+ if (!snapshot?.exists) return;+ invalidTriggerContext.value = { target: snapshot.target, expectedObjectId: snapshot.metadata.objectId ?? undefined, originRevision: sidePanelGuard.capture() };+ setOracleInvalidObjectsOpen(true);}watch(@@ -437,10 +493,44 @@ const sourceEditableText = ref("");const sourceDraft = ref("");const sourceSaving = ref(false);const sourceSaveError = ref("");+const sourceTriggerSnapshot = ref<OracleTriggerSnapshot>();+const sourceDependencyTarget = computed(() => {+ const row = sourceRow.value;+ if (!row) return undefined;+ return objectDependencyTarget({ connectionId: props.connection.id, database: props.database, catalog: props.catalog, schema: row.schema ?? selectedSchema.value ?? props.database, name: row.name, objectType: row.type }, effectiveDatabaseType.value, row.trigger);+});+watch(+ () => [props.connection.id, props.database, props.catalog, sourceRow.value?.id],+ () => {+ sourceSection.value = "source";+ },+ { flush: "sync" },+);+const sourceTriggerResult = ref<OracleTriggerExecutionResult>();+const sourceTriggerIssue = ref("");+const sourceTriggerRequested = ref(false);+const browserTriggerBusy = ref(false);+const browserTriggerActive = ref(true);+const browserTriggerViewRevision = ref(0);+const browserTriggerFeedback = shallowRef<{ target: Readonly<OracleTriggerTarget>; row: ObjectBrowserRow; result: OracleTriggerExecutionResult; snapshot?: OracleTriggerSnapshot; pinnedContext?: ReturnType<typeof objectBrowserPinnedTreeNodeContext> }>();+const browserTriggerContext = () => JSON.stringify([props.connection.id, props.database, props.catalog, selectedSchema.value, objectFilter.value, search.value]);+watch(+ () => [browserTriggerContext(), loadingObjects.value, refreshingObjects.value, loadingMoreObjects.value],+ () => browserTriggerViewRevision.value++,+ { flush: "sync" },+);+watch(showCompileErrorDialog, (open) => {+ if (!open) browserTriggerFeedback.value = undefined;+});+onDeactivated(() => {+ browserTriggerActive.value = false;+});const error = ref("");const showDropConfirm = ref(false);const dropTarget = ref<ObjectBrowserRow | null>(null);const dropPreviewSql = ref("");+const dropPreviewError = ref("");+const triggerDropPreview = shallowRef<BrowserTriggerDropPreview>();const dropTableCascade = ref(false);const batchDropCascade = ref(false);const showRenameDialog = ref(false);@@ -493,6 +583,9 @@ const showBatchDropConfirm = ref(false);const batchDropExecuting = ref(false);const batchDropProgress = ref({ completed: 0, total: 0 });const batchDropPreviewSql = ref("");+const batchDropPreviewError = ref("");+const batchTriggerDropRequested = ref(false);+const batchTriggerDropPreview = shallowRef<BrowserTriggerDropPreview>();const showBatchTruncateConfirm = ref(false);const batchTruncatePreviewSql = ref("");const batchTruncateCascade = ref(false);@@ -572,8 +665,8 @@ const vacuumRiskMessage = computed(() => (vacuumExecuting.value ? t("contextMenuconst sourceDialect = computed(() => codeMirrorSqlDialect(effectiveDatabaseType.value));const sourceFormatDialect = computed<SqlFormatDialect>(() => sqlFormatDialectForDbType(effectiveDatabaseType.value));const objectFilters = computed<ObjectFilter[]>(() =>- usesServerObjectPaging.value- ? ["all", "tables", "views", "procedures", "functions", "sequences", ...(supportsSchemaIndexes.value ? ["indexes" as const] : []), "packages", "types"]+ props.connection.db_type === "oceanbase-oracle"+ ? ["all", "tables", "views", "procedures", "functions", "triggers", "sequences", ...(supportsSchemaIndexes.value ? ["indexes" as const] : []), "packages", "types"]: ([["all", objectCounts.value.all],@@ -590,10 +683,10 @@ const objectFilters = computed<ObjectFilter[]>(() =>["types", objectCounts.value.types],] as Array<[ObjectFilter, number]>)- .filter(([filter, count]) => filter === "all" || count > 0 || (filter === "indexes" && supportsSchemaIndexes.value))+ .filter(([filter, count]) => filter === "all" || count > 0 || (filter === "triggers" && supportsExactTriggerDiscovery.value) || (filter === "indexes" && supportsSchemaIndexes.value)).map(([filter]) => filter),);-const showObjectFilter = computed(() => objectFilters.value.length > 2 || (supportsSchemaIndexes.value && objectFilters.value.includes("indexes")));+const showObjectFilter = computed(() => objectFilters.value.length > 2 || (supportsExactTriggerDiscovery.value && objectFilters.value.length > 1) || (supportsSchemaIndexes.value && objectFilters.value.includes("indexes")));// A scope that holds a single object kind makes "全部 14" and "表 14" the same number, so the// strip is dropped as redundant — which used to drop the only object count the toolbar could// show at all (t8y2/dbx#11624, the common MySQL "tables only" database). Keep that one kind's@@ -747,6 +840,7 @@ watch();onActivated(() => {+ browserTriggerActive.value = true;restoreObjectBrowserViewport();});@@ -774,6 +868,7 @@ watch(objectBrowserRowsLoadGuard.invalidate();rows.value = [];hasMoreObjects.value = false;+ objectPageNextAnchor = undefined;loadingMoreObjects.value = false;loadingObjects.value = true;if (!value.trim()) void loadObjects();@@ -907,6 +1002,7 @@ watch([viewMode, compactCardWidth], () =>);onBeforeUnmount(() => {+ browserTriggerActive.value = false;gridResizeObserver?.disconnect();gridResizeObserver = null;if (viewportFrame) window.cancelAnimationFrame(viewportFrame);@@ -1462,6 +1558,7 @@ const filteredTableDdlContent = computed(() => {});async function openTableInfo(row: ObjectBrowserRow, initialTab?: TableInfoTab, focusObject?: NonNullable<QueryTab["objectPropertiesRequest"]>["focusObject"]) {+ if (!confirmTriggerDraftDiscard()) return;if (row.type === "INDEX" && (!supportsSchemaIndexes.value || !schemaIndexIdentity(row))) {toast(t("schemaIndex.parentUnavailable"), 4000);return;@@ -1716,9 +1813,19 @@ async function fetchTableTriggers(force = false) {let loadedSuccessfully = false;try {const request = tableMetadataRequest(row);+ const readOptions = oracleTriggerObjectReadOptions(props.connection, undefined, request.catalog);+ const cacheRequest = readOptions ? { ...request, oracleTriggerContract: 1 as const } : request;const { value: triggers } = await sidePanelGuard.wait(epoch,- loadObjectMetadataFacet(request, "triggers", () => api.listTriggers(request.connectionId, request.database, request.schema || request.database, request.tableName, request.catalog, ...(request.exactIdentity ? ([true] as const) : [])), { force }),+ loadObjectMetadataFacet(+ cacheRequest,+ "triggers",+ () =>+ readOptions+ ? api.listTriggers(request.connectionId, request.database, request.schema || request.database, request.tableName, request.catalog, readOptions)+ : api.listTriggers(request.connectionId, request.database, request.schema || request.database, request.tableName, request.catalog, ...(request.exactIdentity ? ([true] as const) : [])),+ { force },+ ),metadataLoadBudgetMs(props.connection.query_timeout_secs),);if (sidePanelGuard.isStale(epoch)) return;@@ -1902,6 +2009,10 @@ function onSidePanelResizeEnd() {settingsStore.updateEditorSettings({ tableInfoDrawerWidth: sidePanelWidth.value });}+function confirmTriggerDraftDiscard() {+ return !sourceRow.value || !sourceTriggerRequested.value || !sourceEditing.value || sourceDraft.value === sourceEditableText.value || window.confirm(t("oracleTrigger.discardSourceConfirm"));+}+function closeSidePanel() {selectedTableInfoColumns.value = [];sidePanelRow.value = null;@@ -1919,7 +2030,7 @@ function toggleSidePanel() {return;}}- closeSidePanel();+ if (confirmTriggerDraftDiscard()) closeSidePanel();} else {const targetRow = (selectedRowId.value ? filteredRows.value.find((r) => r.id === selectedRowId.value) : null) ?? filteredRows.value[0];if (targetRow) {@@ -1936,6 +2047,7 @@ function toggleAutoOpenDetailPanel() {}async function openTypeInfo(row: ObjectBrowserRow) {+ if (!confirmTriggerDraftDiscard()) return;selectedRowId.value = row.id;if (sidePanelRow.value?.id === row.id && sidePanelMode.value === "type-info") {if (settingsStore.editorSettings.objectBrowserAutoOpenDetailPanel === false) {@@ -1951,6 +2063,7 @@ async function openTypeInfo(row: ObjectBrowserRow) {}function openTypeDdl(row: ObjectBrowserRow) {+ if (!confirmTriggerDraftDiscard()) return;selectedRowId.value = row.id;sidePanelRow.value = row;sidePanelMode.value = "type-info";@@ -1996,13 +2109,15 @@ async function openSource(row: ObjectBrowserRow) {if (settingsStore.editorSettings.objectBrowserAutoOpenDetailPanel === false) {return;}+ if (!confirmTriggerDraftDiscard()) return;closeSidePanel();return;}+ if (!confirmTriggerDraftDiscard()) return;await loadSourcePanel(row);}-async function openInvalidObjectSource(object: { owner: string; name: string; type: string }) {+async function openInvalidObjectSource(object: { owner: string; name: string; type: string; objectId?: string }, location?: { line: number; position: number }) {const objectType = oracleInvalidObjectSourceKind(object.type);if (!objectType) return;const dialogGeneration = invalidObjectsDialogGeneration;@@ -2022,7 +2137,7 @@ async function openInvalidObjectSource(object: { owner: string; name: string; typrops.database === database &&props.catalog === catalog &&(selectedSchema.value || props.database) === schema;- if (objectType === "TRIGGER") {+ if (objectType === "TRIGGER" && !invalidTriggerContext.value) {try {const source = await api.getObjectSource(connection.id, database, object.owner, object.name, objectType);if (!isCurrentRequest()) return;@@ -2074,6 +2189,7 @@ async function openInvalidObjectSource(object: { owner: string; name: string; tytoast(t("processList.oracleInvalidObjects.sourceLoadFailed", { message: sourceLoadResult.error || tab?.sourceLoad?.error || t("processList.oracleInvalidObjects.sourceUnavailable") }), 5000);return;}+ if (location && objectType === "TRIGGER" && !queryStore.revealOracleTriggerSourceError(tabId, location, object.objectId)) toast(t("oracleTrigger.errorPositionUnavailable"), 3000);setOracleInvalidObjectsOpen(false);}@@ -2086,15 +2202,18 @@ async function loadSourcePanel(row: ObjectBrowserRow, options?: { preserveEditin// any state is reset, otherwise an old response can populate the new row.const epoch = sidePanelGuard.start();const preserveEditing = options?.preserveEditing === true && sourceEditing.value;+ const keptDraft = preserveEditing && sourceRow.value?.id === row.id && sourceTriggerRequested.value ? sourceDraft.value : undefined;sidePanelRow.value = row;sidePanelMode.value = "source";sourceRow.value = row;sourceContent.value = "";sourceError.value = "";- sourceEditing.value = false;+ if (keptDraft === undefined) sourceEditing.value = false;sourceCanEdit.value = true;- sourceEditableText.value = "";- sourceDraft.value = "";+ if (keptDraft === undefined) {+ sourceEditableText.value = "";+ sourceDraft.value = "";+ }sourceSaveError.value = "";// A new source context owns the save spinner: the previous save's finally()// can no longer run once this load starts (the guard epoch moved on) — the@@ -2107,8 +2226,31 @@ async function loadSourcePanel(row: ObjectBrowserRow, options?: { preserveEditinconst schema = row.schema || selectedSchema.value || database;const identity = captureSourceIdentity({ connectionId, database, schema, objectType: row.type, name: row.name });sourceIdentity = undefined;+ sourceTriggerSnapshot.value = undefined;+ sourceTriggerIssue.value = "";+ sourceTriggerRequested.value = row.type === "TRIGGER" && (!!exactOracleTriggerMetadata(row.trigger) || !!oracleTriggerObjectReadOptions(props.connection, undefined, props.catalog));+ if (keptDraft === undefined) sourceTriggerResult.value = undefined;try {- const result = await sidePanelGuard.wait(epoch, api.getObjectSource(connectionId, database, schema, row.name, row.type as ObjectSourceKind, row.signature ?? undefined), metadataLoadBudgetMs(props.connection.query_timeout_secs));+ const readOptions = row.type === "TRIGGER" ? (exactOracleTriggerMetadata(row.trigger) ? { identityMode: "exact" as const, catalog: props.catalog } : oracleTriggerObjectReadOptions(props.connection, undefined, props.catalog)) : undefined;+ if (readOptions) {+ const loaded = await sidePanelGuard.wait(epoch, readOracleTriggerSource({ connectionId, database, catalog: props.catalog, owner: schema, name: row.name, executionSchema: selectedSchema.value || props.schema || schema }), metadataLoadBudgetMs(props.connection.query_timeout_secs));+ if (sidePanelGuard.isStale(epoch)) return;+ const inspected = await inspectExactOracleTriggerSource(loaded.raw, schema, row.name);+ if (sidePanelGuard.isStale(epoch)) return;+ sourceTriggerSnapshot.value = loaded.snapshot;+ sourceTriggerIssue.value = loaded.identityError || inspected.triggerSource.error || "";+ sourceIdentity = loaded.snapshot?.identity;+ sourceCanEdit.value = loaded.snapshot?.exists === true;+ if (keptDraft === undefined || loaded.snapshot) sourceEditableText.value = inspected.editableSource;+ sourceContent.value = loaded.raw.source;+ if (keptDraft === undefined) sourceDraft.value = inspected.editableSource;+ sourceEditing.value = keptDraft !== undefined || (sourceCanEdit.value && (options?.preserveEditing ? preserveEditing : true));+ return;+ }+ const sourceRequest = readOptions+ ? api.getObjectSource(connectionId, database, schema, row.name, row.type as ObjectSourceKind, row.signature ?? undefined, undefined, readOptions)+ : api.getObjectSource(connectionId, database, schema, row.name, row.type as ObjectSourceKind, row.signature ?? undefined);+ const result = await sidePanelGuard.wait(epoch, sourceRequest, metadataLoadBudgetMs(props.connection.query_timeout_secs));if (sidePanelGuard.isStale(epoch)) return;sourceCanEdit.value = result.editable !== false && (!["TRIGGER", "TYPE", "TYPE_BODY"].includes(row.type) || isOracleFamilyTypeSource(effectiveDatabaseType.value, row.type)) && (row.type !== "SEQUENCE" || effectiveDatabaseType.value === "oceanbase-oracle");const editable = sourceCanEdit.value@@ -2139,7 +2281,10 @@ async function loadSourcePanel(row: ObjectBrowserRow, options?: { preserveEditin}} catch (e: any) {if (sidePanelGuard.isStale(epoch)) return;- sourceError.value = e?.message || String(e);+ if (keptDraft !== undefined) {+ sourceEditing.value = true;+ sourceSaveError.value = e?.message || String(e);+ } else sourceError.value = e?.message || String(e);} finally {if (sidePanelGuard.isFresh(epoch)) sourceLoading.value = false;}@@ -2148,7 +2293,7 @@ async function loadSourcePanel(row: ObjectBrowserRow, options?: { preserveEditinasync function refreshActiveSource() {const row = sourceRow.value || (sidePanelMode.value === "source" ? sidePanelRow.value : null);if (!row || sidePanelMode.value !== "source") return;- if (sourceEditing.value && !window.confirm(t("objects.refreshDiscardConfirm"))) return;+ if (!sourceTriggerRequested.value && sourceEditing.value && !window.confirm(t("objects.refreshDiscardConfirm"))) return;await loadSourcePanel(row, { preserveEditing: true });}@@ -2166,6 +2311,7 @@ async function openRequestedProperties() {}function openEventEditor(row: ObjectBrowserRow) {+ if (!confirmTriggerDraftDiscard()) return;selectedRowId.value = row.id;sidePanelGuard.start();sidePanelRow.value = row;@@ -2234,6 +2380,7 @@ async function executeProcedureSql(sql: string) {}function requestDrop(row: ObjectBrowserRow) {+ if (browserTriggerBusy.value && usesExactTriggerDrop(row)) return;if (selectedTableCount.value > 1 && selectedTableIds.value.has(row.id) && selectedTableRows.value.some((item) => item.type === "INDEX")) {toast(t("schemaIndex.editIndividually"), 4000);return;@@ -2248,6 +2395,8 @@ function requestDrop(row: ObjectBrowserRow) {}dropTarget.value = row;dropPreviewSql.value = "";+ dropPreviewError.value = "";+ triggerDropPreview.value = undefined;dropTableCascade.value = false;showDropConfirm.value = true;void refreshDropPreviewSql();@@ -2775,6 +2924,10 @@ async function confirmRename() {async function confirmDrop() {if (!dropTarget.value) return;const row = dropTarget.value;+ if (usesExactTriggerDrop(row)) {+ if (triggerDropPreview.value) await executeBrowserTriggerDrops(triggerDropPreview.value, false);+ return;+ }if (row.type === "INDEX") return;if (isOracleFamilyTypeSource(effectiveDatabaseType.value, row.type)) {await manageTypeDrop(row);@@ -2855,6 +3008,19 @@ async function refreshDropPreviewSql() {return;}dropPreviewSql.value = "";+ triggerDropPreview.value = undefined;+ dropPreviewError.value = "";+ if (usesExactTriggerDrop(row)) {+ try {+ const prepared = await prepareBrowserTriggerDrops([row], false);+ if (requestId !== dropPreviewRequestId || !prepared.isCurrent()) return;+ triggerDropPreview.value = prepared;+ dropPreviewSql.value = prepared.plan.entries.map((entry) => entry.sql).join("\n\n");+ } catch (error) {+ if (requestId === dropPreviewRequestId) dropPreviewError.value = error instanceof Error ? error.message : String(error);+ }+ return;+ }const sql = await buildDropSqlForRow(row, { cascade: canDropTargetCascade.value && dropTableCascade.value }).catch(() => "");if (requestId === dropPreviewRequestId) dropPreviewSql.value = sql;}@@ -2862,6 +3028,7 @@ async function refreshDropPreviewSql() {function dropConfirmTitle(): string {if (!dropTarget.value) return "";const type = dropTarget.value.type;+ if (type === "TRIGGER") return t("contextMenu.confirmDropTriggerTitle");if (type === "VIEW" || type === "MATERIALIZED_VIEW") return t("contextMenu.confirmDropViewTitle");if (type === "PROCEDURE") return t("contextMenu.confirmDropProcedureTitle");if (type === "FUNCTION") return t("contextMenu.confirmDropFunctionTitle");@@ -2873,6 +3040,7 @@ function dropConfirmMessage(): string {if (!dropTarget.value) return "";const name = dropTarget.value.name;const type = dropTarget.value.type;+ if (type === "TRIGGER") return t("contextMenu.confirmDropObjectMessage", { name });if (type === "VIEW" || type === "MATERIALIZED_VIEW") return t("contextMenu.confirmDropViewMessage", { name });if (type === "PROCEDURE") return t("contextMenu.confirmDropProcedureMessage", { name });if (type === "FUNCTION") return t("contextMenu.confirmDropFunctionMessage", { name });@@ -2881,8 +3049,8 @@ function dropConfirmMessage(): string {}function closeSource() {- sourceRow.value = null;- sidePanelRow.value = null;+ if (!confirmTriggerDraftDiscard()) return;+ closeSidePanel();sourceContent.value = "";sourceError.value = "";sourceEditing.value = false;@@ -3149,7 +3317,154 @@ async function fetchSortedTableRowsForDrop(): Promise<ObjectBrowserRow[]> {return sorted.map((t) => nameToRow.get(t.name)!).filter(Boolean);}+interface BrowserTriggerDropPreview {+ plan: OracleTriggerDropBatchPlan;+ rows: readonly ObjectBrowserRow[];+ context: string;+ pinnedContext: ReturnType<typeof objectBrowserPinnedTreeNodeContext>;+ isCurrent: () => boolean;+}+let batchTriggerDropPreviewRequestId = 0;++function usesExactTriggerDrop(row: ObjectBrowserRow): boolean {+ return row.type === "TRIGGER" && (!!exactOracleTriggerMetadata(row.trigger) || !!oracleTriggerObjectReadOptions(props.connection, undefined, props.catalog));+}++async function prepareBrowserTriggerDrops(selected: readonly ObjectBrowserRow[], batch: boolean): Promise<BrowserTriggerDropPreview> {+ const context = browserTriggerContext(),+ revision = browserTriggerViewRevision.value;+ const selection = [...selectedTableIds.value].sort().join("\n");+ const pinnedContext = { ...objectBrowserPinnedTreeNodeContext() };+ const fixed = { connectionId: props.connection.id, database: props.database, catalog: props.catalog, executionSchema: selectedSchema.value || props.schema || props.database };+ const expected = selected.map((row) => ({ id: row.id, objectId: exactOracleTriggerMetadata(row.trigger)?.objectId }));+ const cascade = batch && canBatchDropCascade.value && batchDropCascade.value;+ const current = () =>+ browserTriggerActive.value &&+ browserTriggerViewRevision.value === revision &&+ browserTriggerContext() === context &&+ (batch ? showBatchDropConfirm.value && [...selectedTableIds.value].sort().join("\n") === selection && (canBatchDropCascade.value && batchDropCascade.value) === cascade : showDropConfirm.value && dropTarget.value?.id === selected[0]?.id) &&+ expected.every((item) => rows.value.some((row) => row.id === item.id && (item.objectId === undefined || exactOracleTriggerMetadata(row.trigger)?.objectId === item.objectId)));+ // Verify triggers before dropping a selected parent. The existing FK sorter+ // still orders tables, with exact tuple keys instead of collapsing bare names.+ const tables = selected.filter((row) => row.type === "TABLE");+ const key = (schema: string | undefined | null, name: string) => JSON.stringify([schema ?? fixed.executionSchema, name]);+ const tableIds = new Map(tables.map((row) => [key(row.schema, row.name), row.id]));+ const foreignKeys = await Promise.all(tables.map((row) => api.listForeignKeys(fixed.connectionId, fixed.database, row.schema || fixed.executionSchema, row.name, fixed.catalog).catch(() => [] as ForeignKeyInfo[])));+ const sortedTables = sortTablesByFkDependency(tables.map((row, index) => ({ name: row.id, foreignKeys: foreignKeys[index].map((fk) => ({ ...fk, ref_table: tableIds.get(key(fk.ref_schema ?? row.schema, fk.ref_table)) ?? "" })) })));+ const ordered = [...selected.filter((row) => usesExactTriggerDrop(row)), ...sortedTables.map((table) => tables.find((row) => row.id === table.name)!), ...selected.filter((row) => row.type !== "TABLE" && !usesExactTriggerDrop(row))];+ const entries = [];+ let engine: OracleTriggerDropBatchPlan["engine"] | undefined;+ for (const row of ordered) {+ if (!current()) throw new Error(t("oracleTrigger.reloadBaseline"));+ if (usesExactTriggerDrop(row)) {+ const target = triggerRowTarget(row);+ const metadata = exactOracleTriggerMetadata(row.trigger)!;+ const triggerPlan = await prepareOracleTriggerPlan({ target, action: "delete", expectedObjectId: typeof metadata.objectId === "string" ? metadata.objectId : undefined });+ engine = triggerPlan.before.metadata.engine;+ entries.push({ id: row.id, sql: triggerPlan.steps[0].sql, triggerPlan });+ } else entries.push({ id: row.id, sql: await buildDropSqlForRow(row, { cascade }) });+ }+ if (!current() || !engine) throw new Error(t("oracleTrigger.reloadBaseline"));+ return { plan: prepareOracleTriggerDropBatchPlan({ target: fixed, entries, engine }), rows: ordered, context, pinnedContext, isCurrent: current };+}++function removeVerifiedBrowserDrop(row: ObjectBrowserRow, target: Pick<OracleTriggerTarget, "connectionId" | "database" | "catalog">, pinnedContext: ReturnType<typeof objectBrowserPinnedTreeNodeContext>) {+ const identity = objectBrowserRowPinnedTreeNodeIdentity(row, pinnedContext);+ const base = { ...identity, label: identity.name, objectName: identity.name, signature: identity.signature || undefined, schema: identity.schema || undefined, catalog: identity.catalog || undefined };+ connectionStore.removePinnedTreeNodes([base, ...objectBrowserRowLegacyPinnedTreeNodeIds(row, pinnedContext).map((id) => ({ ...base, id }))], exactOracleTriggerMetadata(row.trigger) ? undefined : canonicalizeObjectBrowserPinnedTreeNodeIdentity(pinnedContext));+ if (props.connection.id === target.connectionId && props.database === target.database && props.catalog === target.catalog) {+ const objectId = exactOracleTriggerMetadata(row.trigger)?.objectId;+ rows.value = rows.value.filter((item) => item.id !== row.id || (objectId !== undefined && exactOracleTriggerMetadata(item.trigger)?.objectId !== objectId));+ setSelectedTableIds(new Set([...selectedTableIds.value].filter((id) => rows.value.some((item) => item.id === id))));+ }+ const objectType = droppedTableObjectTypeForRow(row);+ if (objectType) queryStore.closeDroppedTableObjectTabs({ connectionId: target.connectionId, database: target.database, schema: row.schema ?? pinnedContext.schema, name: row.name, objectType });+ invalidateObjectBrowserRowsCache({ connectionId: target.connectionId, database: target.database });+}++async function executeBrowserTriggerDrops(preview: BrowserTriggerDropPreview, batch: boolean) {+ if (browserTriggerBusy.value || !preview.isCurrent()) return;+ const scope = `oracle-trigger-drop:${uuid()}`;+ const production = useProductionSafetyStore();+ const stop = watch(+ preview.isCurrent,+ (current) => {+ if (!current) production.cancelScope(scope);+ },+ { flush: "sync" },+ );+ browserTriggerBusy.value = true;+ batchDropExecuting.value = batch;+ batchDropProgress.value = { completed: 0, total: preview.rows.length };+ try {+ const result = await executeOracleTriggerDropBatchPlan(preview.plan, {+ confirmed: true,+ confirmationScope: scope,+ isCurrent: preview.isCurrent,+ onProgress: (completed) => {+ batchDropProgress.value = { completed, total: preview.rows.length };+ },+ });+ let completed = 0;+ const details: string[] = [];+ for (const [index, step] of result.steps.entries()) {+ const row = preview.rows[index];+ details.push(`${row.schema ?? preview.plan.target.executionSchema}.${row.name}\n${t(`oceanbasePrimaryKey.${step.state}`)}\n${step.sql}\n${step.error ?? ""}`);+ if (step.state === "committed" && (!step.trigger || step.trigger.verification === "deleted")) {+ removeVerifiedBrowserDrop(row, preview.plan.target, preview.pinnedContext);+ completed++;+ if (!step.trigger) {+ const request = { connectionId: preview.plan.target.connectionId, database: preview.plan.target.database, catalog: preview.plan.target.catalog, schema: row.schema ?? preview.plan.target.executionSchema, tableName: row.name };+ const refreshed = await Promise.allSettled([invalidateObjectMetadataCache(request), invalidateObjectDdl(request)]);+ details.push(...refreshed.flatMap((item) => (item.status === "rejected" ? [String(item.reason)] : [])));+ }+ }+ }+ const failed = result.triggerResults.find((item) => item.result.steps.some((step) => step.state !== "committed"));+ if (failed) {+ const index = preview.plan.entries.findIndex((entry) => entry.id === failed.draftId);+ const target = preview.plan.entries[index].triggerPlan!.target;+ browserTriggerFeedback.value = { target, row: preview.rows[index], result: failed.result, snapshot: failed.result.snapshot, pinnedContext: preview.pinnedContext };+ } else browserTriggerFeedback.value = undefined;+ if (completed === preview.rows.length && !result.triggerResults.some((item) => item.result.refreshError)) toast(batch ? t("contextMenu.batchDropSuccess", { count: completed }) : t("contextMenu.dropTableChildObjectSuccess", { name: preview.rows[0].name }));+ else if (!result.cancelled && browserTriggerActive.value && browserTriggerContext() === preview.context) {+ compileErrorTitle.value = t("oracleStructureResult.resultTitle");+ compileErrorMessage.value = [...details, ...result.triggerResults.map((item) => item.result.refreshError)].filter(Boolean).join("\n\n");+ showCompileErrorDialog.value = true;+ }+ } catch (error) {+ if (browserTriggerActive.value && browserTriggerContext() === preview.context) {+ browserTriggerFeedback.value = undefined;+ compileErrorTitle.value = t("oracleStructureResult.resultTitle");+ compileErrorMessage.value = error instanceof Error ? error.message : String(error);+ showCompileErrorDialog.value = true;+ }+ } finally {+ stop();+ production.cancelScope(scope);+ browserTriggerBusy.value = false;+ batchDropExecuting.value = false;+ if (batch) showBatchDropConfirm.value = false;+ else showDropConfirm.value = false;+ }+}+async function refreshBatchDropPreviewSql() {+ if (batchTriggerDropRequested.value) {+ const requestId = ++batchTriggerDropPreviewRequestId;+ batchTriggerDropPreview.value = undefined;+ batchDropPreviewSql.value = "";+ batchDropPreviewError.value = "";+ try {+ const prepared = await prepareBrowserTriggerDrops([...selectedTableRows.value], true);+ if (requestId !== batchTriggerDropPreviewRequestId || !prepared.isCurrent()) return;+ batchTriggerDropPreview.value = prepared;+ batchDropPreviewSql.value = prepared.plan.entries.map((entry) => entry.sql).join("\n\n");+ } catch (error) {+ if (requestId === batchTriggerDropPreviewRequestId) batchDropPreviewError.value = error instanceof Error ? error.message : String(error);+ }+ return;+ }const statements: string[] = [];const sortedRows = await fetchSortedTableRowsForDrop();const useCascade = canBatchDropCascade.value && batchDropCascade.value;@@ -3162,6 +3477,10 @@ async function refreshBatchDropPreviewSql() {function requestBatchDropTables() {if (selectedTableCount.value === 0) return;+ if (browserTriggerBusy.value) return;+ batchTriggerDropRequested.value = selectedTableRows.value.some(usesExactTriggerDrop);+ batchTriggerDropPreview.value = undefined;+ batchDropPreviewError.value = "";if (selectedTableRows.value.some((row) => row.type === "INDEX")) {toast(t("schemaIndex.editIndividually"), 4000);return;@@ -3181,13 +3500,17 @@ function requestBatchDropTables() {batchDropCascade.value = false;batchDropProgress.value = { completed: 0, total: 0 };batchDropPreviewSql.value = "";- void refreshBatchDropPreviewSql();showBatchDropConfirm.value = true;+ void refreshBatchDropPreviewSql();}async function confirmBatchDropTables() {if (batchDropExecuting.value) return;if (selectedTableRows.value.some((row) => row.type === "INDEX")) return;+ if (batchTriggerDropRequested.value) {+ if (batchTriggerDropPreview.value) await executeBrowserTriggerDrops(batchTriggerDropPreview.value, true);+ return;+ }batchDropExecuting.value = true;let batchSql = "";let batchDropRecorded = false;@@ -3897,6 +4220,13 @@ function onObjectBrowserKeydown(event: KeyboardEvent) {return;}if (!supportsBatchTableActions.value) return;+ if (event.key === "Delete" && !event.isComposing && !event.ctrlKey && !event.metaKey && !event.altKey && !event.shiftKey && !eventTargetUsesNativeClipboard(event) && selectedTableRows.value.some(usesExactTriggerDrop)) {+ event.preventDefault();+ event.stopPropagation();+ if (selectedTableCount.value === 1) requestDrop(selectedTableRows.value[0]);+ else requestBatchDropTables();+ return;+ }if (eventTargetAllowsAppClipboardShortcut(event, "c")) {if (selectedTableCount.value === 0) return;event.preventDefault();@@ -4070,6 +4400,7 @@ async function executeObjectBrowserSqlWithProductionGuard<T>(sql: string, execut}async function compileXuguObject(row: ObjectBrowserRow) {+ browserTriggerFeedback.value = undefined;if (effectiveDatabaseType.value !== "xugu") return;const sql = buildXuguCompileSql({ objectType: row.type, schema: row.schema || selectedSchema.value, name: row.name });if (!sql) return;@@ -4314,6 +4645,14 @@ async function saveSource() {return;}if (!sourceRow.value || !sourceDraft.value.trim()) return;+ if (sourceTriggerRequested.value) {+ if (!sourceTriggerSnapshot.value) {+ sourceSaveError.value = t("oracleTrigger.reloadBaseline");+ return;+ }+ await runSourceTriggerAction("replace");+ return;+ }const row = sourceRow.value;const epoch = sidePanelGuard.capture();const connectionId = props.connection.id;@@ -4389,6 +4728,161 @@ async function saveSource() {}}+async function runSourceTriggerAction(action: OracleTriggerAction) {+ const baseline = sourceTriggerSnapshot.value;+ const row = sourceRow.value;+ if (!baseline || !row || sourceSaving.value || sourceLoading.value) return;+ const epoch = sidePanelGuard.capture(),+ draft = sourceDraft.value;+ const current = () => sidePanelGuard.isFresh(epoch) && sourceRow.value === row && props.connection.id === baseline.target.connectionId && props.database === baseline.target.database && props.catalog === baseline.target.catalog && (action !== "replace" || sourceDraft.value === draft);+ sourceSaving.value = true;+ sourceSaveError.value = "";+ try {+ const plan = await prepareOracleTriggerPlan({ target: baseline.target, action, expectedObjectId: baseline.metadata.objectId ?? undefined, ...(action === "replace" ? { baseline, source: draft } : {}) });+ if (!current()) return;+ const result = await confirmOracleTriggerPlan(plan, { isCurrent: current });+ if (sidePanelGuard.isStale(epoch)) return;+ sourceTriggerResult.value = result;+ const committed = !result.cancelled && result.steps.every((step) => step.state === "committed");+ if (committed && result.snapshot && result.snapshot.metadata.objectId === baseline.metadata.objectId && (action === "replace" || baseline.raw.source === plan.before.raw.source)) {+ sourceTriggerSnapshot.value = result.snapshot;+ sourceIdentity = result.snapshot.identity;+ } else if (result.snapshot) sourceTriggerIssue.value = t("oracleTrigger.reloadBaseline");+ if (!result.cancelled && result.steps.every((step) => step.state === "committed") && !result.steps.some((step) => step.verification === "invalid") && action === "replace") {+ sourceEditing.value = false;+ await loadSourcePanel(row);+ }+ } catch (error) {+ if (sidePanelGuard.isFresh(epoch)) sourceSaveError.value = error instanceof Error ? error.message : String(error);+ } finally {+ if (sidePanelGuard.isFresh(epoch)) sourceSaving.value = false;+ }+}++function openSourceTriggerParent() {+ const parent = sourceTriggerSnapshot.value?.metadata.parent;+ if (!parent || (sourceEditing.value && sourceDraft.value !== sourceEditableText.value && !window.confirm(t("objectDependencies.navigateDiscardConfirm")))) return;+ emit("openTable", { schema: parent.owner, tableName: parent.name, tableType: parent.objectType, catalog: props.catalog });+}++function triggerRowTarget(row: ObjectBrowserRow): OracleTriggerTarget {+ const metadata = exactOracleTriggerMetadata(row.trigger);+ if (!metadata) throw new Error(t("oracleTrigger.reloadBaseline"));+ return { connectionId: props.connection.id, database: props.database, catalog: props.catalog, owner: metadata.owner, name: metadata.name, executionSchema: selectedSchema.value || props.schema || metadata.owner };+}++function mergeBrowserTriggerSnapshot(target: Readonly<OracleTriggerTarget>, snapshot?: OracleTriggerSnapshot, nativeBefore?: OracleTriggerSnapshot, nativeVerified = false) {+ if (!snapshot?.exists || !snapshot.raw.trigger || props.connection.id !== target.connectionId || props.database !== target.database || props.catalog !== target.catalog) return;+ const trigger = snapshot.raw.trigger;+ rows.value = rows.value.map((row) => {+ const metadata = exactOracleTriggerMetadata(row.trigger);+ return row.type === "TRIGGER" && metadata?.owner === target.owner && metadata.name === target.name && (!nativeBefore || (metadata.objectId === nativeBefore.metadata.objectId && snapshot.metadata.objectId === nativeBefore.metadata.objectId))+ ? { ...row, trigger, valid: trigger.valid, updated_at: snapshot.metadata.lastDdlTime ?? row.updated_at }+ : row;+ });+ const source = sourceTriggerSnapshot.value;+ if (source?.target.connectionId === target.connectionId && source.target.database === target.database && source.target.catalog === target.catalog && source.target.owner === target.owner && source.target.name === target.name) {+ // A native action can update our own baseline only when it preserved the+ // version that this editor actually loaded. A read-only refresh is not consent+ // to replace a dirty candidate's baseline with an external definition.+ if (nativeVerified && nativeBefore && snapshot.metadata.objectId === source.metadata.objectId && source.metadata.objectId === nativeBefore.metadata.objectId && source.raw.source === nativeBefore.raw.source) {+ sourceTriggerSnapshot.value = snapshot;+ sourceIdentity = snapshot.identity;+ } else sourceTriggerIssue.value = t("oracleTrigger.reloadBaseline");+ }+}++function describeBrowserTriggerResult(target: Readonly<OracleTriggerTarget>, result: OracleTriggerExecutionResult): string {+ const snapshot = result.snapshot,+ metadata = snapshot?.metadata;+ const enabled = metadata?.reads.enabled?.state === "available" && typeof snapshot?.raw.trigger?.enabled === "boolean" ? t(snapshot.raw.trigger.enabled ? "objects.enabled" : "objects.disabled") : t("oracleTrigger.unknown");+ const valid = metadata?.reads.validity?.state === "available" && typeof snapshot?.raw.trigger?.valid === "boolean" ? (snapshot.raw.trigger.valid ? "VALID" : "INVALID") : t("oracleTrigger.unknown");+ const errors = metadata?.reads.errors?.state === "available" ? metadata.errors?.map((error) => `${error.line ?? "?"}:${error.position ?? "?"} ${error.text}`).join("\n") : `${t("processList.oracleInvalidObjects.errorsTitle")}: ${t("oracleTrigger.unknown")}`;+ return [+ `${target.database} · ${target.owner}.${target.name}`,+ `${t("oracleTrigger.executionSchema")}: ${target.executionSchema}`,+ `${enabled} · ${valid}`,+ ...result.steps.map((step) => `${t(`oceanbasePrimaryKey.${step.state}`)} · ${step.verification}\n${[step.error, step.readbackError].filter(Boolean).join("\n")}`),+ errors,+ result.refreshError,+ ]+ .filter(Boolean)+ .join("\n\n");+}++async function refreshBrowserTriggerFeedback() {+ const feedback = browserTriggerFeedback.value;+ if (!feedback || browserTriggerBusy.value) return;+ browserTriggerBusy.value = true;+ try {+ if (feedback.result.steps.some((step) => step.action === "delete")) {+ await verifyOracleTriggerDeletion({ ...feedback.target });+ if (browserTriggerFeedback.value !== feedback) return;+ if (feedback.pinnedContext) removeVerifiedBrowserDrop(feedback.row, feedback.target, feedback.pinnedContext);+ compileErrorMessage.value += `\n\n${t("contextMenu.dropTableChildObjectSuccess", { name: feedback.target.name })}`;+ browserTriggerFeedback.value = undefined;+ return;+ }+ const read = await readOracleTriggerSource({ ...feedback.target });+ if (browserTriggerFeedback.value !== feedback) return;+ const next = { ...feedback, snapshot: read.snapshot, result: { ...feedback.result, snapshot: read.snapshot } };+ browserTriggerFeedback.value = next;+ mergeBrowserTriggerSnapshot(feedback.target, read.snapshot);+ compileErrorMessage.value = describeBrowserTriggerResult(feedback.target, next.result) + (read.identityError ? `\n\n${read.identityError}` : "");+ } catch (error) {+ if (browserTriggerFeedback.value === feedback) compileErrorMessage.value += `\n\n${error instanceof Error ? error.message : String(error)}`;+ } finally {+ browserTriggerBusy.value = false;+ }+}++async function runBrowserTriggerAction(row: ObjectBrowserRow, action: "enable" | "disable" | "compile") {+ if (browserTriggerBusy.value) return;+ const context = browserTriggerContext(),+ revision = browserTriggerViewRevision.value;+ const metadata = exactOracleTriggerMetadata(row.trigger);+ const expectedId = typeof metadata?.objectId === "string" ? metadata.objectId : undefined;+ const current = () => browserTriggerActive.value && browserTriggerViewRevision.value === revision && browserTriggerContext() === context && rows.value.some((item) => item.id === row.id && (expectedId === undefined || exactOracleTriggerMetadata(item.trigger)?.objectId === expectedId));+ browserTriggerBusy.value = true;+ try {+ const target = triggerRowTarget(row);+ const plan = await prepareOracleTriggerPlan({ target, action, expectedObjectId: expectedId });+ if (!current()) return;+ const result = await confirmOracleTriggerPlan(plan, { isCurrent: current });+ if (result.cancelled) return;+ mergeBrowserTriggerSnapshot(+ plan.target,+ result.snapshot,+ plan.before,+ result.steps.every((step) => step.state === "committed"),+ );+ if (sourceTriggerSnapshot.value?.target.owner === target.owner && sourceTriggerSnapshot.value.target.name === target.name && sourceTriggerSnapshot.value.target.connectionId === target.connectionId) sourceTriggerResult.value = result;+ const complete = result.steps.every((step) => step.state === "committed" && step.verification !== "invalid");+ const message = describeBrowserTriggerResult(plan.target, result);+ if ((!complete || result.refreshError) && browserTriggerActive.value && browserTriggerContext() === context) {+ browserTriggerFeedback.value = { target: plan.target, row, result, snapshot: result.snapshot };+ compileErrorTitle.value = t("oracleStructureResult.resultTitle");+ compileErrorMessage.value = message;+ showCompileErrorDialog.value = true;+ } else {+ const label =+ result.steps.some((step) => step.verification === "invalid") || !complete+ ? message+ : `${t(action === "enable" ? "contextMenu.enableTriggerSuccess" : action === "disable" ? "contextMenu.disableTriggerSuccess" : "contextMenu.compileObjectSuccess", { name: target.name })}${result.snapshot?.raw.trigger?.valid === false ? " · INVALID" : ""}`;+ toast(label, !complete ? 10000 : 4000);+ }+ } catch (error) {+ if (browserTriggerActive.value && browserTriggerContext() === context) {+ browserTriggerFeedback.value = undefined;+ compileErrorTitle.value = t("oracleStructureResult.resultTitle");+ compileErrorMessage.value = error instanceof Error ? error.message : String(error);+ showCompileErrorDialog.value = true;+ }+ } finally {+ browserTriggerBusy.value = false;+ }+}+async function loadSchemas(epoch: number): Promise<boolean> {if (!schemaListLoadGuard.isEpochCurrent(epoch)) return false;if (!needsSchema.value) {@@ -4424,6 +4918,7 @@ function objectBrowserRowsCacheScope(schema: string): ObjectBrowserRowsCacheScopdatabase: props.database,schema,catalog: props.catalog,+ ...(oracleTriggerObjectReadOptions(props.connection, undefined, props.catalog) ? { oracleTriggerContract: 1 as const } : {}),...(supportsSchemaIndexes.value ? { exactIdentity: true } : {}),};}@@ -4495,6 +4990,8 @@ async function loadObjects(options?: { allowCached?: boolean; preserveExistingRo// the toolbar icon — the newest request owns the spinner state from here.loadingObjects.value = false;refreshingObjects.value = false;+ loadingMoreObjects.value = false;+ objectPageNextAnchor = undefined;scaffoldRefreshError.value = "";// True when we are revalidating on top of visible rows (a stale-cache scaffold, or a// same-instance refresh) — a failure then keeps the rows and raises a non-blocking@@ -4565,8 +5062,9 @@ async function loadObjects(options?: { allowCached?: boolean; preserveExistingRo}}-function exactIndexPageAnchor(object: ObjectInfo | undefined): string | undefined {- return object ? JSON.stringify([object.schema, object.name, object.parent_schema, object.parent_name]) : undefined;+function objectPageAnchor(object: ObjectInfo): string {+ if (object.object_type === "INDEX") return JSON.stringify([object.schema, object.name, object.parent_schema, object.parent_name]);+ return exactOracleTriggerMetadata(object.trigger) ? tablePageRowAnchorKey(object.name, object.schema, undefined, object.trigger) : JSON.stringify([object.schema, object.name, object.object_type, object.signature]);}async function loadObjectPage(append: boolean, options?: { preserveExistingRows?: boolean }) {@@ -4574,12 +5072,12 @@ async function loadObjectPage(append: boolean, options?: { preserveExistingRows?const schema = exactIndexList.value ? indexParentSchema() : needsSchema.value ? objectListSchemaForConnection(props.connection, selectedSchema.value) : props.database;const request = objectBrowserRowsLoadGuard.start(objectBrowserRowsCacheScope(schema));const offset = append ? objectPageOffset : 0;- const pageSize = objectPageSize.value;+ const keepExisting = !append && options?.preserveExistingRows && rows.value.length > 0;+ let pageSize = keepExisting ? Math.max(objectPageSize.value, objectPageOffset) : objectPageSize.value;+ const nextAnchor = append ? objectPageNextAnchor : undefined;const filter = search.value.trim();const typeFilter = objectFilter.value;const exactIdentity = exactIndexList.value;- const keepExisting = exactIdentity && !append && options?.preserveExistingRows === true && rows.value.length > 0;- const expectedAnchor = append ? indexNextPageAnchor : undefined;const queryTypes = supportsSchemaIndexes.value && typeFilter === "all" ? sidebarObjectKindsForDatabase(effectiveDatabaseType.value).filter((type) => type !== "INDEX") : undefined;const objectTypes: Partial<Record<ObjectFilter, (SidebarObjectKind | "EVENT")[]>> = {tables: ["TABLE"],@@ -4598,50 +5096,51 @@ async function loadObjectPage(append: boolean, options?: { preserveExistingRows?error.value = "";scaffoldRefreshError.value = "";loadingObjects.value = !append && !keepExisting;- refreshingObjects.value = keepExisting;+ refreshingObjects.value = !!keepExisting;loadingMoreObjects.value = append;if (!append && !keepExisting) {rows.value = [];hasMoreObjects.value = false;objectPageOffset = 0;- indexNextPageAnchor = undefined;+ objectPageNextAnchor = undefined;}try {if (parseSlashDelimitedRegexQuery(filter)) {error.value = t("objects.pagedRegexUnsupported");return;}+ const requestedTypes = queryTypes ?? objectTypes[typeFilter];+ const readOptions = oracleTriggerObjectReadOptions(props.connection, requestedTypes, request.scope.catalog);const fetchPage = (pageOffset: number, size: number) =>objectBrowserRowsLoadGuard.wait(request.epoch,exactIdentity? api.listObjects(request.scope.connectionId, request.scope.database, request.scope.schema, objectTypes[typeFilter], filter || undefined, size + 1, pageOffset, request.scope.catalog, undefined, undefined, true)- : api.listObjects(request.scope.connectionId, request.scope.database, request.scope.schema, queryTypes ?? objectTypes[typeFilter], filter || undefined, size + 1, pageOffset, request.scope.catalog),+ : readOptions+ ? api.listObjects(request.scope.connectionId, request.scope.database, request.scope.schema, requestedTypes, filter || undefined, size + 1, pageOffset, request.scope.catalog, undefined, undefined, readOptions)+ : api.listObjects(request.scope.connectionId, request.scope.database, request.scope.schema, requestedTypes, filter || undefined, size + 1, pageOffset, request.scope.catalog),metadataLoadBudgetMs(props.connection.query_timeout_secs),);let objects = await fetchPage(offset, pageSize);if (!isCurrent()) return;- let pageOffset = offset;- let size = pageSize;- // Match the sidebar's peek-row contract: a moved offset replaces the whole- // displayed window instead of appending an overlapping or incomplete page.- if (exactIdentity && append && expectedAnchor && exactIndexPageAnchor(objects[0]) !== expectedAnchor) {- pageOffset = 0;- size = offset + pageSize;- objects = await fetchPage(pageOffset, size);+ let replaceWindow = !append;+ if (append && nextAnchor && (!objects[0] || objectPageAnchor(objects[0]) !== nextAnchor)) {+ pageSize += offset;+ objects = await fetchPage(0, pageSize);if (!isCurrent()) return;+ replaceWindow = true;}- const page = objects.slice(0, size);+ const page = objects.slice(0, pageSize);const pageRows = buildObjectBrowserRows({objects: page.filter((object) => !supportsSchemaIndexes.value || typeFilter !== "all" || object.object_type !== "INDEX"),database: request.scope.database,fallbackSchema: request.scope.schema,rowSchema: connectionObjectTreeNodeSchema(props.connection, props.database, selectedSchema.value),});- applyObjectBrowserRows(append && pageOffset > 0 ? [...rows.value, ...pageRows] : pageRows);- objectPageOffset = pageOffset + page.length;- hasMoreObjects.value = objects.length > size;- indexNextPageAnchor = exactIdentity && hasMoreObjects.value ? exactIndexPageAnchor(objects[size]) : undefined;+ applyObjectBrowserRows(replaceWindow ? pageRows : [...rows.value, ...pageRows]);+ objectPageOffset = (replaceWindow ? 0 : offset) + page.length;+ hasMoreObjects.value = objects.length > pageSize;+ objectPageNextAnchor = hasMoreObjects.value ? objectPageAnchor(objects[pageSize]) : undefined;} catch (e: unknown) {if (!isCurrent()) return;if (append || keepExisting) scaffoldRefreshError.value = translateBackendError(t, e);@@ -4660,7 +5159,10 @@ async function loadSqlObjectBrowserRows(request: ObjectBrowserRowsLoadHandle) {// Schema indexes use their dedicated exact, server-paged filter. Mixing an// unbounded exact subset into the legacy all view defeats both contracts.const types = supportsSchemaIndexes.value ? sidebarObjectKindsForDatabase(effectiveDatabaseType.value).filter((type) => type !== "INDEX") : undefined;- const objects = await api.listObjects(request.scope.connectionId, request.scope.database, request.scope.schema, types, undefined, undefined, undefined, request.scope.catalog);+ const readOptions = oracleTriggerObjectReadOptions(props.connection, types, request.scope.catalog);+ const objects: ObjectInfo[] = await (readOptions+ ? api.listObjects(request.scope.connectionId, request.scope.database, request.scope.schema, types, undefined, undefined, undefined, request.scope.catalog, undefined, undefined, readOptions)+ : api.listObjects(request.scope.connectionId, request.scope.database, request.scope.schema, types, undefined, undefined, undefined, request.scope.catalog));return buildObjectBrowserRows({objects: objects.filter((object) => !supportsSchemaIndexes.value || object.object_type !== "INDEX"),database: request.scope.database,@@ -4759,7 +5261,7 @@ function onSchemaChange(value: any) {selectedSchema.value = typeof value === "string" && value ? value : undefined;emit("schemaChange", selectedSchema.value);userHasSelectedFilter.value = false;- objectFilter.value = usesServerObjectPaging.value ? (props.selectedObjectFilter ?? props.initialObjectFilter ?? "tables") : "all";+ objectFilter.value = initialObjectBrowserFilter();void loadObjects();}@@ -4798,11 +5300,11 @@ function filterLabel(filter: ObjectFilter) {function selectObjectFilter(filter: ObjectFilter) {if (filter === objectFilter.value) return;- const wasPaged = usesServerObjectPaging.value;+ const wasServerPaged = usesServerObjectPaging.value;userHasSelectedFilter.value = true;objectFilter.value = filter;emit("filterChange", filter);- if (wasPaged || usesServerObjectPaging.value) void loadObjects();+ if (wasServerPaged || usesServerObjectPaging.value) void loadObjects();}watch(@@ -4878,13 +5380,13 @@ watch();watch(- [() => props.connection.id, () => props.database, () => props.schema],+ [() => props.connection.id, () => props.database, () => props.schema, () => props.catalog],async () => {objectBrowserRowsLoadGuard.invalidate();const contextEpoch = schemaListLoadGuard.invalidate();selectedSchema.value = props.schema;userHasSelectedFilter.value = false;- objectFilter.value = usesServerObjectPaging.value ? (props.selectedObjectFilter ?? props.initialObjectFilter ?? "tables") : "all";+ objectFilter.value = initialObjectBrowserFilter();clearTableSelection();selectedRowId.value = null;// Close side panel and invalidate any pending source/table-info requests@@ -5119,6 +5621,25 @@ function getProcFuncMenuItems(item: ObjectBrowserRow): ContextMenuItem[] {];}+function getTriggerMenuItems(item: ObjectBrowserRow): ContextMenuItem[] {+ const metadata = exactOracleTriggerMetadata(item.trigger);+ if (!metadata) return getPackageMenuItems(item);+ const enabled = metadata.reads.enabled?.state === "available" ? item.trigger?.enabled : undefined;+ const databaseType = metadata.engine === "dm" ? "dameng" : metadata.engine;+ return [+ { sidebarActionId: "contextMenu.editObject", label: t("contextMenu.editObject"), action: () => openSource(item), icon: PencilLine },+ { sidebarActionId: "contextMenu.viewSource", label: t("contextMenu.viewSource"), action: () => openSource(item), icon: Code2 },+ { label: "", separator: true },+ ...(enabled !== true ? [{ label: t("contextMenu.enableTrigger"), action: () => runBrowserTriggerAction(item, "enable"), icon: Play, disabled: browserTriggerBusy.value }] : []),+ ...(enabled !== false ? [{ label: t("contextMenu.disableTrigger"), action: () => runBrowserTriggerAction(item, "disable"), icon: CircleX, disabled: browserTriggerBusy.value }] : []),+ ...(!oracleCompileUnsupportedReason(databaseType, "TRIGGER", { triggerProfile: metadata }) ? [{ label: t("contextMenu.compileObject"), action: () => runBrowserTriggerAction(item, "compile"), icon: Wrench, disabled: browserTriggerBusy.value }] : []),+ { label: "", separator: true },+ { label: t("contextMenu.dropTrigger"), action: () => requestDrop(item), icon: Trash2, variant: "destructive" as const, disabled: browserTriggerBusy.value },+ { label: "", separator: true },+ { label: t("contextMenu.copyName"), action: () => copyName(item), icon: Copy },+ ];+}+function getEventMenuItems(item: ObjectBrowserRow): ContextMenuItem[] {return [{ label: t("contextMenu.editObject"), action: () => openEventEditor(item), icon: PencilLine },@@ -5201,6 +5722,7 @@ function getObjectBrowserActionMenuItems(item: ObjectBrowserRow): ContextMenuIteif (item.type === "VIEW" || item.type === "MATERIALIZED_VIEW") return getViewMenuItems(item);if (item.type === "EVENT") return getEventMenuItems(item);if (item.type === "TYPE" || item.type === "TYPE_BODY") return getTypeMenuItems(item);+ if (item.type === "TRIGGER") return getTriggerMenuItems(item);if (isSourceOnlyObjectBrowserRow(item)) return getPackageMenuItems(item);return getProcFuncMenuItems(item);}@@ -5235,15 +5757,40 @@ function getObjectBrowserMenuItems(item: ObjectBrowserRow): ContextMenuItem[] {@confirm="cloneDialog.confirm"/><FirebirdObjectManager v-if="effectiveDatabaseType === 'firebird'" v-model:open="firebirdManagerOpen" :connection-id="connection.id" :database="database" />+ <ObjectSourceDialog+ v-if="triggerCreateContext"+ :key="JSON.stringify(triggerCreateContext)"+ ref="triggerCreateDialog"+ v-model:open="triggerCreateOpen"+ :connection-id="triggerCreateContext.connectionId"+ :database="triggerCreateContext.database"+ :catalog="triggerCreateContext.catalog"+ :schema="triggerCreateContext.schema"+ :execution-schema="triggerCreateContext.schema"+ :database-type="triggerCreateContext.databaseType"+ name="TRG_NEW"+ object-type="TRIGGER"+ :dialect="codeMirrorSqlDialect(triggerCreateContext.databaseType)"+ :format-dialect="sqlFormatDialectForDbType(triggerCreateContext.databaseType)"+ :create-trigger="{ scope: 'TABLE' }"+ initial-editing+ @saved="refreshCreatedTrigger"+ /><OracleInvalidObjectsDialog- v-if="oracleInvalidObjectsSupported"- :open="oracleInvalidObjectsOpen"+ v-if="oracleInvalidObjectsSupported || invalidTriggerContext"+ :open="oracleInvalidObjectsOpen && (!invalidTriggerContext || sidePanelGuard.isFresh(invalidTriggerContext.originRevision))":connection="connection":database="database":schema="selectedSchema || database"+ :trigger-context="invalidTriggerContext"@update:open="setOracleInvalidObjectsOpen"@open-source="openInvalidObjectSource"@compile-finished="refreshAfterInvalidObjectCompile"+ @trigger-result="+ (target, result, before, _tabId, revision) => {+ if (revision === undefined || sidePanelGuard.isFresh(revision)) mergeBrowserTriggerSnapshot(target, result.snapshot, before, !result.cancelled && result.steps.every((step) => step.state === 'committed'));+ }+ "/><div ref="rootRef" data-object-browser-root class="flex h-full min-h-0 min-w-0 flex-col bg-background outline-none" tabindex="0" @keydown="onObjectBrowserKeydown"><SidebarMenuPreferencesDialog v-if="sidebarMenuPreferences" v-model:open="sidebarMenuPreferencesOpen" :scope="sidebarMenuPreferences.scope" :items="sidebarMenuPreferences.items" />@@ -5297,6 +5844,7 @@ function getObjectBrowserMenuItems(item: ObjectBrowserRow): ContextMenuItem[] {content-class="w-56"@update:model-value="onSchemaChange"/>+ <Button v-if="canCreateOracleTrigger && objectFilter === 'triggers'" variant="outline" size="sm" class="h-7 shrink-0 px-2 text-xs" @click="openCreateOracleTrigger">{{ t("contextMenu.createTrigger") }}</Button><!-- Sort selector --><div v-if="showInlineSortAndView && !usesServerObjectPaging" class="flex h-7 shrink-0 items-center rounded border bg-muted/20 p-0.5"><select@@ -5978,30 +6526,38 @@ function getObjectBrowserMenuItems(item: ObjectBrowserRow): ContextMenuItem[] {<span v-if="sourceRow?.valid != null" class="shrink-0 rounded border px-1 py-px text-[10px] font-medium" :class="sourceRow.valid ? 'border-emerald-500/30 text-emerald-600' : 'border-destructive/30 text-destructive'">{{ t(sourceRow.valid ? "objects.validStatus" : "objects.invalidStatus") }}</span>- <template v-if="sourceSection === 'source'">- <Button v-if="sourceEditing" variant="ghost" size="sm" class="h-6 px-2 text-xs" :disabled="sourceSaving || !sourceDraft.trim()" @click="saveSource">- <Loader2 v-if="sourceSaving" class="mr-1 h-3 w-3 animate-spin" />- {{ t("objects.saveSource") }}- </Button>- <Button v-if="sourceEditing" variant="ghost" size="sm" class="h-6 px-2 text-xs" :disabled="sourceSaving" @click="cancelEditSource">- {{ t("objects.cancelEdit") }}- </Button>- <Button v-if="!sourceEditing" variant="ghost" size="icon" class="h-5 w-5" :disabled="!sourceContent" @click="copySource">- <Copy class="h-3 w-3" />- </Button>- <Button v-if="!sourceEditing && sourceCanEdit" variant="ghost" size="icon" class="h-5 w-5" :disabled="!sourceContent" @click="editSource">- <PencilLine class="h-3 w-3" />- </Button>- <Button variant="ghost" size="icon" class="h-5 w-5" :disabled="sourceLoading || sourceSaving" :title="t('structureEditor.refresh')" :aria-label="t('structureEditor.refresh')" @click="refreshActiveSource">- <RefreshCw class="h-3 w-3" :class="{ 'animate-spin': sourceLoading }" />- </Button>- </template>+ <Button v-if="sourceEditing && sourceSection === 'source'" variant="ghost" size="sm" class="h-6 px-2 text-xs" :disabled="sourceSaving || sourceLoading || !sourceDraft.trim()" @click="saveSource">+ <Loader2 v-if="sourceSaving" class="mr-1 h-3 w-3 animate-spin" />+ {{ t("objects.saveSource") }}+ </Button>+ <Button v-if="sourceEditing && sourceSection === 'source'" variant="ghost" size="sm" class="h-6 px-2 text-xs" :disabled="sourceSaving || sourceLoading" @click="cancelEditSource">+ {{ t("objects.cancelEdit") }}+ </Button>+ <Button v-if="!sourceEditing && sourceSection === 'source'" variant="ghost" size="icon" class="h-5 w-5" :disabled="!sourceContent" @click="copySource">+ <Copy class="h-3 w-3" />+ </Button>+ <Button v-if="!sourceEditing && sourceCanEdit && sourceSection === 'source'" variant="ghost" size="icon" class="h-5 w-5" :disabled="!sourceContent" @click="editSource">+ <PencilLine class="h-3 w-3" />+ </Button>+ <Button v-if="sourceSection === 'source'" variant="ghost" size="icon" class="h-5 w-5" :disabled="sourceLoading || sourceSaving" :title="t('structureEditor.refresh')" :aria-label="t('structureEditor.refresh')" @click="refreshActiveSource">+ <RefreshCw class="h-3 w-3" :class="{ 'animate-spin': sourceLoading }" />+ </Button><Button variant="ghost" size="icon" class="h-5 w-5" @click="closeSource"><X class="h-3 w-3" /></Button></div>- <ObjectDependenciesPanel :target="dependencyTarget" v-model:section="sourceSection" @view-sql="viewRelationSql" @open-object="openRelationObject">- <div v-if="sourceLoading" class="flex flex-1 items-center justify-center">+ <ObjectDependenciesPanel :target="sourceDependencyTarget" v-model:section="sourceSection" @view-sql="viewRelationSql" @open-object="openRelationObject">+ <OracleTriggerStatus+ :snapshot="sourceTriggerSnapshot"+ :result="sourceTriggerResult"+ :source-issue="sourceTriggerIssue"+ :busy="sourceLoading || sourceSaving"+ @action="runSourceTriggerAction"+ @parent="openSourceTriggerParent"+ @refresh="refreshActiveSource"+ @diagnostics="openBrowserTriggerDiagnostics"+ />+ <div v-if="sourceLoading && !sourceEditing" class="flex flex-1 items-center justify-center"><Loader2 class="h-4 w-4 animate-spin text-muted-foreground" /></div><div v-else-if="sourceError" class="flex flex-1 items-center justify-center px-4 text-sm text-destructive">@@ -6020,9 +6576,6 @@ function getObjectBrowserMenuItems(item: ObjectBrowserRow): ContextMenuItem[] {force-word-wrap@save="sourceSection === 'source' && saveSource()"/>- <div v-if="sourceSaveError" class="shrink-0 whitespace-pre-wrap break-words border-t px-3 py-2 text-xs text-destructive">- {{ sourceSaveError }}- </div></div><QueryEditorv-else@@ -6039,15 +6592,29 @@ function getObjectBrowserMenuItems(item: ObjectBrowserRow): ContextMenuItem[] {read-onlydata-object-source-preview/>+ <div v-if="sourceSaveError" class="shrink-0 whitespace-pre-wrap break-words border-t px-3 py-2 text-xs text-destructive">+ {{ sourceSaveError }}+ </div></ObjectDependenciesPanel></template></div></div></div>- <DangerConfirmDialog v-model:open="showDropConfirm" :title="dropConfirmTitle()" :message="dropConfirmMessage()" :sql="dropPreviewSql" :confirm-label="t('dangerDialog.deleteConfirm')" @confirm="confirmDrop">- <template v-if="canDropTargetCascade" #options>- <label class="mb-3 flex items-start gap-2 rounded-md border bg-muted/20 px-3 py-2 text-sm">+ <DangerConfirmDialog+ v-model:open="showDropConfirm"+ :title="dropConfirmTitle()"+ :message="dropConfirmMessage()"+ :sql="dropPreviewSql"+ :confirm-label="t('dangerDialog.deleteConfirm')"+ :close-on-confirm="!dropTarget || !usesExactTriggerDrop(dropTarget)"+ :confirm-disabled="!!dropTarget && usesExactTriggerDrop(dropTarget) && (!triggerDropPreview?.isCurrent() || browserTriggerBusy)"+ @confirm="confirmDrop"+ >+ <template #options>+ <p v-if="dropPreviewError" role="alert" class="mb-3 text-sm text-destructive">{{ dropPreviewError }}</p>+ <p v-if="triggerDropPreview" class="mb-3 text-sm text-muted-foreground">{{ t("oracleTrigger.executionSchema") }}: {{ triggerDropPreview.plan.target.executionSchema }}</p>+ <label v-if="canDropTargetCascade" class="mb-3 flex items-start gap-2 rounded-md border bg-muted/20 px-3 py-2 text-sm"><input v-model="dropTableCascade" type="checkbox" class="mt-0.5 h-3.5 w-3.5 shrink-0 accent-primary" @change="refreshDropPreviewSql()" /><span class="grid gap-0.5"><span class="font-medium text-foreground">{{ t("contextMenu.dropTableCascade") }}</span>@@ -6057,8 +6624,20 @@ function getObjectBrowserMenuItems(item: ObjectBrowserRow): ContextMenuItem[] {</template></DangerConfirmDialog>- <DangerConfirmDialog v-model:open="showBatchDropConfirm" :title="batchDropConfirmTitle" :message="batchDropConfirmMessage" :sql="batchDropPreviewSql" :confirm-label="t('objects.dropSelected')" :loading="batchDropExecuting" :close-on-confirm="false" @confirm="confirmBatchDropTables">+ <DangerConfirmDialog+ v-model:open="showBatchDropConfirm"+ :title="batchDropConfirmTitle"+ :message="batchDropConfirmMessage"+ :sql="batchDropPreviewSql"+ :confirm-label="t('objects.dropSelected')"+ :loading="batchDropExecuting && !batchTriggerDropRequested"+ :confirm-disabled="batchTriggerDropRequested && (!batchTriggerDropPreview?.isCurrent() || browserTriggerBusy)"+ :close-on-confirm="false"+ @confirm="confirmBatchDropTables"+ ><template #options>+ <p v-if="batchDropPreviewError" role="alert" class="mb-3 text-sm text-destructive">{{ batchDropPreviewError }}</p>+ <p v-if="batchTriggerDropPreview" class="mb-3 text-sm text-muted-foreground">{{ t("oracleTrigger.executionSchema") }}: {{ batchTriggerDropPreview.plan.target.executionSchema }}</p><div v-if="batchDropExecuting" class="mb-3 rounded-md border bg-muted/20 px-3 py-2.5"><div class="mb-1.5 flex items-center justify-between text-xs tabular-nums text-muted-foreground"><span>{{ batchDropProgress.completed }} / {{ batchDropProgress.total }}</span>@@ -6223,6 +6802,7 @@ function getObjectBrowserMenuItems(item: ObjectBrowserRow): ContextMenuItem[] {</DialogHeader><pre class="max-h-72 overflow-auto whitespace-pre-wrap break-words rounded bg-destructive/5 p-3 text-sm text-destructive"> {{ compileErrorMessage }}</pre><DialogFooter>+ <Button v-if="browserTriggerFeedback" variant="outline" :disabled="browserTriggerBusy" @click="refreshBrowserTriggerFeedback">{{ t("oracleTrigger.verifyReadOnly") }}</Button><Button @click="showCompileErrorDialog = false">{{ t("common.close") }}</Button></DialogFooter></DialogContent>diff --git a/apps/desktop/src/components/objects/ObjectSourceDialog.vue b/apps/desktop/src/components/objects/ObjectSourceDialog.vueindex 71426bfd33..3fec8fdd8f 100644--- a/apps/desktop/src/components/objects/ObjectSourceDialog.vue+++ b/apps/desktop/src/components/objects/ObjectSourceDialog.vue@@ -1,5 +1,5 @@<script setup lang="ts">-import { computed, onBeforeUnmount, ref, watch } from "vue";+import { computed, defineAsyncComponent, onBeforeUnmount, ref, shallowRef, watch } from "vue";import { useI18n } from "vue-i18n";import { Clipboard, Loader2, PencilLine, RefreshCw } from "@lucide/vue";import { useToast } from "@/composables/useToast";@@ -8,7 +8,12 @@ import { useSettingsStore } from "@/stores/settingsStore";import { copyToClipboard } from "@/lib/common/clipboard";import { formatSqlForDisplay, type SqlFormatDialect } from "@/lib/sql/sqlFormatter";import { buildEditableObjectSource, buildExecutableObjectSourceStatements, prepareObjectSourceSave, objectSourceSaveSuccessMessage, formatObjectSourceSaveError, resolveObjectSourceEditDraft } from "@/lib/table/objectSourceEditor";-import { loadObjectSourceWithRoutineFallback } from "@/lib/table/objectSourceLoad";+import { inspectExactOracleTriggerSource, loadObjectSourceWithRoutineFallback, oracleTriggerErrorEditorOffset } from "@/lib/table/objectSourceLoad";+import { oracleTriggerReadOptions } from "@/lib/database/oracleTriggerIdentity";+import { readOracleTriggerSource, prepareOracleTriggerPlan, type OracleTriggerSnapshot, type OracleTriggerExecutionResult, type OracleTriggerAction, type OracleTriggerTarget } from "@/lib/database/oracleTriggerPlan";+import { confirmOracleTriggerPlan } from "@/lib/database/oracleTriggerActions";+import { buildOracleTriggerCreateDraft, oracleTriggerDefinitionScopes, type OracleTriggerSqlBinding } from "@/lib/database/oracleTriggerSql";+import OracleTriggerStatus from "@/components/objects/OracleTriggerStatus.vue";import { assertSourceIdentity, beginSourceSave, captureSourceIdentity, renewSourceIdentity, type SourceIdentitySnapshot } from "@/lib/table/objectSourceIdentity";import { jdbcRoutineMetadata, xuguRoutineMetadataFromDefinition, type RoutineMetadata } from "@/lib/table/routineParameters";import { executeWithProductionSqlGuard } from "@/lib/database/productionExecutionGuard";@@ -22,8 +27,10 @@ import { objectDependencyTarget, type ObjectDependencyTarget, type ObjectDetailsimport { useQueryStore } from "@/stores/queryStore";import type { SqlObjectNavigationTarget } from "@/lib/sql/sqlNavigation";import { Button } from "@/components/ui/button";+import { Input } from "@/components/ui/input";import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog";-import type { DatabaseType, ObjectSourceKind } from "@/types/database";+import type { DatabaseType, ObjectSourceKind, OracleTriggerMetadata } from "@/types/database";+const OracleInvalidObjectsDialog = defineAsyncComponent(() => import("@/components/objects/OracleInvalidObjectsDialog.vue"));const props = withDefaults(defineProps<{@@ -32,15 +39,18 @@ const props = withDefaults(database: string;schema?: string;catalog?: string;+ executionSchema?: string;name: string;relationName?: string;signature?: string;objectType: ObjectSourceKind;+ triggerIdentityMode?: "exact";databaseType?: DatabaseType;dialect: "mysql" | "postgres" | "sqlserver";formatDialect?: SqlFormatDialect;initialEditing?: boolean;initialSection?: ObjectDetailsSection;+ createTrigger?: OracleTriggerSqlBinding;}>(),{initialEditing: false,@@ -51,6 +61,8 @@ const emit = defineEmits<{"update:open": [value: boolean];saved: [];"open-object": [context: ObjectDependencyTarget, target: SqlObjectNavigationTarget];+ "trigger-read": [snapshot: OracleTriggerSnapshot];+ "trigger-result": [target: Readonly<OracleTriggerTarget>, result: OracleTriggerExecutionResult];}>();const { t } = useI18n();@@ -59,7 +71,15 @@ const connectionStore = useConnectionStore();const settingsStore = useSettingsStore();const queryStore = useQueryStore();const section = ref<ObjectDetailsSection>(props.initialSection || "source");-const dependencyTarget = computed(() => objectDependencyTarget({ connectionId: props.connectionId, database: props.database, schema: props.schema || props.database, catalog: props.catalog, name: props.name, objectType: resolvedObjectType.value, section: section.value }, props.databaseType));+const dependencyTarget = computed(() =>+ props.createTrigger && !triggerSnapshot.value?.exists+ ? undefined+ : objectDependencyTarget(+ { connectionId: props.connectionId, database: props.database, schema: triggerOwner.value, catalog: props.catalog, name: triggerName.value, objectType: resolvedObjectType.value, section: section.value },+ props.databaseType,+ createProfile.value ? { name: createProfile.value.name, oracle_metadata: createProfile.value } : undefined,+ ),+);function viewDependencySql(context: ObjectDependencyTarget, sql: string) {queryStore.createTab(context.connectionId, context.database, t("objectDependencies.viewSql"), "query", context.schema, sql, context.catalog, { forceNew: true });}@@ -80,6 +100,59 @@ const sourceEditable = ref(true);const error = ref("");const saveError = ref("");const routineMetadata = ref<RoutineMetadata | null>(null);+const triggerSnapshot = ref<OracleTriggerSnapshot>();+const triggerResult = ref<OracleTriggerExecutionResult>();+const triggerSourceIssue = ref("");+const triggerDiagnosticOpen = ref(false);+const sourceRevealRequest = ref<{ id: number; line: number; column: number }>();+let sourceRevealSequence = 0;+const triggerDiagnosticContext = shallowRef<{ target: Readonly<OracleTriggerTarget>; expectedObjectId?: string; originRevision: number }>();+const triggerDiagnosticConnection = computed(() => (triggerDiagnosticContext.value ? connectionStore.getConfig(triggerDiagnosticContext.value.target.connectionId) : undefined));+function openTriggerDiagnostics() {+ const snapshot = triggerSnapshot.value;+ if (!snapshot?.exists) return;+ triggerDiagnosticContext.value = { target: snapshot.target, expectedObjectId: snapshot.metadata.objectId ?? undefined, originRevision: loadSerial };+ triggerDiagnosticOpen.value = true;+}+function returnFromTriggerDiagnostics(object: { owner: string; name: string; objectId?: string }, location?: { line: number; position: number }) {+ const snapshot = triggerSnapshot.value;+ if (!snapshot || snapshot.target.owner !== object.owner || snapshot.target.name !== object.name) return;+ triggerDiagnosticOpen.value = false;+ section.value = "source";+ if (!editing.value) editSource();+ if (!location) return;+ const text = editing.value ? draft.value : content.value;+ const offset = object.objectId === snapshot.metadata.objectId ? oracleTriggerErrorEditorOffset(snapshot.raw, text, location) : undefined;+ if (offset === undefined) {+ toast(t("oracleTrigger.errorPositionUnavailable"), 3000);+ return;+ }+ const lines = text.replace(/\r\n?/g, "\n").slice(0, offset).split("\n");+ sourceRevealRequest.value = { id: ++sourceRevealSequence, line: lines.length, column: lines[lines.length - 1].length + 1 };+}+function acceptDiagnosticTriggerResult(target: Readonly<OracleTriggerTarget>, result: OracleTriggerExecutionResult, before: OracleTriggerSnapshot, _originTabId?: string, originRevision?: number) {+ if (originRevision !== undefined && loadSerial !== originRevision) return;+ emit("trigger-result", target, result);+ const baseline = triggerSnapshot.value;+ if (!props.open || !baseline || JSON.stringify(baseline.target) !== JSON.stringify(target)) return;+ triggerResult.value = result;+ if (!result.cancelled && result.steps.every((step) => step.state === "committed") && result.snapshot?.metadata.objectId === baseline.metadata.objectId && baseline.raw.source === before.raw.source) triggerSnapshot.value = result.snapshot;+ else if (result.snapshot) triggerSourceIssue.value = t("oracleTrigger.reloadBaseline");+}+const isOracleTrigger = computed(() => props.objectType === "TRIGGER" && !!oracleTriggerReadOptions(props.databaseType) && (props.triggerIdentityMode === "exact" || !!props.createTrigger));+const createName = ref(props.name);+const createOwner = ref(props.schema || props.database);+const createScope = ref<OracleTriggerSqlBinding["scope"]>(props.createTrigger?.scope || "TABLE");+const createBindingOwner = ref(props.createTrigger?.owner || "");+const createBindingName = ref(props.createTrigger?.name || "");+const createProfile = ref<OracleTriggerMetadata>();+const triggerOwner = computed(() => (props.createTrigger ? createOwner.value : props.schema || props.database));+const triggerName = computed(() => (props.createTrigger ? createName.value : props.name));+const createBinding = computed<OracleTriggerSqlBinding>(() => ({ scope: createScope.value, ...(["TABLE", "VIEW", "SCHEMA"].includes(createScope.value) ? { owner: createBindingOwner.value } : {}), ...(["TABLE", "VIEW"].includes(createScope.value) ? { name: createBindingName.value } : {}) }));+const createScopes = computed(() =>+ createProfile.value ? oracleTriggerDefinitionScopes(createProfile.value) : props.databaseType === "oceanbase-oracle" ? ["TABLE", "VIEW"] : props.databaseType === "dameng" ? ["TABLE", "VIEW", "SCHEMA", "DATABASE", "TIMER"] : ["TABLE", "VIEW", "SCHEMA", "DATABASE"],+);+let loadedSourceKey = "";/** May differ from props.objectType after PROCEDURE/FUNCTION/PACKAGE fallback resolution. */const resolvedObjectType = ref<ObjectSourceKind>(props.objectType);let loadSerial = 0;@@ -92,12 +165,14 @@ const canEdit = computed(() => sourceEditable.value && (props.objectType !== "SEconst managedType = computed(() => isOracleFamilyTypeSource(props.databaseType, resolvedObjectType.value));const isViewLike = computed(() => props.objectType === "VIEW" || props.objectType === "MATERIALIZED_VIEW");const editLabel = computed(() => (isViewLike.value ? t("contextMenu.editView") : t("contextMenu.editObject")));-const title = computed(() => `${editing.value ? editLabel.value : t("contextMenu.viewSource")} - ${props.name}`);+const title = computed(() => `${props.createTrigger && !triggerSnapshot.value?.exists ? t("contextMenu.createTrigger") : editing.value ? editLabel.value : t("contextMenu.viewSource")} - ${triggerName.value}`);const hasRoutineMetadata = computed(() => !!routineMetadata.value && (routineMetadata.value.parameters.length > 0 || !!routineMetadata.value.returnType));watch(- () => [props.open, props.connectionId, props.database, props.schema, props.catalog, props.name, props.relationName, props.signature, props.objectType, props.databaseType, props.initialEditing, props.initialSection] as const,+ () => [props.open, props.connectionId, props.database, props.schema, props.catalog, props.executionSchema, props.name, props.relationName, props.signature, props.objectType, props.triggerIdentityMode, props.databaseType, props.initialEditing, props.initialSection] as const,() => {+ triggerDiagnosticOpen.value = false;+ sourceRevealRequest.value = undefined;if (props.open) {section.value = props.initialSection || "source";void loadSource();@@ -106,23 +181,37 @@ watch({ immediate: true, flush: "sync" },);-async function loadSource(nextEditing = props.initialEditing && canEdit.value) {+async function loadSource(nextEditing = props.initialEditing && canEdit.value, readCreatedTarget = false) {const serial = ++loadSerial;- const target = { ...props };+ const target = { ...props, schema: triggerOwner.value, name: triggerName.value };+ const previouslyExisted = triggerSnapshot.value?.exists;+ const sourceKey = JSON.stringify([target.connectionId, target.database, target.catalog, target.schema, target.name, target.objectType, target.triggerIdentityMode]);+ if (sourceKey !== loadedSourceKey) createProfile.value = undefined;+ const keepDraft = isOracleTrigger.value && (sourceKey === loadedSourceKey || !!props.createTrigger) && editing.value;resolvedObjectType.value = target.objectType;const identity = captureSourceIdentity({ ...target, schema: target.schema || target.database });sourceIdentity = undefined;saving.value = false;- content.value = "";- editableText.value = "";- draft.value = "";+ if (!keepDraft) {+ content.value = "";+ editableText.value = "";+ draft.value = "";+ }error.value = "";saveError.value = "";routineMetadata.value = null;+ triggerSnapshot.value = undefined;+ triggerSourceIssue.value = "";+ if (!keepDraft) triggerResult.value = undefined;sourceEditable.value = true;- editing.value = false;+ if (!keepDraft) editing.value = false;loading.value = true;try {+ if (props.createTrigger && !readCreatedTarget && !previouslyExisted) {+ editing.value = true;+ loadedSourceKey = sourceKey;+ return;+ }if (!target.databaseType) throw new Error("Connection type is unavailable.");// issue #9035:连接建立也纳入弹窗的加载态。调用方不再先 await ensureConnected// 才打开弹窗,否则弹窗挂载前会有一段没有任何反馈的等待。@@ -130,6 +219,24 @@ async function loadSource(nextEditing = props.initialEditing && canEdit.value) {if (serial !== loadSerial) return;connectionStore.activeConnectionId = target.connectionId;const schema = target.schema || target.database;+ if (isOracleTrigger.value) {+ const loaded = await readOracleTriggerSource({ connectionId: target.connectionId, database: target.database, catalog: target.catalog, owner: schema, name: target.name, executionSchema: target.executionSchema || schema });+ if (serial !== loadSerial) return;+ const inspected = await inspectExactOracleTriggerSource(loaded.raw, schema, target.name);+ if (serial !== loadSerial) return;+ triggerSnapshot.value = loaded.snapshot;+ if (loaded.snapshot) emit("trigger-read", loaded.snapshot);+ triggerSourceIssue.value = loaded.identityError || inspected.triggerSource.error || "";+ sourceIdentity = loaded.snapshot?.identity;+ sourceEditable.value = !!props.createTrigger || loaded.snapshot?.exists === true;+ if (loaded.snapshot) createProfile.value = loaded.snapshot.metadata;+ content.value = loaded.raw.source;+ editableText.value = inspected.editableSource;+ if (!keepDraft) draft.value = nextEditing && canEdit.value ? inspected.editableSource : "";+ editing.value = keepDraft || (nextEditing && canEdit.value);+ loadedSourceKey = sourceKey;+ return;+ }const { source: result, objectType: resolvedType } = await loadObjectSourceWithRoutineFallback(api.getObjectSource, target.connectionId, target.database, schema, target.name, target.objectType, target.signature, target.relationName);if (serial !== loadSerial) return;const editableAllowed = result.editable !== false;@@ -159,7 +266,12 @@ async function loadSource(nextEditing = props.initialEditing && canEdit.value) {toast(t("objects.sourceReadOnly"), 3000);}} catch (e: any) {- if (serial === loadSerial) error.value = e?.message || String(e);+ if (serial === loadSerial) {+ if (keepDraft) {+ editing.value = true;+ saveError.value = e?.message || String(e);+ } else error.value = e?.message || String(e);+ }} finally {if (serial === loadSerial) loading.value = false;}@@ -193,8 +305,8 @@ function cancelEditSource() {async function refreshSource() {if (loading.value || saving.value) return;- if (editing.value && !window.confirm(t("objects.refreshDiscardConfirm"))) return;- await loadSource(editing.value && canEdit.value);+ if (!isOracleTrigger.value && editing.value && !window.confirm(t("objects.refreshDiscardConfirm"))) return;+ await loadSource(editing.value && canEdit.value, !!props.createTrigger);}async function saveSource() {@@ -204,6 +316,10 @@ async function saveSource() {return;}if (!draft.value.trim() || !props.databaseType) return;+ if (isOracleTrigger.value) {+ await runTriggerAction(props.createTrigger && !triggerSnapshot.value?.exists ? "create" : "replace");+ return;+ }const databaseType = props.databaseType;const connectionId = props.connectionId,database = props.database,@@ -277,12 +393,105 @@ async function saveSource() {}}+async function runTriggerAction(action: OracleTriggerAction) {+ if (saving.value || loading.value || !props.open) return;+ const baseline = triggerSnapshot.value;+ if (!baseline && action !== "create") {+ saveError.value = t("oracleTrigger.reloadBaseline");+ return;+ }+ const serial = loadSerial,+ source = draft.value;+ const target = baseline?.exists ? baseline.target : { connectionId: props.connectionId, database: props.database, catalog: props.catalog, owner: triggerOwner.value, name: triggerName.value, executionSchema: props.executionSchema || props.schema || props.database };+ const selection = action === "create" ? { ...createBinding.value } : undefined;+ const bindingKey = JSON.stringify(createBinding.value);+ const current = () =>+ props.open &&+ triggerName.value === target.name &&+ triggerOwner.value === target.owner &&+ props.connectionId === target.connectionId &&+ props.database === target.database &&+ props.catalog === target.catalog &&+ (props.executionSchema || props.schema || props.database) === target.executionSchema &&+ serial === loadSerial &&+ (!["create", "replace"].includes(action) || draft.value === source) &&+ (action !== "create" || JSON.stringify(createBinding.value) === bindingKey);+ saving.value = true;+ saveError.value = "";+ try {+ const plan = await prepareOracleTriggerPlan({ target, action, expectedObjectId: baseline?.exists ? (baseline.metadata.objectId ?? undefined) : undefined, ...(["create", "replace"].includes(action) ? { baseline, source, selection } : {}) });+ if (!current()) return;+ const result = await confirmOracleTriggerPlan(plan, { isCurrent: current });+ emit("trigger-result", plan.target, result);+ if (serial !== loadSerial) return;+ triggerResult.value = result;+ const committed = !result.cancelled && result.steps.every((step) => step.state === "committed");+ if (committed && result.snapshot && (action === "create" || (result.snapshot.metadata.objectId === baseline?.metadata.objectId && (action === "replace" || baseline?.raw.source === plan.before.raw.source)))) triggerSnapshot.value = result.snapshot;+ else if (result.snapshot) triggerSourceIssue.value = t("oracleTrigger.reloadBaseline");+ if (!result.cancelled && result.steps.every((step) => step.state === "committed") && !result.steps.some((step) => step.verification === "invalid")) {+ emit("saved");+ if (action === "create" || action === "replace") await loadSource(false, !!props.createTrigger);+ }+ } catch (error) {+ if (serial === loadSerial) saveError.value = error instanceof Error ? error.message : String(error);+ } finally {+ if (serial === loadSerial) saving.value = false;+ }+}++async function generateTriggerDefinition() {+ if (saving.value || loading.value || triggerSnapshot.value?.exists) return;+ if (draft.value.trim() && !window.confirm(t("objects.refreshDiscardConfirm"))) return;+ const serial = loadSerial;+ const target = { connectionId: props.connectionId, database: props.database, catalog: props.catalog, owner: triggerOwner.value, name: triggerName.value, executionSchema: props.executionSchema || props.schema || props.database };+ const binding = { ...createBinding.value };+ const previousDraft = draft.value;+ loading.value = true;+ saveError.value = "";+ try {+ await connectionStore.ensureConnected(target.connectionId);+ const loaded = await readOracleTriggerSource(target);+ if (serial !== loadSerial || !props.open || target.owner !== triggerOwner.value || target.name !== triggerName.value || JSON.stringify(binding) !== JSON.stringify(createBinding.value) || draft.value !== previousDraft) return;+ if (!loaded.snapshot) throw new Error(loaded.identityError);+ createProfile.value = loaded.snapshot.metadata;+ if (loaded.snapshot.exists) throw new Error("A visible trigger already exists; change the name or open its existing source");+ draft.value = buildOracleTriggerCreateDraft(loaded.snapshot.metadata, target.owner, target.name, binding);+ editing.value = true;+ } catch (error) {+ if (serial === loadSerial) saveError.value = error instanceof Error ? error.message : String(error);+ } finally {+ if (serial === loadSerial) loading.value = false;+ }+}++function openTriggerParent() {+ const parent = triggerSnapshot.value?.metadata.parent;+ if (!parent) return;+ openDependencyObject(+ { connectionId: props.connectionId, database: props.database, schema: triggerOwner.value, catalog: props.catalog, name: triggerName.value, objectType: "TRIGGER" },+ { name: parent.name, schema: parent.owner, type: parent.objectType === "VIEW" ? "view" : "table", nameQuoted: true, schemaQuoted: true },+ );+}+function closeDialog() {emit("update:open", false);}++defineExpose({ hasUnsavedDraft: () => editing.value && draft.value !== editableText.value });</script><template>+ <OracleInvalidObjectsDialog+ v-if="triggerDiagnosticContext && triggerDiagnosticConnection"+ :open="triggerDiagnosticOpen && props.open && triggerDiagnosticContext.originRevision === loadSerial"+ :connection="triggerDiagnosticConnection"+ :database="triggerDiagnosticContext.target.database"+ :schema="triggerDiagnosticContext.target.owner"+ :trigger-context="triggerDiagnosticContext"+ @update:open="triggerDiagnosticOpen = $event"+ @open-source="returnFromTriggerDiagnostics"+ @trigger-result="acceptDiagnosticTriggerResult"+ /><Dialog :open="props.open" @update:open="(value) => emit('update:open', value)"><DialogContent class="h-[min(760px,calc(var(--dbx-viewport-height)-2rem))] grid-rows-[auto_minmax(0,1fr)_auto] sm:max-w-[900px]"><DialogHeader>@@ -290,7 +499,28 @@ function closeDialog() {</DialogHeader><ObjectDependenciesPanel :target="dependencyTarget" v-model:section="section" :open="props.open" @view-sql="viewDependencySql" @open-object="openDependencyObject">- <div v-if="loading" class="flex min-h-0 flex-1 items-center justify-center gap-2 text-sm text-muted-foreground">+ <div v-if="isOracleTrigger && props.createTrigger" class="shrink-0 space-y-3 border-b pb-3 text-sm" data-trigger-create>+ <div class="grid grid-cols-1 gap-3 sm:grid-cols-3">+ <label class="space-y-1">{{ t("eventTrigger.owner") }}<Input v-model="createOwner" :disabled="saving || !!triggerSnapshot?.exists" data-trigger-create-owner /></label>+ <label class="space-y-1">{{ t("structureEditor.triggerName") }}<Input v-model="createName" :disabled="saving || !!triggerSnapshot?.exists" data-trigger-create-name /></label>+ <label class="space-y-1"+ >{{ t("oracleTrigger.scope")+ }}<select v-model="createScope" class="h-9 w-full rounded-md border bg-background px-3" :disabled="saving || !!triggerSnapshot?.exists" data-trigger-create-scope>+ <option v-for="scope in createScopes" :key="scope" :value="scope">{{ scope }}</option>+ </select></label+ >+ <label v-if="['TABLE', 'VIEW', 'SCHEMA'].includes(createScope)" class="space-y-1"+ >{{ t(createScope === "SCHEMA" ? "oracleTrigger.scopeOwner" : "oracleTrigger.parentOwner") }}<Input v-model="createBindingOwner" :disabled="saving || !!triggerSnapshot?.exists" data-trigger-create-parent-owner+ /></label>+ <label v-if="['TABLE', 'VIEW'].includes(createScope)" class="space-y-1">{{ t("oracleTrigger.parentName") }}<Input v-model="createBindingName" :disabled="saving || !!triggerSnapshot?.exists" data-trigger-create-parent-name /></label>+ <div v-if="!triggerSnapshot?.exists" class="flex items-end">+ <Button variant="outline" :disabled="saving || loading || !createName.length || !createOwner.length" @click="generateTriggerDefinition">{{ t("contextMenu.generateSql") }}</Button>+ </div>+ </div>+ <p v-if="createProfile?.engine === 'oceanbase-oracle'" class="text-muted-foreground">{{ t("oracleTrigger.obSchemaUnsupported") }} {{ t("oracleTrigger.obDatabaseUnknown") }}</p>+ </div>+ <OracleTriggerStatus v-if="isOracleTrigger" :snapshot="triggerSnapshot" :result="triggerResult" :source-issue="triggerSourceIssue" :busy="loading || saving" @action="runTriggerAction" @parent="openTriggerParent" @refresh="refreshSource" @diagnostics="openTriggerDiagnostics" />+ <div v-if="loading && !editing" class="flex min-h-0 flex-1 items-center justify-center gap-2 text-sm text-muted-foreground"><Loader2 class="h-4 w-4 animate-spin" /><span>{{ t("common.loading") }}</span></div>@@ -304,6 +534,8 @@ function closeDialog() {<div v-else-if="editing" class="object-source-dialog-editor flex min-h-0 flex-1 flex-col overflow-hidden rounded border" data-object-source-editor><QueryEditorv-model="draft"+ :reveal-request="sourceRevealRequest"+ @editor-reveal-consumed="sourceRevealRequest = undefined"class="min-h-0 flex-1":connection-id="props.connectionId":database="props.database"@@ -323,6 +555,8 @@ function closeDialog() {<RoutineMetadataPanel v-if="hasRoutineMetadata && routineMetadata" :parameters="routineMetadata.parameters" :return-type="routineMetadata.returnType" /><QueryEditorv-if="content || !hasRoutineMetadata"+ :reveal-request="sourceRevealRequest"+ @editor-reveal-consumed="sourceRevealRequest = undefined":key="`${props.connectionId}:${props.database}:${props.schema || ''}:${props.name}:${props.objectType}`":model-value="content"class="object-source-dialog-editor min-h-0 flex-1 overflow-hidden rounded border"@@ -354,10 +588,10 @@ function closeDialog() {<PencilLine class="h-4 w-4" />{{ editLabel }}</Button>- <Button v-if="editing && section === 'source'" variant="outline" :disabled="saving" @click="cancelEditSource">+ <Button v-if="editing && section === 'source'" variant="outline" :disabled="saving || loading" @click="cancelEditSource">{{ t("objects.cancelEdit") }}</Button>- <Button v-if="editing && section === 'source'" :disabled="saving || !draft.trim()" @click="saveSource">+ <Button v-if="editing && section === 'source'" :disabled="saving || loading || !draft.trim()" @click="saveSource"><Loader2 v-if="saving" class="h-4 w-4 animate-spin" />{{ t(managedType ? "objects.typeManagementPreviewSave" : "objects.saveSource") }}</Button>diff --git a/apps/desktop/src/components/objects/OracleInvalidObjectsDialog.vue b/apps/desktop/src/components/objects/OracleInvalidObjectsDialog.vueindex 1b639bdf17..b50eb534ab 100644--- a/apps/desktop/src/components/objects/OracleInvalidObjectsDialog.vue+++ b/apps/desktop/src/components/objects/OracleInvalidObjectsDialog.vue@@ -15,6 +15,8 @@ import { effectiveDatabaseTypeForConnection } from "@/lib/database/jdbcDialect";import { uuid } from "@/lib/common/utils";import { formatError, normalizeBackendError } from "@/lib/backend/errorUtils";import { oracleWriteRejected } from "@/lib/database/oracleSecurity";+import { readOracleTriggerSnapshot, prepareOracleTriggerPlan, type OracleTriggerSnapshot, type OracleTriggerTarget, type OracleTriggerExecutionResult } from "@/lib/database/oracleTriggerPlan";+import { confirmOracleTriggerPlan } from "@/lib/database/oracleTriggerActions";import {oracleCompileUnsupportedReason,oracleInvalidObjectSourceKind,@@ -30,11 +32,12 @@ import {type OracleObjectError,} from "@/lib/database/oracleInvalidObjects";-const props = defineProps<{ open: boolean; connection: ConnectionConfig; database: string; schema: string }>();+const props = defineProps<{ open: boolean; connection: ConnectionConfig; database: string; schema: string; triggerContext?: { target: Readonly<OracleTriggerTarget>; expectedObjectId?: string; originTabId?: string; originRevision?: number } }>();const emit = defineEmits<{"update:open": [open: boolean];- "open-source": [object: OracleInvalidObject];+ "open-source": [object: OracleInvalidObject, location?: Pick<OracleObjectError, "line" | "position">];"compile-finished": [scope: { connectionId: string; database: string; schema: string }];+ "trigger-result": [target: Readonly<OracleTriggerTarget>, result: OracleTriggerExecutionResult, before: OracleTriggerSnapshot, originTabId?: string, originRevision?: number];}>();const { t } = useI18n();const objects = ref<OracleInvalidObject[]>([]);@@ -52,6 +55,8 @@ const fullReadError = ref("");const fullReadGeneration = ref(0);const verifyMissingOnNextRead = ref(false);const errors = ref<OracleObjectError[]>([]);+const triggerSnapshot = shallowRef<OracleTriggerSnapshot>();+const diagnosticErrors = computed(() => (props.triggerContext ? (triggerSnapshot.value?.metadata.errors ?? []) : errors.value));const errorsTruncated = ref(false);const loadError = ref("");const errorLoadError = ref("");@@ -114,6 +119,8 @@ let singleCompilationGeneration = 0;let diagnosticGeneration = 0;let listLoadGeneration = 0;const databaseType = computed(() => (effectiveDatabaseTypeForConnection(props.connection) ?? props.connection.db_type) as DatabaseType);+const compileDatabaseType = computed(() => (props.triggerContext && triggerSnapshot.value ? (triggerSnapshot.value.metadata.engine === "dm" ? "dameng" : triggerSnapshot.value.metadata.engine) : databaseType.value));+const compileOptions = computed(() => (props.triggerContext ? { triggerProfile: triggerSnapshot.value?.metadata } : undefined));type ListCache = { keys: Array<string | number>; sizes: Array<number | null> };type ListScroller = {$el: HTMLElement;@@ -237,7 +244,8 @@ function onRowTab(event: KeyboardEvent, object: OracleInvalidObject, control: "c}function canCompileObject(object: OracleInvalidObject): boolean {- return !unverifiedKeys.value.has(selectionKey(object)) && !oracleCompileUnsupportedReason(databaseType.value, object.type);+ if (props.triggerContext && (object.type !== "TRIGGER" || object.objectId !== triggerSnapshot.value?.metadata.objectId)) return false;+ return !unverifiedKeys.value.has(selectionKey(object)) && !oracleCompileUnsupportedReason(compileDatabaseType.value, object.type, compileOptions.value);}function removeValidObject(object: OracleInvalidObject) {@@ -380,6 +388,15 @@ async function loadList(existingToken?: number, options?: { allowLastDdlTimeChanoutcome.value = "";}try {+ const context = props.triggerContext;+ if (context) {+ if (context.target.connectionId !== props.connection.id || context.target.database !== props.database) throw new Error(t("oracleTrigger.reloadBaseline"));+ const snapshot = await readOracleTriggerSnapshot(context.target);+ if (!isCurrent(token) || readId !== listLoadGeneration) return;+ if (!snapshot.exists || (context.expectedObjectId !== undefined && snapshot.metadata.objectId !== context.expectedObjectId)) throw new Error(t("oracleTrigger.reloadBaseline"));+ showTriggerSnapshot(snapshot);+ return;+ }const result = await query(buildOracleInvalidObjectsSql(props.schema, 501), 501);if (!isCurrent(token) || readId !== listLoadGeneration) return;const rows = mapOracleInvalidObjects(result.rows, props.schema);@@ -410,6 +427,23 @@ async function loadList(existingToken?: number, options?: { allowLastDdlTimeChan}}+function showTriggerSnapshot(snapshot: OracleTriggerSnapshot) {+ triggerSnapshot.value = snapshot;+ const metadata = snapshot.metadata;+ const object: OracleInvalidObject = { owner: metadata.owner, name: metadata.name, type: "TRIGGER", objectId: metadata.objectId!, lastDdlTime: metadata.lastDdlTime ?? "" };+ selected.value = object;+ objects.value = snapshot.raw.trigger?.valid === true && metadata.reads.validity?.state === "available" ? [] : [object];+ fullObjects.value = [...objects.value];+ fullReadState.value = "complete";+ truncated.value = false;+ currentView.value = "detail";+ const read = metadata.reads.errors;+ errorsTruncated.value = read?.state === "incomplete";+ errorLoadError.value = read?.state === "available" || read?.state === "incomplete" ? "" : read?.message || t(`oracleSecurity.${read?.state === "denied" ? "denied" : read?.state === "error" ? "error" : "unavailable"}`);+ if (metadata.reads.validity?.state !== "available") outcome.value = t("processList.oracleInvalidObjects.compileUnknown");+ else if (snapshot.raw.trigger?.valid === true) outcome.value = t("processList.oracleInvalidObjects.compileValid");+}+async function startFullRead(token = generation.value) {if (!isCurrent(token) || compiling.value) return;const readId = ++fullReadGeneration.value;@@ -467,6 +501,10 @@ async function startFullRead(token = generation.value) {}async function loadErrors(object: OracleInvalidObject, token = generation.value) {+ if (props.triggerContext) {+ await loadList(token);+ return;+ }const requestId = ++diagnosticGeneration;errorLoadError.value = "";errors.value = [];@@ -555,13 +593,14 @@ async function submitCompile(scope: ExecutionScope, sql: string) {}}-const unsupportedReason = computed(() => (selected.value ? oracleCompileUnsupportedReason(databaseType.value, selected.value.type) : "unsupported-type"));+const unsupportedReason = computed(() => (selected.value ? oracleCompileUnsupportedReason(compileDatabaseType.value, selected.value.type, compileOptions.value) : "unsupported-type"));const singleTargetPresent = computed(() => {if (!selected.value) return false;return canCompileObject(selected.value) && objects.value.some((object) => sameObject(object, selected.value!));});async function compileSingle() {+ if (props.triggerContext) return compileExactTrigger();const target = selected.value ? { ...selected.value } : null;if (!target || unsupportedReason.value || compiling.value) return;const scope = captureExecutionScope();@@ -707,6 +746,40 @@ async function compileSingle() {}}+async function compileExactTrigger() {+ const context = props.triggerContext;+ const selectedObject = selected.value;+ if (!context || !selectedObject || compiling.value || unsupportedReason.value || !singleTargetPresent.value) return;+ const token = generation.value;+ const contextKey = JSON.stringify(context);+ const current = () => isCurrent(token) && JSON.stringify(props.triggerContext) === contextKey;+ compiling.value = true;+ outcome.value = "";+ try {+ const plan = await prepareOracleTriggerPlan({ target: context.target, action: "compile", expectedObjectId: selectedObject.objectId });+ if (!current()) return;+ const result = await confirmOracleTriggerPlan(plan, { isCurrent: current });+ if (result.steps.some((step) => step.receipt !== undefined)) emit("trigger-result", plan.target, result, plan.before, context.originTabId, context.originRevision);+ if (!current() || result.cancelled) return;+ if (result.snapshot?.exists && result.snapshot.metadata.objectId === selectedObject.objectId) showTriggerSnapshot(result.snapshot);+ const step = result.steps[0];+ outcome.value =+ step?.state === "committed" && step.verification === "valid"+ ? t("processList.oracleInvalidObjects.compileValid")+ : step?.state === "committed" && step.verification === "invalid"+ ? t("processList.oracleInvalidObjects.compileStillInvalid")+ : step?.state === "rejected"+ ? t("oracleSecurity.writeRejected")+ : t("processList.oracleInvalidObjects.compileUnknown");+ const detail = [step?.error, step?.readbackError, result.refreshError].filter(Boolean).join("\n");+ if (detail) outcome.value += `\n${detail}`;+ } catch (error) {+ if (current()) outcome.value = writeErrorMessage(error);+ } finally {+ if (current()) compiling.value = false;+ }+}+function batchIsCurrent(run: BatchRun): boolean {return batchRun.value?.id === run.id && scopeIsCurrent(run.scope);}@@ -1040,15 +1113,20 @@ function rowStatusLabel(object: OracleInvalidObject): string {return status === "invalid" ? "INVALID" : batchStatusLabel(status);}+function openErrorSource(error: { line?: number | null; position?: number | null }) {+ if (!selected.value || !Number.isSafeInteger(error.line) || !Number.isSafeInteger(error.position) || (error.line ?? 0) < 1 || (error.position ?? 0) < 1) return;+ emit("open-source", selected.value, { line: error.line!, position: error.position! });+}+function close() {generation.value++;emit("update:open", false);}watch(- () => [props.open, JSON.stringify(props.connection), props.database, props.schema] as const,+ () => [props.open, JSON.stringify(props.connection), props.database, props.schema, JSON.stringify(props.triggerContext)] as const,([open], previous) => {- const scopeChanged = !!previous && (previous[1] !== JSON.stringify(props.connection) || previous[2] !== props.database || previous[3] !== props.schema);+ const scopeChanged = !!previous && (previous[1] !== JSON.stringify(props.connection) || previous[2] !== props.database || previous[3] !== props.schema || previous[4] !== JSON.stringify(props.triggerContext));if (scopeChanged || !open) {singleCompilationGeneration++;batchExecutionGeneration++;@@ -1063,6 +1141,7 @@ watch(verifyMissingOnNextRead.value = false;objects.value = [];selected.value = null;+ triggerSnapshot.value = undefined;errors.value = [];errorsTruncated.value = false;diagnosticGeneration++;@@ -1211,6 +1290,10 @@ onBeforeUnmount(() => {<div class="min-w-0"><div class="break-all text-sm font-semibold">{{ selected.owner }}.{{ selected.name }}</div><div class="mt-1 text-xs text-muted-foreground">{{ selected.type }} · {{ t("processList.oracleInvalidObjects.objectId", { id: selected.objectId }) }}</div>+ <div v-if="triggerContext && triggerSnapshot" class="mt-1 flex flex-wrap gap-x-4 gap-y-1 text-sm">+ <span>{{ t("eventTrigger.enabled") }}: {{ triggerSnapshot.metadata.reads.enabled?.state === "available" && typeof triggerSnapshot.raw.trigger?.enabled === "boolean" ? t(triggerSnapshot.raw.trigger.enabled ? "objects.enabled" : "objects.disabled") : t("oracleTrigger.unknown") }}</span>+ <span>{{ t("objects.validity") }}: {{ triggerSnapshot.metadata.reads.validity?.state === "available" && typeof triggerSnapshot.raw.trigger?.valid === "boolean" ? (triggerSnapshot.raw.trigger.valid ? "VALID" : "INVALID") : t("oracleTrigger.unknown") }}</span>+ </div></div><Button v-if="oracleInvalidObjectSourceKind(selected.type)" variant="outline" size="sm" class="h-7 shrink-0 gap-1.5 text-xs" :disabled="compiling" @click="emit('open-source', selected)"><Wrench class="h-3.5 w-3.5" />{{ t("processList.oracleInvalidObjects.openSource") }}</Button></div>@@ -1218,8 +1301,9 @@ onBeforeUnmount(() => {<div class="mb-2 text-xs font-medium">{{ t("processList.oracleInvalidObjects.errorsTitle") }}</div><div v-if="errorLoadError" class="rounded border border-destructive/40 bg-destructive/10 p-3 text-xs text-destructive">{{ errorLoadError }}</div><p v-if="!errorLoadError && errorsTruncated" class="mb-2 rounded border bg-muted/30 p-2 text-xs text-muted-foreground">{{ t("processList.oracleInvalidObjects.errorsTruncated") }}</p>- <p v-if="!errorLoadError && errors.length === 0 && !compiling" class="py-4 text-xs text-muted-foreground">{{ t("processList.oracleInvalidObjects.noErrors") }}</p>- <div v-if="!errorLoadError && errors.length > 0" class="overflow-auto rounded border">+ <p v-if="loadError" role="alert" class="mb-2 text-sm text-destructive">{{ loadError }}</p>+ <p v-if="!errorLoadError && !errorsTruncated && diagnosticErrors.length === 0 && !compiling" class="py-4 text-xs text-muted-foreground">{{ t("processList.oracleInvalidObjects.noErrors") }}</p>+ <div v-if="!errorLoadError && diagnosticErrors.length > 0" class="overflow-auto rounded border"><table class="w-full border-collapse text-xs"><thead class="sticky top-0 bg-muted/60"><tr>@@ -1229,9 +1313,12 @@ onBeforeUnmount(() => {</tr></thead><tbody>- <tr v-for="error in errors" :key="error.sequence" class="border-t align-top">- <td class="whitespace-nowrap px-2 py-1.5 font-mono">{{ error.line }}</td>- <td class="whitespace-nowrap px-2 py-1.5 font-mono">{{ error.position }}</td>+ <tr v-for="(error, index) in diagnosticErrors" :key="error.sequence ?? index" class="border-t align-top">+ <td class="whitespace-nowrap px-2 py-1.5 font-mono">+ <Button v-if="triggerContext && error.line && error.position" variant="link" size="sm" class="h-auto p-0 font-mono" :aria-label="t('editor.locateError', { line: error.line, column: error.position })" :disabled="compiling" @click="openErrorSource(error)">{{ error.line }}</Button+ ><span v-else>{{ error.line ?? "?" }}</span>+ </td>+ <td class="whitespace-nowrap px-2 py-1.5 font-mono">{{ error.position ?? "?" }}</td><td class="break-words px-2 py-1.5 font-mono">{{ error.text }}</td></tr></tbody>@@ -1242,12 +1329,13 @@ onBeforeUnmount(() => {</p><details v-if="selected && !unsupportedReason" class="mt-3 text-xs"><summary class="cursor-pointer text-muted-foreground">{{ t("processList.oracleInvalidObjects.batchSqlDetails") }}</summary>- <pre class="mt-1 max-h-32 overflow-auto whitespace-pre-wrap break-all rounded bg-muted/30 p-2 font-mono">{{ buildOracleCompileSql(databaseType, selected.owner, selected) }}</pre>+ <pre class="mt-1 max-h-32 overflow-auto whitespace-pre-wrap break-all rounded bg-muted/30 p-2 font-mono">{{ buildOracleCompileSql(compileDatabaseType, selected.owner, selected, compileOptions) }}</pre></details><p v-if="outcome" class="mt-3 rounded border bg-muted/20 p-3 text-xs" role="status">{{ outcome }}</p></div><DialogFooter class="mx-0 mb-0 shrink-0 border-t px-4 py-3">- <Button variant="outline" @click="returnFromDetail">{{ t("processList.oracleInvalidObjects.batchCurrentList") }}</Button>+ <Button v-if="!triggerContext" variant="outline" @click="returnFromDetail">{{ t("processList.oracleInvalidObjects.batchCurrentList") }}</Button>+ <Button v-else variant="outline" :disabled="loading || compiling" @click="loadList()"><RefreshCw class="mr-1.5 size-4" :class="{ 'animate-spin': loading }" />{{ t("oracleTrigger.verifyReadOnly") }}</Button><Button variant="outline" :disabled="compiling" @click="close">{{ t("common.close") }}</Button><Button variant="destructive" :disabled="!!unsupportedReason || compiling || !!loadError || !singleTargetPresent" @click="compileSingle"><Loader2 v-if="compiling" class="mr-1.5 h-3.5 w-3.5 animate-spin" />{{ t("processList.oracleInvalidObjects.compile") }}</Button></DialogFooter>diff --git a/apps/desktop/src/components/objects/OracleTriggerStatus.vue b/apps/desktop/src/components/objects/OracleTriggerStatus.vuenew file mode 100644index 0000000000..3c4789d4e6--- /dev/null+++ b/apps/desktop/src/components/objects/OracleTriggerStatus.vue@@ -0,0 +1,62 @@+<script setup lang="ts">+import { computed } from "vue";+import { useI18n } from "vue-i18n";+import { Button } from "@/components/ui/button";+import { oracleCompileUnsupportedReason } from "@/lib/database/oracleInvalidObjects";+import type { OracleTriggerAction, OracleTriggerExecutionResult, OracleTriggerSnapshot } from "@/lib/database/oracleTriggerPlan";++const props = defineProps<{ snapshot?: OracleTriggerSnapshot; result?: OracleTriggerExecutionResult; busy?: boolean; sourceIssue?: string }>();+const emit = defineEmits<{ action: [action: OracleTriggerAction]; parent: []; refresh: []; diagnostics: [] }>();+const { t } = useI18n();+const metadata = computed(() => props.snapshot?.metadata);+const trigger = computed(() => props.snapshot?.raw.trigger);+const compileAvailable = computed(() => !!metadata.value && !oracleCompileUnsupportedReason(metadata.value.engine === "dm" ? "dameng" : metadata.value.engine, "TRIGGER", { triggerProfile: metadata.value }));+const uncertain = computed(() => props.result?.steps.some((step) => step.state === "unknown" || (step.state === "committed" && (step.verification === "mismatch" || step.verification === "unverified"))));+const refused = computed(() => props.result?.steps.some((step) => step.state === "rejected"));+</script>++<template>+ <section v-if="snapshot || sourceIssue || result" class="shrink-0 space-y-2 border-b px-3 py-2 text-sm" data-oracle-trigger-status>+ <div v-if="metadata && snapshot?.exists" class="flex flex-wrap items-center gap-x-4 gap-y-2">+ <span+ >{{ t("eventTrigger.owner") }}: <span class="font-mono whitespace-pre-wrap">{{ metadata.owner }}</span></span+ >+ <span>{{ t("eventTrigger.enabled") }}: {{ metadata.reads.enabled?.state === "available" && typeof trigger?.enabled === "boolean" ? t(trigger.enabled ? "objects.enabled" : "objects.disabled") : t("oracleTrigger.unknown") }}</span>+ <span>{{ t("objects.validity") }}: {{ metadata.reads.validity?.state === "available" && typeof trigger?.valid === "boolean" ? (trigger.valid ? "VALID" : "INVALID") : t("oracleTrigger.unknown") }}</span>+ <Button v-if="metadata.parent && (metadata.scope === 'TABLE' || metadata.scope === 'VIEW')" variant="link" size="sm" class="h-auto whitespace-pre-wrap p-0 font-mono" :disabled="metadata.reads.parent?.state !== 'available'" @click="emit('parent')"+ >{{ metadata.parent.owner }}.{{ metadata.parent.name }} · {{ metadata.parent.objectType }}</Button+ >+ <span v-else class="font-mono whitespace-pre-wrap">{{ metadata.scope }}{{ metadata.scopeOwner ? ` · ${metadata.scopeOwner}` : "" }}</span>+ <div class="ml-auto flex flex-wrap gap-1">+ <Button v-if="trigger?.valid === false || metadata.errors?.length" variant="outline" size="sm" :disabled="busy" @click="emit('diagnostics')">{{ t("processList.oracleInvalidObjects.errorsTitle") }}</Button>+ <Button variant="outline" size="sm" :disabled="busy" @click="emit('action', 'enable')">{{ t("contextMenu.enableTrigger") }}</Button>+ <Button variant="outline" size="sm" :disabled="busy" @click="emit('action', 'disable')">{{ t("contextMenu.disableTrigger") }}</Button>+ <Button v-if="compileAvailable" variant="outline" size="sm" :disabled="busy" @click="emit('action', 'compile')">{{ t("processList.oracleInvalidObjects.compile") }}</Button>+ </div>+ </div>+ <p v-if="sourceIssue" role="alert" class="whitespace-pre-wrap break-words text-muted-foreground">{{ sourceIssue }}</p>+ <div v-if="result && !result.cancelled" aria-live="polite" class="space-y-1">+ <p v-for="(step, index) in result.steps" :key="index" class="break-words" :class="step.state !== 'committed' || step.verification === 'invalid' ? 'text-destructive' : 'text-muted-foreground'">+ {{ t(`oceanbasePrimaryKey.${step.state}`) }}+ <template v-if="step.verification !== 'applied'">+ · {{ step.verification === "valid" ? "VALID" : step.verification === "invalid" ? "INVALID" : step.verification === "deleted" ? t("processList.oracleInvalidObjects.batchStatus.deleted") : t("oracleStructureResult.readbackFailed") }}+ </template>+ <span v-if="step.error || step.readbackError" class="block whitespace-pre-wrap">{{ [step.error, step.readbackError].filter(Boolean).join("\n") }}</span>+ </p>+ <p v-if="uncertain" role="alert" class="text-destructive">{{ t("oracleSecurity.writeUnknown") }}</p>+ <p v-else-if="refused" role="alert" class="text-destructive">{{ t("oracleSecurity.writeRejected") }}</p>+ <p v-if="result.refreshError" role="alert" class="whitespace-pre-wrap text-destructive">{{ result.refreshError }}</p>+ <Button v-if="uncertain || refused || result.refreshError" variant="outline" size="sm" :disabled="busy" @click="emit('refresh')">{{ t("oracleTrigger.verifyReadOnly") }}</Button>+ </div>+ <div v-if="metadata && metadata.reads.errors?.state !== 'available'" class="text-muted-foreground">+ {{+ metadata.reads.errors?.state === "incomplete"+ ? t("processList.oracleInvalidObjects.errorsTruncated")+ : `${t("processList.oracleInvalidObjects.errorsTitle")}: ${t(`oracleSecurity.${metadata.reads.errors?.state === "denied" ? "denied" : metadata.reads.errors?.state === "error" ? "error" : "unavailable"}`)}`+ }}+ </div>+ <ol v-if="metadata?.errors?.length" class="max-h-28 overflow-auto space-y-1 font-mono text-xs text-destructive" :aria-label="t('processList.oracleInvalidObjects.errorsTitle')">+ <li v-for="(error, index) in metadata.errors" :key="index">{{ error.line ?? "?" }}:{{ error.position ?? "?" }} {{ error.text }}</li>+ </ol>+ </section>+</template>diff --git a/apps/desktop/src/components/objects/__tests__/ObjectBrowser.oceanbasePagination.component.spec.ts b/apps/desktop/src/components/objects/__tests__/ObjectBrowser.oceanbasePagination.component.spec.tsindex bd1e30a369..133014c52f 100644--- a/apps/desktop/src/components/objects/__tests__/ObjectBrowser.oceanbasePagination.component.spec.ts+++ b/apps/desktop/src/components/objects/__tests__/ObjectBrowser.oceanbasePagination.component.spec.ts@@ -6,14 +6,15 @@ import ObjectBrowser from "@/components/objects/ObjectBrowser.vue";import { invalidateObjectBrowserRowsCache } from "@/lib/table/objectBrowserRowsCache";import type { ConnectionConfig, ObjectBrowserFilter, ObjectInfo } from "@/types/database";-const mocks = vi.hoisted(() => ({ listObjects: vi.fn(), listSchemas: vi.fn(), listSchemaIndexes: vi.fn().mockResolvedValue([]) }));+const mocks = vi.hoisted(() => ({ listObjects: vi.fn(), listSchemas: vi.fn(), getObjectSource: vi.fn(), listSchemaIndexes: vi.fn().mockResolvedValue([]) }));vi.mock("@/lib/backend/api", () => ({listObjects: (...args: unknown[]) => (args[10] === true ? mocks.listSchemaIndexes(...args) : mocks.listObjects(...args)),listSchemas: (...args: unknown[]) => mocks.listSchemas(...args),+ getObjectSource: (...args: unknown[]) => mocks.getObjectSource(...args),listObjectStatistics: vi.fn().mockResolvedValue([]),}));vi.mock("@/stores/connectionStore", () => ({- useConnectionStore: () => ({ getConfig: () => connection, ensureConnected: vi.fn().mockResolvedValue(undefined), orderByPinnedTreeNodes: (rows: unknown[]) => rows }),+ useConnectionStore: () => ({ getConfig: () => connection, connectedIds: new Set([connection.id]), connectionStateRevision: () => 0, ensureConnected: vi.fn().mockResolvedValue(undefined), orderByPinnedTreeNodes: (rows: unknown[]) => rows }),}));vi.mock("@/stores/queryStore", () => ({ useQueryStore: () => ({}) }));vi.mock("@/stores/settingsStore", () => ({@@ -40,7 +41,7 @@ vi.mock("vue-virtual-scroller", () => ({}));vi.mock("@/components/ui/searchable-select", () => ({ SearchableSelect: { render: () => null } }));vi.mock("@/components/ui/ToolbarOverflowMenu.vue", () => ({ default: { render: () => null } }));-vi.mock("@/components/editor/QueryEditor.vue", () => ({ default: { render: () => null } }));+vi.mock("@/components/editor/QueryEditor.vue", () => ({ default: defineComponent({ props: { modelValue: String }, setup: (props) => () => h("pre", { "data-source-text": "" }, props.modelValue) }) }));vi.mock("@/components/editor/DangerConfirmDialog.vue", () => ({ default: { render: () => null } }));vi.mock("@/components/objects/ProcedureExecutionDialog.vue", () => ({ default: { render: () => null } }));vi.mock("@/components/objects/CustomTypeInfoPanel.vue", () => ({ default: { render: () => null } }));@@ -52,6 +53,8 @@ const object = (name: string, schema = "APP"): ObjectInfo => ({ name, schema, obbeforeEach(() => {vi.clearAllMocks();+ mocks.listObjects.mockReset();+ mocks.getObjectSource.mockReset();mocks.listSchemas.mockReset().mockResolvedValue(["APP", "OTHER"]);invalidateObjectBrowserRowsCache({});});@@ -63,17 +66,19 @@ afterEach(() => {invalidateObjectBrowserRowsCache({});vi.useRealTimers();vi.restoreAllMocks();+ vi.unstubAllGlobals();});-async function mountBrowser(selectedObjectFilter: ObjectBrowserFilter | null = "all") {+async function mountBrowser(selectedObjectFilter: ObjectBrowserFilter | null = "all", catalog?: string, config = connection) {const schema = ref("APP");+ const selectedCatalog = ref(catalog);const host = document.createElement("div");document.body.append(host);- const app = createApp({ setup: () => () => h(ObjectBrowser, { connection, database: "APP", schema: schema.value, selectedObjectFilter: selectedObjectFilter ?? undefined }) });+ const app = createApp({ setup: () => () => h(ObjectBrowser, { connection: config, database: "APP", schema: schema.value, catalog: selectedCatalog.value, selectedObjectFilter: selectedObjectFilter ?? undefined }) });mountedApps.push({ app, host });app.mount(host);await vi.waitFor(() => expect(mocks.listObjects).toHaveBeenCalled());- return { host, schema };+ return { host, schema, catalog: selectedCatalog };}async function searchObjects(host: HTMLElement, query: string) {@@ -84,6 +89,210 @@ async function searchObjects(host: HTMLElement, query: string) {}describe("OceanBase Oracle object pagination (#11418)", () => {+ const triggerObject = (name: string, id = name): ObjectInfo => ({+ name,+ schema: " Raw Owner ",+ object_type: "TRIGGER",+ trigger: { name, timing: "BEFORE", event: "UPDATE", oracle_metadata: { contractVersion: 1, identityMode: "exact", engine: "oracle", owner: " Raw Owner ", name, objectId: id, scope: "SCHEMA", scopeOwner: " Raw Owner ", reads: { identity: { state: "available" } } } },+ });++ it.each(["oracle", "dameng", "jdbc"] as const)("starts explicit %s trigger discovery with bounded exact pages", async (db_type) => {+ const config = { ...connection, db_type, ...(db_type === "jdbc" ? { driver_profile: "oracle", database_info: { productName: "Oracle" } } : {}) } as ConnectionConfig;+ mocks.listObjects.mockResolvedValue([triggerObject(' Tr"g ')]);+ const { host } = await mountBrowser("triggers", " Catalog ", config);+ await vi.waitFor(() => expect(host.querySelector("[title=' Tr\"g ']")).not.toBeNull());+ expect(mocks.listObjects).toHaveBeenNthCalledWith(1, config.id, "APP", "APP", ["TRIGGER"], undefined, 3, 0, " Catalog ", undefined, undefined, { identityMode: "exact", catalog: " Catalog " });+ });++ it("reloads the legacy all list after leaving native trigger paging", async () => {+ mocks.listObjects.mockResolvedValueOnce([triggerObject("ONLY_TRIGGER")]).mockResolvedValueOnce([object("LEGACY_TABLE"), triggerObject("ONLY_TRIGGER")]);+ const { host } = await mountBrowser("triggers", undefined, { ...connection, db_type: "oracle" });+ await vi.waitFor(() => expect(host.querySelector('[title="ONLY_TRIGGER"]')).not.toBeNull());+ [...host.querySelectorAll("button")].find((button) => button.textContent?.trim() === "objects.all")!.click();+ await vi.waitFor(() => expect(host.querySelector('[title="LEGACY_TABLE"]')).not.toBeNull());+ expect(mocks.listObjects.mock.calls[1]?.[3]).not.toContain("INDEX");+ expect(mocks.listObjects.mock.calls[1]?.[3]).toContain("TRIGGER");+ expect(mocks.listObjects.mock.calls[1]?.slice(4, 8)).toEqual([undefined, undefined, undefined, undefined]);+ expect(mocks.listObjects.mock.calls[1]?.[10]).toEqual({ identityMode: "exact" });+ });++ it.each(["oracle", "dameng"] as const)("preserves the %s default full-list read and offers trigger discovery even when empty", async (db_type) => {+ mocks.listObjects.mockResolvedValueOnce([object("LEGACY_TABLE")]).mockResolvedValueOnce([]);+ const { host } = await mountBrowser(null, undefined, { ...connection, db_type });+ await vi.waitFor(() => expect(host.querySelector('[title="LEGACY_TABLE"]')).not.toBeNull());+ expect(mocks.listObjects.mock.calls[0]?.[3]).not.toContain("INDEX");+ expect(mocks.listObjects.mock.calls[0]?.[3]).toContain("TRIGGER");+ expect(mocks.listObjects.mock.calls[0]?.slice(4, 7)).toEqual([undefined, undefined, undefined]);+ expect(mocks.listObjects.mock.calls[0]?.[10]).toEqual({ identityMode: "exact" });+ const triggers = [...host.querySelectorAll("button")].find((button) => button.textContent?.trim().startsWith("tree.triggers"));+ expect(triggers).toBeDefined();+ triggers!.click();+ await vi.waitFor(() => expect(mocks.listObjects).toHaveBeenCalledTimes(2));+ expect(mocks.listObjects.mock.calls[1]?.slice(3, 7)).toEqual([["TRIGGER"], undefined, 3, 0]);+ await vi.waitFor(() => expect([...host.querySelectorAll("button")].some((button) => button.textContent?.trim() === "contextMenu.createTrigger")).toBe(true));+ });++ it("discards a delayed native trigger page after returning to legacy all", async () => {+ let resolve!: (objects: ObjectInfo[]) => void;+ mocks.listObjects+ .mockResolvedValueOnce([triggerObject("A"), triggerObject("B"), triggerObject("C")])+ .mockReturnValueOnce(+ new Promise<ObjectInfo[]>((done) => {+ resolve = done;+ }),+ )+ .mockResolvedValueOnce([object("LEGACY_TABLE")]);+ const { host } = await mountBrowser("triggers", undefined, { ...connection, db_type: "oracle" });+ await vi.waitFor(() => expect(host.querySelector("[data-object-load-more]")).not.toBeNull());+ host.querySelector<HTMLButtonElement>("[data-object-load-more]")!.click();+ await vi.waitFor(() => expect(mocks.listObjects).toHaveBeenCalledTimes(2));+ [...host.querySelectorAll("button")].find((button) => button.textContent?.trim() === "objects.all")!.click();+ await vi.waitFor(() => expect(host.querySelector('[title="LEGACY_TABLE"]')).not.toBeNull());+ resolve([triggerObject("C")]);+ await nextTick();+ expect(host.querySelector('[title="C"]')).toBeNull();+ expect(host.querySelector('[title="LEGACY_TABLE"]')).not.toBeNull();+ expect(host.querySelector("[data-object-load-more]")).toBeNull();+ });++ it("reloads the exact trigger list when only the catalog changes and ignores its old page", async () => {+ let resolve!: (objects: ObjectInfo[]) => void;+ mocks.listObjects+ .mockResolvedValueOnce([triggerObject("A"), triggerObject("B"), triggerObject("C")])+ .mockReturnValueOnce(+ new Promise<ObjectInfo[]>((done) => {+ resolve = done;+ }),+ )+ .mockResolvedValueOnce([triggerObject("NEW_CATALOG")]);+ const { host, catalog } = await mountBrowser("triggers", " Old Catalog ");+ await vi.waitFor(() => expect(host.querySelector("[data-object-load-more]")).not.toBeNull());+ host.querySelector<HTMLButtonElement>("[data-object-load-more]")!.click();+ await vi.waitFor(() => expect(mocks.listObjects).toHaveBeenCalledTimes(2));+ catalog.value = " New Catalog ";+ await vi.waitFor(() => expect(host.querySelector('[title="NEW_CATALOG"]')).not.toBeNull());+ expect(mocks.listObjects.mock.calls[2]?.[7]).toBe(" New Catalog ");+ expect(mocks.listObjects.mock.calls[2]?.[10]).toEqual({ identityMode: "exact", catalog: " New Catalog " });+ resolve([triggerObject("C")]);+ await nextTick();+ expect(host.querySelector('[title="C"]')).toBeNull();+ });++ it("keeps the old window and retries read-only after a drift reread fails", async () => {+ mocks.listObjects+ .mockResolvedValueOnce([triggerObject("A"), triggerObject("B"), triggerObject("C")])+ .mockResolvedValueOnce([triggerObject("CHANGED")])+ .mockRejectedValueOnce(new Error("window reread denied"))+ .mockResolvedValueOnce([triggerObject("C")]);+ const { host } = await mountBrowser("triggers");+ await vi.waitFor(() => expect(host.querySelector("[data-object-load-more]")).not.toBeNull());+ host.querySelector<HTMLButtonElement>("[data-object-load-more]")!.click();+ await vi.waitFor(() => expect(host.textContent).toContain("window reread denied"));+ expect(host.querySelector('[title="A"]')).not.toBeNull();+ expect(host.querySelector('[title="B"]')).not.toBeNull();+ expect(host.querySelector('[title="CHANGED"]')).toBeNull();+ host.querySelector<HTMLButtonElement>("[data-object-load-more]")!.click();+ await vi.waitFor(() => expect(host.querySelector('[title="C"]')).not.toBeNull());+ expect(mocks.listObjects.mock.calls[3]?.slice(5, 7)).toEqual([3, 2]);+ expect(host.textContent).not.toContain("window reread denied");+ });++ it.each(["object-id", "quoted-name", "empty"])("replaces a shifted trigger page window instead of appending (%s)", async (change) => {+ const a = triggerObject("A"),+ b = triggerObject("B"),+ peek = triggerObject(' Quoted"Name ', "9007199254740993");+ const changed = triggerObject(change === "quoted-name" ? ' quoted"Name ' : peek.name, change === "object-id" ? "9007199254740994" : peek.trigger!.oracle_metadata!.objectId!);+ mocks.listObjects+ .mockResolvedValueOnce([a, b, peek])+ .mockResolvedValueOnce(change === "empty" ? [] : [changed])+ .mockResolvedValueOnce(change === "empty" ? [a] : [a, b, changed]);+ const { host } = await mountBrowser("triggers");+ await vi.waitFor(() => expect(host.querySelector("[data-object-load-more]")).not.toBeNull());+ host.querySelector<HTMLButtonElement>("[data-object-load-more]")!.click();+ await vi.waitFor(() => expect(mocks.listObjects).toHaveBeenCalledTimes(3));+ expect(mocks.listObjects.mock.calls[2]?.slice(5, 7)).toEqual([5, 0]);+ await vi.waitFor(() => expect(host.querySelector("[data-object-load-more]")).toBeNull());+ expect(host.querySelector('[title="A"]')).not.toBeNull();+ expect(host.querySelector('[title="B"]') !== null).toBe(change !== "empty");+ });++ it("keeps the visible paged list while refreshing and after refresh failure", async () => {+ let reject!: (error: Error) => void;+ mocks.listObjects.mockResolvedValueOnce([object("KEEP_VISIBLE")]).mockReturnValueOnce(+ new Promise((_resolve, fail) => {+ reject = fail;+ }),+ );+ const { host } = await mountBrowser();+ await vi.waitFor(() => expect(host.querySelector('[title="KEEP_VISIBLE"]')).not.toBeNull());+ host.querySelector<HTMLButtonElement>('[title^="grid.refresh"]')!.click();+ await vi.waitFor(() => expect(mocks.listObjects).toHaveBeenCalledTimes(2));+ expect(host.querySelector('[title="KEEP_VISIBLE"]')).not.toBeNull();+ reject(new Error("refresh permission denied"));+ await vi.waitFor(() => expect(host.textContent).toContain("refresh permission denied"));+ expect(host.querySelector('[title="KEEP_VISIBLE"]')).not.toBeNull();+ });++ it("opens the existing source editor to create the first trigger from an empty trigger filter", async () => {+ mocks.listObjects.mockResolvedValue([]);+ const { host } = await mountBrowser("triggers", "Catalog");+ const create = [...host.querySelectorAll<HTMLButtonElement>("button")].find((button) => button.textContent?.trim() === "contextMenu.createTrigger");+ expect(create).toBeDefined();+ create!.click();+ await vi.waitFor(() => expect(document.querySelector<HTMLInputElement>("[data-trigger-create-name]")?.value).toBe("TRG_NEW"));+ expect(document.querySelector<HTMLInputElement>("[data-trigger-create-owner]")?.value).toBe("APP");+ expect(mocks.getObjectSource).not.toHaveBeenCalled();+ });++ it("opens a raw cross-owner trigger with exact source options from the existing object row", async () => {+ const trigger = {+ name: " Trigger ",+ event: "UPDATE",+ timing: "BEFORE",+ enabled: true,+ valid: false,+ oracle_metadata: {+ contractVersion: 1,+ identityMode: "exact",+ engine: "oceanbase-oracle",+ owner: " Trigger Owner ",+ name: " Trigger ",+ scope: "VIEW",+ objectId: "9007199254740993",+ parent: { owner: " Parent Owner ", name: " Parent ", objectType: "VIEW" },+ reads: { identity: { state: "available" } },+ },+ };+ const source = 'TRIGGER " Trigger " BEFORE UPDATE ON " Parent Owner "." Parent " BEGIN /* ' + "中文😀".repeat(12_000) + " */ NULL; END;";+ mocks.listObjects.mockResolvedValue([{ name: trigger.name, schema: " Trigger Owner ", object_type: "TRIGGER", trigger }]);+ mocks.getObjectSource.mockResolvedValue({ name: trigger.name, schema: " Trigger Owner ", object_type: "TRIGGER", source, trigger });+ const { host } = await mountBrowser("triggers", " Catalog ");+ await vi.waitFor(() => expect(host.querySelector('[title=" Trigger "]')).not.toBeNull());+ const row = host.querySelector('[title=" Trigger "]')!.closest(".grid")!;+ row.dispatchEvent(new MouseEvent("click", { bubbles: true, detail: 1 }));+ await vi.waitFor(() => expect(mocks.getObjectSource).toHaveBeenCalled());+ expect(mocks.listObjects.mock.calls[0][10]).toEqual({ identityMode: "exact", catalog: " Catalog " });+ expect(mocks.getObjectSource).toHaveBeenCalledWith(connection.id, "APP", " Trigger Owner ", " Trigger ", "TRIGGER", undefined, undefined, { identityMode: "exact", catalog: " Catalog " });+ await vi.waitFor(() => expect(host.querySelector("[data-source-text]")?.textContent).toBe(source));+ expect(Array.from(host.querySelectorAll("button")).some((button) => button.textContent?.trim() === "tree.triggers")).toBe(true);+ mocks.getObjectSource.mockRejectedValue(new Error("metadata temporarily offline"));+ const discard = vi.fn(() => false);+ vi.stubGlobal("confirm", discard);+ const refresh = host.querySelector<HTMLButtonElement>('[aria-label="structureEditor.refresh"]')!;+ refresh.click();+ await vi.waitFor(() => expect(host.textContent).toContain("metadata temporarily offline"));+ refresh.click();+ await vi.waitFor(() => expect(mocks.getObjectSource).toHaveBeenCalledTimes(3));+ await nextTick();+ await vi.waitFor(() => expect(refresh.disabled).toBe(false));+ expect(discard).not.toHaveBeenCalled();+ await vi.waitFor(() => expect(host.querySelector("[data-source-text]")?.textContent === source).toBe(true));+ Array.from(host.querySelectorAll<HTMLButtonElement>("button"))+ .find((button) => button.textContent?.trim() === "objects.saveSource")!+ .click();+ await vi.waitFor(() => expect(host.textContent?.includes("oracleTrigger.reloadBaseline")).toBe(true));+ });+it("ends local waiting when the object request never returns", async () => {vi.useFakeTimers();mocks.listObjects.mockReturnValue(new Promise(() => undefined));@@ -132,7 +341,7 @@ describe("OceanBase Oracle object pagination (#11418)", () => {mocks.listObjects.mockResolvedValueOnce([object("O11418_10"), object("O11418_2"), object("O11418_3")]).mockResolvedValueOnce([object("O11418_3")]);const { host } = await mountBrowser();await vi.waitFor(() => expect(host.querySelector('[title="O11418_10"]')).not.toBeNull());- expect(mocks.listObjects).toHaveBeenNthCalledWith(1, connection.id, "APP", "APP", expect.not.arrayContaining(["INDEX"]), undefined, 3, 0, undefined);+ expect(mocks.listObjects).toHaveBeenNthCalledWith(1, connection.id, "APP", "APP", expect.not.arrayContaining(["INDEX"]), undefined, 3, 0, undefined, undefined, undefined, { identityMode: "exact" });expect(host.querySelector('[title="O11418_3"]')).toBeNull();expect(Array.from(host.querySelectorAll('[title^="O11418_"]')).map((el) => el.getAttribute("title"))).toEqual(["O11418_10", "O11418_2"]);@@ -140,7 +349,7 @@ describe("OceanBase Oracle object pagination (#11418)", () => {expect(more).not.toBeNull();more!.click();await vi.waitFor(() => expect(host.querySelector('[title="O11418_3"]')).not.toBeNull());- expect(mocks.listObjects).toHaveBeenNthCalledWith(2, connection.id, "APP", "APP", expect.not.arrayContaining(["INDEX"]), undefined, 3, 2, undefined);+ expect(mocks.listObjects).toHaveBeenNthCalledWith(2, connection.id, "APP", "APP", expect.not.arrayContaining(["INDEX"]), undefined, 3, 2, undefined, undefined, undefined, { identityMode: "exact" });expect(host.querySelector("[data-object-load-more]")).toBeNull();});@@ -153,7 +362,7 @@ describe("OceanBase Oracle object pagination (#11418)", () => {await searchObjects(host, "needle");await vi.waitFor(() => expect(host.querySelector('[title="O11418_LATE_VIEW"]')).not.toBeNull());expect(host.querySelector('[title="O11418_1"]')).toBeNull();- expect(mocks.listObjects).toHaveBeenNthCalledWith(2, connection.id, "APP", "APP", expect.not.arrayContaining(["INDEX"]), "needle", 3, 0, undefined);+ expect(mocks.listObjects).toHaveBeenNthCalledWith(2, connection.id, "APP", "APP", expect.not.arrayContaining(["INDEX"]), "needle", 3, 0, undefined, undefined, undefined, { identityMode: "exact" });const views = Array.from(host.querySelectorAll("button")).find((button) => button.textContent?.trim() === "objects.views");expect(views).toBeDefined();@@ -213,12 +422,16 @@ describe("OceanBase Oracle object pagination (#11418)", () => {});it("renders an empty final page without retaining a load-more action", async () => {- mocks.listObjects.mockResolvedValueOnce([object("O11418_1"), object("O11418_2"), object("O11418_3")]).mockResolvedValueOnce([]);+ mocks.listObjects+ .mockResolvedValueOnce([object("O11418_1"), object("O11418_2"), object("O11418_3")])+ .mockResolvedValueOnce([])+ .mockResolvedValueOnce([object("O11418_1"), object("O11418_2")]);const { host } = await mountBrowser();await vi.waitFor(() => expect(host.querySelector("[data-object-load-more]")).not.toBeNull());host.querySelector<HTMLButtonElement>("[data-object-load-more]")!.click();await vi.waitFor(() => expect(host.querySelector("[data-object-load-more]")).toBeNull());expect(host.querySelector('[title="O11418_1"]')).not.toBeNull();expect(host.querySelector('[title="O11418_2"]')).not.toBeNull();+ expect(mocks.listObjects.mock.calls.at(-1)?.slice(5, 7)).toEqual([5, 0]);});});diff --git a/apps/desktop/src/components/objects/__tests__/ObjectBrowser.oracleTriggerActions.spec.ts b/apps/desktop/src/components/objects/__tests__/ObjectBrowser.oracleTriggerActions.spec.tsnew file mode 100644index 0000000000..a1d55d0870--- /dev/null+++ b/apps/desktop/src/components/objects/__tests__/ObjectBrowser.oracleTriggerActions.spec.ts@@ -0,0 +1,511 @@+// @vitest-environment happy-dom+import { createApp, h, nextTick, type App } from "vue";+import { EditorView } from "@codemirror/view";+import { undo } from "@codemirror/commands";+import { createPinia, setActivePinia } from "pinia";+import { afterEach, beforeEach, expect, it, vi } from "vitest";+import ObjectBrowser from "../ObjectBrowser.vue";+import { TooltipProvider } from "@/components/ui/tooltip";+import LightTooltip from "@/components/ui/LightTooltip.vue";+import i18n from "@/i18n";+import { useConnectionStore } from "@/stores/connectionStore";+import { useQueryStore } from "@/stores/queryStore";+import { useSqlExecutionDangerStore } from "@/stores/sqlExecutionDangerStore";+import { invalidateObjectBrowserRowsCache } from "@/lib/table/objectBrowserRowsCache";+import { invalidateObjectMetadataCache } from "@/lib/metadata/objectMetadataCache";+import type { ConnectionConfig, ObjectSource } from "@/types/database";++const rpc = vi.hoisted(() => ({+ listObjects: vi.fn(),+ listSchemas: vi.fn(),+ getObjectSource: vi.fn(),+ executeQuery: vi.fn(),+ prepareOracleTriggerSql: vi.fn(),+ buildDropObjectSql: vi.fn(),+ buildDropTableSql: vi.fn(),+ listForeignKeys: vi.fn(async () => []),+ listPlugins: vi.fn(async () => []),+ listInstalledAgents: vi.fn(async () => []),+ loadSchemaCache: vi.fn(async () => null),+ saveSchemaCache: vi.fn(async () => undefined),+ deleteSchemaCachePrefix: vi.fn(async () => undefined),+ listObjectStatistics: vi.fn(async () => []),+ checkConnectionHealth: vi.fn(async () => undefined),+ saveOpenTabsState: vi.fn(async () => undefined),+ saveHistory: vi.fn(async () => undefined),+ cancelQuery: vi.fn(async () => true),+}));+vi.mock("@/lib/backend/api", async (original) => ({ ...(await original<typeof import("@/lib/backend/api")>()), ...rpc }));+const owner = " Trigger.Owner ",+ name = ' Tr"ig ',+ parentOwner = " Parent.Owner ",+ parentName = " View ",+ executionSchema = "Browse.Owner";+const config = { id: "browser-exact-trigger-actions", name: "Trigger browser", db_type: "oceanbase-oracle", username: executionSchema, database: "service" } as ConnectionConfig;+const quote = (value: string) => `"${value.replaceAll('"', '""')}"`;+const dropSql = (triggerOwner: string) => `DROP TRIGGER ${quote(triggerOwner)}.${quote(name)};`;+let raw: ObjectSource;+let app: App | undefined;+const openDependencyObject = vi.fn();+beforeEach(async () => {+ vi.clearAllMocks();+ invalidateObjectBrowserRowsCache({});+ await invalidateObjectMetadataCache({ connectionId: config.id });+ i18n.global.locale.value = "en";+ raw = {+ name,+ schema: owner,+ object_type: "TRIGGER",+ source: "BEGIN NULL; END;",+ editable: false,+ trigger: {+ name,+ timing: "INSTEAD OF",+ event: "INSERT",+ statement: "BEGIN NULL; END;",+ enabled: false,+ valid: false,+ oracle_metadata: {+ contractVersion: 1,+ identityMode: "exact",+ engine: "oceanbase-oracle",+ engineVersion: "4.2.5.7_107",+ owner,+ name,+ objectId: "trigger-id",+ scope: "VIEW",+ parent: { owner: parentOwner, name: parentName, objectType: "VIEW" },+ definition: { origin: "catalog-body", format: "body", complete: false },+ errors: [{ sequence: 1, line: 3, position: 7, text: "Missing procedure" }],+ reads: { identity: { state: "available" }, scope: { state: "available" }, parent: { state: "available" }, enabled: { state: "available" }, validity: { state: "available" }, definition: { state: "denied" }, errors: { state: "available" } },+ },+ },+ };+ rpc.listSchemas.mockReset().mockResolvedValue([executionSchema]);+ rpc.listObjects.mockReset().mockImplementation(async () => [{ name, schema: owner, object_type: "TRIGGER", valid: raw.trigger!.valid, trigger: JSON.parse(JSON.stringify(raw.trigger)) }]);+ rpc.getObjectSource.mockReset().mockImplementation(async () => JSON.parse(JSON.stringify(raw)));+ rpc.buildDropObjectSql.mockReset().mockImplementation(async (input) => `DROP ${input.objectType} ${quote(input.schema)}.${quote(input.name)};`);+ rpc.buildDropTableSql.mockReset().mockImplementation(async (input) => `DROP TABLE ${quote(input.schema)}.${quote(input.tableName)};`);+ rpc.executeQuery.mockReset().mockImplementation(async (_id, _db, sql: string) => {+ if (sql.endsWith(" ENABLE;")) raw.trigger!.enabled = true;+ if (sql.endsWith(" DISABLE;")) raw.trigger!.enabled = false;+ return { columns: [], rows: [], affected_rows: 0 };+ });+});+afterEach(() => {+ app?.unmount();+ app = undefined;+ document.body.innerHTML = "";+ vi.restoreAllMocks();+ vi.unstubAllGlobals();+});++async function mountTriggerBrowser(filter: "all" | "triggers" = "triggers", connection = config) {+ const pinia = createPinia();+ setActivePinia(pinia);+ const connections = useConnectionStore();+ connections.connections = [connection];+ connections.connectedIds.add(connection.id);+ const host = document.createElement("div");+ document.body.append(host);+ app = createApp({ render: () => h(TooltipProvider, {}, { default: () => h(ObjectBrowser, { connection, database: "service", schema: executionSchema, catalog: " Catalog ", selectedObjectFilter: filter, onOpenDependencyObject: openDependencyObject }) }) });+ app.use(pinia);+ app.use(i18n);+ app.component("LightTooltip", LightTooltip);+ app.mount(host);+ await vi.waitFor(() => expect([...host.querySelectorAll<HTMLElement>("[title]")].some((item) => item.title === name)).toBe(true));+ return host;+}++it.each(["native", "oracle-jdbc", "dm-jdbc"])("reuses dependency sections in the %s source panel without destroying its draft, undo or exact navigation context", async (provider) => {+ raw.source = `CREATE OR REPLACE TRIGGER ${quote(owner)}.${quote(name)} INSTEAD OF INSERT ON ${quote(parentOwner)}.${quote(parentName)} DISABLE BEGIN NULL; END;`;+ raw.trigger!.oracle_metadata!.definition = { origin: "DBMS_METADATA", format: "ddl", complete: true };+ raw.trigger!.oracle_metadata!.reads.definition = { state: "available" };+ const connection = provider === "native" ? config : { ...config, db_type: "jdbc" as const, driver_profile: provider === "dm-jdbc" ? "dameng" : "oracle", database_info: { productName: provider === "dm-jdbc" ? "DM DBMS" : "Oracle" } };+ if (provider !== "native") {+ raw.trigger!.oracle_metadata!.engine = provider === "dm-jdbc" ? "dm" : "oracle";+ raw.trigger!.oracle_metadata!.engineVersion = provider === "dm-jdbc" ? "8.1" : "19.0";+ }+ rpc.prepareOracleTriggerSql.mockImplementation(async (input) => ({ definition: input.source, comparisonSource: input.source, header: { scope: "RELATION", owner: parentOwner, name: parentName, viewOnly: true, pluggable: false }, requiresStateRestore: false }));+ rpc.executeQuery.mockResolvedValue({+ columns: ["DIRECTION", "OBJECT_OWNER", "OBJECT_NAME", "OBJECT_TYPE", "REFERENCED_OWNER", "REFERENCED_NAME", "REFERENCED_TYPE", "DEPENDENCY_TYPE", "REFERENCED_LINK_NAME"],+ rows: [["DEPENDS_ON", owner, name, "TRIGGER", parentOwner, parentName, "VIEW", "HARD", null]],+ });+ const host = await mountTriggerBrowser("triggers", connection);+ [...host.querySelectorAll<HTMLElement>("[title]")]+ .find((item) => item.title === name)!+ .closest(".grid")!+ .dispatchEvent(new MouseEvent("click", { bubbles: true, detail: 1 }));+ await vi.waitFor(() => expect(host.querySelector("[data-object-source-editor] .cm-editor")).not.toBeNull(), { timeout: 30_000 });+ const view = EditorView.findFromDOM(host.querySelector<HTMLElement>("[data-object-source-editor] .cm-editor")!)!;+ const original = view.state.doc.toString();+ view.dispatch({ changes: { from: 0, insert: "-- keep browser draft\n" }, selection: { anchor: 2, head: 5 } });+ await nextTick();+ const draft = view.state.doc.toString();+ const section = () => host.querySelector<HTMLButtonElement>('[data-object-section="dependencies"]');+ expect(section()).not.toBeNull();+ section()!.click();+ const dependency = () => [...host.querySelectorAll<HTMLButtonElement>("[data-object-details] table button")].find((item) => item.textContent?.trim() === parentName.trim());+ await vi.waitFor(() => expect(dependency()).toBeDefined());+ expect(rpc.executeQuery).toHaveBeenCalledWith(config.id, "service", expect.stringContaining("d.TYPE = 'TRIGGER'"), owner, expect.stringContaining("object-dependencies-"), { catalog: " Catalog " });+ useQueryStore().createTab("other-connection", "other-database", "Other query");+ const confirm = vi.fn(() => false);+ vi.stubGlobal("confirm", confirm);+ dependency()!.click();+ expect(confirm).toHaveBeenCalledOnce();+ expect(openDependencyObject).not.toHaveBeenCalled();+ host.querySelector<HTMLButtonElement>('[data-object-section="source"]')!.click();+ await nextTick();+ expect(EditorView.findFromDOM(host.querySelector<HTMLElement>("[data-object-source-editor] .cm-editor")!)).toBe(view);+ expect(view.state.doc.toString()).toBe(draft);+ expect([view.state.selection.main.anchor, view.state.selection.main.head]).toEqual([2, 5]);+ expect(undo(view)).toBe(true);+ expect(view.state.doc.toString()).toBe(original);+ section()!.click();+ await nextTick();+ dependency()!.click();+ expect(openDependencyObject).toHaveBeenCalledWith(expect.objectContaining({ connectionId: config.id, database: "service", catalog: " Catalog ", schema: owner, name, objectType: "TRIGGER" }), { schema: parentOwner, name: parentName, type: "view", schemaQuoted: true, nameQuoted: true });+ expect(rpc.executeQuery.mock.calls.every((call) => call[2].includes("ALL_DEPENDENCIES"))).toBe(true);+});++it.each(["panel-toggle", "source-close", "same-row", "other-row"])("keeps the trigger editor and undo when cancelling %s, then leaves only after explicit discard", async (action) => {+ raw.source = `CREATE OR REPLACE TRIGGER ${quote(owner)}.${quote(name)} INSTEAD OF INSERT ON ${quote(parentOwner)}.${quote(parentName)} DISABLE BEGIN NULL; END;`;+ raw.trigger!.oracle_metadata!.definition = { origin: "DBMS_METADATA", format: "ddl", complete: true };+ raw.trigger!.oracle_metadata!.reads.definition = { state: "available" };+ const second = structuredClone(raw);+ second.name = second.trigger!.name = second.trigger!.oracle_metadata!.name = "OtherTrigger";+ second.trigger!.oracle_metadata!.objectId = "other-trigger-id";+ second.source = raw.source.replace(quote(name), quote(second.name));+ rpc.listObjects.mockResolvedValue([raw, second].map((item) => ({ name: item.name, schema: owner, object_type: "TRIGGER", trigger: item.trigger })));+ rpc.getObjectSource.mockImplementation(async (_id, _db, _owner, requestedName) => structuredClone(requestedName === second.name ? second : raw));+ rpc.prepareOracleTriggerSql.mockImplementation(async (input) => ({ definition: input.source, comparisonSource: input.source, header: { scope: "RELATION", owner: parentOwner, name: parentName, viewOnly: true, pluggable: false }, requiresStateRestore: false }));+ const host = await mountTriggerBrowser();+ const clickRow = (rowName: string) =>+ [...host.querySelectorAll<HTMLElement>("[title]")]+ .find((item) => item.title === rowName)!+ .closest(".grid")!+ .dispatchEvent(new MouseEvent("click", { bubbles: true, detail: 1 }));+ clickRow(name);+ await vi.waitFor(() => expect(host.querySelector("[data-object-source-editor] .cm-editor")).not.toBeNull(), { timeout: 30_000 });+ const editor = () => host.querySelector<HTMLElement>("[data-object-source-editor] .cm-editor");+ const view = EditorView.findFromDOM(editor()!)!;+ const original = view.state.doc.toString();+ view.dispatch({ changes: { from: 0, insert: "-- keep on cancelled navigation\n" }, selection: { anchor: 2, head: 5 } });+ await nextTick();+ const draft = view.state.doc.toString();+ const confirm = vi.fn(() => false);+ vi.stubGlobal("confirm", confirm);+ const leave = () => {+ if (action === "source-close") [...host.querySelector("[data-object-details]")!.previousElementSibling!.querySelectorAll<HTMLButtonElement>("button")].at(-1)!.click();+ else if (action === "panel-toggle") host.querySelector<HTMLButtonElement>(`button[title="${i18n.global.t("objects.closeDetailPanel")}"]`)!.click();+ else clickRow(action === "same-row" ? name : second.name);+ };+ const reads = rpc.getObjectSource.mock.calls.length;+ leave();+ await nextTick();+ expect(confirm).toHaveBeenCalledOnce();+ expect(editor()).not.toBeNull();+ expect(EditorView.findFromDOM(editor()!)).toBe(view);+ expect(view.state.doc.toString()).toBe(draft);+ expect([view.state.selection.main.anchor, view.state.selection.main.head]).toEqual([2, 5]);+ expect(rpc.getObjectSource).toHaveBeenCalledTimes(reads);+ expect(undo(view)).toBe(true);+ expect(view.state.doc.toString()).toBe(original);+ view.dispatch({ changes: { from: 0, insert: "-- explicit discard\n" } });+ await nextTick();+ confirm.mockReturnValue(true);+ leave();+ await vi.waitFor(() => expect(action === "other-row" ? host.textContent?.includes(second.name) && editor() !== view.dom : !editor()).toBe(true));+ if (action === "other-row") {+ await vi.waitFor(() => expect(editor()).not.toBeNull());+ expect(EditorView.findFromDOM(editor()!)!.state.doc.toString()).toContain(quote(second.name));+ expect(EditorView.findFromDOM(editor()!)!.state.doc.toString()).not.toContain("explicit discard");+ }+ expect(confirm).toHaveBeenCalledTimes(2);+ expect(rpc.executeQuery).not.toHaveBeenCalled();+});++it("retains the latest browser draft and editor across an incomplete identity read and a successful retry", async () => {+ raw.source = `CREATE OR REPLACE TRIGGER ${quote(owner)}.${quote(name)} INSTEAD OF INSERT ON ${quote(parentOwner)}.${quote(parentName)} DISABLE BEGIN NULL; END;`;+ raw.trigger!.oracle_metadata!.definition = { origin: "DBMS_METADATA", format: "ddl", complete: true };+ raw.trigger!.oracle_metadata!.reads.definition = { state: "available" };+ rpc.prepareOracleTriggerSql.mockImplementation(async (input) => ({ definition: input.source, comparisonSource: input.source, header: { scope: "RELATION", owner: parentOwner, name: parentName, viewOnly: true, pluggable: false }, requiresStateRestore: false }));+ const host = await mountTriggerBrowser();+ [...host.querySelectorAll<HTMLElement>("[title]")]+ .find((item) => item.title === name)!+ .closest(".grid")!+ .dispatchEvent(new MouseEvent("click", { bubbles: true, detail: 1 }));+ const editor = () => host.querySelector<HTMLElement>("[data-object-source-editor] .cm-editor");+ await vi.waitFor(() => expect(editor()).not.toBeNull(), { timeout: 30_000 });+ const view = EditorView.findFromDOM(editor()!)!;+ view.dispatch({ changes: { from: 0, insert: "-- preserve incomplete refresh draft\n" } });+ await nextTick();+ const incomplete = structuredClone(raw);+ incomplete.trigger!.oracle_metadata!.reads.identity = { state: "incomplete", message: "identity changed while reading" };+ rpc.getObjectSource.mockResolvedValueOnce(incomplete);+ const refresh = () => host.querySelector<HTMLButtonElement>(`button[aria-label="${i18n.global.t("structureEditor.refresh")}"]`)!;+ refresh().click();+ await nextTick();+ await vi.waitFor(() => expect(refresh().disabled).toBe(false));+ await vi.waitFor(() => expect(host.textContent).toContain("identity is unavailable"));+ expect(editor()).not.toBeNull();+ expect(EditorView.findFromDOM(editor()!)).toBe(view);+ view.dispatch({ changes: { from: view.state.doc.length, insert: "\n-- latest correction" } });+ await nextTick();+ const latest = view.state.doc.toString();+ rpc.getObjectSource.mockResolvedValueOnce(structuredClone(raw));+ refresh().click();+ await nextTick();+ await vi.waitFor(() => expect(refresh().disabled).toBe(false));+ expect(EditorView.findFromDOM(editor()!)).toBe(view);+ expect(view.state.doc.toString()).toBe(latest);+ expect(undo(view)).toBe(true);+ expect(rpc.executeQuery).not.toHaveBeenCalled();+});++it("does not authorize saving the old browser draft from an unknown same-ID concurrent body readback", async () => {+ raw.source = `CREATE OR REPLACE TRIGGER ${quote(owner)}.${quote(name)} INSTEAD OF INSERT ON ${quote(parentOwner)}.${quote(parentName)} DISABLE BEGIN NULL; END;`;+ raw.trigger!.oracle_metadata!.definition = { origin: "DBMS_METADATA", format: "ddl", complete: true };+ raw.trigger!.oracle_metadata!.reads.definition = { state: "available" };+ const initial = raw.source;+ rpc.prepareOracleTriggerSql.mockImplementation(async (input) => ({ definition: input.source, comparisonSource: input.source, header: { scope: "RELATION", owner: parentOwner, name: parentName, viewOnly: true, pluggable: false }, requiresStateRestore: false }));+ const host = await mountTriggerBrowser();+ [...host.querySelectorAll<HTMLElement>("[title]")]+ .find((item) => item.title === name)!+ .closest(".grid")!+ .dispatchEvent(new MouseEvent("click", { bubbles: true, detail: 1 }));+ await vi.waitFor(() => expect(host.querySelector("[data-object-source-editor] .cm-editor")).not.toBeNull(), { timeout: 30_000 });+ const view = EditorView.findFromDOM(host.querySelector<HTMLElement>("[data-object-source-editor] .cm-editor")!)!;+ view.dispatch({ changes: { from: 0, insert: "-- keep my version\n" } });+ await nextTick();+ const draft = view.state.doc.toString();+ rpc.executeQuery.mockImplementation(async (_id, _db, sql) => {+ if (sql.startsWith("SELECT")) return { columns: ["OWNER", "OBJECT_NAME", "OBJECT_TYPE", "OBJECT_ID"], rows: [[parentOwner, parentName, "VIEW", "parent-id"]] };+ raw.source = initial.replace("NULL;", "other_session_proc;");+ return { columns: [], rows: [] };+ });+ [...host.querySelectorAll<HTMLButtonElement>("[data-oracle-trigger-status] button")].find((item) => item.textContent?.trim() === i18n.global.t("processList.oracleInvalidObjects.compile"))!.click();+ const danger = useSqlExecutionDangerStore();+ await vi.waitFor(() => expect(danger.pending).toBeDefined());+ danger.confirm();+ await vi.waitFor(() => expect(host.textContent).toContain(i18n.global.t("oracleTrigger.reloadBaseline")));+ [...host.querySelectorAll<HTMLButtonElement>("button")].find((item) => item.textContent?.trim() === i18n.global.t("objects.saveSource"))!.click();+ await vi.waitFor(() => expect(!!danger.pending || host.textContent?.includes(i18n.global.t("objects.sourceIdentityChanged"))).toBe(true));+ const confirmed = !!danger.pending;+ danger.cancelAll();+ expect(confirmed).toBe(false);+ expect(view.state.doc.toString()).toBe(draft);+ expect(rpc.executeQuery).toHaveBeenCalledOnce();+});++it.each(["before", "after"])("keeps the source panel bound to its displayed physical trigger when replacement happens %s compile", async (when) => {+ const host = await mountTriggerBrowser();+ [...host.querySelectorAll<HTMLElement>("[title]")]+ .find((item) => item.title === name)!+ .closest(".grid")!+ .dispatchEvent(new MouseEvent("click", { bubbles: true, detail: 1 }));+ const compile = () => [...host.querySelectorAll<HTMLButtonElement>("[data-oracle-trigger-status] button")].find((item) => item.textContent?.trim() === i18n.global.t("processList.oracleInvalidObjects.compile"));+ await vi.waitFor(() => expect(compile()).toBeDefined());+ if (when === "before") raw.trigger!.oracle_metadata!.objectId = "replacement-id";+ else+ rpc.executeQuery.mockImplementation(async () => {+ raw.trigger!.oracle_metadata!.objectId = "replacement-id";+ return { columns: [], rows: [] };+ });+ compile()!.click();+ const danger = useSqlExecutionDangerStore();+ if (when === "after") {+ await vi.waitFor(() => expect(danger.pending).toBeDefined());+ danger.confirm();+ await vi.waitFor(() => expect(host.textContent).toContain(i18n.global.t("oracleTrigger.reloadBaseline")));+ compile()!.click();+ }+ await vi.waitFor(() => expect(!!danger.pending || host.textContent?.includes("displayed trigger was replaced")).toBe(true));+ const confirmed = !!danger.pending;+ danger.cancelAll();+ expect(confirmed).toBe(false);+ expect(host.textContent).toContain("displayed trigger was replaced");+ expect(rpc.executeQuery).toHaveBeenCalledTimes(when === "before" ? 0 : 1);+});++it.each(["source", "error-position"])("opens exact INVALID diagnostics from the existing source panel and repairs through a bound source tab (%s)", async (entry) => {+ if (entry === "error-position") {+ raw.source = `TRIGGER ${quote(owner)}.${quote(name)} INSTEAD OF INSERT ON ${quote(parentOwner)}.${quote(parentName)}\nBEGIN\n missing_proc;\nEND;`;+ raw.trigger!.oracle_metadata!.definition = { origin: "ALL_SOURCE", format: "declaration", complete: true };+ raw.trigger!.oracle_metadata!.reads.definition = { state: "available" };+ raw.trigger!.oracle_metadata!.errors = [{ sequence: 1, line: 3, position: 3, text: "Missing procedure" }];+ rpc.prepareOracleTriggerSql.mockImplementation(async (input) => ({+ definition: input.source.startsWith("TRIGGER") ? "CREATE OR REPLACE " + input.source : input.source,+ comparisonSource: input.source,+ header: { scope: "RELATION", owner: parentOwner, name: parentName, viewOnly: true, pluggable: false },+ requiresStateRestore: false,+ }));+ }+ const host = await mountTriggerBrowser();+ [...host.querySelectorAll<HTMLElement>("[title]")]+ .find((item) => item.title === name)!+ .closest(".grid")!+ .dispatchEvent(new MouseEvent("click", { bubbles: true, detail: 1 }));+ await vi.waitFor(() => expect(host.querySelector("[data-oracle-trigger-status]")).not.toBeNull());+ const diagnostics = [...host.querySelectorAll<HTMLButtonElement>("[data-oracle-trigger-status] button")].find((item) => item.textContent?.trim() === i18n.global.t("processList.oracleInvalidObjects.errorsTitle"));+ expect(diagnostics).toBeDefined();+ diagnostics!.click();+ const dialog = () => document.querySelector('[role="dialog"]');+ await vi.waitFor(() => expect(dialog()?.textContent).toContain("Missing procedure"));+ expect(dialog()?.textContent).toContain(owner);+ const openSource = [...dialog()!.querySelectorAll<HTMLButtonElement>("button")].find((item) =>+ entry === "source" ? item.textContent?.trim() === i18n.global.t("processList.oracleInvalidObjects.openSource") : item.getAttribute("aria-label") === i18n.global.t("editor.locateError", { line: 3, column: 3 }),+ );+ openSource!.click();+ await vi.waitFor(() => expect(useQueryStore().tabs.some((tab) => tab.objectSource?.name === name && tab.objectSource.schema === owner)).toBe(true));+ const tab = useQueryStore().tabs.find((item) => item.objectSource?.name === name)!;+ expect(useQueryStore().oracleTriggerSourceState(tab.id)?.baseline?.target).toMatchObject({ owner, name, catalog: " Catalog " });+ expect(tab.title).not.toContain("Repair -");+ if (entry === "error-position") await vi.waitFor(() => expect(tab.editorRevealRequest).toMatchObject({ line: 3, column: 3 }));+ expect(rpc.executeQuery).not.toHaveBeenCalled();+});++it.each([+ { action: "enable", recreated: false },+ { action: "disable", recreated: false },+ { action: "compile", recreated: false },+ { action: "enable", recreated: true },+] as const)("runs $action from the existing trigger context menu with exact identity (recreated=$recreated)", async ({ action, recreated }) => {+ raw.trigger!.enabled = action !== "enable";+ const host = await mountTriggerBrowser();+ const label = () => [...host.querySelectorAll<HTMLElement>("[title]")].find((item) => item.title === name);+ await vi.waitFor(() => expect(label()).toBeDefined());+ label()!+ .closest(".grid")!+ .dispatchEvent(new MouseEvent("contextmenu", { bubbles: true, clientX: 20, clientY: 20 }));+ const text = i18n.global.t(action === "compile" ? "contextMenu.compileObject" : action === "enable" ? "contextMenu.enableTrigger" : "contextMenu.disableTrigger");+ const menuButtons = () => [...document.querySelectorAll<HTMLButtonElement>("[data-dbx-context-menu] button")];+ await vi.waitFor(() => expect(menuButtons().some((item) => item.textContent?.trim() === i18n.global.t("contextMenu.viewSource"))).toBe(true));+ const menuItem = () => menuButtons().find((item) => item.textContent?.trim() === text);+ await vi.waitFor(() => expect(menuItem()).toBeDefined());+ if (recreated)+ rpc.getObjectSource.mockImplementation(async () => {+ const replaced: ObjectSource = JSON.parse(JSON.stringify(raw));+ replaced.trigger!.oracle_metadata!.objectId = "replacement-id";+ return replaced;+ });+ menuItem()!.click();+ if (recreated) {+ await vi.waitFor(() => expect(document.body.textContent).toContain("was replaced"));+ expect(useSqlExecutionDangerStore().pending).toBeUndefined();+ expect(rpc.executeQuery).not.toHaveBeenCalled();+ return;+ }+ const danger = useSqlExecutionDangerStore();+ await vi.waitFor(() => expect(danger.pending).toBeDefined());+ const sql = `ALTER TRIGGER " Trigger.Owner "." Tr""ig " ${action.toUpperCase()}${action === "compile" ? "" : ";"}`;+ expect(danger.pending!.sql).toBe(sql);+ danger.confirm();+ await vi.waitFor(() => expect(rpc.executeQuery).toHaveBeenCalledWith(config.id, "service", sql, executionSchema, undefined, { catalog: " Catalog ", timeoutSecs: 60 }));+ await vi.waitFor(() => expect(rpc.getObjectSource.mock.calls.length).toBeGreaterThanOrEqual(3));+ expect(rpc.getObjectSource.mock.calls.every((call) => call[2] === owner && call[3] === name && call[7]?.catalog === " Catalog ")).toBe(true);+ expect(rpc.executeQuery.mock.calls.filter((call) => !call[2].startsWith("SELECT"))).toHaveLength(1);+ if (action === "compile") await vi.waitFor(() => expect(document.body.textContent).toContain("Missing procedure"));+});++it.each(["menu", "keyboard", "batch-success", "batch-mixed", "batch-unknown", "batch-unknown-reconcile", "batch-cancel"] as const)("drops exact triggers through %s without collapsing names or replaying uncertain writes", async (entry) => {+ const mixed = entry === "batch-mixed";+ const actualParentName = mixed ? "PARENT_TABLE" : parentName;+ const actualParentOwner = mixed ? "PARENT_OWNER" : parentOwner;+ if (mixed) {+ raw.trigger!.oracle_metadata!.scope = "TABLE";+ raw.trigger!.oracle_metadata!.parent!.objectType = "TABLE";+ raw.trigger!.oracle_metadata!.parent!.name = actualParentName;+ raw.trigger!.oracle_metadata!.parent!.owner = actualParentOwner;+ }+ const secondOwner = " Second.Owner ";+ const second: ObjectSource = JSON.parse(JSON.stringify(raw));+ second.schema = secondOwner;+ second.trigger!.oracle_metadata!.owner = secondOwner;+ second.trigger!.oracle_metadata!.objectId = "second-id";+ const batch = entry.startsWith("batch"),+ sources = new Map([[owner, raw], ...(batch ? [[secondOwner, second] as const] : [])]);+ const deleted = new Set<string>();+ let deletedParent = false,+ denyGlobal = entry.includes("unknown");+ const parentDrop = `DROP TABLE ${quote(actualParentOwner)}.${quote(actualParentName)};`;+ rpc.listObjects.mockImplementation(async () => [+ ...[...sources].filter(([triggerOwner]) => !deleted.has(triggerOwner)).map(([triggerOwner, value]) => ({ name, schema: triggerOwner, object_type: "TRIGGER", trigger: JSON.parse(JSON.stringify(value.trigger)) })),+ ...(mixed && !deletedParent ? [{ name: actualParentName, schema: actualParentOwner, object_type: "TABLE" }] : []),+ ]);+ rpc.getObjectSource.mockImplementation(async (_id, _db, requestedOwner) => {+ const response: ObjectSource = JSON.parse(JSON.stringify(sources.get(requestedOwner)!));+ if (deleted.has(requestedOwner)) {+ response.source = "";+ Object.assign(response.trigger!.oracle_metadata!, { objectId: null, scope: "UNKNOWN", parent: null, errors: null });+ response.trigger!.oracle_metadata!.reads.identity = { state: "empty" };+ }+ return response;+ });+ rpc.executeQuery.mockImplementation(async (_id, _db, sql: string) => {+ if (sql.startsWith("SELECT USER")) return { columns: ["USER"], rows: [[executionSchema]] };+ if (sql.includes("FROM DBA_OBJECTS")) {+ if (denyGlobal) throw new Error("global dictionary denied after DROP");+ return { columns: ["OWNER", "OBJECT_NAME"], rows: [] };+ }+ if (sql.startsWith("SELECT")) return { columns: ["OWNER", "OBJECT_NAME", "OBJECT_TYPE", "OBJECT_ID"], rows: deletedParent ? [] : [[actualParentOwner, actualParentName, mixed ? "TABLE" : "VIEW", "parent-id"]] };+ if (mixed && sql === parentDrop) {+ deletedParent = true;+ return { columns: [], rows: [], affected_rows: 0 };+ }+ const triggerOwner = [...sources.keys()].find((value) => sql === dropSql(value));+ if (!triggerOwner) throw new Error(`Unexpected fixture write: ${sql}`);+ deleted.add(triggerOwner);+ return { columns: [], rows: [], affected_rows: 0 };+ });+ const host = await mountTriggerBrowser(mixed ? "all" : "triggers");+ const rowLabels = () => [...host.querySelectorAll<HTMLElement>("[title]")].filter((item) => item.title === name && item.closest<HTMLElement>(".vue-recycle-scroller__item-view")?.style.visibility !== "hidden");+ if (entry === "menu") {+ rowLabels()[0]+ .closest(".grid")!+ .dispatchEvent(new MouseEvent("contextmenu", { bubbles: true, clientX: 20, clientY: 20 }));+ const drop = () => [...document.querySelectorAll<HTMLButtonElement>("[data-dbx-context-menu] button")].find((button) => button.textContent?.trim() === i18n.global.t("contextMenu.dropTrigger"));+ await vi.waitFor(() => expect(drop()).toBeDefined());+ drop()!.click();+ } else {+ for (const label of rowLabels()) label.closest(".grid")!.dispatchEvent(new MouseEvent("click", { bubbles: true, ctrlKey: true, detail: 1 }));+ if (mixed)+ [...host.querySelectorAll<HTMLElement>("[title]")]+ .find((item) => item.title === actualParentName)!+ .closest(".grid")!+ .dispatchEvent(new MouseEvent("click", { bubbles: true, ctrlKey: true, detail: 1 }));+ await nextTick();+ if (entry === "keyboard") host.querySelector<HTMLElement>("[data-object-browser-root]")!.dispatchEvent(new KeyboardEvent("keydown", { key: "Delete", bubbles: true }));+ else [...host.querySelectorAll<HTMLButtonElement>("button")].find((button) => button.textContent?.trim() === i18n.global.t("objects.dropSelected"))!.click();+ }+ const dialog = () => document.querySelector<HTMLElement>('[role="dialog"]');+ await vi.waitFor(() => expect(dialog()).not.toBeNull());+ await vi.waitFor(() => expect(dialog()!.textContent).toContain(dropSql(owner)));+ if (batch) expect(dialog()!.textContent).toContain(dropSql(secondOwner));+ const confirm = () => [...dialog()!.querySelectorAll<HTMLButtonElement>("button")].find((button) => button.textContent?.trim() === i18n.global.t(batch ? "objects.dropSelected" : "dangerDialog.deleteConfirm"));+ await vi.waitFor(() => expect(confirm()?.disabled).toBe(false));+ if (entry === "batch-cancel") [...dialog()!.querySelectorAll<HTMLButtonElement>("button")].find((button) => button.textContent?.trim() === i18n.global.t("common.cancel"))!.click();+ else confirm()!.click();+ const writes = () => rpc.executeQuery.mock.calls.filter((call) => !call[2].startsWith("SELECT")).map((call) => call[2]);+ if (entry === "batch-cancel") expect(writes()).toEqual([]);+ else if (entry.includes("unknown")) {+ await vi.waitFor(() => expect(document.body.textContent).toContain("global dictionary denied after DROP"));+ expect(writes()).toEqual([dropSql(owner)]);+ expect(rowLabels()).toHaveLength(2);+ if (entry === "batch-unknown-reconcile") {+ denyGlobal = false;+ const verify = [...document.querySelectorAll<HTMLButtonElement>("[role='dialog'] button")].find((button) => button.textContent?.trim() === i18n.global.t("oracleTrigger.verifyReadOnly"));+ expect(verify).toBeDefined();+ await vi.waitFor(() => expect(verify!.disabled).toBe(false));+ const readCount = rpc.getObjectSource.mock.calls.length;+ verify!.click();+ await vi.waitFor(() => expect(rpc.getObjectSource.mock.calls.length).toBeGreaterThan(readCount));+ await vi.waitFor(() => expect(rowLabels(), document.body.textContent ?? "").toHaveLength(1));+ expect(writes()).toEqual([dropSql(owner)]);+ }+ } else {+ await vi.waitFor(() => expect(rowLabels()).toHaveLength(0));+ expect(writes()).toEqual(batch ? [dropSql(owner), dropSql(secondOwner), ...(mixed ? [parentDrop] : [])] : [dropSql(owner)]);+ expect(rpc.getObjectSource).toHaveBeenCalled();+ }+});diff --git a/apps/desktop/src/components/objects/__tests__/ObjectBrowser.schemaIndexes.component.spec.ts b/apps/desktop/src/components/objects/__tests__/ObjectBrowser.schemaIndexes.component.spec.tsindex f63f7d0a86..b0c4fcb847 100644--- a/apps/desktop/src/components/objects/__tests__/ObjectBrowser.schemaIndexes.component.spec.ts+++ b/apps/desktop/src/components/objects/__tests__/ObjectBrowser.schemaIndexes.component.spec.ts@@ -241,7 +241,8 @@ describe("schema index browsing and draft navigation", () => {expect(host.querySelector('[title="ORDINARY"]')).not.toBeNull();expect(host.querySelector('[title="LEGACY_WRONG"]')).toBeNull();expect(host.querySelector('[title=" Ix(a) "]')).toBeNull();- expect(mocks.listObjects.mock.calls.every((call) => !call[10] && !call[3]?.includes("INDEX"))).toBe(true);+ expect(mocks.listObjects.mock.calls.every((call) => call[10] !== true && !call[3]?.includes("INDEX"))).toBe(true);+ expect(mocks.listObjects.mock.calls[0][10]).toEqual({ identityMode: "exact" });});it("loads indexes only after choosing the dedicated bounded exact filter", async () => {diff --git a/apps/desktop/src/components/objects/__tests__/ObjectBrowser.slowSchemaList.component.spec.ts b/apps/desktop/src/components/objects/__tests__/ObjectBrowser.slowSchemaList.component.spec.tsindex 96fb3dac6d..9770bdeed3 100644--- a/apps/desktop/src/components/objects/__tests__/ObjectBrowser.slowSchemaList.component.spec.ts+++ b/apps/desktop/src/components/objects/__tests__/ObjectBrowser.slowSchemaList.component.spec.ts@@ -112,7 +112,8 @@ describe("ObjectBrowser with a slow schema list", () => {await vi.waitFor(() => expect(host.textContent).toContain("TEST2026"));// Schema index metadata is read only in the dedicated paged filter.- expect(mocks.listObjects).toHaveBeenCalledWith("dameng-slow-schemas", "TEST", "TEST", expect.arrayContaining(["TABLE", "VIEW"]), undefined, undefined, undefined, undefined);+ expect(mocks.listObjects).toHaveBeenCalledWith("dameng-slow-schemas", "TEST", "TEST", expect.arrayContaining(["TABLE", "VIEW", "TRIGGER"]), undefined, undefined, undefined, undefined, undefined, undefined, { identityMode: "exact" });+ expect(mocks.listObjects.mock.calls[0][3]).not.toContain("INDEX");expect(mocks.listObjects).toHaveBeenCalledTimes(1);expect(mocks.listSchemas).toHaveBeenCalledWith("dameng-slow-schemas", "TEST");expect(host.textContent).not.toContain("objects.empty");diff --git a/apps/desktop/src/components/objects/__tests__/ObjectBrowser.viewSourceSave.spec.ts b/apps/desktop/src/components/objects/__tests__/ObjectBrowser.viewSourceSave.spec.tsindex 3aadfda7ea..d6ebbc32ac 100644--- a/apps/desktop/src/components/objects/__tests__/ObjectBrowser.viewSourceSave.spec.ts+++ b/apps/desktop/src/components/objects/__tests__/ObjectBrowser.viewSourceSave.spec.ts@@ -87,7 +87,7 @@ vi.mock("@/components/objects/OracleInvalidObjectsDialog.vue", async () => {return {default: defineComponent({props: { open: Boolean },- emits: ["update:open", "open-source", "compile-finished"],+ emits: ["update:open", "open-source", "compile-finished", "trigger-result"],setup(props, { emit }) {return () =>props.open@@ -341,9 +341,11 @@ describe("ObjectBrowser view source save", () => {if (prefix === ddlPrefix) await new Promise<void>((resolve) => (release = resolve));});const { host } = await mountOracleBrowserWithSchema();- const scope = { connectionId: oracleConnection.id, database: "ORCL", schema: "APP_A", exactIdentity: true };+ const scope = { connectionId: oracleConnection.id, database: "ORCL", schema: "APP_A", oracleTriggerContract: 1 as const, exactIdentity: true };expect(getCachedObjectBrowserRows(scope)).toBeDefined();+ expect(getCachedObjectBrowserRows({ connectionId: oracleConnection.id, database: "ORCL", schema: "APP_A" })).toBeUndefined();expect(getCachedObjectBrowserRows({ ...scope, exactIdentity: false })).toBeUndefined();+ expect(getCachedObjectBrowserRows({ ...scope, oracleTriggerContract: undefined })).toBeUndefined();const listCalls = mocks.listObjects.mock.calls.length;[...host.querySelectorAll<HTMLButtonElement>("button")].find((button) => button.textContent?.includes("processList.oracleInvalidObjects.title"))?.click();await nextTick();diff --git a/apps/desktop/src/components/objects/__tests__/ObjectDependenciesPanel.spec.ts b/apps/desktop/src/components/objects/__tests__/ObjectDependenciesPanel.spec.tsindex 8bd95928ed..e1d8194015 100644--- a/apps/desktop/src/components/objects/__tests__/ObjectDependenciesPanel.spec.ts+++ b/apps/desktop/src/components/objects/__tests__/ObjectDependenciesPanel.spec.ts@@ -11,7 +11,7 @@ const backend = vi.hoisted(() => ({ executeQuery: vi.fn(), cancelQuery: vi.fn(asvi.mock("@/lib/backend/api", async (original) => ({ ...(await original<typeof import("@/lib/backend/api")>()), ...backend }));const target = { connectionId: "source-connection", database: "ORCL", schema: "Original.Owner", name: "P", objectType: "PROCEDURE" as const };const mounted: Array<{ app: App; host: HTMLElement; pinia: Pinia }> = [];-function mountPanel(initial: ObjectDetailsSection = "source", identity: ObjectDependencyTarget = target, includeSource?: boolean) {+function mountPanel(initial: ObjectDetailsSection = "source", identity: ObjectDependencyTarget = target, includeSource?: boolean, withOpen = true) {const pinia = createPinia();const connections = useConnectionStore(pinia);connections.connectedIds.add(target.connectionId);@@ -27,7 +27,7 @@ function mountPanel(initial: ObjectDetailsSection = "source", identity: ObjectDetarget: identity,includeSource,section: section.value,- open: open.value,+ ...(withOpen ? { open: open.value } : {}),"onUpdate:section": (value: ObjectDetailsSection) => {section.value = value;},@@ -71,6 +71,18 @@ afterEach(() => {});describe("object details shared sections", () => {+ it("opens dependency sections when optional open is omitted, while an explicit close still suppresses reads", async () => {+ const omitted = mountPanel("dependencies", target, undefined, false);+ await vi.waitFor(() => expect(omitted.host.textContent).toContain("Mixed.Table"));+ expect(omitted.host.querySelector('[data-object-section="dependencies"]')).not.toBeNull();+ const closed = mountPanel();+ closed.open.value = false;+ closed.section.value = "dependencies";+ await nextTick();+ expect(closed.host.querySelector("[data-object-details]")).toBeNull();+ expect(backend.executeQuery).toHaveBeenCalledOnce();+ });+it("shows foreign keys and owning objects separately in table properties without mounting a source editor", async () => {const identity: ObjectDependencyTarget = { ...target, name: "Child.Table", objectType: "TABLE" };const { host, onOpenObject } = mountPanel("dependencies", identity, false);diff --git a/apps/desktop/src/components/objects/__tests__/ObjectSourceDialog.dependencies.spec.ts b/apps/desktop/src/components/objects/__tests__/ObjectSourceDialog.dependencies.spec.tsindex 06d9d26e89..2068ae0711 100644--- a/apps/desktop/src/components/objects/__tests__/ObjectSourceDialog.dependencies.spec.ts+++ b/apps/desktop/src/components/objects/__tests__/ObjectSourceDialog.dependencies.spec.ts@@ -80,9 +80,9 @@ afterEach(() => {describe("source dialog dependency integration", () => {it("keeps the real CodeMirror draft, undo history and selection through dependency refresh", async () => {const { open, onOpenObject } = mountDialog();- await vi.waitFor(() => expect(button("contextMenu.editObject")?.disabled).toBe(false));+ await vi.waitFor(() => expect(button("contextMenu.editObject")?.disabled).toBe(false), { timeout: 30_000 });button("contextMenu.editObject").click();- await vi.waitFor(() => expect(document.querySelector("[data-object-source-editor] .cm-editor")).not.toBeNull());+ await vi.waitFor(() => expect(document.querySelector("[data-object-source-editor] .cm-editor")).not.toBeNull(), { timeout: 30_000 });const editor = document.querySelector<HTMLElement>("[data-object-source-editor] .cm-editor")!;const view = EditorView.findFromDOM(editor)!;const original = view.state.doc.toString();diff --git a/apps/desktop/src/components/objects/__tests__/ObjectSourceDialog.oracleTrigger.spec.ts b/apps/desktop/src/components/objects/__tests__/ObjectSourceDialog.oracleTrigger.spec.tsnew file mode 100644index 0000000000..098fe3769d--- /dev/null+++ b/apps/desktop/src/components/objects/__tests__/ObjectSourceDialog.oracleTrigger.spec.ts@@ -0,0 +1,527 @@+// @vitest-environment happy-dom+import { createApp, h, nextTick, reactive } from "vue";+import { createPinia, setActivePinia } from "pinia";+import { createI18n } from "vue-i18n";+import { EditorView } from "@codemirror/view";+import { undo } from "@codemirror/commands";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { useConnectionStore } from "@/stores/connectionStore";+import { useSqlExecutionDangerStore } from "@/stores/sqlExecutionDangerStore";+import ObjectSourceDialog from "../ObjectSourceDialog.vue";+import type { ConnectionConfig, DatabaseType, ObjectSource } from "@/types/database";+import type { OracleTriggerSqlBinding } from "@/lib/database/oracleTriggerSql";++const owner = "Trigger.Owner",+ parent = "Parent.Owner",+ name = "Quoted Trigger";+const definition = `CREATE OR REPLACE TRIGGER "${owner}"."${name}" INSTEAD OF UPDATE ON "${parent}"."V" DISABLE BEGIN NULL; END;`;+const backend = vi.hoisted(() => ({+ getObjectSource: vi.fn(),+ executeQuery: vi.fn(),+ prepareOracleTriggerSql: vi.fn(),+ buildEditableObjectSource: vi.fn(async (input) => input.source),+ buildExecutableObjectSourceStatements: vi.fn(async (input) => [input.source]),+ checkConnectionHealth: vi.fn(async () => undefined),+ loadSchemaCache: vi.fn(async () => null),+ saveSchemaCache: vi.fn(async () => undefined),+ deleteSchemaCachePrefix: vi.fn(async () => undefined),+ listInstalledAgents: vi.fn(async () => []),+ listPlugins: vi.fn(async () => []),+ listCompletionObjects: vi.fn(async () => []),+ cancelQuery: vi.fn(async () => true),+}));+vi.mock("@/lib/backend/api", async (original) => ({ ...(await original<typeof import("@/lib/backend/api")>()), ...backend }));+let raw: ObjectSource;+const cleanups: (() => void)[] = [];+function button(label: string) {+ return [...document.querySelectorAll<HTMLButtonElement>("button")].find((element) => element.textContent?.trim() === label);+}+function editor() {+ const root = document.querySelector<HTMLElement>("[data-object-source-editor] .cm-editor, [data-object-source-preview] .cm-editor");+ return root ? EditorView.findFromDOM(root) : null;+}+async function mount(initialEditing = true, createTrigger?: OracleTriggerSqlBinding, databaseType: DatabaseType = "oceanbase-oracle", exact = true) {+ const pinia = createPinia();+ setActivePinia(pinia);+ const connections = useConnectionStore();+ connections.connections = [{ id: "trigger-dialog", name: "Trigger test", db_type: databaseType, database: "service", username: "Execution.Owner" } as ConnectionConfig];+ connections.connectedIds.add("trigger-dialog");+ const state = reactive({ open: true, schema: owner, name });+ const saved = vi.fn();+ const opened = vi.fn();+ const host = document.createElement("div");+ document.body.append(host);+ const app = createApp({+ render: () =>+ h(ObjectSourceDialog, {+ ...state,+ connectionId: "trigger-dialog",+ database: "service",+ executionSchema: "Execution.Owner",+ triggerIdentityMode: exact ? "exact" : undefined,+ objectType: "TRIGGER",+ databaseType,+ dialect: "mysql",+ initialEditing,+ createTrigger,+ onSaved: saved,+ onOpenObject: opened,+ }),+ });+ app.use(pinia);+ app.use(createI18n({ legacy: false, locale: "en", messages: { en: {} }, missingWarn: false, fallbackWarn: false }));+ app.mount(host);+ cleanups.push(() => {+ app.unmount();+ host.remove();+ });+ await vi.waitFor(() => expect(editor()).not.toBeNull(), { timeout: 30_000 });+ return { state, saved, opened, danger: useSqlExecutionDangerStore() };+}+beforeEach(() => {+ vi.clearAllMocks();+ raw = {+ name,+ schema: owner,+ object_type: "TRIGGER",+ source: definition,+ editable: false,+ trigger: {+ name,+ event: "UPDATE",+ timing: "INSTEAD OF",+ enabled: false,+ valid: true,+ oracle_metadata: {+ contractVersion: 1,+ identityMode: "exact",+ engine: "oceanbase-oracle",+ engineVersion: "4.2.5.7_107",+ owner,+ name,+ objectId: "9007199254740993",+ scope: "VIEW",+ parent: { owner: parent, name: "V", objectType: "VIEW" },+ definition: { origin: "DBMS_METADATA", format: "ddl", complete: true },+ errors: [],+ reads: { identity: { state: "available" }, scope: { state: "available" }, parent: { state: "available" }, enabled: { state: "available" }, validity: { state: "available" }, definition: { state: "available" }, errors: { state: "available" } },+ },+ },+ };+ backend.getObjectSource.mockImplementation(async () => JSON.parse(JSON.stringify(raw)));+ backend.prepareOracleTriggerSql.mockImplementation(async (input) => ({ definition: input.source, comparisonSource: input.source, header: { scope: "RELATION", owner: parent, name: "V", viewOnly: true, pluggable: false }, requiresStateRestore: false }));+ backend.executeQuery.mockImplementation(async (_id, _db, sql) => (sql.startsWith("SELECT") ? { columns: ["OWNER", "OBJECT_NAME", "OBJECT_TYPE", "OBJECT_ID"], rows: [[parent, "V", "VIEW", "parent-id"]] } : { columns: [], rows: [], affected_rows: 0 }));+});+afterEach(() => {+ for (const cleanup of cleanups.splice(0)) cleanup();+ vi.restoreAllMocks();+ vi.unstubAllGlobals();+});++describe("exact Oracle-family trigger in the existing source dialog", () => {+ it.each(["oracle", "dameng"] as const)("preserves the original editable %s dialog contract without opting into exact mode", async (databaseType) => {+ raw = { name, schema: owner, object_type: "TRIGGER", source: definition, editable: true };+ const { saved } = await mount(true, undefined, databaseType, false);+ expect(button("objects.saveSource")).toBeDefined();+ const candidate = definition.replace("NULL;", "legacy_correction;");+ const view = editor()!;+ view.dispatch({ changes: { from: 0, to: view.state.doc.length, insert: candidate } });+ await nextTick();+ button("objects.saveSource")!.click();+ await vi.waitFor(() => expect(saved).toHaveBeenCalledOnce());+ expect(backend.prepareOracleTriggerSql).not.toHaveBeenCalled();+ expect(backend.getObjectSource.mock.calls.every((call) => call[7] === undefined)).toBe(true);+ expect(backend.executeQuery).toHaveBeenCalledExactlyOnceWith("trigger-dialog", "service", candidate, owner);+ });++ it.each(["oracle", "dameng"] as const)("does not downgrade an explicitly exact %s request to the legacy writable path", async (databaseType) => {+ raw = { name, schema: owner, object_type: "TRIGGER", source: definition, editable: true };+ await mount(true, undefined, databaseType, true);+ expect(button("objects.saveSource")).toBeUndefined();+ expect(backend.getObjectSource.mock.calls[0][7]).toMatchObject({ identityMode: "exact" });+ expect(backend.buildEditableObjectSource).not.toHaveBeenCalled();+ expect(backend.buildExecutableObjectSourceStatements).not.toHaveBeenCalled();+ expect(backend.executeQuery).not.toHaveBeenCalled();+ });++ it("keeps a manually completed candidate through denied baseline recovery, then saves only after an authoritative reload", async () => {+ raw.source = "BEGIN NULL; END;";+ raw.trigger!.oracle_metadata!.definition = { origin: "catalog-body", format: "body", complete: false };+ raw.trigger!.oracle_metadata!.reads.definition = { state: "denied" };+ const { danger, saved } = await mount();+ const view = editor()!;+ const candidate = definition.replace("NULL;", "corrected_proc;");+ view.dispatch({ changes: { from: 0, to: view.state.doc.length, insert: candidate } });+ await nextTick();+ button("objects.saveSource")!.click();+ await vi.waitFor(() => expect(document.querySelector("[data-object-source-editor] .text-destructive")).not.toBeNull());+ expect(danger.pending).toBeUndefined();+ expect(backend.executeQuery).not.toHaveBeenCalled();+ raw.source = definition;+ raw.trigger!.oracle_metadata!.definition = { origin: "DBMS_METADATA", format: "ddl", complete: true };+ raw.trigger!.oracle_metadata!.reads.definition = { state: "available" };+ button("structureEditor.refresh")!.click();+ await nextTick();+ await vi.waitFor(() => expect(button("structureEditor.refresh")!.disabled).toBe(false));+ expect(editor()).toBe(view);+ expect(view.state.doc.toString()).toBe(candidate);+ backend.executeQuery.mockImplementation(async (_id, _db, sql) => {+ if (sql.startsWith("SELECT")) return { columns: ["OWNER", "OBJECT_NAME", "OBJECT_TYPE", "OBJECT_ID"], rows: [[parent, "V", "VIEW", "parent-id"]] };+ raw.source = sql;+ return { columns: [], rows: [] };+ });+ button("objects.saveSource")!.click();+ await vi.waitFor(() => expect(danger.pending, document.body.textContent ?? "").toBeDefined());+ expect(danger.pending!.sql).toBe(candidate);+ danger.confirm();+ await vi.waitFor(() => expect(saved).toHaveBeenCalledOnce());+ expect(raw.source).toBe(candidate);+ expect(backend.executeQuery.mock.calls.filter((call) => !call[2].startsWith("SELECT"))).toHaveLength(1);+ });++ it("never adopts a concurrent body from unknown compile readback as consent to save the old draft", async () => {+ const { danger, saved } = await mount();+ const view = editor()!;+ view.dispatch({ changes: { from: 0, insert: "-- my correction\n" } });+ await nextTick();+ const draft = view.state.doc.toString();+ backend.executeQuery.mockImplementation(async (_id, _db, sql) => {+ if (sql.startsWith("SELECT")) return { columns: ["OWNER", "OBJECT_NAME", "OBJECT_TYPE", "OBJECT_ID"], rows: [[parent, "V", "VIEW", "parent-id"]] };+ raw.source = definition.replace("NULL;", "other_session_proc;");+ return { columns: [], rows: [] };+ });+ button("processList.oracleInvalidObjects.compile")!.click();+ await vi.waitFor(() => expect(danger.pending).toBeDefined());+ danger.confirm();+ await vi.waitFor(() => expect(document.body.textContent).toContain("oracleTrigger.reloadBaseline"));+ button("objects.saveSource")!.click();+ await vi.waitFor(() => expect(!!danger.pending || !!document.querySelector("[data-object-source-editor] .text-destructive")).toBe(true));+ const confirmed = !!danger.pending;+ danger.cancelAll();+ expect(confirmed).toBe(false);+ expect(saved).not.toHaveBeenCalled();+ expect(editor()).toBe(view);+ expect(view.state.doc.toString()).toBe(draft);+ expect(backend.executeQuery).toHaveBeenCalledOnce();+ });++ it.each(["available", "denied", "missing-columns", "partial", "empty"])("uses the same dependency panel for an exact DM8 trigger and reports %s without losing its draft", async (result) => {+ raw.trigger!.oracle_metadata!.engine = "dm";+ raw.trigger!.oracle_metadata!.engineVersion = "8.1.3";+ const { opened } = await mount(true, undefined, "dameng");+ const view = editor()!;+ view.dispatch({ changes: { from: 0, insert: "-- keep this DM draft\n" } });+ await nextTick();+ const draft = view.state.doc.toString();+ backend.executeQuery.mockImplementation(async () => {+ if (result === "denied") throw new Error("DM dictionary denied");+ return {+ columns: result === "missing-columns" ? [] : ["DIRECTION", "OBJECT_OWNER", "OBJECT_NAME", "OBJECT_TYPE", "REFERENCED_OWNER", "REFERENCED_NAME", "REFERENCED_TYPE", "DEPENDENCY_TYPE", "REFERENCED_LINK_NAME"],+ rows:+ result === "empty" || result === "missing-columns"+ ? []+ : [+ ["DEPENDS_ON", owner, name, "TRIGGER", parent, "V", "VIEW", "HARD", null],+ ["REFERENCED_BY", "Caller", "UsesTrigger", "PROCEDURE", owner, name, "TRIGGER", "HARD", null],+ ["DEPENDS_ON", owner, name, "TRIGGER", "Remote", "V", "VIEW", "HARD", "REMOTE_DB"],+ ["DEPENDS_ON", owner, name, "TRIGGER", parent, "Unknown", "UNRECOGNIZED", "HARD", null],+ ],+ truncated: result === "partial",+ };+ });+ button("objectDependencies.dependencies")!.click();+ await vi.waitFor(() => expect(backend.executeQuery).toHaveBeenCalledOnce());+ const call = backend.executeQuery.mock.calls[0];+ expect(call[2]).toContain("d.TYPE = 'TRIGGER'");+ expect(call[2]).toContain(`d.OWNER = '${owner}'`);+ expect(call[3]).toBe(owner);+ expect(call[4]).toContain("object-dependencies-");+ expect(call[5]).toEqual({ catalog: undefined });+ if (result === "denied") await vi.waitFor(() => expect(document.body.textContent).toContain("DM dictionary denied"));+ else if (result === "missing-columns") await vi.waitFor(() => expect(document.body.textContent).toContain("unexpected column layout"));+ else if (result === "empty") await vi.waitFor(() => expect(document.body.textContent).toContain("objectDependencies.empty"));+ else {+ await vi.waitFor(() => expect(button("V")).toBeDefined());+ expect(document.body.textContent).toContain("objectDependencies.remoteObject");+ expect(document.body.textContent).toContain("objectDependencies.unsupportedObject");+ if (result === "partial") expect(document.body.textContent).toContain("objectDependencies.partial");+ button("objectDependencies.dependents")!.click();+ await nextTick();+ expect(button("UsesTrigger")).toBeDefined();+ }+ expect(opened).not.toHaveBeenCalled();+ button("objects.source")!.click();+ await nextTick();+ expect(editor()).toBe(view);+ expect(view.state.doc.toString()).toBe(draft);+ expect(undo(view)).toBe(true);+ expect(view.state.doc.toString()).toBe(definition);+ });++ it.each(["TABLE", "VIEW"] as const)("opens the independent %s parent only after preserving the existing dirty-draft guard", async (kind) => {+ raw.trigger!.oracle_metadata!.scope = kind;+ raw.trigger!.oracle_metadata!.parent!.objectType = kind;+ const { opened } = await mount();+ const view = editor()!;+ view.dispatch({ changes: { from: 0, insert: "-- retain me\n" } });+ await nextTick();+ const confirm = vi.fn(() => false);+ vi.stubGlobal("confirm", confirm);+ button(`${parent}.V · ${kind}`)!.click();+ expect(confirm).toHaveBeenCalledOnce();+ expect(opened).not.toHaveBeenCalled();+ expect(view.state.doc.toString()).toContain("-- retain me");+ confirm.mockReturnValue(true);+ button(`${parent}.V · ${kind}`)!.click();+ expect(opened).toHaveBeenCalledWith(expect.objectContaining({ schema: owner, name, connectionId: "trigger-dialog" }), { schema: parent, name: "V", type: kind.toLowerCase(), schemaQuoted: true, nameQuoted: true });+ expect(backend.executeQuery).not.toHaveBeenCalled();+ });++ it("does not confirm native compilation of a same-name replacement", async () => {+ const { danger } = await mount();+ raw.trigger!.oracle_metadata!.objectId = "replacement-id";+ button("processList.oracleInvalidObjects.compile")!.click();+ await vi.waitFor(() => expect(!!danger.pending || document.body.textContent?.includes("displayed trigger was replaced")).toBe(true));+ const confirmed = !!danger.pending;+ danger.cancelAll();+ expect(confirmed).toBe(false);+ expect(editor()!.state.doc.toString()).toBe(definition);+ expect(backend.executeQuery).not.toHaveBeenCalled();+ });++ it("keeps the original baseline and draft when a post-compile read sees a new physical object", async () => {+ const { danger, saved } = await mount();+ const view = editor()!;+ view.dispatch({ changes: { from: 0, insert: "-- unsaved repair\n" } });+ await nextTick();+ const draft = view.state.doc.toString();+ backend.executeQuery.mockImplementation(async () => {+ raw.trigger!.oracle_metadata!.objectId = "replacement-id";+ return { columns: [], rows: [] };+ });+ button("processList.oracleInvalidObjects.compile")!.click();+ await vi.waitFor(() => expect(danger.pending).toBeDefined());+ danger.confirm();+ await vi.waitFor(() => expect(document.body.textContent).toContain("oceanbasePrimaryKey.unknown"));+ expect(editor()).toBe(view);+ expect(view.state.doc.toString()).toBe(draft);+ expect(document.body.textContent).toContain("oracleTrigger.reloadBaseline");+ expect(saved).not.toHaveBeenCalled();+ button("processList.oracleInvalidObjects.compile")!.click();+ await vi.waitFor(() => expect(!!danger.pending || document.body.textContent?.includes("displayed trigger was replaced")).toBe(true));+ const confirmed = !!danger.pending;+ danger.cancelAll();+ expect(confirmed).toBe(false);+ expect(backend.executeQuery).toHaveBeenCalledOnce();+ });++ it.each([false, true])("locates dictionary errors only in unchanged stored text without replacing the dirty draft (changed=%s)", async (changed) => {+ const stored = `TRIGGER "${owner}"."${name}" INSTEAD OF UPDATE ON "${parent}"."V"\nBEGIN\n missing_proc;\nEND;`;+ raw.source = stored;+ raw.trigger!.valid = false;+ raw.trigger!.oracle_metadata!.definition = { origin: "ALL_SOURCE", format: "declaration", complete: true };+ raw.trigger!.oracle_metadata!.errors = [{ sequence: 1, line: 3, position: 3, text: "Missing procedure" }];+ backend.prepareOracleTriggerSql.mockImplementation(async (input) => ({+ definition: input.source.startsWith("TRIGGER") ? "CREATE OR REPLACE " + input.source : input.source,+ comparisonSource: input.source,+ header: { scope: "RELATION", owner: parent, name: "V", viewOnly: true, pluggable: false },+ requiresStateRestore: false,+ }));+ await mount();+ const view = editor()!;+ const previous = view.state.doc.toString();+ view.dispatch({ changes: changed ? { from: previous.indexOf("missing_proc"), to: previous.indexOf("missing_proc") + "missing_proc".length, insert: "corrected_proc" } : { from: 0, insert: "-- keep this unsaved comment\n" } });+ const draft = view.state.doc.toString();+ const selection = view.state.selection.main.head;+ await nextTick();+ button("processList.oracleInvalidObjects.errorsTitle")!.click();+ const locate = () => [...document.querySelectorAll<HTMLButtonElement>("button")].find((item) => item.getAttribute("aria-label") === "editor.locateError");+ await vi.waitFor(() => expect(locate()).toBeDefined(), { timeout: 10_000 });+ locate()!.click();+ await vi.waitFor(() => expect(document.querySelectorAll('[role="dialog"]')).toHaveLength(1));+ if (!changed) await vi.waitFor(() => expect(view.state.selection.main.head).toBe(draft.indexOf("missing_proc")));+ else expect(view.state.selection.main.head).toBe(selection);+ expect(editor()).toBe(view);+ expect(view.state.doc.toString()).toBe(draft);+ expect(backend.executeQuery).not.toHaveBeenCalled();+ });++ it("returns from exact INVALID diagnostics and compile to the same dirty editor with undo intact", async () => {+ raw.trigger!.valid = false;+ raw.trigger!.oracle_metadata!.errors = [{ sequence: 1, line: 2, position: 3, text: "Missing procedure" }];+ const { danger } = await mount();+ const view = editor()!;+ view.dispatch({ changes: { from: 0, insert: "-- my unsaved repair\n" } });+ const draft = view.state.doc.toString();+ await nextTick();+ button("processList.oracleInvalidObjects.errorsTitle")!.click();+ const diagnosticButton = (label: string) => [...([...document.querySelectorAll('[role="dialog"]')].find((dialog) => dialog.textContent?.includes("processList.oracleInvalidObjects.title"))?.querySelectorAll<HTMLButtonElement>("button") ?? [])].find((item) => item.textContent?.trim() === label);+ await vi.waitFor(() => expect(diagnosticButton("processList.oracleInvalidObjects.compile")).toBeDefined(), { timeout: 10_000 });+ diagnosticButton("processList.oracleInvalidObjects.compile")!.click();+ await vi.waitFor(() => expect(danger.pending).toBeDefined());+ danger.confirm();+ await vi.waitFor(() => expect(document.body.textContent).toContain("processList.oracleInvalidObjects.compileStillInvalid"));+ expect(editor()).toBe(view);+ expect(view.state.doc.toString()).toBe(draft);+ button("processList.oracleInvalidObjects.openSource")!.click();+ await nextTick();+ expect(editor()).toBe(view);+ expect(view.state.doc.toString()).toBe(draft);+ expect(undo(view)).toBe(true);+ expect(view.state.doc.toString()).toBe(definition);+ expect(backend.executeQuery.mock.calls.filter((call) => !call[2].startsWith("SELECT"))).toHaveLength(1);+ });++ it.each([+ { databaseType: "oracle", scope: "SCHEMA", bindingOwner: "Event.Scope", header: 'AFTER CREATE ON "Event.Scope".SCHEMA', proof: ["Event.Scope", "scope-id"] },+ { databaseType: "oracle", scope: "DATABASE", header: "AFTER CREATE ON DATABASE", proof: ["ORCL", "2", "PDB"] },+ { databaseType: "dameng", scope: "TIMER", header: "AFTER TIMER ON DATABASE\nFOR EACH 1 DAY FOR EACH 1 MINUTE", proof: ["DM", "2026-01-01 00:00:00"] },+ ] as const)("previews a real $databaseType $scope definition without inventing a parent table", async ({ databaseType, scope, header, proof, ...selection }) => {+ raw.source = "";+ raw.trigger!.oracle_metadata!.objectId = null;+ raw.trigger!.oracle_metadata!.engine = databaseType === "dameng" ? "dm" : "oracle";+ raw.trigger!.oracle_metadata!.engineVersion = databaseType === "dameng" ? "8.1.3" : "19.0.0";+ raw.trigger!.oracle_metadata!.reads.identity = { state: "empty" };+ backend.prepareOracleTriggerSql.mockImplementation(async (input) => ({ definition: input.source, comparisonSource: input.source, header: { scope, ...(scope === "SCHEMA" ? { owner: "Event.Scope" } : {}), viewOnly: false, pluggable: false }, requiresStateRestore: false }));+ backend.executeQuery.mockResolvedValue({ columns: [], rows: [proof] });+ const { danger } = await mount(true, { scope, ...("bindingOwner" in selection ? { owner: selection.bindingOwner } : {}) }, databaseType);+ button("contextMenu.generateSql")!.click();+ await vi.waitFor(() => expect(editor()!.state.doc.toString()).toBe(`CREATE TRIGGER "${owner}"."${name}"\n${header}\nBEGIN\n NULL;\nEND;`));+ button("objects.saveSource")!.click();+ await vi.waitFor(() => expect(danger.pending).toBeDefined());+ expect(danger.pending!.sql).toContain(header);+ expect(backend.executeQuery.mock.calls.every((call) => call[2].startsWith("SELECT") && !call[2].includes("ALL_OBJECTS"))).toBe(true);+ danger.cancelAll();+ await nextTick();+ expect(editor()!.state.doc.toString()).toContain(header);+ });++ it("does not offer unverified OceanBase scope templates or overwrite edits typed while metadata loads", async () => {+ raw.source = "";+ raw.trigger!.oracle_metadata!.objectId = null;+ raw.trigger!.oracle_metadata!.reads.identity = { state: "empty" };+ let resolveRead!: (source: ObjectSource) => void;+ backend.getObjectSource.mockImplementation(+ () =>+ new Promise((resolve) => {+ resolveRead = resolve;+ }),+ );+ await mount(true, { scope: "TABLE", owner: parent, name: "T" });+ expect([...document.querySelectorAll<HTMLOptionElement>("[data-trigger-create-scope] option")].map((option) => option.value)).toEqual(["TABLE", "VIEW"]);+ button("contextMenu.generateSql")!.click();+ await vi.waitFor(() => expect(backend.getObjectSource).toHaveBeenCalledOnce());+ editor()!.dispatch({ changes: { from: 0, insert: "-- preserve my manual definition" } });+ await nextTick();+ resolveRead(JSON.parse(JSON.stringify(raw)));+ await vi.waitFor(() => expect(button("contextMenu.generateSql")!.disabled).toBe(false));+ expect(editor()!.state.doc.toString()).toBe("-- preserve my manual definition");+ expect(backend.executeQuery).not.toHaveBeenCalled();+ });++ it.each(["TABLE", "VIEW"] as const)("creates the first $scope trigger, then corrects INVALID through replacement instead of replaying CREATE", async (scope) => {+ const parentName = scope === "VIEW" ? "V" : "T";+ const created = `CREATE TRIGGER "${owner}"."${name}"\n${scope === "VIEW" ? "INSTEAD OF" : "BEFORE"} INSERT ON "${parent}"."${parentName}"\nFOR EACH ROW\nBEGIN\n NULL;\nEND;`;+ raw.source = "";+ raw.trigger!.oracle_metadata!.objectId = null;+ raw.trigger!.oracle_metadata!.reads.identity = { state: "empty" };+ raw.trigger!.oracle_metadata!.definition!.complete = false;+ raw.trigger!.oracle_metadata!.scope = scope;+ raw.trigger!.oracle_metadata!.parent = { owner: parent, name: parentName, objectType: scope };+ const canonical = (source: string) => source.replace(/^CREATE(?: OR REPLACE)? TRIGGER/, "CREATE OR REPLACE TRIGGER");+ backend.prepareOracleTriggerSql.mockImplementation(async (input) => ({+ definition: input.purpose === "replace" ? canonical(input.source) : input.source,+ comparisonSource: canonical(input.source),+ header: { scope: "RELATION", owner: parent, name: parentName, viewOnly: scope === "VIEW", pluggable: false },+ requiresStateRestore: false,+ }));+ let writes = 0;+ backend.executeQuery.mockImplementation(async (_id, _db, sql) => {+ if (sql.startsWith("SELECT")) return { columns: ["OWNER", "OBJECT_NAME", "OBJECT_TYPE", "OBJECT_ID"], rows: [[parent, parentName, scope, "parent-id"]] };+ writes++;+ raw.source = sql;+ raw.trigger!.enabled = true;+ raw.trigger!.valid = writes > 1;+ raw.trigger!.oracle_metadata!.objectId = "created-id";+ raw.trigger!.oracle_metadata!.reads.identity = { state: "available" };+ raw.trigger!.oracle_metadata!.definition!.complete = true;+ raw.trigger!.oracle_metadata!.errors = writes === 1 ? [{ line: 4, position: 3, text: "Fix this definition" }] : [];+ return { columns: [], rows: [], affected_rows: 0 };+ });+ const { danger, saved } = await mount(true, { scope, owner: parent, name: parentName });+ expect(backend.getObjectSource).not.toHaveBeenCalled(); // Opening creation is read-only and does not invent an existing source.+ button("contextMenu.generateSql")!.click();+ await vi.waitFor(() => expect(editor()!.state.doc.toString()).toBe(created));+ button("objects.saveSource")!.click();+ await vi.waitFor(() => expect(danger.pending).toBeDefined());+ expect(danger.pending!.sql).toBe(created);+ expect(danger.pending!.targetLabel).toContain(`${parent}.${parentName}`);+ expect(danger.pending!.targets).toBeUndefined();+ danger.confirm();+ await vi.waitFor(() => expect(document.body.textContent).toContain("Fix this definition"));+ expect(editor()!.state.doc.toString()).toBe(created);+ expect(saved).not.toHaveBeenCalled();+ expect(document.querySelector<HTMLInputElement>("[data-trigger-create-name]")!.disabled).toBe(true);+ expect(backend.executeQuery.mock.calls.filter((call) => !call[2].startsWith("SELECT"))).toHaveLength(1);+ const view = editor()!;+ view.dispatch({ changes: { from: view.state.doc.toString().indexOf("NULL;"), to: view.state.doc.toString().indexOf("NULL;") + 5, insert: "NULL; -- corrected\n" } });+ await nextTick();+ button("objects.saveSource")!.click();+ await vi.waitFor(() => expect(danger.pending).toBeDefined());+ expect(danger.pending!.sql).toMatch(/^CREATE OR REPLACE TRIGGER/);+ danger.confirm();+ await vi.waitFor(() => expect(saved).toHaveBeenCalledOnce());+ expect(backend.prepareOracleTriggerSql.mock.calls.filter(([input]) => input.purpose === "create")).toHaveLength(1);+ expect(backend.executeQuery.mock.calls.filter((call) => !call[2].startsWith("SELECT"))).toHaveLength(2);+ });++ it("shows a full disabled draft and previews the exact SQL before the existing guard and verified save", async () => {+ const { saved, danger } = await mount();+ expect(editor()!.state.doc.toString()).toBe(definition);+ expect(document.querySelector("[data-oracle-trigger-status]")?.textContent).toContain(`${parent}.V`);+ button("objects.saveSource")!.click();+ await vi.waitFor(() => expect(danger.pending).toBeDefined());+ expect(danger.pending?.sql).toBe(definition);+ expect(danger.pending?.targetLabel).toContain("Execution.Owner");+ expect(danger.pending?.targets).toBeUndefined();+ expect(backend.executeQuery.mock.calls.every((call) => call[2].startsWith("SELECT"))).toBe(true);+ danger.confirm();+ await vi.waitFor(() => expect(saved).toHaveBeenCalledOnce());+ expect(backend.executeQuery.mock.calls.filter((call) => !call[2].startsWith("SELECT"))).toEqual([["trigger-dialog", "service", definition, "Execution.Owner", undefined, { catalog: undefined, timeoutSecs: 60 }]]);+ });++ it("preserves the actual CodeMirror draft after an unknown save and read-only refresh", async () => {+ const { saved, danger } = await mount();+ const view = editor()!;+ view.dispatch({ changes: { from: view.state.doc.length, insert: "\n-- keep my correction" } });+ await nextTick();+ const draft = view.state.doc.toString();+ backend.executeQuery.mockImplementation(async (_id, _db, sql) => {+ if (sql.startsWith("SELECT")) return { columns: ["OWNER", "OBJECT_NAME", "OBJECT_TYPE", "OBJECT_ID"], rows: [[parent, "V", "VIEW", "parent-id"]] };+ throw new Error("response lost");+ });+ button("objects.saveSource")!.click();+ await vi.waitFor(() => expect(danger.pending).toBeDefined());+ danger.confirm();+ await vi.waitFor(() => expect(document.body.textContent).toContain("response lost"));+ expect(editor()!.state.doc.toString()).toBe(draft);+ expect(saved).not.toHaveBeenCalled();+ button("structureEditor.refresh")!.click();+ await nextTick();+ await vi.waitFor(() => expect(!!editor() && !button("structureEditor.refresh")!.disabled).toBe(true));+ expect(editor()!.state.doc.toString()).toBe(draft);+ expect(editor()).toBe(view);+ expect(backend.executeQuery.mock.calls.filter((call) => !call[2].startsWith("SELECT"))).toHaveLength(1);+ });++ it("cancels the queued SQL confirmation when this dialog changes target, sending no DDL", async () => {+ const { state, danger, saved } = await mount();+ button("objects.saveSource")!.click();+ await vi.waitFor(() => expect(danger.pending).toBeDefined());+ state.open = false;+ await nextTick();+ await vi.waitFor(() => expect(danger.pending).toBeUndefined());+ expect(backend.executeQuery.mock.calls.every((call) => call[2].startsWith("SELECT"))).toBe(true);+ expect(saved).not.toHaveBeenCalled();+ });+});diff --git a/apps/desktop/src/components/objects/__tests__/OceanbaseClone.entrypoints.spec.ts b/apps/desktop/src/components/objects/__tests__/OceanbaseClone.entrypoints.spec.tsindex 1d69b8ef0c..e85438a33f 100644--- a/apps/desktop/src/components/objects/__tests__/OceanbaseClone.entrypoints.spec.ts+++ b/apps/desktop/src/components/objects/__tests__/OceanbaseClone.entrypoints.spec.ts@@ -23,6 +23,7 @@ vi.mock("@/lib/backend/api", async (importOriginal) => ({loadSchemaCache: vi.fn().mockResolvedValue(null),deleteSchemaCachePrefix: vi.fn().mockResolvedValue(undefined),checkConnectionHealth: vi.fn().mockResolvedValue(undefined),+ saveConnectionDatabaseInfo: vi.fn().mockResolvedValue(undefined),listSchemas: vi.fn().mockResolvedValue(["APP"]),listDatabases: vi.fn().mockResolvedValue(["APP"]),listObjects: vi.fn().mockResolvedValue([{ name: "SOURCE", object_type: "TABLE", schema: "APP" }]),diff --git a/apps/desktop/src/components/objects/__tests__/OracleInvalidObjectsDialog.guard.spec.ts b/apps/desktop/src/components/objects/__tests__/OracleInvalidObjectsDialog.guard.spec.tsindex d38892439f..c78b18299c 100644--- a/apps/desktop/src/components/objects/__tests__/OracleInvalidObjectsDialog.guard.spec.ts+++ b/apps/desktop/src/components/objects/__tests__/OracleInvalidObjectsDialog.guard.spec.ts@@ -15,7 +15,7 @@ vi.mock("@/lib/backend/api", () => ({unlockConnectionWrites: mocks.unlock,lockConnectionWrites: mocks.lock,}));-vi.mock("vue-i18n", () => ({ useI18n: () => ({ t: (key: string, values?: Record<string, unknown>) => (values ? `${key}:${Object.values(values).join(",")}` : key) }) }));+vi.mock("vue-i18n", async (original) => ({ ...(await original<typeof import("vue-i18n")>()), useI18n: () => ({ t: (key: string, values?: Record<string, unknown>) => (values ? `${key}:${Object.values(values).join(",")}` : key) }) }));function passthrough(tag: string) {return defineComponent({diff --git a/apps/desktop/src/components/objects/__tests__/OracleInvalidObjectsDialog.oracleTrigger.spec.ts b/apps/desktop/src/components/objects/__tests__/OracleInvalidObjectsDialog.oracleTrigger.spec.tsnew file mode 100644index 0000000000..c45554c6b3--- /dev/null+++ b/apps/desktop/src/components/objects/__tests__/OracleInvalidObjectsDialog.oracleTrigger.spec.ts@@ -0,0 +1,167 @@+// @vitest-environment happy-dom+import { createApp, h, nextTick, ref, type App } from "vue";+import { createPinia, getActivePinia, setActivePinia } from "pinia";+import { afterEach, beforeEach, expect, it, vi } from "vitest";+import i18n from "@/i18n";+import { useConnectionStore } from "@/stores/connectionStore";+import { useSqlExecutionDangerStore } from "@/stores/sqlExecutionDangerStore";+import type { ConnectionConfig, ObjectSource } from "@/types/database";+import OracleInvalidObjectsDialog from "../OracleInvalidObjectsDialog.vue";++const rpc = vi.hoisted(() => ({+ getObjectSource: vi.fn(),+ executeQuery: vi.fn(),+ closeClientConnectionSession: vi.fn(async () => undefined),+ listPlugins: vi.fn(async () => []),+ listInstalledAgents: vi.fn(async () => []),+ loadSchemaCache: vi.fn(async () => null),+ saveSchemaCache: vi.fn(async () => undefined),+ deleteSchemaCachePrefix: vi.fn(async () => undefined),+}));+vi.mock("@/lib/backend/api", async (original) => ({ ...(await original<typeof import("@/lib/backend/api")>()), ...rpc }));+const owner = " Trigger.Owner ",+ name = ' Tr"igger ',+ executionSchema = "Execution.Owner";+const config = { id: "trigger-diagnostics", name: "Trigger diagnostics", db_type: "oceanbase-oracle", username: executionSchema, database: "service" } as ConnectionConfig;+const target = { connectionId: config.id, database: "service", catalog: " Catalog ", owner, name, executionSchema };+let raw: ObjectSource;+let app: App | undefined;+beforeEach(() => {+ vi.clearAllMocks();+ setActivePinia(createPinia());+ i18n.global.locale.value = "en";+ const connections = useConnectionStore();+ connections.connections = [config];+ connections.connectedIds.add(config.id);+ raw = {+ name,+ schema: owner,+ object_type: "TRIGGER",+ source: "BEGIN NULL; END;",+ editable: false,+ trigger: {+ name,+ event: "UPDATE",+ timing: "BEFORE",+ enabled: false,+ valid: false,+ oracle_metadata: {+ contractVersion: 1,+ identityMode: "exact",+ engine: "oceanbase-oracle",+ engineVersion: "4.2.5.7_107",+ owner,+ name,+ objectId: "9007199254740993",+ scope: "SCHEMA",+ scopeOwner: owner,+ definition: { origin: "catalog-body", format: "body", complete: false },+ errors: [{ sequence: 1, line: 2, position: 3, text: "Missing procedure" }],+ reads: { identity: { state: "available" }, scope: { state: "available" }, enabled: { state: "available" }, validity: { state: "available" }, definition: { state: "denied" }, errors: { state: "available" } },+ },+ },+ };+ rpc.getObjectSource.mockImplementation(async () => JSON.parse(JSON.stringify(raw)));+ rpc.executeQuery.mockResolvedValue({ columns: [], rows: [] });+});+afterEach(() => {+ app?.unmount();+ app = undefined;+ useSqlExecutionDangerStore().cancelAll();+ vi.restoreAllMocks();+ document.body.innerHTML = "";+});+async function mount(expectedObjectId = "9007199254740993", connection = config) {+ const host = document.createElement("div");+ document.body.append(host);+ const openSource = vi.fn();+ const open = ref(true);+ useConnectionStore().connections = [connection];+ app = createApp({ render: () => h(OracleInvalidObjectsDialog, { open: open.value, connection, database: "service", schema: executionSchema, triggerContext: { target, expectedObjectId }, onOpenSource: openSource }) });+ app.use(getActivePinia()!);+ app.use(i18n);+ app.mount(host);+ await vi.waitFor(() => expect(rpc.getObjectSource).toHaveBeenCalled());+ await nextTick();+ return { openSource, open };+}+const button = (key: string) => [...document.querySelectorAll<HTMLButtonElement>("button")].find((item) => item.textContent?.trim() === i18n.global.t(key));++it("preselects the exact raw trigger and compiles with the shared actor, retaining INVALID after an accepted receipt", async () => {+ const { openSource } = await mount();+ await vi.waitFor(() => expect(document.body.textContent).toContain("Missing procedure"));+ expect(rpc.getObjectSource).toHaveBeenCalledWith(config.id, "service", owner, name, "TRIGGER", undefined, undefined, { identityMode: "exact", catalog: " Catalog " });+ const compile = button("processList.oracleInvalidObjects.compile")!;+ expect(compile.disabled).toBe(false);+ compile.click();+ const danger = useSqlExecutionDangerStore();+ await vi.waitFor(() => expect(danger.pending).toBeDefined());+ expect(danger.pending?.sql).toBe('ALTER TRIGGER " Trigger.Owner "." Tr""igger " COMPILE');+ danger.confirm();+ await vi.waitFor(() => expect(document.body.textContent).toContain(i18n.global.t("processList.oracleInvalidObjects.compileStillInvalid")));+ expect(rpc.executeQuery).toHaveBeenCalledTimes(1);+ expect(rpc.executeQuery.mock.calls[0]?.[3]).toBe(executionSchema);+ expect(rpc.executeQuery.mock.calls[0]?.[4]).toBeUndefined();+ expect(rpc.executeQuery.mock.calls[0]?.[5]).toEqual(expect.objectContaining({ catalog: " Catalog " }));+ expect(document.body.textContent).toContain("Missing procedure");+ button("processList.oracleInvalidObjects.openSource")!.click();+ expect(openSource).toHaveBeenCalledWith(expect.objectContaining({ owner, name, type: "TRIGGER", objectId: "9007199254740993" }));+});++it("shows denied error metadata rather than an empty error list", async () => {+ raw.trigger!.oracle_metadata!.reads.errors = { state: "denied", message: "ALL_ERRORS denied" };+ raw.trigger!.oracle_metadata!.errors = [];+ await mount();+ await vi.waitFor(() => expect(document.body.textContent).toContain("ALL_ERRORS denied"));+ expect(document.body.textContent).not.toContain(i18n.global.t("processList.oracleInvalidObjects.noErrors"));+ expect(rpc.executeQuery).not.toHaveBeenCalled();+});++it("opens the same exact source with the selected dictionary error coordinates", async () => {+ const { openSource } = await mount();+ const label = i18n.global.t("editor.locateError", { line: 2, column: 3 });+ await vi.waitFor(() => expect([...document.querySelectorAll("button")].some((item) => item.getAttribute("aria-label") === label)).toBe(true));+ [...document.querySelectorAll<HTMLButtonElement>("button")].find((item) => item.getAttribute("aria-label") === label)!.click();+ expect(openSource).toHaveBeenCalledWith(expect.objectContaining({ owner, name, type: "TRIGGER" }), { line: 2, position: 3 });+ expect(rpc.executeQuery).not.toHaveBeenCalled();+});++it("refuses a same-name replacement without reading a guessed schema or submitting DDL", async () => {+ raw.trigger!.oracle_metadata!.objectId = "replacement-id";+ await mount();+ await vi.waitFor(() => expect(document.body.textContent).toContain(i18n.global.t("oracleTrigger.reloadBaseline")));+ expect(rpc.executeQuery).not.toHaveBeenCalled();+ expect(useSqlExecutionDangerStore().pending).toBeUndefined();+});++it("cancels an unissued compile when the diagnostic context closes", async () => {+ const { open } = await mount();+ await vi.waitFor(() => expect(button("processList.oracleInvalidObjects.compile")).toBeDefined());+ button("processList.oracleInvalidObjects.compile")!.click();+ const danger = useSqlExecutionDangerStore();+ await vi.waitFor(() => expect(danger.pending).toBeDefined());+ open.value = false;+ await vi.waitFor(() => expect(danger.pending).toBeUndefined());+ expect(rpc.executeQuery).not.toHaveBeenCalled();+});++it("limits DM diagnostics to this trigger and reads back native disable after a failed compile without sending ENABLE", async () => {+ raw.trigger!.enabled = true;+ raw.trigger!.oracle_metadata!.engine = "dm";+ raw.trigger!.oracle_metadata!.engineVersion = "8.1.3";+ rpc.executeQuery.mockImplementation(async () => {+ raw.trigger!.enabled = false;+ return { columns: [], rows: [], execution_error: true, error: "Compilation failed" };+ });+ await mount(undefined, { ...config, db_type: "dameng" });+ await vi.waitFor(() => expect(button("processList.oracleInvalidObjects.compile")).toBeDefined());+ button("processList.oracleInvalidObjects.compile")!.click();+ const danger = useSqlExecutionDangerStore();+ await vi.waitFor(() => expect(danger.pending).toBeDefined());+ danger.confirm();+ await vi.waitFor(() => expect(document.body.textContent).toContain(i18n.global.t("processList.oracleInvalidObjects.compileUnknown")));+ expect(document.body.textContent).toContain("INVALID");+ expect(document.body.textContent).toContain(i18n.global.t("objects.disabled"));+ expect(rpc.executeQuery).toHaveBeenCalledTimes(1);+ expect(rpc.executeQuery.mock.calls[0]?.[2]).toBe('ALTER TRIGGER " Trigger.Owner "." Tr""igger " COMPILE');+});diff --git a/apps/desktop/src/components/objects/__tests__/OracleInvalidObjectsDialog.spec.ts b/apps/desktop/src/components/objects/__tests__/OracleInvalidObjectsDialog.spec.tsindex 4182ed58d1..d321dd70c7 100644--- a/apps/desktop/src/components/objects/__tests__/OracleInvalidObjectsDialog.spec.ts+++ b/apps/desktop/src/components/objects/__tests__/OracleInvalidObjectsDialog.spec.ts@@ -56,7 +56,7 @@ function passthrough(tag: string): Component {});}-vi.mock("vue-i18n", () => ({ useI18n: () => ({ t: (key: string, values?: Record<string, unknown>) => (values === undefined ? key : `${key}:${Object.values(values).join(",")}`) }) }));+vi.mock("vue-i18n", async (original) => ({ ...(await original<typeof import("vue-i18n")>()), useI18n: () => ({ t: (key: string, values?: Record<string, unknown>) => (values === undefined ? key : `${key}:${Object.values(values).join(",")}`) }) }));vi.mock("@lucide/vue", () => {const Icon = passthrough("span");return { AlertTriangle: Icon, CheckIcon: Icon, ChevronDown: Icon, Circle: Icon, CircleHelp: Icon, CircleMinus: Icon, CircleX: Icon, Clock: Icon, Loader2: Icon, RefreshCw: Icon, Wrench: Icon };diff --git a/apps/desktop/src/components/sidebar/ConnectionTree.vue b/apps/desktop/src/components/sidebar/ConnectionTree.vueindex d5653401ec..e91b7924f8 100644--- a/apps/desktop/src/components/sidebar/ConnectionTree.vue+++ b/apps/desktop/src/components/sidebar/ConnectionTree.vue@@ -36,6 +36,7 @@ import { isCancelSearchShortcut, isCopySidebarSelectionShortcut, isDisconnectSidimport { sidebarNodeSupportsDdlView } from "@/lib/sidebar/sidebarTreeDdlShortcut";import { DEFAULT_DATABASE_TREE_LABEL, hasTreeNodeDatabaseContext } from "@/lib/sidebar/treeNodeContext";import { objectSourceTargetForTreeNode } from "@/lib/sidebar/treeNodeClick";+import { exactOracleTriggerNodeMetadata } from "@/lib/database/oracleTriggerIdentity";import { supportsTypeObjectSource } from "@/lib/database/databaseObjectCapabilities";import { copyToClipboard } from "@/lib/common/clipboard";import { connectionPasteTargetGroupId, copySelectedConnectionsToClipboards, selectedConnectionDisconnectTargets, selectedConnectionEditTarget } from "@/lib/sidebar/sidebarConnectionSelection";@@ -89,10 +90,11 @@ import { Button } from "@/components/ui/button";import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog";import { codeMirrorSqlDialect } from "@/lib/database/jdbcDialect";import { sqlFormatDialectForDbType } from "@/lib/sql/sqlFormatter";-import { createSidebarActionTarget, findSidebarActionTarget, matchesSidebarActionTarget, type SidebarActionTarget } from "@/lib/sidebar/sidebarActionTarget";+import { createSidebarActionTarget, findSidebarActionTarget, matchesSidebarActionTarget, type SidebarActionRequest, type SidebarActionTarget } from "@/lib/sidebar/sidebarActionTarget";import { syncSidebarTreeNodeExpansion } from "@/lib/sidebar/sidebarTreeExpansion";import { openSidebarDangerDialog } from "@/lib/sidebar/sidebarDangerDialog";import { resetSidebarTreeDialogState } from "./sidebarTreeDialogState";+import type { OracleTriggerSqlBinding } from "@/lib/database/oracleTriggerSql";import { SidebarDdlViewDialog, SidebarElasticsearchIndexMetadataDialog, SidebarObjectSourceDialog, SidebarProcedureExecutionDialog, SidebarVisibleDatabasesDialog, SidebarVisibleNacosNamespacesDialog, SidebarVisibleSchemasDialog } from "./sidebarAsyncDialogs";import { sortConnectionListForDisplay } from "@/lib/sidebar/connectionListSort";import { sidebarDisplayTableName } from "@/lib/sidebar/sidebarTableNameDisplay";@@ -157,7 +159,7 @@ const sidebarDdlTarget = ref<TreeNode | null>(null);const sidebarDdlOpen = ref(false);const sidebarElasticsearchIndexMetadataTarget = ref<{ node: TreeNode; kind: ElasticsearchIndexMetadataKind } | null>(null);const sidebarElasticsearchIndexMetadataOpen = ref(false);-const sidebarObjectSourceTarget = ref<{ node: TreeNode; initialEditing: boolean; initialSection?: ObjectDetailsSection } | null>(null);+const sidebarObjectSourceTarget = ref<{ node: TreeNode; initialEditing: boolean; initialSection?: ObjectDetailsSection; createTrigger?: SidebarActionRequest<OracleTriggerSqlBinding> } | null>(null);const sidebarObjectSourceOpen = ref(false);const sidebarProcedureTarget = ref<TreeNode | null>(null);const sidebarProcedureOpen = ref(false);@@ -530,7 +532,11 @@ const { scopes: globalTableSearchScopes, isLoading: isGlobalIndexLoading } = useload: loadGlobalTableSearchIndexes,onError: (error) => toast(error instanceof Error ? error.message : String(error), 5000),});-const { results: remoteSearchResults, isLoading: isRemoteSearchLoading } = useSidebarRemoteSearch({+const {+ results: remoteSearchResults,+ isLoading: isRemoteSearchLoading,+ removeVerifiedTriggerNode: removeVerifiedRemoteTriggerNode,+} = useSidebarRemoteSearch({query: searchQuery,enabled: computed(() => !regexMode.value && !settingsStore.editorSettings.sidebarGlobalSearchLocal && !searchableNodeTypes.value),context: [...globalSearchContext, () => store.sidebarObjectSearchRevision],@@ -1511,6 +1517,7 @@ provide(sidebarTreeContextKey, {// collapse while a projection is about to start, and the deferred query// keeps the currently rendered projection alive while clearing settles.isSearchProjectionActive: () => isTreeSearchFiltering.value || !!deferredSearchQuery.value,+ removeVerifiedTriggerNode: removeVerifiedRemoteTriggerNode,getTreeLoadSearchOptions: () => {if (!deferredSearchQuery.value) return undefined;return { searchFilter: "", allowGlobalSearchMismatch: true, expectedSidebarSearchQuery: "" };@@ -2249,7 +2256,7 @@ function openSidebarElasticsearchIndexMetadata(node: TreeNode, kind: ElasticsearsidebarElasticsearchIndexMetadataOpen.value = true;}-function openSidebarObjectSource(node: TreeNode, initialEditing: boolean, initialSection?: ObjectDetailsSection) {+function openSidebarObjectSource(node: TreeNode, initialEditing: boolean, initialSection?: ObjectDetailsSection, createTrigger?: SidebarActionRequest<OracleTriggerSqlBinding>) {if (!node.connectionId || !hasTreeNodeDatabaseContext(node) || !objectSourceTargetForTreeNode(node)) return;// TYPE/TYPE_BODY only have a source implementation on Xugu; PostgreSQL-family// connections list user-defined types without a CREATE TYPE getter this cycle.@@ -2258,7 +2265,7 @@ function openSidebarObjectSource(node: TreeNode, initialEditing: boolean, initiabeginSidebarAction();// issue #9035:弹窗立即挂载。此前先 await ensureConnected 再开弹窗,这段时间// 界面上没有任何反馈;现在连接与取源都在弹窗自身的加载态之内完成。- sidebarObjectSourceTarget.value = { node: target, initialEditing, initialSection };+ sidebarObjectSourceTarget.value = { node: target, initialEditing, initialSection, createTrigger };sidebarObjectSourceOpen.value = true;}@@ -2383,7 +2390,7 @@ async function executeSidebarProcedureSql(sql: string) {}async function refreshSidebarActionTarget() {- const target = sidebarObjectSourceTarget.value?.node || sidebarDdlTarget.value || sidebarInstallExtensionTarget.value;+ const target = sidebarObjectSourceTarget.value?.createTrigger?.target || sidebarObjectSourceTarget.value?.node || sidebarDdlTarget.value || sidebarInstallExtensionTarget.value;if (!target) return;const currentTarget = findSidebarActionTarget(store.treeNodes, target);if (!currentTarget) return;@@ -2404,7 +2411,7 @@ watch(sidebarElasticsearchIndexMetadataOpen, (open) => {watch(sidebarObjectSourceOpen, (open) => {if (!open) {- const nodeId = sidebarObjectSourceTarget.value?.node.id;+ const nodeId = sidebarObjectSourceTarget.value?.createTrigger?.target.id || sidebarObjectSourceTarget.value?.node.id;sidebarObjectSourceTarget.value = null;restoreSidebarTreeFocusAfterDialog(nodeId);}@@ -3048,6 +3055,9 @@ defineExpose({:format-dialect="sidebarObjectSourceFormatDialect":initial-editing="sidebarObjectSourceTarget.initialEditing":initial-section="sidebarObjectSourceTarget.initialSection"+ :create-trigger="sidebarObjectSourceTarget.createTrigger?.payload"+ :execution-schema="sidebarObjectSourceTarget.node.schema || sidebarObjectSourceTarget.node.database"+ :trigger-identity-mode="exactOracleTriggerNodeMetadata(sidebarObjectSourceTarget.node) ? 'exact' : undefined"@open-object="(context: ObjectDependencyTarget, target: SqlObjectNavigationTarget) => emit('open-dependency-object', context, target)"@saved="refreshSidebarActionTarget"/>diff --git a/apps/desktop/src/components/sidebar/SidebarTreeItemDialogs.vue b/apps/desktop/src/components/sidebar/SidebarTreeItemDialogs.vueindex ecc34c14aa..2a75185e05 100644--- a/apps/desktop/src/components/sidebar/SidebarTreeItemDialogs.vue+++ b/apps/desktop/src/components/sidebar/SidebarTreeItemDialogs.vue@@ -947,6 +947,10 @@ watch(</DialogHeader><pre class="max-h-72 overflow-auto whitespace-pre-wrap break-words rounded bg-destructive/5 p-3 text-sm text-destructive">{{ compileErrorMessage }}</pre><DialogFooter>+ <Button v-if="controller.hasTriggerActionFeedback" variant="outline" :disabled="controller.triggerRecoveryBusy" :aria-busy="controller.triggerRecoveryBusy" @click="controller.refreshTriggerActionFeedback()">+ <Loader2 v-if="controller.triggerRecoveryBusy" class="mr-2 size-4 animate-spin" aria-hidden="true" />{{ t("oracleTrigger.verifyReadOnly") }}+ </Button>+ <Button v-if="controller.hasTriggerActionFeedback" variant="outline" @click="controller.viewTriggerActionSource()">{{ t("contextMenu.viewSource") }}</Button><Button @click="showCompileErrorDialog = false">{{ t("common.close") }}</Button></DialogFooter></DialogContent>diff --git a/apps/desktop/src/components/sidebar/SidebarTreeRuntimeHost.vue b/apps/desktop/src/components/sidebar/SidebarTreeRuntimeHost.vueindex 7a00f3d472..32bd68b888 100644--- a/apps/desktop/src/components/sidebar/SidebarTreeRuntimeHost.vue+++ b/apps/desktop/src/components/sidebar/SidebarTreeRuntimeHost.vue@@ -1,4 +1,5 @@<script setup lang="ts">+import { uuid } from "@/lib/common/utils";import { computed, defineAsyncComponent, nextTick, watch, onBeforeUnmount, onScopeDispose, inject, reactive, ref, shallowRef } from "vue";import { Dialog, DialogContent, DialogTitle } from "@/components/ui/dialog";import PluginWorkbenchHost from "@/components/plugins/PluginWorkbenchHost.vue";@@ -118,8 +119,25 @@ import { requestObjectBrowserSearchFocus } from "@/lib/tabs/objectBrowserSearchFimport { isXuguTypeMemberContainer } from "@/lib/sidebar/xuguTypeMembers";import { isXuguSyntheticTreeNode } from "@/lib/sidebar/xuguPublicSynonyms";import { buildXuguSchedulerJobSql, type XuguSchedulerJobAction } from "@/lib/database/xuguSchedulerJobSql";+import { nativeJobAdminSupported } from "@/lib/database/nativeJobAdmin";import { canViewDatabaseObjectDependencies, databaseDependencyProviderFor } from "@/lib/database/databaseObjectDependencies";import { oracleTarget } from "@/lib/database/oracleObjectDependencies";+import { exactOracleTriggerNodeMetadata, oracleTriggerReadOptions } from "@/lib/database/oracleTriggerIdentity";+import type { OracleTriggerSqlBinding } from "@/lib/database/oracleTriggerSql";+import {+ prepareOracleTriggerPlan,+ prepareOracleTriggerDropBatchPlan,+ executeOracleTriggerDropBatchPlan,+ readOracleTriggerSnapshot,+ verifyOracleTriggerDeletion,+ type OracleTriggerAction,+ type OracleTriggerPlan,+ type OracleTriggerDropBatchPlan,+ type OracleTriggerExecutionResult,+} from "@/lib/database/oracleTriggerPlan";+import { useProductionSafetyStore } from "@/stores/productionSafetyStore";+import { confirmOracleTriggerPlan } from "@/lib/database/oracleTriggerActions";+import { oracleCompileUnsupportedReason } from "@/lib/database/oracleInvalidObjects";import type { ObjectDetailsSection } from "@/lib/database/objectDependencyDetails";import { elasticsearchClearIndexPreview, isElasticsearchClearConfirmed, isElasticsearchIndexPattern } from "@/lib/sidebar/elasticsearchIndexActions";import { sidebarObjectTemplateForGroup } from "@/lib/sidebar/databaseObjectTemplates";@@ -268,7 +286,7 @@ import { buildXuguCompileSql } from "@/lib/database/xuguCompileSql";import { buildDamengCompileViewSql } from "@/lib/database/damengCompileSql";import { buildTriggerToggleSql, supportsTriggerToggle } from "@/lib/database/triggerToggleSql";import type { SidebarDataOpenRequest } from "@/lib/sidebar/sidebarDataOpenCoordinator";-import { createSidebarActionTarget, findSidebarActionTarget, releaseRemovedSidebarActionTarget, type SidebarActionTarget } from "@/lib/sidebar/sidebarActionTarget";+import { createSidebarActionRequest, createSidebarActionTarget, findSidebarActionTarget, releaseRemovedSidebarActionTarget, type SidebarActionRequest, type SidebarActionTarget } from "@/lib/sidebar/sidebarActionTarget";import { collapseSubtreeDescendants } from "@/lib/sidebar/sidebarTreeCollapse";import { createSidebarMenuContext, normalizeSidebarMenuDescriptors } from "@/lib/sidebar/sidebarTreeMenuDescriptors";import { driverProfileDatabaseWorkspace } from "@/lib/database/driverProfileExtensions";@@ -548,7 +566,7 @@ const emit = defineEmits<{"context-menu": [event: MouseEvent, node: TreeNode, items: ContextMenuItem[]];"open-ddl": [node: TreeNode];"open-elasticsearch-index-metadata": [node: TreeNode, kind: ElasticsearchIndexMetadataKind];- "open-object-source": [node: TreeNode, initialEditing: boolean, initialSection?: ObjectDetailsSection];+ "open-object-source": [node: TreeNode, initialEditing: boolean, initialSection?: ObjectDetailsSection, createTrigger?: SidebarActionRequest<OracleTriggerSqlBinding>];"open-procedure": [node: TreeNode];"open-settings": [initialTab: string];"open-connection-settings": [connectionId: string];@@ -762,9 +780,9 @@ function claimTreeItemDialogOwnership() {sidebarTreeDialogOwner.value = treeItemDialogOwner;}-function routeTreeItemDialogController() {+function routeTreeItemDialogController(node = activeNode.value) {const controller = getTreeItemDialogController();- const target = createSidebarActionTarget(activeNode.value);+ const target = createSidebarActionTarget(node);sidebarFormTarget.value = target;const routedController = createRoutedSidebarDialogController(controller, {node: target,@@ -886,6 +904,10 @@ async function openDirectNavigationNode(node: TreeNode, requestId: number) {queryStore.createTab(node.connectionId, "", `${connectionName}:access-control`, "nacos-access-control");} else if (node.type === "meilisearch-system") {queryStore.createTab(node.connectionId, "default", t("meilisearch.systemManagement"), "meilisearch-system");+ } else if (node.type === "dameng-job-admin") {+ queryStore.openDamengJobAdmin(node.connectionId);+ } else if (node.type === "database-job-admin") {+ queryStore.openDatabaseJobAdmin(node.connectionId);}}@@ -1149,9 +1171,6 @@ async function toggle(requestId = beginNavigationRequest()) {} else if (node.type === "dameng-roles" && node.connectionId) {await connectionStore.ensureConnected(node.connectionId);queryStore.openDamengRoles(node.connectionId);- } else if (node.type === "dameng-job-admin" && node.connectionId) {- await connectionStore.ensureConnected(node.connectionId);- queryStore.openDamengJobAdmin(node.connectionId);} else if (node.type === "mongo-db" && node.connectionId && node.database) {await connectionStore.loadMongoCollections(node.connectionId, node.database);} else if (node.type === "vector-database" && node.connectionId && node.database) {@@ -2206,6 +2225,18 @@ async function openDamengJobAdmin() {}}+async function openDatabaseJobAdmin() {+ const node = activeNode.value;+ if (!node.connectionId) return;+ try {+ await connectionStore.ensureConnected(node.connectionId);+ connectionStore.activeConnectionId = node.connectionId;+ queryStore.openDatabaseJobAdmin(node.connectionId);+ } catch (error) {+ toast(t("connection.connectFailed", { message: translateBackendError(t, error) }), 5000);+ }+}+function scheduleOpenData(node: TreeNode) {emit("open-data", node, true, "default", openData);}@@ -3072,6 +3103,11 @@ async function refreshDropTableChildObjectPreviewSql() {function openObjectSourceDialog(initialEditing: boolean, viewPackageBody = false, dependencyNode?: TreeNode) {const node = dependencyNode || activeNode.value;const initialSection = dependencyNode ? "dependencies" : undefined;+ // JOB has native catalog identity, not GET_DDL source. Keep Xugu's existing source path.+ if (node.type === "job" && node.connectionId && nativeJobAdminSupported(connectionStore.getConfig(node.connectionId))) {+ queryStore.openDatabaseJobAdmin(node.connectionId, node.schema && currentDatabaseType() !== "dameng" ? { kind: "scheduler", owner: node.schema, name: node.objectName || node.label } : undefined);+ return;+ }if (!node.connectionId || !node.database) return;if (viewPackageBody && (node.type !== "package" || node.xuguPackageBodyAvailable !== true || currentDatabaseType() !== "xugu")) return;const sourceNode: TreeNode = viewPackageBody ? { ...node, type: "package-body" } : node;@@ -3112,7 +3148,7 @@ async function openDatabaseObjectDependencies() {const node = activeNode.value;const provider = databaseDependencyProviderFor(currentDatabaseType());if (!provider || !node.connectionId || !node.database || !provider.supports(node)) return;- if (currentDatabaseType() === "oracle" || currentDatabaseType() === "oceanbase-oracle") {+ if (currentDatabaseType() === "oracle" || currentDatabaseType() === "oceanbase-oracle" || (currentDatabaseType() === "dameng" && node.type === "trigger")) {const target = oracleTarget(node);if (!target) return;const connection = connectionStore.getConfig(node.connectionId);@@ -3128,7 +3164,7 @@ async function openDatabaseObjectDependencies() {queryStore.openObjectProperties({ connectionId: node.connectionId, database: propertyDatabase, catalog: node.catalog, schema: node.parentSchema, name: node.parentName, objectType: "TABLE", initialTab: "relations", focusObject: { owner: target.schema, name: target.name, type: "INDEX" } });return;}- openObjectSourceDialog(false, false, { ...node, type: target.type.toLowerCase() as "procedure" | "function" | "package", schema: target.schema, objectName: target.name, label: target.name, parentType: undefined, parentName: undefined, parentSchema: undefined });+ openObjectSourceDialog(false, false, { ...node, type: target.type.toLowerCase() as "procedure" | "function" | "package" | "trigger", schema: target.schema, objectName: target.name, label: target.name, parentType: undefined, parentName: undefined, parentSchema: undefined });return;}const sql = provider.buildQuery(node);@@ -3225,6 +3261,10 @@ function findTreeNodeById(nodes: readonly TreeNode[], id: string): TreeNode | nu}async function toggleTriggerState(node: TreeNode, enabled: boolean) {+ if (exactOracleTriggerNodeMetadata(node)) {+ await runExactTriggerNodeAction(node, enabled ? "enable" : "disable");+ return;+ }if (!node.connectionId || !node.database) return;const databaseType = databaseTypeForNode(node);const triggerName = node.meta && "name" in node.meta ? (node.meta as TriggerInfo).name : node.objectName || node.label.replace(/\s+\(.+\)$/, "");@@ -3263,8 +3303,138 @@ async function toggleTriggerState(node: TreeNode, enabled: boolean) {}}+const triggerActionBusy = new Set<string>();+const triggerActionHostActive = ref(true);+const triggerActionFeedback = shallowRef<{ node: TreeNode; plan: OracleTriggerPlan; message: string }>();+const triggerRecoveryBusy = ref(false);+const hasTriggerActionFeedback = computed(() => !!triggerActionFeedback.value && sidebarTreeDialogOwner.value === treeItemDialogOwner && compileErrorMessage.value === triggerActionFeedback.value.message);+watch(showCompileErrorDialog, (open) => {+ if (!open) triggerActionFeedback.value = undefined;+});++function removeVerifiedTriggerNode(node: TreeNode, plan: OracleTriggerPlan) {+ const live = findSidebarActionTarget(visibleTreeNodes(), createSidebarActionTarget(node));+ if (!live || exactOracleTriggerNodeMetadata(live)?.objectId !== plan.before.metadata.objectId) return;+ closeDroppedTableObjectTabsForNode(live);+ connectionStore.removeTreeNode(live.id);+ sidebarTreeContext?.removeVerifiedTriggerNode?.(live);+ releaseActiveNodeReference([live.id]);+}++async function refreshTriggerActionFeedback() {+ const feedback = triggerActionFeedback.value;+ if (!feedback || !hasTriggerActionFeedback.value || triggerRecoveryBusy.value) return;+ const current = () => triggerActionHostActive.value && showCompileErrorDialog.value && triggerActionFeedback.value === feedback && hasTriggerActionFeedback.value;+ triggerRecoveryBusy.value = true;+ try {+ let detail: string;+ if (feedback.plan.action === "delete") {+ await verifyOracleTriggerDeletion(feedback.plan.target, feedback.plan);+ if (!current()) return;+ removeVerifiedTriggerNode(feedback.node, feedback.plan);+ detail = t("processList.oracleInvalidObjects.batchStatus.deleted");+ } else {+ const snapshot = await readOracleTriggerSnapshot(feedback.plan.target);+ if (!current()) return;+ if (!snapshot.exists || snapshot.metadata.objectId !== feedback.plan.before.metadata.objectId) throw new Error(t("oracleTrigger.reloadBaseline"));+ const live = findSidebarActionTarget(visibleTreeNodes(), createSidebarActionTarget(feedback.node));+ const trigger = snapshot.raw.trigger;+ if (live && trigger && exactOracleTriggerNodeMetadata(live)?.objectId === feedback.plan.before.metadata.objectId) live.meta = trigger;+ detail = `${t("eventTrigger.enabled")}: ${snapshot.metadata.reads.enabled?.state === "available" && typeof trigger?.enabled === "boolean" ? t(trigger.enabled ? "objects.enabled" : "objects.disabled") : t("oracleTrigger.unknown")}\n${t("objects.validity")}: ${snapshot.metadata.reads.validity?.state === "available" && typeof trigger?.valid === "boolean" ? (trigger.valid ? "VALID" : "INVALID") : t("oracleTrigger.unknown")}\n${snapshot.metadata.errors?.map((error) => `${error.line ?? "?"}:${error.position ?? "?"} ${error.text}`).join("\n") ?? ""}`;+ }+ feedback.message += `\n\n${t("oracleTrigger.verifyReadOnly")}\n${detail}`;+ compileErrorMessage.value = feedback.message;+ } catch (error) {+ if (current()) {+ feedback.message += `\n\n${error instanceof Error ? error.message : String(error)}`;+ compileErrorMessage.value = feedback.message;+ }+ } finally {+ triggerRecoveryBusy.value = false;+ }+}++function viewTriggerActionSource() {+ const feedback = triggerActionFeedback.value;+ if (!feedback || !hasTriggerActionFeedback.value) return;+ showCompileErrorDialog.value = false;+ activateActionTarget(feedback.node);+ openObjectSourceDialog(false);+}++function reportExactTriggerResult(node: TreeNode, plan: OracleTriggerPlan, result: OracleTriggerExecutionResult) {+ if (result.cancelled || !triggerActionHostActive.value) return;+ const successful = result.steps.every((step) => step.state === "committed") && !result.steps.some((step) => step.verification === "invalid");+ const snapshot = result.snapshot;+ if (snapshot?.exists && snapshot.raw.trigger && snapshot.metadata.objectId === plan.before.metadata.objectId) {+ const live = findSidebarActionTarget(visibleTreeNodes(), createSidebarActionTarget(node));+ if (live && exactOracleTriggerNodeMetadata(live)?.objectId === plan.before.metadata.objectId) live.meta = snapshot.raw.trigger;+ }+ if (successful && !result.refreshError) {+ toast(+ plan.action === "delete"+ ? t("contextMenu.dropTableChildObjectSuccess", { name: plan.target.name })+ : plan.action === "compile"+ ? t("contextMenu.compileObjectSuccess", { name: plan.target.name })+ : plan.action === "enable" || plan.action === "disable"+ ? t(plan.action === "enable" ? "contextMenu.enableTriggerSuccess" : "contextMenu.disableTriggerSuccess", { name: plan.target.name })+ : t("objects.sourceSaved"),+ 2500,+ );+ return;+ }+ // The existing operation-error dialog retains the fixed target, SQL, native+ // errors and per-step outcomes instead of reducing unknown to a success toast.+ compileErrorTitle.value = t("oracleStructureResult.resultTitle");+ compileErrorMessage.value = `${plan.target.owner}.${plan.target.name}\n\n${result.steps.map((step) => `${t(`oceanbasePrimaryKey.${step.state}`)} · ${step.verification}\n${step.sql}\n${[step.error, step.readbackError].filter(Boolean).join("\n")}`).join("\n\n")}\n${result.refreshError ?? ""}\n${snapshot?.metadata.errors?.map((error) => `${error.line ?? "?"}:${error.position ?? "?"} ${error.text}`).join("\n") ?? ""}`;+ triggerActionFeedback.value = { node: createSidebarActionTarget(node), plan, message: compileErrorMessage.value };+ claimTreeItemDialogOwnership();+ routeTreeItemDialogController(node);+ showCompileErrorDialog.value = true;+}++async function prepareExactTriggerNodePlan(node: TreeNode, action: OracleTriggerAction): Promise<OracleTriggerPlan> {+ const exact = exactOracleTriggerNodeMetadata(node);+ if (!exact || !node.connectionId || !node.database) throw new Error(t("oracleTrigger.reloadBaseline"));+ const target = { connectionId: node.connectionId, database: node.database, catalog: node.catalog, owner: exact.owner, name: exact.name, executionSchema: node.schema || exact.owner };+ const expectedObjectId = exact.objectId ?? undefined;+ await connectionStore.ensureConnected(target.connectionId);+ return prepareOracleTriggerPlan({ target, action, expectedObjectId });+}++async function runExactTriggerNodeAction(node: TreeNode, action: OracleTriggerAction) {+ if (triggerActionBusy.has(node.id)) return;+ triggerActionBusy.add(node.id);+ const selection = JSON.stringify([connectionStore.selectedTreeNodeId, connectionStore.selectedTreeNodeIds]);+ const target = createSidebarActionTarget(node);+ const expectedObjectId = exactOracleTriggerNodeMetadata(node)?.objectId;+ const current = () => {+ const live = findSidebarActionTarget(visibleTreeNodes(), target);+ return triggerActionHostActive.value && !!live && JSON.stringify([connectionStore.selectedTreeNodeId, connectionStore.selectedTreeNodeIds]) === selection && exactOracleTriggerNodeMetadata(live)?.objectId === expectedObjectId;+ };+ try {+ const plan = await prepareExactTriggerNodePlan(node, action);+ if (!current()) return;+ const result = await confirmOracleTriggerPlan(plan, { isCurrent: current });+ if (action !== "delete" && triggerActionHostActive.value && result.snapshot?.metadata.objectId === plan.before.metadata.objectId && !result.cancelled && result.steps.every((step) => step.state === "committed")) {+ try {+ await connectionStore.refreshTreeNode(node, { skipObjectCacheInvalidation: true });+ } catch (error) {+ result.refreshError = [result.refreshError, error instanceof Error ? error.message : String(error)].filter(Boolean).join("\n");+ }+ }+ if (action === "delete" && result.steps.some((step) => step.state === "committed" && step.verification === "deleted")) removeVerifiedTriggerNode(node, plan);+ reportExactTriggerResult(node, plan, result);+ } catch (error) {+ if (triggerActionHostActive.value) toast(t("contextMenu.tableOperationFailed", { message: error instanceof Error ? error.message : String(error) }), 5000);+ } finally {+ triggerActionBusy.delete(node.id);+ }+}+function triggerToggleMenuItems(node: TreeNode): ContextMenuItem[] {- const dbType = databaseTypeForNode(node);+ const exact = exactOracleTriggerNodeMetadata(node);+ const dbType = exact ? (exact.engine === "dm" ? "dameng" : exact.engine) : databaseTypeForNode(node);if (!supportsTriggerToggle(dbType)) return [];const triggerName = node.meta && "name" in node.meta ? (node.meta as TriggerInfo).name : node.objectName || node.label.replace(/\s+\(.+\)$/, "");if (!triggerName) return [];@@ -3363,6 +3533,7 @@ function requestDropTableChildObject() {}function canDropTreeNode(node: TreeNode): boolean {+ if (exactOracleTriggerNodeMetadata(node)) return !!node.connectionId && !!node.database;if (["neo4j", "nebula"].includes(databaseTypeForNode(node) || "")) return false;if (isSqlServerLinkedNode(node)) return false;if (isManagedTypeNode(node)) return !!node.connectionId && !!node.database;@@ -3545,8 +3716,56 @@ async function emptySqlForTreeNode(node: TreeNode): Promise<string | null> {});}+const exactBatchDropPreview = shallowRef<{ targets: TreeNode[]; selection: string; entries: { node: TreeNode; sql: string; trigger?: OracleTriggerPlan }[]; plan: OracleTriggerDropBatchPlan }>();+const exactBatchDropLoading = ref(false);+const exactBatchDropError = ref("");+const exactBatchDropExecuting = ref(false);+let exactBatchDropSerial = 0;++function isExactBatchDropPreviewCurrent(preview: NonNullable<typeof exactBatchDropPreview.value>): boolean {+ return (+ triggerActionHostActive.value &&+ sidebarTreeDialogOwner.value === treeItemDialogOwner &&+ exactBatchDropPreview.value === preview &&+ preview.targets === batchDropTargets.value &&+ JSON.stringify([connectionStore.selectedTreeNodeId, connectionStore.selectedTreeNodeIds]) === preview.selection &&+ preview.entries.every(({ node, trigger }) => {+ const live = findSidebarActionTarget(visibleTreeNodes(), createSidebarActionTarget(node));+ return !!live && (!trigger || exactOracleTriggerNodeMetadata(live)?.objectId === trigger.before.metadata.objectId);+ })+ );+}async function refreshBatchDropPreviewSql() {const targets = batchDropTargets.value;+ const serial = ++exactBatchDropSerial;+ exactBatchDropPreview.value = undefined;+ exactBatchDropError.value = "";+ if (targets.some((target) => !!exactOracleTriggerNodeMetadata(target))) {+ exactBatchDropLoading.value = true;+ batchDropPreviewSql.value = "";+ const selection = JSON.stringify([connectionStore.selectedTreeNodeId, connectionStore.selectedTreeNodeIds]);+ try {+ const entries: { node: TreeNode; sql: string; trigger?: OracleTriggerPlan }[] = [];+ for (const node of targets) {+ const trigger = exactOracleTriggerNodeMetadata(node) ? await prepareExactTriggerNodePlan(node, "delete") : undefined;+ const sql = trigger?.steps[0]?.sql ?? (await dropSqlForTreeNode(node, { cascade: canBatchDropCascade.value && batchDropCascade.value }));+ if (!sql) throw new Error("Drop SQL preview is unavailable");+ entries.push({ node, sql, trigger });+ }+ if (serial !== exactBatchDropSerial || targets !== batchDropTargets.value) return;+ const first = entries.find((entry) => entry.trigger)!.trigger!;+ if (entries.some(({ node }) => node.connectionId !== first.target.connectionId || node.database !== first.target.database || node.catalog !== first.target.catalog)) throw new Error("Select trigger deletions within the same connection, database and catalog");+ const plan = prepareOracleTriggerDropBatchPlan({ target: first.target, engine: first.before.metadata.engine, entries: entries.map(({ node, sql, trigger }) => ({ id: node.id, sql, ...(trigger ? { triggerPlan: trigger } : { executionSchema: node.schema }) })) });+ exactBatchDropPreview.value = { targets, selection, entries, plan };+ batchDropPreviewSql.value = entries.map((entry) => entry.sql).join("\n\n");+ } catch (error) {+ if (serial === exactBatchDropSerial) exactBatchDropError.value = error instanceof Error ? error.message : String(error);+ } finally {+ if (serial === exactBatchDropSerial) exactBatchDropLoading.value = false;+ }+ return;+ }+ exactBatchDropLoading.value = false;const mongoIndexTargets = targets.filter(canDropMongoIndexNode);if (mongoIndexTargets.length) {batchDropPreviewSql.value = mongoIndexTargets.map((target) => mongoIndexDropPreview(target, mongoIndexNameForNode(target))).join("\n");@@ -3586,8 +3805,9 @@ function requestBatchDrop() {explainIndividualIndexEditing();return;}- const targets = selectedBatchDropTargets();- if (!targets.length) return;+ const selected = selectedBatchDropTargets();+ if (!selected.length) return;+ const targets = selected.some((target) => !!exactOracleTriggerNodeMetadata(target)) ? selected.map(createSidebarActionTarget) : selected.slice();const managed = targets.filter(isManagedTypeNode);if (managed.length) {void (async () => {@@ -3733,6 +3953,10 @@ function requestDropSelectedNodes(): boolean {}function requestDropSelectedNode(): boolean {+ if (exactOracleTriggerNodeMetadata(activeNode.value)) {+ void runExactTriggerNodeAction(createSidebarActionTarget(activeNode.value), "delete");+ return true;+ }if (isSchemaIndexNode(activeNode.value)) return requestSchemaIndexDelete(activeNode.value);if (["neo4j", "nebula"].includes(currentDatabaseType() || "")) return false;if (activeNode.value.type === "table") {@@ -4465,6 +4689,10 @@ async function confirmBatchDrop() {explainIndividualIndexEditing();return;}+ if (targets.some((target) => !!exactOracleTriggerNodeMetadata(target))) {+ await confirmExactBatchTriggerDrop();+ return;+ }try {const mongoIndexTargets = targets.filter(canDropMongoIndexNode);if (mongoIndexTargets.length) {@@ -4621,6 +4849,93 @@ async function confirmBatchDrop() {}}+async function confirmExactBatchTriggerDrop() {+ const preview = exactBatchDropPreview.value;+ if (!preview || exactBatchDropExecuting.value || exactBatchDropLoading.value || exactBatchDropError.value || !isExactBatchDropPreviewCurrent(preview)) return false;+ const scope = `oracle-trigger-tree-drop:${uuid()}`;+ const production = useProductionSafetyStore();+ const current = () => isExactBatchDropPreviewCurrent(preview);+ const ownsView = () => triggerActionHostActive.value && sidebarTreeDialogOwner.value === treeItemDialogOwner && exactBatchDropPreview.value === preview;+ const stop = watch(+ current,+ (fresh) => {+ if (!fresh) production.cancelScope(scope);+ },+ { flush: "sync" },+ );+ exactBatchDropExecuting.value = true;+ batchDropProgress.value = { completed: 0, total: preview.entries.length };+ let retirePreview = false;+ try {+ const result = await executeOracleTriggerDropBatchPlan(preview.plan, {+ confirmed: true,+ confirmationScope: scope,+ isCurrent: current,+ timeoutSecs: queryTimeoutSecsForConnection(connectionStore.getConfig(preview.plan.target.connectionId), settingsStore.editorSettings.globalQueryTimeoutSecs),+ onProgress: (completed) => {+ if (ownsView()) batchDropProgress.value = { completed, total: preview.entries.length };+ },+ });+ if (!triggerActionHostActive.value) return false;+ if (result.cancelled && result.steps.every((step) => step.state === "notExecuted")) return false;+ retirePreview = true;+ for (const [index, step] of result.steps.entries()) {+ const entry = preview.entries[index];+ if (step.state !== "committed") continue;+ if (entry.trigger) {+ if (step.trigger?.verification === "deleted") removeVerifiedTriggerNode(entry.node, entry.trigger);+ } else {+ const live = findSidebarActionTarget(connectionStore.treeNodes, createSidebarActionTarget(entry.node));+ if (live) {+ closeDroppedTableObjectTabsForNode(live);+ connectionStore.removeTreeNode(live.id);+ releaseActiveNodeReference([live.id]);+ }+ await recordTableMutationHistory(getTableMutationHistoryStoreOrNull(), {+ connectionId: entry.node.connectionId!,+ connectionName: connectionStore.getConfig(entry.node.connectionId!)?.name,+ database: entry.node.database!,+ sql: entry.sql,+ elapsedMs: step.elapsedMs!,+ success: true,+ target: entry.node.label,+ }).catch(() => undefined);+ }+ }+ if (!ownsView()) return false;+ const attention = result.triggerResults.some((outcome) => !!outcome.result.refreshError);+ if (result.steps.every((step) => step.state === "committed") && !attention) {+ toast(t("contextMenu.batchDropSuccess", { count: result.steps.length }), 3000);+ showBatchDropConfirm.value = false;+ return true;+ }+ const message = result.steps+ .map((step, index) => {+ const entry = preview.entries[index];+ const native = result.triggerResults.find((outcome) => outcome.draftId === entry.node.id)?.result;+ return `${t(`oceanbasePrimaryKey.${step.state}`)} · ${entry.node.schema ?? ""}.${entry.node.objectName || entry.node.label}\n${step.sql}\n${[step.trigger?.verification, step.error, native?.refreshError, step.state !== "committed" ? entry.trigger?.before.raw.source : undefined].filter(Boolean).join("\n")}`;+ })+ .join("\n\n");+ const failure = preview.entries.find((entry, index) => entry.trigger && result.steps[index].state !== "committed");+ compileErrorTitle.value = t("oracleStructureResult.resultTitle");+ compileErrorMessage.value = message;+ triggerActionFeedback.value = failure?.trigger ? { node: failure.node, plan: failure.trigger, message } : undefined;+ claimTreeItemDialogOwnership();+ routeTreeItemDialogController(failure?.node);+ showCompileErrorDialog.value = true;+ showBatchDropConfirm.value = false;+ return false;+ } catch (error) {+ if (ownsView()) exactBatchDropError.value = error instanceof Error ? error.message : String(error);+ return false;+ } finally {+ stop();+ production.cancelScope(scope);+ exactBatchDropExecuting.value = false;+ if (retirePreview && exactBatchDropPreview.value === preview) exactBatchDropPreview.value = undefined;+ }+}+async function confirmBatchTruncate() {const targets = batchTruncateTargets.value.slice();if (!targets.length) return;@@ -5935,6 +6250,30 @@ function createSidebarObjectTemplate() {queryStore.updateSql(tabId, template.sql);}+function canCreateOracleTriggerAt(node: TreeNode): boolean {+ return !!node.connectionId && !!node.database && !!oracleTriggerReadOptions(databaseTypeForNode(node)) && ["schema", "group-triggers", "table", "view"].includes(node.type) && !!(node.schema || (node.type === "schema" && node.label));+}++function createOracleTrigger() {+ const node = activeNode.value;+ if (!canCreateOracleTriggerAt(node)) return;+ const parent =+ node.type === "group-triggers" && node.tableName+ ? flattenTree(connectionStore.treeNodes)+ .map((item) => item.node)+ .find((item) => item.children?.some((child) => child.id === node.id))+ : node;+ const relation = parent && (parent.type === "table" || parent.type === "view") ? parent : undefined;+ const selection: OracleTriggerSqlBinding = relation ? { scope: relation.type === "view" ? "VIEW" : "TABLE", owner: relation.schema, name: relation.objectName || relation.label } : { scope: "TABLE", ...(node.tableName ? { owner: node.schema, name: node.tableName } : {}) };+ emit(+ "open-object-source",+ { ...node, id: `${node.id}:new-trigger`, type: "trigger", schema: node.schema || node.label, label: "TRG_NEW", objectName: "TRG_NEW", tableName: relation?.objectName || relation?.label || node.tableName, children: undefined, meta: undefined },+ true,+ undefined,+ createSidebarActionRequest(node, connectionStore.selectedTreeNodeIds, selection),+ );+}+const canExpand = computed(() => {if (activeNode.value.type === "type" && customTypeCapabilities(currentDatabaseType()).details) {return activeNode.value.hasMembers === true || (activeNode.value.hasMembers === undefined && supportsOracleTypeAttributeExpansion(currentDatabaseType()));@@ -6302,6 +6641,21 @@ routeDangerDialog(showBatchDropConfirm, () =>get sql() {return batchDropPreviewSql.value;},+ get confirmDisabled() {+ return batchDropTargets.value.some((node) => !!exactOracleTriggerNodeMetadata(node)) && (exactBatchDropExecuting.value || exactBatchDropLoading.value || !exactBatchDropPreview.value || !isExactBatchDropPreviewCurrent(exactBatchDropPreview.value) || !!exactBatchDropError.value);+ },+ get detailsText() {+ return (+ exactBatchDropError.value ||+ exactBatchDropPreview.value?.entries+ .map(({ node, trigger }) =>+ trigger+ ? `${trigger.target.owner}.${trigger.target.name}\n${t("oracleTrigger.executionSchema")}: ${trigger.target.executionSchema}\nON ${trigger.before.metadata.parent ? `${trigger.before.metadata.parent.owner}.${trigger.before.metadata.parent.name} · ${trigger.before.metadata.parent.objectType}` : trigger.before.metadata.scope}`+ : `${node.schema ?? ""}.${node.objectName || node.label}`,+ )+ .join("\n\n")+ );+ },confirmLabel: batchDropMenuLabel(),get progress() {return batchDropProgress.value.total > 0 ? batchDropProgress.value : undefined;@@ -6702,6 +7056,10 @@ function databaseSpecificDialogCapabilities() {showCompileErrorDialog,compileErrorTitle,compileErrorMessage,+ hasTriggerActionFeedback,+ triggerRecoveryBusy,+ refreshTriggerActionFeedback,+ viewTriggerActionSource,schemaCommentText,schemaCommentLoading,schemaCommentPreviewSql,@@ -6726,6 +7084,7 @@ function getTreeItemDialogController(): Record<string, any> {const availableGroups = computed(() => connectionGroupDestinationRows(connectionStore.sidebarLayout));onBeforeUnmount(() => {+ triggerActionHostActive.value = false;stopDangerDialogRouting?.();});@@ -6953,6 +7312,8 @@ function buildConnectionSidebarMenu(context: SidebarMenuFactoryContext): booleanitems.push({ sidebarActionId: "contextMenu.damengUsers", label: t("contextMenu.damengUsers"), action: openDamengUsers, icon: UsersRound });items.push({ sidebarActionId: "contextMenu.damengRoles", label: t("contextMenu.damengRoles"), action: openDamengRoles, icon: ShieldCheck });items.push({ sidebarActionId: "contextMenu.damengJobAdmin", label: t("contextMenu.damengJobAdmin"), action: openDamengJobAdmin, icon: CalendarClock });+ } else if (node.connectionId && nativeJobAdminSupported(connectionStore.getConfig(node.connectionId))) {+ items.push({ sidebarActionId: "nativeJobs.title", label: t("nativeJobs.title"), action: openDatabaseJobAdmin, icon: CalendarClock });}if (canCopyFinalProxyPort.value) {items.push({ sidebarActionId: "contextMenu.copyFinalProxyPort", label: t("contextMenu.copyFinalProxyPort"), action: copyFinalProxyPort, icon: Network });@@ -7187,6 +7548,7 @@ function buildDatabaseSidebarMenu(context: SidebarMenuFactoryContext): boolean {if (canOpenObjectBrowser.value) {items.push({ sidebarActionId: "contextMenu.openObjectBrowser", label: t("contextMenu.openObjectBrowser"), action: openObjectBrowser, icon: TableProperties });}+ if (canCreateOracleTriggerAt(node)) items.push({ sidebarActionId: "contextMenu.createTrigger", label: t("contextMenu.createTrigger"), action: createOracleTrigger, icon: Plus });if (supportsConnectionQueryActions(currentDatabaseType())) {items.push({ sidebarActionId: "contextMenu.newQuery", label: t("contextMenu.newQuery"), action: newQuery, icon: TerminalSquare });items.push({ sidebarActionId: "savedSql.openDefaultQuery", label: t("savedSql.openDefaultQuery"), action: () => newQuery({ reuseQueryTabByScope: true }), icon: TerminalSquare });@@ -7444,6 +7806,10 @@ function buildSpecialSidebarMenu(context: SidebarMenuFactoryContext): boolean {items.push({ label: t("contextMenu.openDamengJobAdmin"), action: openDamengJobAdmin, icon: CalendarClock });return true;}+ if (node.type === "database-job-admin") {+ items.push({ label: t("nativeJobs.title"), action: openDatabaseJobAdmin, icon: CalendarClock });+ return true;+ }if (node.type === "redis-db" || node.type === "mongo-db" || node.type === "vector-database") {items.push({ label: t("contextMenu.newQuery"), action: newQuery, icon: TerminalSquare });@@ -7692,6 +8058,7 @@ function buildObjectSidebarMenu(context: SidebarMenuFactoryContext): boolean {if (canOpenStructureEditor.value) {items.push({ sidebarActionId: "contextMenu.editStructure", label: t("contextMenu.editStructure"), action: openStructureEditor, icon: PencilRuler });}+ if (canCreateOracleTriggerAt(node)) items.push({ sidebarActionId: "contextMenu.createTrigger", label: t("contextMenu.createTrigger"), action: createOracleTrigger, icon: Plus });if (canRenameObject.value) {items.push({sidebarActionId: "contextMenu.renameObject",@@ -7829,6 +8196,44 @@ function buildObjectSidebarMenu(context: SidebarMenuFactoryContext): boolean {return true;}+ const exactTrigger = exactOracleTriggerNodeMetadata(node);+ if (exactTrigger) {+ items.push(copyNameMenuItem());+ items.push({ label: t("contextMenu.viewSource"), action: () => openObjectSourceDialog(false), icon: Code2 });+ items.push({ label: t("contextMenu.editObject"), action: () => openObjectSourceDialog(true), icon: Pencil });+ items.push(...triggerToggleMenuItems(node));+ if (!oracleCompileUnsupportedReason(exactTrigger.engine === "dm" ? "dameng" : exactTrigger.engine, "TRIGGER", { triggerProfile: exactTrigger })) items.push({ label: t("processList.oracleInvalidObjects.compile"), action: () => runExactTriggerNodeAction(node, "compile"), icon: Wrench });+ if (canViewDatabaseObjectDependencies(currentDatabaseType(), node)) items.push({ label: t("contextMenu.viewDependencies"), action: openDatabaseObjectDependencies, icon: Network });+ if (exactTrigger.parent)+ items.push({+ label: `${t("contextMenu.viewObject")} · ${exactTrigger.parent.owner}.${exactTrigger.parent.name}`,+ action: () => {+ const parent = exactTrigger.parent!;+ openDataInNewTabImmediately({+ ...node,+ id: JSON.stringify([node.connectionId, node.database, node.catalog, parent.owner, parent.name, parent.objectType]),+ type: parent.objectType === "VIEW" ? "view" : "table",+ label: parent.name,+ objectName: parent.name,+ schema: parent.owner,+ tableName: undefined,+ meta: undefined,+ });+ },+ icon: TableProperties,+ });+ items.push({+ label: deleteMenuLabel(t("contextMenu.dropTrigger")),+ action: deleteMenuAction(() => {+ void runExactTriggerNodeAction(node, "delete");+ }),+ icon: Trash2,+ shortcut: shortcutDelete,+ variant: "destructive" as const,+ });+ items.push({ label: t("contextMenu.changeOpenMode"), action: () => emit("open-settings", "navigation"), icon: Settings2 });+ return true;+ }if (isSchemaIndexNode(node)) {items.push({ label: t("contextMenu.copyName"), action: copyName, icon: Copy, shortcut: shortcutCopyName.value });if (!schemaIndexNodeIdentity(node)) items.push({ label: t("schemaIndex.parentUnavailable"), disabled: true });@@ -7957,7 +8362,8 @@ function buildObjectSidebarMenu(context: SidebarMenuFactoryContext): boolean {}if (node.type === "job") {- items.push({ label: t("contextMenu.viewSource"), action: () => openObjectSourceDialog(false), icon: Code2 });+ const nativeJobs = nativeJobAdminSupported(connectionStore.getConfig(node.connectionId || ""));+ items.push({ label: t(nativeJobs ? "nativeJobs.title" : "contextMenu.viewSource"), action: () => openObjectSourceDialog(false), icon: nativeJobs ? CalendarClock : Code2 });items.push({ label: t("contextMenu.copyName"), action: copyName, icon: Copy, shortcut: shortcutCopyName.value });if (currentDatabaseType() === "xugu") {items.push({ label: "", separator: true });@@ -8059,8 +8465,9 @@ function buildObjectGroupSidebarMenu(context: SidebarMenuFactoryContext): booleaconst hasMongoDropAllIndexesAction = node.type === "group-indexes" && canDropAllMongoIndexes.value;const canCreateGroupView = node.type === "group-views" && !!node.connectionId && !!node.database && !["neo4j", "nebula"].includes(currentDatabaseType() || "");const canCreateTableGroup = isTableVGroupContainerNode(node);+ const canCreateTrigger = canCreateOracleTriggerAt(node);const canCreateSchemaIndex = node.type === "group-database-indexes" && supportsSchemaIndexManagement(currentDatabaseType()) && !connectionIsEffectivelyReadOnly(connectionStore.getConfig(node.connectionId || ""));- const hasGroupAction = (node.type === "group-tables" && canCreateTable.value) || canCreateTableGroup || canCreateGroupView || !!objectTemplate || hasMongoCreateIndexAction || hasMongoDropAllIndexesAction || canCreateSchemaIndex;+ const hasGroupAction = (node.type === "group-tables" && canCreateTable.value) || canCreateTableGroup || canCreateGroupView || canCreateTrigger || !!objectTemplate || hasMongoCreateIndexAction || hasMongoDropAllIndexesAction || canCreateSchemaIndex;const canLoadAllObjectGroup = node.type === "group-tables" || node.type === "group-dolt-system-tables" || node.type === "group-views" || node.type === "group-materialized-views";if (node.type === "group-tables" && canCreateTable.value) {items.push({ label: t("contextMenu.createTable"), action: createTable, icon: Plus });@@ -8077,6 +8484,7 @@ function buildObjectGroupSidebarMenu(context: SidebarMenuFactoryContext): booleaif (objectTemplate) {items.push({ label: t(objectTemplate.titleKey), action: createSidebarObjectTemplate, icon: Plus });}+ if (canCreateTrigger) items.push({ sidebarActionId: "contextMenu.createTrigger", label: t("contextMenu.createTrigger"), action: createOracleTrigger, icon: Plus });if (canCreateTableGroup) {items.push({sidebarActionId: "contextMenu.createGroup",diff --git a/apps/desktop/src/components/sidebar/TreeItem.vue b/apps/desktop/src/components/sidebar/TreeItem.vueindex a949606d61..93fe458d32 100644--- a/apps/desktop/src/components/sidebar/TreeItem.vue+++ b/apps/desktop/src/components/sidebar/TreeItem.vue@@ -338,6 +338,7 @@ function getIconInfo(node: TreeNode): { icon: any; colorClass: string } | null {case "dameng-roles":return { icon: ShieldCheck, colorClass: "text-primary" };case "dameng-job-admin":+ case "database-job-admin":return { icon: CalendarClock, colorClass: "text-primary" };case "saved-sql-root":return { icon: node.isExpanded ? FolderOpen : FolderClosed, colorClass: "text-blue-500" };diff --git a/apps/desktop/src/components/sidebar/__tests__/ConnectionTree.remoteSearch.spec.ts b/apps/desktop/src/components/sidebar/__tests__/ConnectionTree.remoteSearch.spec.tsindex 6aae4d8763..a22852e3b1 100644--- a/apps/desktop/src/components/sidebar/__tests__/ConnectionTree.remoteSearch.spec.ts+++ b/apps/desktop/src/components/sidebar/__tests__/ConnectionTree.remoteSearch.spec.ts@@ -15,7 +15,12 @@ const source = parse(readFileSync("apps/desktop/src/components/sidebar/Connectioconst script = ts.createSourceFile("ConnectionTree.ts", source, ts.ScriptTarget.Latest, true);const statements = script.statements.filter((statement) => {if (ts.isFunctionDeclaration(statement)) return ["loadGlobalRemoteSearchResults", "isGlobalTableIndexParent", "discoverGlobalSearchChildren"].includes(statement.name?.text ?? "");- return ts.isVariableStatement(statement) && statement.declarationList.declarations.some((declaration) => ["globalSearchContext", "{ results: remoteSearchResults, isLoading: isRemoteSearchLoading }"].includes(declaration.name.getText(script)));+ return (+ ts.isVariableStatement(statement) &&+ statement.declarationList.declarations.some((declaration) =>+ ts.isIdentifier(declaration.name) ? declaration.name.text === "globalSearchContext" : ts.isObjectBindingPattern(declaration.name) && declaration.name.elements.some((element) => ts.isIdentifier(element.name) && element.name.text === "remoteSearchResults"),+ )+ );});const compiled = ts.transpileModule(statements.map((statement) => statement.getText(script)).join("\n"), { compilerOptions: { target: ts.ScriptTarget.ES2022 } }).outputText;const cleanups: Array<() => void> = [];diff --git a/apps/desktop/src/components/sidebar/__tests__/SidebarTreeRuntimeHost.expansion.spec.ts b/apps/desktop/src/components/sidebar/__tests__/SidebarTreeRuntimeHost.expansion.spec.tsindex d28dcb7de3..93b83c0575 100644--- a/apps/desktop/src/components/sidebar/__tests__/SidebarTreeRuntimeHost.expansion.spec.ts+++ b/apps/desktop/src/components/sidebar/__tests__/SidebarTreeRuntimeHost.expansion.spec.ts@@ -45,6 +45,8 @@ const queryStore = {updateSql: vi.fn(),setTableMeta: vi.fn(),openNacosAdmin: vi.fn(),+ openDamengJobAdmin: vi.fn(),+ openDatabaseJobAdmin: vi.fn(),openObjectBrowser: vi.fn(() => "object-browser-tab"),};@@ -108,6 +110,24 @@ afterEach(() => {});describe("SidebarTreeRuntimeHost expansion", () => {+ it.each(["dameng-job-admin", "database-job-admin"] as const)("opens %s through the direct-navigation production path", async (type) => {+ const node: TreeNode = { id: `c:${type}`, label: "Jobs", type, connectionId: "c", database: "" };+ const host = ref<InstanceType<typeof SidebarTreeRuntimeHost> | null>(null);+ const app = createApp(defineComponent({ setup: () => () => h(SidebarTreeRuntimeHost, { ref: host, node, depth: 0 }) }));+ mountedApps.push(app);+ const container = document.createElement("div");+ document.body.append(container);+ app.use(i18n);+ app.mount(container);+ host.value?.handleRowClick(node, 1);+ host.value?.handleRowClick(node, 2);+ host.value?.handleRowDoubleClick(node, new MouseEvent("dblclick"));+ const open = type === "dameng-job-admin" ? queryStore.openDamengJobAdmin : queryStore.openDatabaseJobAdmin;+ await vi.waitFor(() => expect(open).toHaveBeenCalledExactlyOnceWith("c"));+ expect(connectionStore.loadObjectGroupChildren).not.toHaveBeenCalled();+ expect(node.children).toBeUndefined();+ });+it.each(["oracle", "oceanbase-oracle", "dameng"] as const)("lazy-loads unknown TYPE members for %s on row activation", async (dbType) => {const typeNode: TreeNode = { id: `${dbType}:demo:APP:TYPE_OBJ`, label: "TYPE_OBJ", type: "type", connectionId: dbType, database: "demo", schema: "APP", objectName: "TYPE_OBJ", hasMembers: undefined };connectionStore.getConfig.mockReturnValue({ db_type: dbType });diff --git a/apps/desktop/src/components/sidebar/__tests__/SidebarTreeRuntimeHost.oracleTriggerActions.spec.ts b/apps/desktop/src/components/sidebar/__tests__/SidebarTreeRuntimeHost.oracleTriggerActions.spec.tsnew file mode 100644index 0000000000..650b599fc0--- /dev/null+++ b/apps/desktop/src/components/sidebar/__tests__/SidebarTreeRuntimeHost.oracleTriggerActions.spec.ts@@ -0,0 +1,572 @@+// @vitest-environment happy-dom+import { createApp, h, nextTick, ref, watch, type App } from "vue";+import { createPinia, getActivePinia, setActivePinia } from "pinia";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import i18n from "@/i18n";+import type { ConnectionConfig, ObjectSource, TreeNode, TriggerInfo } from "@/types/database";+import type { ContextMenuItem } from "@/components/ui/CustomContextMenu.vue";+import { useConnectionStore } from "@/stores/connectionStore";+import { useSettingsStore } from "@/stores/settingsStore";+import { useQueryStore } from "@/stores/queryStore";+import { useSqlExecutionDangerStore } from "@/stores/sqlExecutionDangerStore";+import { useProductionSafetyStore } from "@/stores/productionSafetyStore";+import type { SidebarDangerDialogRequest } from "@/lib/sidebar/sidebarDangerDialog";+import { compileErrorMessage, showCompileErrorDialog, showBatchDropConfirm } from "../sidebarTreeDialogState";+import SidebarTreeRuntimeHost from "../SidebarTreeRuntimeHost.vue";+import SidebarTreeItemDialogs from "../SidebarTreeItemDialogs.vue";+import { sidebarTreeContextKey } from "@/lib/sidebar/sidebarTreeContext";+import { useSidebarRemoteSearch } from "@/composables/useSidebarRemoteSearch";+import { useToast } from "@/composables/useToast";++const rpc = vi.hoisted(() => ({+ getObjectSource: vi.fn(),+ executeQuery: vi.fn(),+ listTriggers: vi.fn(),+ buildDropObjectSql: vi.fn(),+ checkConnectionHealth: vi.fn(async () => undefined),+ listPlugins: vi.fn(async () => []),+ listInstalledAgents: vi.fn(async () => []),+ loadSchemaCache: vi.fn(async () => null),+ saveSchemaCache: vi.fn(async () => undefined),+ saveOpenTabsState: vi.fn(async () => undefined),+ deleteSchemaCachePrefix: vi.fn(async () => undefined),+}));+vi.mock("@/lib/backend/api", async (original) => ({ ...(await original<typeof import("@/lib/backend/api")>()), ...rpc }));+const owner = " Trigger.Owner ",+ parent = " Parent.Owner ";+const names = [' Tr"igger ', "SecondTrigger"];+const quote = (value: string) => `"${value.replaceAll('"', '""')}"`;+const configs = { id: "native-trigger-menu", name: "Test", db_type: "oceanbase-oracle", database: "service", username: "Execution.Owner" } as ConnectionConfig;+const cleanup: (() => void)[] = [];+let enabled = false,+ invalid = false,+ denyGlobal = false;+let gone = new Set<string>();+let objectIds = new Map<string, string>();+let parentId = "parent-id";+let ddl: string[];+let request: SidebarDangerDialogRequest | undefined;+function trigger(name: string): TriggerInfo {+ return {+ name,+ timing: "INSTEAD OF",+ event: "UPDATE",+ enabled,+ valid: !invalid,+ oracle_metadata: {+ contractVersion: 1,+ identityMode: "exact",+ engine: configs.db_type === "dameng" ? "dm" : "oceanbase-oracle",+ engineVersion: configs.db_type === "dameng" ? "8.1.3" : "4.2.5.7_107",+ owner,+ name,+ objectId: objectIds.get(name) ?? `900719925474099${names.indexOf(name) + 3}`,+ scope: "VIEW",+ parent: { owner: parent, name: "V", objectType: "VIEW" },+ definition: { origin: "catalog-body", format: "body", complete: false },+ errors: invalid ? [{ sequence: 1, line: 2, position: 3, text: "Missing procedure" }] : [],+ reads: { identity: { state: "available" }, scope: { state: "available" }, parent: { state: "available" }, enabled: { state: "available" }, validity: { state: "available" }, definition: { state: "denied" }, errors: { state: "available" } },+ },+ };+}+beforeEach(() => {+ vi.clearAllMocks();+ useToast().message.value = "";+ configs.db_type = "oceanbase-oracle";+ configs.is_production = false;+ localStorage.clear();+ rpc.deleteSchemaCachePrefix.mockResolvedValue(undefined);+ enabled = false;+ invalid = false;+ denyGlobal = false;+ gone = new Set();+ objectIds = new Map();+ parentId = "parent-id";+ ddl = [];+ request = undefined;+ setActivePinia(createPinia());+ showCompileErrorDialog.value = false;+ showBatchDropConfirm.value = false;+ rpc.getObjectSource.mockImplementation(async (_id, _db, _owner, name) => {+ const info = trigger(name);+ if (gone.has(name)) {+ info.oracle_metadata!.objectId = null;+ info.oracle_metadata!.reads.identity = { state: "empty" };+ }+ return { name, schema: owner, object_type: "TRIGGER", source: gone.has(name) ? "" : "BEGIN NULL; END;", editable: false, trigger: info } as ObjectSource;+ });+ rpc.listTriggers.mockImplementation(async () => names.filter((name) => !gone.has(name)).map(trigger));+ rpc.buildDropObjectSql.mockImplementation(async (input) => `DROP TRIGGER ${quote(input.schema)}.${quote(input.name)};`);+ rpc.executeQuery.mockImplementation(async (_id, _db, sql) => {+ if (sql.startsWith("SELECT USER")) return { columns: ["SESSION_USER"], rows: [["Execution.Owner"]] };+ if (sql.includes("DBA_OBJECTS")) {+ if (denyGlobal) throw new Error("global dictionary denied");+ return { columns: ["OWNER", "OBJECT_NAME"], rows: [] };+ }+ if (sql.startsWith("SELECT")) return { columns: ["OWNER", "OBJECT_NAME", "OBJECT_TYPE", "OBJECT_ID"], rows: [[parent, "V", "VIEW", parentId]] };+ ddl.push(sql);+ if (sql.startsWith("DROP")) gone.add(names.find((name) => sql.includes(quote(name)))!);+ if (sql.endsWith(" ENABLE;")) enabled = true;+ return { columns: [], rows: [], affected_rows: 0 };+ });+});+afterEach(() => {+ for (const fn of cleanup.splice(0)) fn();+ useSqlExecutionDangerStore().cancelAll();+ useProductionSafetyStore().cancel();+ vi.restoreAllMocks();+ document.body.innerHTML = "";+});+async function mount(count = 1, searchProjection = false) {+ const store = useConnectionStore();+ store.connections = [configs];+ store.connectedIds.add(configs.id);+ const group: TreeNode = { id: "trigger-parent-group", label: "Triggers", type: "group-triggers", connectionId: configs.id, database: "service", schema: parent, tableName: "V", isExpanded: true };+ const nodes: TreeNode[] = names.slice(0, count).map((name) => ({ id: `trigger-node:${name}`, label: `${name} (display only)`, objectName: name, type: "trigger", connectionId: configs.id, database: "service", schema: owner, tableName: "V", meta: trigger(name) }));+ group.children = nodes;+ store.treeNodes = searchProjection ? [] : [group];+ const visibleNodes = ref(searchProjection ? [] : nodes);+ let removeSearchNode = (_node: TreeNode) => {};+ store.selectedTreeNodeId = nodes[0].id;+ store.selectedTreeNodeIds = nodes.map((node) => node.id);+ const component = ref<InstanceType<typeof SidebarTreeRuntimeHost> | null>(null);+ const dialogController = ref<Record<string, any>>();+ const openSource = vi.fn();+ const host = document.createElement("div");+ document.body.append(host);+ const app: App = createApp({+ setup() {+ if (searchProjection) {+ const query = ref("");+ const remote = useSidebarRemoteSearch({+ query,+ enabled: ref(true),+ context: [() => store.sidebarObjectSearchRevision],+ load: async () => [{ parentNodeId: group.id, nodeType: group.type, connectionId: configs.id, database: "service", schema: parent, children: nodes.filter((node) => !gone.has(node.objectName!)) }],+ onError: (error) => {+ throw error;+ },+ });+ watch(+ remote.results,+ (results) => {+ visibleNodes.value = results.flatMap((result) => result.children);+ },+ { flush: "sync" },+ );+ removeSearchNode = remote.removeVerifiedTriggerNode;+ query.value = "trigger";+ }+ return () =>+ h("div", [+ h(SidebarTreeRuntimeHost, {+ ref: component,+ node: group,+ depth: 0,+ onOpenObjectSource: openSource,+ onOpenDangerDialog: (next) => {+ request = next;+ },+ onOpenDialogController: (next) => {+ dialogController.value = next;+ },+ }),+ dialogController.value ? h(SidebarTreeItemDialogs, { controller: dialogController.value }) : null,+ ]);+ },+ });+ app.use(getActivePinia()!);+ app.use(i18n);+ if (searchProjection) app.provide(sidebarTreeContextKey, { getVisibleNodes: () => visibleNodes.value, getVisibleNodeIndex: (id) => visibleNodes.value.findIndex((node) => node.id === id), isSearchProjectionActive: () => true, removeVerifiedTriggerNode: (node) => removeSearchNode(node) });+ app.mount(host);+ let mounted = true;+ const unmount = () => {+ if (!mounted) return;+ mounted = false;+ app.unmount();+ host.remove();+ };+ cleanup.push(unmount);+ await nextTick();+ if (searchProjection) await vi.waitFor(() => expect(visibleNodes.value).toHaveLength(count));+ const buildMenu = (node: TreeNode) => (component.value as unknown as { buildContextMenu(node: TreeNode): ContextMenuItem[] }).buildContextMenu(node);+ return { store, nodes, group, visibleNodes, openSource, buildMenu, unmount, menu: buildMenu(nodes[0]) };+}+const flatten = (items: ContextMenuItem[]): ContextMenuItem[] => items.flatMap((item) => [item, ...flatten(item.children ?? [])]);++describe("exact trigger actions through the actual tree menu", () => {+ it.each(["contextMenu.enableTrigger", "processList.oracleInvalidObjects.compile", "delete"])("executes %s for an exact search-only result", async (label) => {+ const { menu, store, visibleNodes } = await mount(1, true);+ const pending = flatten(menu).find((item) => (label === "delete" ? item.variant === "destructive" : item.label === i18n.global.t(label)))!.action!();+ const danger = useSqlExecutionDangerStore();+ await vi.waitFor(() => expect(danger.pending).toBeDefined());+ danger.confirm();+ await pending;+ await vi.waitFor(() => expect(ddl).toHaveLength(1));+ expect(store.treeNodes).toEqual([]);+ expect(ddl).toHaveLength(1);+ expect(ddl[0]).toContain(quote(names[0]));+ if (label === "delete") await vi.waitFor(() => expect(visibleNodes.value).toEqual([]));+ if (label !== "contextMenu.enableTrigger") {+ const feedbackKey = label === "delete" ? "contextMenu.dropTableChildObjectSuccess" : "contextMenu.compileObjectSuccess";+ expect(i18n.global.te(feedbackKey)).toBe(true);+ await vi.waitFor(() => expect(useToast().message.value).toBe(i18n.global.t(feedbackKey, { name: names[0] })));+ }+ });++ it("deletes a search-only trigger batch through the original guarded sequence", async () => {+ const { menu, visibleNodes } = await mount(2, true);+ flatten(menu).find((item) => item.variant === "destructive")!.action!();+ await vi.waitFor(() => expect(request && !request.confirmDisabled).toBe(true));+ await request!.confirm();+ expect(ddl).toEqual(names.map((name) => `DROP TRIGGER ${quote(owner)}.${quote(name)};`));+ await vi.waitFor(() => expect(visibleNodes.value).toEqual([]));+ });++ it("retains a search-only result when deletion cannot be authoritatively verified", async () => {+ denyGlobal = true;+ const { menu, visibleNodes } = await mount(1, true);+ flatten(menu).find((item) => item.variant === "destructive")!.action!();+ const danger = useSqlExecutionDangerStore();+ await vi.waitFor(() => expect(danger.pending).toBeDefined());+ danger.confirm();+ await vi.waitFor(() => expect(showCompileErrorDialog.value).toBe(true));+ expect(visibleNodes.value).toHaveLength(1);+ expect(ddl).toEqual([`DROP TRIGGER ${quote(owner)}.${quote(names[0])};`]);+ });++ it("cancels an unissued search-only action when its projection disappears", async () => {+ const { menu, visibleNodes } = await mount(1, true);+ const pending = flatten(menu).find((item) => item.label === i18n.global.t("contextMenu.enableTrigger"))!.action!();+ const danger = useSqlExecutionDangerStore();+ await vi.waitFor(() => expect(danger.pending).toBeDefined());+ visibleNodes.value = [];+ danger.confirm();+ await pending;+ expect(ddl).toEqual([]);+ });++ it("does not dispatch a search-only deletion batch after the projection disappears", async () => {+ const { menu, visibleNodes } = await mount(2, true);+ flatten(menu).find((item) => item.variant === "destructive")!.action!();+ await vi.waitFor(() => expect(request && !request.confirmDisabled).toBe(true));+ visibleNodes.value = [];+ await request!.confirm();+ expect(ddl).toEqual([]);+ });++ it.each(["unmount", "selection"])("cancels the unissued batch production confirmation on %s", async (change) => {+ configs.is_production = true;+ const { menu, store, group, unmount } = await mount(2);+ flatten(menu).find((item) => item.variant === "destructive")!.action!();+ await vi.waitFor(() => expect(request && !request.confirmDisabled).toBe(true));+ const pending = request!.confirm();+ const production = useProductionSafetyStore();+ await vi.waitFor(() => expect(production.pending).toBeDefined());+ if (change === "unmount") unmount();+ else {+ store.selectedTreeNodeId = group.id;+ store.selectedTreeNodeIds = [group.id];+ }+ await vi.waitFor(() => expect(production.pending).toBeUndefined());+ await pending;+ expect(ddl).toEqual([]);+ expect(showCompileErrorDialog.value).toBe(false);+ });++ it("finishes the dispatched deletion on its fixed target but stops remaining batch objects after a UI selection change", async () => {+ const { menu, store, nodes, group } = await mount(2);+ const [first, second] = nodes;+ const execute = rpc.executeQuery.getMockImplementation()!;+ let finish!: () => void;+ rpc.executeQuery.mockImplementation(async (...args) => {+ const result = await execute(...args);+ if (args[2].startsWith("DROP") && ddl.length === 1)+ await new Promise<void>((resolve) => {+ finish = resolve;+ });+ return result;+ });+ flatten(menu).find((item) => item.variant === "destructive")!.action!();+ await vi.waitFor(() => expect(request && !request.confirmDisabled).toBe(true));+ const pending = request!.confirm();+ await vi.waitFor(() => expect(finish).toBeDefined());+ store.selectedTreeNodeId = group.id;+ store.selectedTreeNodeIds = [group.id];+ finish();+ await pending;+ expect(ddl).toEqual([`DROP TRIGGER ${quote(owner)}.${quote(names[0])};`]);+ expect(store.treeNodes[0].children?.some((node) => node.id === first.id)).toBe(false);+ expect(store.treeNodes[0].children?.some((node) => node.id === second.id)).toBe(true);+ expect(compileErrorMessage.value).toContain(i18n.global.t("oceanbasePrimaryKey.notExecuted"));+ expect(compileErrorMessage.value).not.toContain(i18n.global.t("oceanbasePrimaryKey.unknown"));+ });++ it("reviews a trigger deletion batch once in the production guard, with both confirmed SQL statements", async () => {+ configs.is_production = true;+ const { menu } = await mount(2);+ flatten(menu).find((item) => item.variant === "destructive")!.action!();+ await vi.waitFor(() => expect(request && !request.confirmDisabled).toBe(true));+ const production = useProductionSafetyStore();+ let settled = false;+ const pending = Promise.resolve(request!.confirm()).finally(() => {+ settled = true;+ });+ const reviews: string[] = [];+ for (let index = 0; index < 3 && !settled; index++) {+ await vi.waitFor(() => expect(settled || !!production.pending).toBe(true));+ if (production.pending) {+ reviews.push(production.pending.sql);+ production.confirm();+ }+ }+ await pending;+ expect(reviews).toHaveLength(1);+ expect(reviews[0]).toContain(quote(names[0]));+ expect(reviews[0]).toContain(quote(names[1]));+ expect(ddl).toHaveLength(2);+ });++ it("keeps batch unknown nodes and pins, then removes only the read-only verified deletion without replay", async () => {+ denyGlobal = true;+ const { menu, store, nodes } = await mount(2);+ const [first, second] = nodes;+ nodes.forEach((node) => store.toggleTreeNodePin(node));+ flatten(menu).find((item) => item.variant === "destructive")!.action!();+ await vi.waitFor(() => expect(request && !request.confirmDisabled).toBe(true));+ await request!.confirm();+ expect(ddl).toEqual([`DROP TRIGGER ${quote(owner)}.${quote(names[0])};`]);+ expect(store.isTreeNodePinned(first)).toBe(true);+ expect(store.isTreeNodePinned(second)).toBe(true);+ await nextTick();+ const verify = () => [...document.querySelectorAll<HTMLButtonElement>("button")].find((button) => button.textContent?.trim() === i18n.global.t("oracleTrigger.verifyReadOnly"));+ expect(verify()).toBeDefined();+ denyGlobal = false;+ verify()!.click();+ await vi.waitFor(() =>+ expect(+ store.treeNodes[0].children?.some((node) => node.id === first.id),+ compileErrorMessage.value,+ ).toBe(false),+ );+ expect(store.treeNodes[0].children?.some((node) => node.id === second.id)).toBe(true);+ expect(store.isTreeNodePinned(first)).toBe(false);+ expect(store.isTreeNodePinned(second)).toBe(true);+ await request!.confirm();+ expect(ddl).toHaveLength(1);+ });++ it("keeps a recreated row and its pin when the original batch deletion was verified before cache cleanup", async () => {+ const { menu, store, nodes } = await mount(2);+ const first = nodes[0];+ store.toggleTreeNodePin(first);+ let replaced = false;+ rpc.deleteSchemaCachePrefix.mockImplementation(async () => {+ if (!replaced && ddl.length) {+ replaced = true;+ gone.delete(names[0]);+ objectIds.set(names[0], "recreated-after-verify");+ const live = store.treeNodes[0].children!.find((node) => node.id === first.id)!;+ const meta = JSON.parse(JSON.stringify(live.meta)) as TriggerInfo;+ meta.oracle_metadata!.objectId = "recreated-after-verify";+ live.meta = meta;+ }+ });+ flatten(menu).find((item) => item.variant === "destructive")!.action!();+ await vi.waitFor(() => expect(request && !request.confirmDisabled).toBe(true));+ await request!.confirm();+ const live = store.treeNodes[0].children!.find((node) => node.id === first.id);+ expect((live?.meta as TriggerInfo | undefined)?.oracle_metadata?.objectId).toBe("recreated-after-verify");+ expect(store.isTreeNodePinned(first)).toBe(true);+ expect(ddl).toHaveLength(1);+ });++ it.each(["dialog", "query-tab"] as const)("opens DM8 trigger dependencies in the existing %s container without a general query or DDL", async (mode) => {+ configs.db_type = "dameng";+ useSettingsStore().editorSettings.routineSourceOpenMode = mode;+ const { menu, openSource } = await mount();+ const dependencies = flatten(menu).find((item) => item.label === i18n.global.t("contextMenu.viewDependencies"));+ expect(dependencies).toBeDefined();+ await dependencies!.action!();+ if (mode === "dialog") expect(openSource).toHaveBeenCalledWith(expect.objectContaining({ type: "trigger", schema: owner, objectName: names[0], meta: expect.objectContaining({ oracle_metadata: expect.objectContaining({ engine: "dm" }) }) }), false, "dependencies");+ else {+ const store = useQueryStore();+ await vi.waitFor(() => expect(store.tabs.some((tab) => tab.objectSource?.name === names[0])).toBe(true), { timeout: 30_000 });+ const tab = store.tabs.find((item) => item.objectSource?.name === names[0])!;+ expect(tab.objectDetails).toMatchObject({ schema: owner, name: names[0], objectType: "TRIGGER", section: "dependencies" });+ expect(store.oracleTriggerSourceState(tab.id)?.baseline?.metadata.engine).toBe("dm");+ }+ expect(ddl).toEqual([]);+ expect(rpc.executeQuery).not.toHaveBeenCalled();+ });++ it("does not replace the displayed physical identity from a mismatched post-compile snapshot", async () => {+ const { menu, store, nodes } = await mount();+ const source = rpc.getObjectSource.getMockImplementation()!;+ rpc.getObjectSource.mockImplementation(async (...args) => {+ const result = await source(...args);+ if (ddl.length) result.trigger!.oracle_metadata!.objectId = "replacement-id";+ return result;+ });+ const pending = flatten(menu).find((item) => item.label === i18n.global.t("processList.oracleInvalidObjects.compile"))!.action!();+ const danger = useSqlExecutionDangerStore();+ await vi.waitFor(() => expect(danger.pending).toBeDefined());+ danger.confirm();+ await pending;+ expect(showCompileErrorDialog.value).toBe(true);+ expect(compileErrorMessage.value).toContain("mismatch");+ const live = store.treeNodes[0].children!.find((node) => node.id === nodes[0].id)!;+ expect((live.meta as TriggerInfo).oracle_metadata?.objectId).toBe("9007199254740993");+ expect(ddl).toHaveLength(1);+ expect(rpc.listTriggers).not.toHaveBeenCalled();+ });++ it.each(["contextMenu.enableTrigger", "processList.oracleInvalidObjects.compile"])("rejects a same-name replacement before confirming %s", async (label) => {+ const { menu } = await mount();+ const source = rpc.getObjectSource.getMockImplementation()!;+ rpc.getObjectSource.mockImplementation(async (...args) => {+ const result = await source(...args);+ result.trigger.oracle_metadata.objectId = "replacement-id";+ return result;+ });+ let settled = false;+ const pending = Promise.resolve(flatten(menu).find((item) => item.label === i18n.global.t(label))!.action!()).finally(() => {+ settled = true;+ });+ const danger = useSqlExecutionDangerStore();+ await vi.waitFor(() => expect(settled || !!danger.pending).toBe(true));+ expect(danger.pending).toBeUndefined();+ await pending;+ expect(ddl).toEqual([]);+ });++ it("cancels a pending trigger confirmation when the tree host unmounts", async () => {+ const { menu, unmount } = await mount();+ const pending = flatten(menu).find((item) => item.label === i18n.global.t("contextMenu.enableTrigger"))!.action!();+ const danger = useSqlExecutionDangerStore();+ await vi.waitFor(() => expect(danger.pending).toBeDefined());+ unmount();+ await nextTick();+ expect(danger.pending).toBeUndefined();+ await pending;+ expect(ddl).toEqual([]);+ });++ it.each(["deleted", "parent-replaced", "trigger-replaced"])("retains an unverified deletion and reconciles it without replay (%s)", async (after) => {+ denyGlobal = true;+ const { menu, store, nodes } = await mount();+ flatten(menu).find((item) => item.variant === "destructive")!.action!();+ const danger = useSqlExecutionDangerStore();+ await vi.waitFor(() => expect(danger.pending).toBeDefined());+ danger.confirm();+ await vi.waitFor(() => expect(showCompileErrorDialog.value).toBe(true));+ expect(store.treeNodes[0].children?.some((node) => node.id === nodes[0].id)).toBe(true);+ await nextTick();+ const verify = [...document.querySelectorAll("button")].find((button) => button.textContent?.trim() === i18n.global.t("oracleTrigger.verifyReadOnly"));+ expect(verify).toBeDefined();+ denyGlobal = false;+ if (after === "parent-replaced") parentId = "new-parent-id";+ if (after === "trigger-replaced") gone.delete(names[0]);+ verify!.click();+ await vi.waitFor(() => expect(verify!.getAttribute("aria-busy")).not.toBe("true"));+ await vi.waitFor(() => expect(compileErrorMessage.value).toContain(after === "deleted" ? i18n.global.t("processList.oracleInvalidObjects.batchStatus.deleted") : after === "parent-replaced" ? "owning object changed" : "trigger still exists"));+ expect(store.treeNodes[0].children?.some((node) => node.id === nodes[0].id)).toBe(after !== "deleted");+ expect(ddl).toEqual([`DROP TRIGGER ${quote(owner)}.${quote(names[0])};`]);+ });++ it("finishes the original readback without reopening a dialog after an in-flight compile unmounts", async () => {+ invalid = true;+ const { menu, unmount } = await mount();+ const execute = rpc.executeQuery.getMockImplementation()!;+ let release!: () => void;+ const gate = new Promise<void>((resolve) => {+ release = resolve;+ });+ let dispatched = false;+ rpc.executeQuery.mockImplementation(async (...args) => {+ if (!args[2].startsWith("SELECT")) {+ dispatched = true;+ await gate;+ }+ return execute(...args);+ });+ const pending = flatten(menu).find((item) => item.label === i18n.global.t("processList.oracleInvalidObjects.compile"))!.action!();+ const danger = useSqlExecutionDangerStore();+ await vi.waitFor(() => expect(danger.pending).toBeDefined());+ danger.confirm();+ await vi.waitFor(() => expect(dispatched).toBe(true));+ unmount();+ release();+ await pending;+ expect(ddl).toEqual([`ALTER TRIGGER ${quote(owner)}.${quote(names[0])} COMPILE`]);+ expect(rpc.getObjectSource.mock.calls.at(-1)?.slice(0, 5)).toEqual([configs.id, "service", owner, names[0], "TRIGGER"]);+ expect(rpc.listTriggers).not.toHaveBeenCalled();+ expect(showCompileErrorDialog.value).toBe(false);+ });++ it("opens creation from an empty Schema trigger group without requiring an existing trigger", async () => {+ const { store, group, buildMenu, openSource } = await mount();+ group.children = [];+ group.tableName = undefined;+ group.schema = owner;+ store.selectedTreeNodeId = group.id;+ store.selectedTreeNodeIds = [group.id];+ const create = flatten(buildMenu(group)).find((item) => item.label === i18n.global.t("contextMenu.createTrigger"));+ expect(create).toBeDefined();+ await create!.action!();+ expect(openSource).toHaveBeenCalledWith(expect.objectContaining({ type: "trigger", schema: owner, objectName: "TRG_NEW" }), true, undefined, expect.objectContaining({ target: expect.objectContaining({ id: group.id, type: "group-triggers" }), payload: { scope: "TABLE" } }));+ expect(ddl).toEqual([]);+ expect(rpc.getObjectSource).not.toHaveBeenCalled();+ });++ it("uses the raw trigger owner and refreshes its independent parent after native enable", async () => {+ const { menu } = await mount();+ const pending = flatten(menu).find((item) => item.label === i18n.global.t("contextMenu.enableTrigger"))!.action!();+ const danger = useSqlExecutionDangerStore();+ await vi.waitFor(() => expect(danger.pending).toBeDefined());+ expect(danger.pending?.sql).toBe(`ALTER TRIGGER ${quote(owner)}.${quote(names[0])} ENABLE;`);+ danger.confirm();+ await pending;+ expect(ddl).toEqual([`ALTER TRIGGER ${quote(owner)}.${quote(names[0])} ENABLE;`]);+ expect(rpc.listTriggers).toHaveBeenCalledWith(configs.id, "service", parent, "V", undefined, { identityMode: "exact" });+ });++ it.each(["dialog", "query-tab"] as const)("shows real INVALID diagnostics and opens the fixed source target in %s mode", async (mode) => {+ invalid = true;+ useSettingsStore().editorSettings.routineSourceOpenMode = mode;+ const { menu, store, group, openSource } = await mount();+ const pending = flatten(menu).find((item) => item.label === i18n.global.t("processList.oracleInvalidObjects.compile"))!.action!();+ const danger = useSqlExecutionDangerStore();+ await vi.waitFor(() => expect(danger.pending).toBeDefined());+ danger.confirm();+ await pending;+ expect(ddl).toEqual([`ALTER TRIGGER ${quote(owner)}.${quote(names[0])} COMPILE`]);+ expect(showCompileErrorDialog.value).toBe(true);+ expect(compileErrorMessage.value).toContain("Missing procedure");+ expect(enabled).toBe(false);+ store.selectedTreeNodeId = group.id;+ store.selectedTreeNodeIds = [group.id];+ await nextTick();+ const source = [...document.querySelectorAll("button")].find((button) => button.textContent?.trim() === i18n.global.t("contextMenu.viewSource"));+ expect(source).toBeDefined();+ source!.click();+ await nextTick();+ if (mode === "dialog") expect(openSource).toHaveBeenCalledWith(expect.objectContaining({ type: "trigger", schema: owner, objectName: names[0] }), false, undefined);+ else await vi.waitFor(() => expect(useQueryStore().tabs.some((tab) => tab.objectSource?.schema === owner && tab.objectSource.name === names[0])).toBe(true));+ expect(showCompileErrorDialog.value).toBe(false);+ expect(ddl).toHaveLength(1);+ });++ it.each([true, false])("stops remaining confirmed batch targets only when deletion is unverified (global denied=%s)", async (denied) => {+ denyGlobal = denied;+ const { menu } = await mount(2);+ flatten(menu).find((item) => item.variant === "destructive")!.action!();+ await vi.waitFor(() => expect(request && !request.confirmDisabled && request.sql?.includes(quote(names[1]))).toBe(true));+ await request!.confirm();+ expect(ddl).toEqual((denied ? names.slice(0, 1) : names).map((name) => `DROP TRIGGER ${quote(owner)}.${quote(name)};`));+ if (denied) {+ expect(compileErrorMessage.value).toContain("global dictionary denied");+ expect(compileErrorMessage.value).toContain(i18n.global.t("oceanbasePrimaryKey.notExecuted"));+ }+ });+});diff --git a/apps/desktop/src/components/sidebar/__tests__/TreeItem.mqttI18n.spec.ts b/apps/desktop/src/components/sidebar/__tests__/TreeItem.mqttI18n.spec.tsindex 28872a0e56..bbf7efc65d 100644--- a/apps/desktop/src/components/sidebar/__tests__/TreeItem.mqttI18n.spec.ts+++ b/apps/desktop/src/components/sidebar/__tests__/TreeItem.mqttI18n.spec.ts@@ -67,7 +67,7 @@ function runtimeHost(): SidebarTreeRuntimeHost {};}-async function mountMqttConsoleNode() {+async function mountMqttConsoleNode(override?: Partial<TreeNode>) {const container = document.createElement("div");document.body.append(container);const node: TreeNode = {@@ -76,6 +76,7 @@ async function mountMqttConsoleNode() {type: "mqtt-topic",connectionId: "mqtt-1",children: [],+ ...override,};const runtime = createSidebarTreeRuntime();runtime.bindHost(runtimeHost());@@ -115,4 +116,15 @@ describe("TreeItem MQTT console i18n", () => {expect(row.textContent).toContain("MQTT 控制台");expect(row.textContent).not.toContain("MQTT Console");});++ it("translates the native Job entry in an existing tree", async () => {+ await setLocale("zh-CN");+ const row = await mountMqttConsoleNode({ id: "ob-1:__native_jobs", type: "database-job-admin", label: "tree.nativeJobs" });+ expect(row.textContent).toContain("原生作业");+ expect(row.textContent).not.toContain("tree.nativeJobs");+ await setLocale("en");+ await nextTick();+ expect(row.textContent).not.toContain("tree.nativeJobs");+ expect(row.textContent).not.toContain("原生作业");+ });});diff --git a/apps/desktop/src/components/structure/TableStructureEditor.charsetCollation.spec.ts b/apps/desktop/src/components/structure/TableStructureEditor.charsetCollation.spec.tsindex a76394ee00..f827d05fde 100644--- a/apps/desktop/src/components/structure/TableStructureEditor.charsetCollation.spec.ts+++ b/apps/desktop/src/components/structure/TableStructureEditor.charsetCollation.spec.ts@@ -28,7 +28,7 @@ const mocks = vi.hoisted(() => ({toast: vi.fn(),}));-vi.mock("vue-i18n", () => ({ useI18n: () => ({ t: (key: string) => key }) }));+vi.mock("vue-i18n", async (original) => ({ ...(await original<typeof import("vue-i18n")>()), useI18n: () => ({ t: (key: string) => key }) }));vi.mock("@lucide/vue", async () => {const { defineComponent, h } = await import("vue");diff --git a/apps/desktop/src/components/structure/TableStructureEditor.primaryKey.spec.ts b/apps/desktop/src/components/structure/TableStructureEditor.primaryKey.spec.tsindex 6b1e571960..d14f9268a3 100644--- a/apps/desktop/src/components/structure/TableStructureEditor.primaryKey.spec.ts+++ b/apps/desktop/src/components/structure/TableStructureEditor.primaryKey.spec.ts@@ -34,7 +34,7 @@ const mocks = vi.hoisted(() => ({toast: vi.fn(),}));-vi.mock("vue-i18n", () => ({ useI18n: () => ({ t: (key: string) => key }) }));+vi.mock("vue-i18n", async (original) => ({ ...(await original<typeof import("vue-i18n")>()), useI18n: () => ({ t: (key: string) => key }) }));vi.mock("@lucide/vue", async () => {const { defineComponent, h } = await import("vue");diff --git a/apps/desktop/src/components/structure/TableStructureEditor.vue b/apps/desktop/src/components/structure/TableStructureEditor.vueindex c8b0577449..39016fdc4b 100644--- a/apps/desktop/src/components/structure/TableStructureEditor.vue+++ b/apps/desktop/src/components/structure/TableStructureEditor.vue@@ -7,18 +7,33 @@ import { getColumnDefaultValuePresets } from "@/lib/table/columnDefaultPresets";import { applyDdlStoragePreference } from "@/lib/sql/ddlStorage";import { compactDdlSql } from "@/lib/sql/ddlCompact";import DdlStorageToggle from "@/components/objects/DdlStorageToggle.vue";+import { exactOracleTriggerMetadata, oracleTriggerReadOptions } from "@/lib/database/oracleTriggerIdentity";+import { executeOracleTriggerStructurePlan, readOracleTriggerSource, verifyOracleTriggerDeletion, type OracleTriggerExecutionResult, type OracleTriggerSnapshot, type OracleTriggerTarget } from "@/lib/database/oracleTriggerPlan";+import { prepareOracleTriggerStructurePlan, reconcileOracleTriggerStructureDraft, type OracleTriggerStructurePlan } from "@/lib/database/oracleTriggerStructurePlan";+import { inspectExactOracleTriggerSource } from "@/lib/table/objectSourceLoad";import StructureIndexColumnPicker from "./StructureIndexColumnPicker.vue";import TableColumnPasteDialog from "./TableColumnPasteDialog.vue";import { createPastedColumnDrafts, parseTableColumnDefinitions } from "@/lib/table/tableColumnDefinitionPaste";import { resolveNextEditorToolbarTier, type EditorToolbarTier } from "@/lib/tabs/editorToolbarLayout";import DangerConfirmDialog from "@/components/editor/DangerConfirmDialog.vue";import { executeOceanbasePrimaryKeyPlan, readOceanbasePrimaryKeySnapshot, prepareOraclePrimaryKeyChange, OceanbasePrimaryKeyValidationError, type ExistingPrimaryKeyChange, type OceanbasePrimaryKeyPlan, type PrimaryKeyTarget } from "@/lib/database/oceanbasePrimaryKey";-import { executeOracleForeignKeyCreatePlan, executeOracleForeignKeyPlan, prepareOracleForeignKeyCreatePlan, prepareOracleForeignKeyPlan, readOracleForeignKeyDefinitions, type OracleForeignKeyCreatePlan, type OracleForeignKeyPlan } from "@/lib/database/oracleForeignKeys";+import {+ executeOracleForeignKeyCreatePlan,+ executeOracleForeignKeyPlan,+ preflightOracleForeignKeyCreatePlan,+ prepareOracleForeignKeyCreatePlan,+ prepareOracleForeignKeyPlan,+ readOracleForeignKeyCreateResult,+ readOracleForeignKeyDefinitions,+ type OracleForeignKeyCreatePlan,+ type OracleForeignKeyCreateExecutionResult,+ type OracleForeignKeyPlan,+} from "@/lib/database/oracleForeignKeys";import { executeOracleConstraintPlan, oracleConstraintDefinitionFromInfo, prepareOracleConstraintPlan, type OracleConstraintPlan, type OracleConstraintTarget } from "@/lib/database/oracleConstraints";import { executeOracleIndexPlan, mergeOracleIndexDraftsAfterRefresh, oracleIndexSnapshotMatchesLoaded, oracleIndexSnapshotMatchesLoadedColumns, prepareOracleIndexPlan, type OracleIndexDefinition, type OracleIndexLoadBaseline, type OracleIndexPlan } from "@/lib/database/oracleIndexes";import { readOracleIndexSnapshot } from "@/lib/database/oracleConstraints";-import { computed, nextTick, onActivated, onBeforeUnmount, onDeactivated, onMounted, ref, shallowRef, watch } from "vue";+import { computed, defineAsyncComponent, nextTick, onActivated, onBeforeUnmount, onDeactivated, onMounted, ref, shallowRef, watch } from "vue";import { uuid } from "@/lib/common/utils";import { useI18n } from "vue-i18n";import { RecycleScroller } from "vue-virtual-scroller";@@ -75,6 +90,7 @@ import { useProductionSafetyStore } from "@/stores/productionSafetyStore";import { productionContextForDatabase } from "@/lib/database/productionSafety";import { useQueryStore } from "@/stores/queryStore";import { useHistoryStore } from "@/stores/historyStore";+import { useSqlExecutionDangerStore } from "@/stores/sqlExecutionDangerStore";import { matchesShortcut } from "@/lib/editor/keyboardShortcuts";import { selectLineEndsDefaultShortcut, shortcutToCodeMirrorKey } from "@/lib/editor/shortcutRegistry";import { selectLineEnds } from "@/lib/editor/selectLineEnds";@@ -135,7 +151,7 @@ import { sortStructureIndexesByColumns, type StructureIndexColumnSort } from "@/import { getConcurrentIndexAvailability, concurrentIndexNamesInStatements, normalizeUnsupportedConcurrentIndexes, type ConcurrentIndexAvailability } from "@/lib/table/concurrentIndexAvailability";import { orderedColumnIndexes, uniqueDataGridColumnOrderKeys } from "@/lib/dataGrid/dataGridColumnOrder";import { loadTableDataGridColumnOrder, notifyTableDataGridColumnOrderChanged, removeTableDataGridColumnOrder, saveTableDataGridColumnOrder, tableDataGridColumnOrderScopeKey } from "@/lib/dataGrid/dataGridColumnLayoutStorage";-import { codeMirrorSqlDialectForConnection, connectionObjectTreeQuerySchema, connectionUsesDatabaseObjectTreeMode, tableStructureDatabaseTypeForConnection } from "@/lib/database/jdbcDialect";+import { codeMirrorSqlDialect, codeMirrorSqlDialectForConnection, connectionObjectTreeQuerySchema, connectionUsesDatabaseObjectTreeMode, tableStructureDatabaseTypeForConnection } from "@/lib/database/jdbcDialect";import { postgresListRolesSql, usersFromPostgresRolesResult } from "@/lib/database/databaseUserAdmin";import type { CatalogInfo, ColumnInfo, ConnectionConfig, ConstraintInfo, PgPartitionKind, PgPartitionNode, PgTablePartitioning, TableInfo, TableInfoTab, TableStructureEditorDraft, TableStructureEditorTarget, TableStructureEditorViewport } from "@/types/database";import {@@ -203,6 +219,7 @@ import type { CreateDatabaseCharsetMetadata } from "@/lib/database/createDatabasimport * as api from "@/lib/backend/api";import { EditorView } from "@codemirror/view";+const ObjectSourceDialog = defineAsyncComponent(() => import("@/components/objects/ObjectSourceDialog.vue"));const { t } = useI18n();const { isDark, themePalette } = useTheme();const store = useConnectionStore();@@ -253,6 +270,8 @@ const previewSqlText = computed(() => joinSqlStatementsForScript(pendingStatemenconst props = defineProps<{connectionId: string;+ /** Result/draft ownership when a dispatched sequence outlives the visible tab. */+ originTabId?: string;database: string;catalog?: string;schema?: string;@@ -267,8 +286,8 @@ const props = defineProps<{}>();const emit = defineEmits<{- "update:draft": [draft: TableStructureEditorDraft | undefined];- saved: [commentChanged: boolean, createdTableName?: string];+ "update:draft": [draft: TableStructureEditorDraft | undefined, originTabId?: string];+ saved: [commentChanged: boolean, createdTableName?: string, originTabId?: string];close: [];openSettings: [initialTab?: string, initialSection?: string];/** Jump from the DDL view to the table's data tab (issue #6724). */@@ -997,6 +1016,107 @@ const triggersLoaded = ref(false);// selected trigger's editors render in the detail pane below (#8822).const selectedTriggerId = ref<string | null>(null);const selectedTrigger = computed(() => triggers.value.find((trigger) => trigger.id === selectedTriggerId.value) ?? null);+const triggerSourceOpen = ref(false);+const triggerSourceDialog = ref<InstanceType<typeof ObjectSourceDialog>>();+const triggerSourceTarget = shallowRef<{ draftId: string; loadedDraft: string; dirtyAtOpen: boolean; didWrite: boolean; tableKey: string; target: OracleTriggerTarget }>();+const triggerSourceRefreshRequired = ref(new Set<string>());+const triggerStructurePlan = shallowRef<OracleTriggerStructurePlan>();+const triggerStructureRecovery = ref<TableStructureEditorDraft["oracleTriggerStructureRecovery"]>();+let triggerStructureFingerprint = "";+const triggerStructureActive = ref(true);+let triggerStructureConfirmationScope: string | undefined;+function cancelTriggerStructureConfirmation() {+ if (!triggerStructureConfirmationScope) return;+ useSqlExecutionDangerStore().cancelScope(triggerStructureConfirmationScope);+ productionSafetyStore.cancelScope(triggerStructureConfirmationScope);+}+const triggerStructureKey = () => JSON.stringify([props.connectionId, props.database, props.catalog, props.schema, props.tableName]);+const triggerSourceKey = (target: Readonly<OracleTriggerTarget>) => JSON.stringify([target.connectionId, target.database, target.catalog, target.owner, target.name, target.executionSchema]);+let triggerBaselineRequest = 0;+watch(+ () => [triggerStructureKey(), selectedTrigger.value?.original] as const,+ async () => {+ const request = ++triggerBaselineRequest;+ const trigger = selectedTrigger.value;+ const metadata = exactOracleTriggerMetadata(trigger?.original);+ if (!trigger || !metadata || trigger.loadedOracleSource !== undefined) return;+ const key = triggerStructureKey();+ try {+ const loaded = await readOracleTriggerSource({ connectionId: props.connectionId, database: props.database, catalog: props.catalog, owner: metadata.owner, name: metadata.name, executionSchema: props.schema || metadataSchema.value! });+ if (request !== triggerBaselineRequest || key !== triggerStructureKey() || !triggers.value.includes(trigger)) return;+ if (!loaded.snapshot?.exists || loaded.snapshot.metadata.objectId !== metadata.objectId) throw new Error(t("oracleTrigger.reloadBaseline"));+ if (triggerChanged(trigger) && (trigger.name !== trigger.original!.name || trigger.statement !== trigger.original!.statement || trigger.timing !== trigger.original!.timing || trigger.event !== trigger.original!.event)) throw new Error(t("oracleTrigger.reloadBaseline"));+ const inspected = await inspectExactOracleTriggerSource(loaded.snapshot.raw, metadata.owner, metadata.name);+ if (request !== triggerBaselineRequest || key !== triggerStructureKey() || !triggers.value.includes(trigger)) return;+ trigger.loadedOracleSource = loaded.snapshot.raw.source;+ trigger.loadedOracleStructured = inspected.triggerSource.complete && inspected.triggerSource.prepared?.structuredEditable === true;+ syncDraftToParent();+ } catch (error) {+ if (request === triggerBaselineRequest && key === triggerStructureKey()) errorMessage.value = error instanceof Error ? error.message : String(error);+ }+ },+);+watch(triggerStructureKey, () => {+ triggerSourceOpen.value = false;+ triggerSourceRefreshRequired.value.clear();+});++function openTriggerFullSource(trigger: EditableStructureTrigger) {+ const metadata = exactOracleTriggerMetadata(trigger.original);+ if (!metadata || !oracleTriggerReadOptions(databaseType.value)) return;+ const next = { connectionId: props.connectionId, database: props.database, catalog: props.catalog, owner: metadata.owner, name: metadata.name, executionSchema: props.schema || metadataSchema.value };+ if (triggerSourceTarget.value && triggerSourceKey(triggerSourceTarget.value.target) !== triggerSourceKey(next) && triggerSourceDialog.value?.hasUnsavedDraft() && !window.confirm(t("objects.refreshDiscardConfirm"))) return;+ triggerSourceTarget.value = { draftId: trigger.id, loadedDraft: JSON.stringify(trigger), dirtyAtOpen: triggerChanged(trigger), didWrite: false, tableKey: triggerStructureKey(), target: next };+ triggerSourceOpen.value = true;+}++function mergeTriggerSourceSnapshot(snapshot: OracleTriggerSnapshot) {+ const context = triggerSourceTarget.value;+ if (!context || !context.didWrite || context.tableKey !== triggerStructureKey() || triggerSourceKey(snapshot.target) !== triggerSourceKey(context.target)) return;+ const index = triggers.value.findIndex((trigger) => trigger.id === context.draftId);+ if (index < 0) return;+ if (!snapshot.exists || !snapshot.raw.trigger || context.dirtyAtOpen || JSON.stringify(triggers.value[index]) !== context.loadedDraft) {+ triggerSourceRefreshRequired.value.add(context.draftId);+ errorMessage.value = `${context.target.owner}.${context.target.name}: ${t("oracleTrigger.reloadBaseline")}`;+ return;+ }+ const updated = { ...createTriggerDrafts([snapshot.raw.trigger])[0]!, id: context.draftId };+ triggers.value.splice(index, 1, updated);+ context.loadedDraft = JSON.stringify(updated);+ triggerSourceRefreshRequired.value.delete(context.draftId);+ scheduleSqlPreviewRefresh();+}++function recordTriggerSourceResult(target: Readonly<OracleTriggerTarget>, result: OracleTriggerExecutionResult) {+ const context = triggerSourceTarget.value;+ if (!context || context.tableKey !== triggerStructureKey() || triggerSourceKey(target) !== triggerSourceKey(context.target) || result.cancelled || !result.steps.some((step) => step.state !== "notExecuted")) return;+ context.didWrite = true;+ if (result.snapshot) mergeTriggerSourceSnapshot(result.snapshot);+ else {+ triggerSourceRefreshRequired.value.add(context.draftId);+ errorMessage.value = `${target.owner}.${target.name}: ${t("oracleTrigger.reloadBaseline")}`;+ }+}++async function reloadTriggerDraftAfterSource(trigger: EditableStructureTrigger) {+ const metadata = exactOracleTriggerMetadata(trigger.original);+ if (!metadata || (triggerChanged(trigger) && !window.confirm(t("oracleTrigger.refreshDraftConfirm")))) return;+ const key = triggerStructureKey();+ const previous = JSON.stringify(trigger);+ try {+ const loaded = await readOracleTriggerSource({ connectionId: props.connectionId, database: props.database, catalog: props.catalog, owner: metadata.owner, name: metadata.name, executionSchema: props.schema || metadataSchema.value });+ if (key !== triggerStructureKey()) return;+ const index = triggers.value.findIndex((item) => item.id === trigger.id);+ if (index < 0 || JSON.stringify(triggers.value[index]) !== previous) return;+ if (!loaded.snapshot?.exists || !loaded.snapshot.raw.trigger) throw new Error(loaded.identityError || t("oracleTrigger.reloadBaseline"));+ triggers.value.splice(index, 1, { ...createTriggerDrafts([loaded.snapshot.raw.trigger])[0]!, id: trigger.id });+ triggerSourceRefreshRequired.value.delete(trigger.id);+ errorMessage.value = "";+ scheduleSqlPreviewRefresh();+ } catch (error) {+ if (key === triggerStructureKey()) errorMessage.value = error instanceof Error ? error.message : String(error);+ }+}// Inline rename state: the list row itself stays a click-to-select target;// the pencil button flips the name cell into an input (#8822 feedback).const renamingTriggerId = ref<string | null>(null);@@ -2222,6 +2342,7 @@ const primaryKeyConfirmationScope = `structure-primary-key:${uuid()}`;const oracleForeignKeyConfirmationScope = `structure-oracle-foreign-key:${uuid()}`;onBeforeUnmount(() => {primaryKeyUnmounted = true;+ cancelTriggerStructureConfirmation();if (primaryKeyBusy.value) productionSafetyStore.cancelScope(primaryKeyConfirmationScope);if (saving.value) productionSafetyStore.cancelScope(oracleForeignKeyConfirmationScope);if (saving.value) productionSafetyStore.cancelScope(oracleConstraintConfirmationScope);@@ -2820,7 +2941,7 @@ function onStructureContentScroll(tab: TableInfoTab, event: Event) {function createCurrentDraft(initialized = true): TableStructureEditorDraft {return {- dirty: hasPendingStructureChanges() || ddlDirty.value,+ dirty: !!triggerStructureRecovery.value || hasPendingStructureChanges() || ddlDirty.value,activeTab: activeTab.value as TableStructureEditorDraft["activeTab"],ddlDraft: ddlDraft.value,// Only carried alongside an actual edit: without a draft the baseline is@@ -2853,6 +2974,7 @@ function createCurrentDraft(initialized = true): TableStructureEditorDraft {existingPrimaryKey: existingPrimaryKeyDraft.value ? cloneDraftValue(existingPrimaryKeyDraft.value) : undefined,oracleConstraintChange: oracleConstraintDraft.value ? cloneDraftValue(oracleConstraintDraft.value) : undefined,oracleForeignKeyCreateRecovery: oracleForeignKeyCreateRecovery.value ? cloneDraftValue(oracleForeignKeyCreateRecovery.value) : undefined,+ oracleTriggerStructureRecovery: triggerStructureRecovery.value ? cloneDraftValue(triggerStructureRecovery.value) : undefined,constraintsLoaded: constraintsLoaded.value,triggers: cloneDraftValue(triggers.value),triggersLoaded: triggersLoaded.value,@@ -2870,9 +2992,9 @@ function createCurrentDraft(initialized = true): TableStructureEditorDraft {};}-function emitDraftToParent(draft: TableStructureEditorDraft | undefined) {- lastSyncedDraft = draft;- emit("update:draft", draft);+function emitDraftToParent(draft: TableStructureEditorDraft | undefined, originTabId?: string) {+ if (originTabId === undefined || originTabId === props.originTabId) lastSyncedDraft = draft;+ emit("update:draft", draft, originTabId);}function syncStructureScrollDraftToParent() {@@ -2963,6 +3085,7 @@ function restoreDraft(draft: TableStructureEditorDraft) {existingPrimaryKeyDraft.value = draft.existingPrimaryKey ? cloneDraftValue(draft.existingPrimaryKey) : undefined;oracleConstraintDraft.value = draft.oracleConstraintChange ? cloneDraftValue(draft.oracleConstraintChange) : undefined;oracleForeignKeyCreateRecovery.value = draft.oracleForeignKeyCreateRecovery ? cloneDraftValue(draft.oracleForeignKeyCreateRecovery) : undefined;+ triggerStructureRecovery.value = draft.oracleTriggerStructureRecovery ? cloneDraftValue(draft.oracleTriggerStructureRecovery) : undefined;if (oracleForeignKeyCreateRecovery.value) {primaryKeyResultTitle.value = "oracleForeignKey.resultTitle";primaryKeyResultMessage.value = `${metadataSchema.value}.${oracleForeignKeyCreateRecovery.value.tableName}: ${t("oracleForeignKey.createdTablePartial")}`;@@ -3307,7 +3430,16 @@ function structureChangeOptions(): BuildTableStructureChangeSqlOptions {}),indexes: sanitizeStructureIndexesForCapabilities(indexes.value, structureCapabilities.value),foreignKeys: foreignKeys.value,- triggers: triggers.value,+ triggers: triggers.value.map((trigger) => {+ const metadata = exactOracleTriggerMetadata(trigger.original);+ const oracleExact =+ metadata?.parent && (metadata.scope === "TABLE" || metadata.scope === "VIEW")+ ? { owner: metadata.owner, parentType: metadata.scope }+ : !trigger.original && oracleTriggerReadOptions(databaseType.value) && metadataSchema.value+ ? (trigger.oracleExact ?? { owner: metadataSchema.value, parentType: props.tableType === "view" ? ("VIEW" as const) : ("TABLE" as const) })+ : undefined;+ return { ...trigger, oracleExact };+ }),tableComment: tableComment.value,originalTableComment: isCreateMode.value ? undefined : originalTableComment.value,mysqlAutoIncrementValue: isCreateMode.value && canEditMysqlAutoIncrement.value ? mysqlAutoIncrementValue.value || undefined : undefined,@@ -3339,6 +3471,7 @@ function partitionSqlOptions(): TablePartitionSqlOptions {async function refreshSqlPreview() {const requestId = ++sqlPreviewRequestId;+ triggerStructurePlan.value = undefined;existingPrimaryKeyPlan.value = undefined;existingPrimaryKeySession.value = undefined;oracleConstraintPlan.value = undefined;@@ -3495,6 +3628,28 @@ async function refreshSqlPreview() {if (requestId !== sqlPreviewRequestId || JSON.stringify(target) !== JSON.stringify({ ...primaryKeyTarget(), schema: metadataSchema.value, tableName: newTableName.value.trim(), databaseType: target.databaseType })) return;const currentConfig = store.getConfig(target.connectionId);if (store.connectionStateRevision(target.connectionId) !== connectionRevision || (currentConfig ? connectionConfigFingerprint(currentConfig) : "") !== configFingerprint) throw new Error(t("oracleForeignKey.refreshRequired"));+ if (options.triggers?.some((trigger) => trigger.oracleExact && triggerChanged(trigger)) && !plan.triggerOperations?.length) throw new Error("Update the trigger SQL provider before saving this table");+ if (plan.triggerOperations?.length) {+ const triggerPlan = await prepareOracleTriggerStructurePlan({+ target: {+ connectionId: target.connectionId,+ database: target.database,+ catalog: target.catalog,+ owner: target.schema,+ tableName: foldCreatedTableName(target.tableName, target.databaseType),+ executionSchema: props.schema || target.schema,+ parentType: "TABLE",+ databaseType: target.databaseType,+ newTable: true,+ },+ statements: plan.statements,+ operations: plan.triggerOperations,+ triggers: options.triggers!,+ });+ if (requestId !== sqlPreviewRequestId || !connectionCurrent()) return;+ triggerStructurePlan.value = triggerPlan;+ triggerStructureFingerprint = JSON.stringify(structureChangeOptions());+ }newOracleForeignKeyPlan.value = plan;newOracleForeignKeySession.value = { revision: connectionRevision, configFingerprint, draftFingerprint: JSON.stringify({ options: plan.options, changes: plan.changes, partitioning: plan.partitioning }) };pendingStatements.value = [...plan.statements];@@ -3616,7 +3771,33 @@ async function refreshSqlPreview() {if (requestId !== sqlPreviewRequestId) return;const statements = [...result.statements, ...ownerResult.statements, ...(mysqlAutoIncrementStatement ? [mysqlAutoIncrementStatement] : []), ...partitionResult.statements];// SQLite type-change apply regenerates this revision-checked plan, so its preview must stay byte-for-byte aligned.- pendingStatements.value = hasSqliteTypeChange.value ? statements : statements.map((statement) => applyDdlGenerationPreferences(statement, sqlFormatDialectForDbType(databaseType.value)));+ const triggerOperations = "triggerOperations" in result ? result.triggerOperations : undefined;+ const exactChanges = options.triggers?.some((trigger) => trigger.oracleExact && triggerChanged(trigger));+ if (exactChanges && !result.warnings.length && !("oracleTriggerContract" in result && result.oracleTriggerContract === 1) && !triggerOperations?.length) throw new Error("Update the trigger SQL provider and regenerate the table preview; exact trigger operations are missing");+ const exactStatement = (index: number) => triggerOperations?.some((operation) => index >= operation.statementIndex && index < operation.statementIndex + operation.statementCount);+ const actualStatements = hasSqliteTypeChange.value ? statements : statements.map((statement, index) => (exactStatement(index) ? statement : applyDdlGenerationPreferences(statement, sqlFormatDialectForDbType(databaseType.value))));+ if (triggerOperations?.length && !result.warnings.length) {+ const plan = await prepareOracleTriggerStructurePlan({+ target: {+ connectionId: props.connectionId,+ database: props.database,+ catalog: props.catalog,+ owner: metadataSchema.value!,+ tableName: isCreateMode.value ? foldCreatedTableName(newTableName.value, databaseType.value) : props.tableName!,+ executionSchema: props.schema || metadataSchema.value!,+ parentType: props.tableType === "view" ? "VIEW" : "TABLE",+ databaseType: databaseType.value as "oracle" | "oceanbase-oracle" | "dameng",+ newTable: isCreateMode.value,+ },+ statements: actualStatements,+ operations: triggerOperations,+ triggers: options.triggers!,+ });+ if (requestId !== sqlPreviewRequestId) return;+ triggerStructurePlan.value = plan;+ triggerStructureFingerprint = JSON.stringify(structureChangeOptions());+ }+ pendingStatements.value = actualStatements;warnings.value = [...result.warnings, ...ownerResult.warnings, ...partitionResult.warnings];sqliteSchemaRevision.value = "schemaRevision" in result && typeof result.schemaRevision === "string" ? result.schemaRevision : undefined;} catch (e: any) {@@ -3646,6 +3827,7 @@ const canApply = computed(!mysqlTableEngineLoading.value &&!sqlPreviewLoading.value &&!sqlPreviewPending.value &&+ !triggerStructureRecovery.value &&(ddlDirty.value || (!hydratingRestoredDraft.value && !needsColumnDraftMetadataHydration() && !draftHydrationError.value)) &&pendingStatements.value.length > 0 &&warnings.value.length === 0 &&@@ -3662,6 +3844,8 @@ function clearDraft() {}function resetState() {+ triggerStructurePlan.value = undefined;+ triggerStructureRecovery.value = undefined;invalidateDraftHydration();restoredDraftTarget = "";draftHydrationError.value = "";@@ -4081,7 +4265,14 @@ async function loadStructure(: Promise.resolve(undefined);const triggersPromise = effectiveScope.triggers? tableMetadataCapabilities.value.triggers- ? loadObjectMetadataFacet(metadataRequest, "triggers", () => api.listTriggers(connectionId, database, schema, tableName, catalog, ...(metadataRequest.exactIdentity ? ([true] as const) : [])), { force: forceMetadata }).then((result) => result.value)+ ? loadObjectMetadataFacet(+ { ...metadataRequest, ...(oracleTriggerReadOptions(databaseType.value) ? { oracleTriggerContract: 1 as const } : {}) },+ "triggers",+ () => api.listTriggers(connectionId, database, schema, tableName, catalog, oracleTriggerReadOptions(databaseType.value, catalog) ?? (metadataRequest.exactIdentity || undefined)),+ {+ force: forceMetadata,+ },+ ).then((result) => result.value): Promise.resolve([]): Promise.resolve(undefined);// Partition metadata is a live catalog read (not persisted), so it is@@ -6177,13 +6368,13 @@ function toggleDropTrigger(trigger: EditableStructureTrigger) {}function canEditTriggerDraft(trigger: EditableStructureTrigger): boolean {- return canToggleTriggerEnabled(trigger) && canEditStructuredTriggerDraft(databaseType.value, trigger);+ return canToggleTriggerEnabled(trigger) && (!exactOracleTriggerMetadata(trigger.original) || trigger.loadedOracleSource !== undefined) && canEditStructuredTriggerDraft(databaseType.value, trigger);}// ALTER TRIGGER ... ENABLE/DISABLE leaves the source untouched, so it stays available for// triggers whose source the structured form cannot rebuild.function canToggleTriggerEnabled(trigger: EditableStructureTrigger): boolean {- return !triggersLoading.value && canEditTriggers.value && !trigger.markedForDrop;+ return !triggersLoading.value && canEditTriggers.value && !trigger.markedForDrop && !triggerSourceRefreshRequired.value.has(trigger.id);}function primarySqlOperation(sql: string): string {@@ -6829,6 +7020,16 @@ async function applyOracleForeignKeyCreatePlan(): Promise<boolean> {const canStart = () => sameTarget() && changes === JSON.stringify(oracleForeignKeyChanges()) && JSON.stringify({ options: currentOptions(), changes: oracleForeignKeyChanges(), partitioning: currentPartitioning() }) === plannedSession.draftFingerprint && isCreateMode.value;const stillCurrent = () => canStart() && connectionCurrent();if (!stillCurrent()) return false;+ if (triggerStructurePlan.value)+ return applyTriggerStructure({+ preflight: async () => {+ if (!(await preflightOracleForeignKeyCreatePlan(plan, canStart, connectionCurrent))) throw new Error(t("oracleForeignKey.refreshRequired"));+ },+ readback: async (steps) => {+ const read = await readOracleForeignKeyCreateResult(plan, steps, connectionCurrent);+ if (read.readbackError) throw new Error(read.readbackError);+ },+ });oracleForeignKeyBusy.value = true;saving.value = true;const startedAt = Date.now();@@ -7004,6 +7205,206 @@ async function applyOracleForeignKeyCreatePlan(): Promise<boolean> {}}+async function reconcileTriggerStructure(): Promise<void> {+ const recovery = triggerStructureRecovery.value;+ if (!recovery || saving.value || !window.confirm(t("oracleTrigger.reconcileConfirm"))) return;+ const key = triggerStructureKey();+ const draft = createCurrentDraft();+ const fingerprint = JSON.stringify(structureChangeOptions());+ const target = recovery.target;+ const config = store.getConfig(target.connectionId);+ const revision = store.connectionStateRevision(target.connectionId);+ const configFingerprint = config ? connectionConfigFingerprint(config) : "";+ const current = () =>+ key === triggerStructureKey() &&+ !primaryKeyUnmounted &&+ fingerprint === JSON.stringify(structureChangeOptions()) &&+ store.isCurrentConnectionStateRevision(target.connectionId, revision) &&+ store.connectionStateRevision(target.connectionId) === revision &&+ (store.getConfig(target.connectionId) ? connectionConfigFingerprint(store.getConfig(target.connectionId)!) : "") === configFingerprint;+ const changed = {+ columns: new Set(columns.value.filter(columnChanged).map((item) => item.id)),+ indexes: new Set(indexes.value.filter(indexChanged).map((item) => item.id)),+ foreignKeys: new Set(foreignKeys.value.filter(foreignKeyChanged).map((item) => item.id)),+ triggers: new Set(triggers.value.filter(triggerChanged).map((item) => item.id)),+ };+ saving.value = true;+ try {+ const literal = (value: string) => `'${value.replaceAll("'", "''")}'`;+ const identity = await api.executeQuery(+ target.connectionId,+ target.database,+ `SELECT OWNER, OBJECT_NAME, OBJECT_TYPE, TO_CHAR(OBJECT_ID) AS OBJECT_ID FROM ALL_OBJECTS WHERE OWNER = ${literal(target.owner)} AND OBJECT_NAME = ${literal(target.tableName)} AND OBJECT_TYPE = ${literal(target.parentType)}`,+ target.executionSchema,+ undefined,+ { catalog: target.catalog, maxRows: 2 },+ );+ if (identity.execution_error || identity.truncated || identity.has_more || identity.rows.length > 1) throw new Error(identity.error?.detail || t("oracleTrigger.reloadBaseline"));+ if (!identity.rows.length && target.newTable) {+ // A newly confirmed plain CREATE can be prepared again only after this explicit read.+ if (!current()) return;+ triggerStructureRecovery.value = undefined;+ syncDraftToParent();+ scheduleSqlPreviewRefresh();+ return;+ }+ const row = identity.rows[0];+ if (row?.length !== 4 || row[0] !== target.owner || row[1] !== target.tableName || row[2] !== target.parentType || typeof row[3] !== "string" || !row[3]) throw new Error(t("oracleTrigger.reloadBaseline"));+ const [nextColumns, nextIndexes, nextKeys, nextTriggers, nextConstraints, nextComment] = await Promise.all([+ changed.columns.size || target.newTable ? api.getColumns(target.connectionId, target.database, target.owner, target.tableName, target.catalog) : Promise.resolve(draft.columns.flatMap((item) => (item.original ? [item.original] : []))),+ changed.indexes.size || (target.newTable && draft.indexes.length) ? api.listIndexes(target.connectionId, target.database, target.owner, target.tableName, target.catalog) : Promise.resolve(draft.indexes.flatMap((item) => (item.original ? [item.original] : []))),+ changed.foreignKeys.size || (target.newTable && draft.foreignKeys.length) ? api.listForeignKeys(target.connectionId, target.database, target.owner, target.tableName, target.catalog) : Promise.resolve(draft.foreignKeys.flatMap((item) => (item.original ? [item.original] : []))),+ api.listTriggers(target.connectionId, target.database, target.owner, target.tableName, target.catalog, { identityMode: "exact" }),+ changed.columns.size && draft.constraintsLoaded ? api.listConstraints(target.connectionId, target.database, target.owner, target.tableName, target.catalog) : Promise.resolve(draft.constraints ?? []),+ target.newTable || draft.tableComment !== draft.originalTableComment ? api.getTableComment(target.connectionId, target.database, target.owner, target.tableName, target.catalog) : Promise.resolve(draft.originalTableComment),+ ]);+ if (nextTriggers.some((trigger) => !exactOracleTriggerMetadata(trigger))) throw new Error(t("oracleTrigger.reloadBaseline"));+ for (const trigger of draft.triggers.filter((item) => item.markedForDrop && item.original && !nextTriggers.some((next) => next.oracle_metadata?.owner === item.original!.oracle_metadata?.owner && next.name === item.original!.name))) {+ const metadata = exactOracleTriggerMetadata(trigger.original);+ if (metadata) await verifyOracleTriggerDeletion({ connectionId: target.connectionId, database: target.database, catalog: target.catalog, owner: metadata.owner, name: metadata.name, executionSchema: target.executionSchema });+ }+ if (!current()) return;+ const next = reconcileOracleTriggerStructureDraft(draft, { columns: nextColumns, indexes: nextIndexes, foreignKeys: nextKeys, triggers: nextTriggers, constraints: nextConstraints, comment: nextComment ?? "" }, changed, target.databaseType);+ for (const trigger of next.triggers.filter((item) => changed.triggers.has(item.id) && item.original)) {+ const metadata = exactOracleTriggerMetadata(trigger.original);+ if (!metadata) throw new Error(t("oracleTrigger.reloadBaseline"));+ const loaded = await readOracleTriggerSource({ connectionId: target.connectionId, database: target.database, catalog: target.catalog, owner: metadata.owner, name: metadata.name, executionSchema: target.executionSchema });+ if (!loaded.snapshot?.exists || loaded.snapshot.metadata.objectId !== metadata.objectId || loaded.snapshot.raw.trigger?.statement !== trigger.original!.statement || loaded.snapshot.raw.trigger?.enabled !== trigger.original!.enabled) throw new Error(t("oracleTrigger.reloadBaseline"));+ const inspected = await inspectExactOracleTriggerSource(loaded.snapshot.raw, metadata.owner, metadata.name);+ trigger.loadedOracleSource = loaded.snapshot.raw.source;+ trigger.loadedOracleStructured = inspected.triggerSource.complete && inspected.triggerSource.prepared?.structuredEditable === true;+ }+ if (!current()) return;+ restoreDraft(next);+ triggerSourceRefreshRequired.value.clear();+ errorMessage.value = "";+ syncDraftToParent();+ if (target.newTable) {+ emitDraftToParent({ ...next, newTableName: "" });+ emit("saved", false, target.tableName);+ } else scheduleSqlPreviewRefresh();+ } catch (error) {+ if (key === triggerStructureKey()) errorMessage.value = error instanceof Error ? error.message : String(error);+ } finally {+ saving.value = false;+ }+}++async function applyTriggerStructure(validation?: { preflight: () => Promise<void>; readback: (steps: OracleForeignKeyCreateExecutionResult["steps"]) => Promise<void> }): Promise<boolean> {+ const plan = triggerStructurePlan.value;+ if (!plan || triggerStructureRecovery.value) return false;+ const targetKey = triggerStructureKey();+ const originTabId = props.originTabId;+ const fingerprint = triggerStructureFingerprint;+ const current = () => !primaryKeyUnmounted && triggerStructureActive.value && targetKey === triggerStructureKey() && fingerprint === JSON.stringify(structureChangeOptions());+ const danger = useSqlExecutionDangerStore();+ const scopeId = `structure-trigger:${uuid()}`;+ triggerStructureConfirmationScope = scopeId;+ const stop = watch(+ current,+ (value) => {+ if (!value) cancelTriggerStructureConfirmation();+ },+ { flush: "sync" },+ );+ const started = Date.now();+ const submittedDraft = createCurrentDraft();+ const refreshScope = captureStructureRefreshScope();+ saving.value = true;+ try {+ const confirmed =+ current() &&+ (await danger.requestConfirmation({+ sql: plan.statements.join("\n\n"),+ kind: "sql",+ scopeId,+ connectionName: connection.value?.name,+ database: plan.target.database,+ databaseType: plan.target.databaseType,+ targets: [+ `${plan.target.owner}.${plan.target.tableName}`,+ ...plan.groups.map((group) => `TRIGGER ${group.operation.owner}.${group.operation.name}`),+ `${t("oracleTrigger.executionSchema")}: ${plan.target.executionSchema}`,+ ...(plan.statements.length > 1 ? [t("oracleTrigger.nonAtomic")] : []),+ ],+ }));+ const result = await executeOracleTriggerStructurePlan(plan, {+ confirmed,+ confirmationScope: scopeId,+ isCurrent: current,+ timeoutSecs: queryTimeoutSecsForConnection(store.getConfig(plan.target.connectionId), settingsStore.editorSettings.globalQueryTimeoutSecs),+ preflight: validation?.preflight,+ });+ if (result.cancelled) return false;+ let complete = result.steps.every((step) => step.state === "committed" && step.trigger?.verification !== "invalid");+ let details = result.steps.map((step) => `${step.statementIndex + 1}. ${step.state}: ${step.sql}${step.error ? `\n${step.error}` : ""}`).join("\n\n");+ // Preserve the submitted draft and attempted indexes before any refresh or UI navigation.+ if (result.steps.some((step) => step.state !== "notExecuted")) {+ const recovery = { target: { ...plan.target }, steps: cloneDraftValue(result.steps), details };+ if (targetKey === triggerStructureKey()) triggerStructureRecovery.value = recovery;+ emitDraftToParent({ ...(targetKey === triggerStructureKey() ? createCurrentDraft() : submittedDraft), dirty: true, oracleTriggerStructureRecovery: recovery }, originTabId);+ if (targetKey !== triggerStructureKey()) toast(`${plan.target.owner}.${plan.target.tableName}\n${details}`, 10000);+ }+ if (complete && validation) {+ try {+ await validation.readback(result.steps);+ } catch (error) {+ complete = false;+ details += `\n\n${error instanceof Error ? error.message : String(error)}`;+ if (targetKey === triggerStructureKey() && triggerStructureRecovery.value) {+ triggerStructureRecovery.value.details = details;+ syncDraftToParent();+ }+ }+ }+ await recordStructureHistory(plan.statements.join("\n\n"), started, complete, undefined, complete ? undefined : details);+ if (targetKey !== triggerStructureKey()) return false;+ if (!complete || !current()) {+ errorMessage.value = t("oracleTrigger.reloadBaseline");+ primaryKeyResultDetails.value = details;+ primaryKeyResultTitle.value = "oracleStructureResult.resultTitle";+ primaryKeyResultMessage.value = `${plan.target.owner}.${plan.target.tableName}: ${t("oracleTrigger.reloadBaseline")}`;+ primaryKeyResultOpen.value = true;+ return false;+ }+ if (plan.target.newTable) {+ triggerStructureRecovery.value = undefined;+ clearDraft();+ emit("saved", tableComment.value !== originalTableComment.value, plan.target.tableName, originTabId);+ } else {+ const metadataMatch = { connectionId: plan.target.connectionId, database: plan.target.database, catalog: plan.target.catalog, schema: plan.target.owner, tableName: plan.target.tableName };+ invalidateTableMetadataCache(metadataMatch);+ await invalidateObjectMetadataCache(metadataMatch);+ await invalidateObjectDdl(metadataMatch);+ saving.value = false;+ postSaveRefreshing.value = true;+ skipNextRefreshVersion = true;+ emit("saved", tableComment.value !== originalTableComment.value, undefined, originTabId);+ const refresh = await loadStructure(true, refreshScope, false, { blockSecondaryMetadata: true });+ postSaveRefreshing.value = false;+ if (refresh?.error) {+ const recovery = triggerStructureRecovery.value;+ restoreDraft({ ...submittedDraft, dirty: true, oracleTriggerStructureRecovery: recovery });+ errorMessage.value = refresh.error;+ return false;+ }+ triggerStructureRecovery.value = undefined;+ syncDraftToParent();+ }+ toast(t(plan.target.newTable ? "structureEditor.created" : "structureEditor.saved"), 4000);+ return true;+ } catch (error) {+ if (targetKey === triggerStructureKey()) errorMessage.value = error instanceof Error ? error.message : String(error);+ return false;+ } finally {+ stop();+ danger.cancelScope(scopeId);+ productionSafetyStore.cancelScope(scopeId);+ if (triggerStructureConfirmationScope === scopeId) triggerStructureConfirmationScope = undefined;+ saving.value = false;+ }+}+async function applyChanges() {const indexWriteWarning = schemaIndexWriteWarning();if (indexWriteWarning) {@@ -7025,6 +7426,10 @@ async function applyChanges() {if (oracleIndexMutation) return applyOracleIndexPlan();if (newOracleForeignKeyPlan.value) return applyOracleForeignKeyCreatePlan();if (existingOracleForeignKeyPlan.value) return applyOracleForeignKeyPlan();+ if (triggerSourceRefreshRequired.value.size) {+ errorMessage.value = t("oracleTrigger.reloadBaseline");+ return false;+ }// Layer B runtime guard: a stale `concurrently: true` whose availability is// no longer enabled must never be executed — reject the save with an// explicit error even if normalization was skipped (race / non-UI caller).@@ -7033,6 +7438,11 @@ async function applyChanges() {errorMessage.value = blockingConcurrentWarning;return false;}+ if (triggerStructureRecovery.value) {+ errorMessage.value = t("oracleTrigger.reloadBaseline");+ return false;+ }+ if (triggerStructurePlan.value) return applyTriggerStructure();const sql = previewSqlText.value;const submittedStarRocksTarget = starrocksStatusTarget.value;const connection = store.getConfig(props.connectionId);@@ -7399,6 +7809,7 @@ onMounted(() => {});onActivated(() => {+ triggerStructureActive.value = true;registerStructureEditorShortcuts();observeStructureToolbar();observeStructureHorizontalScroller();@@ -7420,6 +7831,8 @@ onActivated(() => {if (activeTab.value === "ddl") scheduleDdlEditorInit();});onDeactivated(() => {+ triggerStructureActive.value = false;+ cancelTriggerStructureConfirmation();stopStructureToolbarObserver();copyColumnsDialogOpen.value = false;pasteColumnsDialogOpen.value = false;@@ -7774,6 +8187,26 @@ watch(<template><div ref="rootRef" class="flex h-full min-h-0 flex-col gap-2 overflow-hidden p-[var(--structure-shell-padding)] text-[length:var(--structure-font-size)]" :data-structure-density="localStructureDensity" :style="structureDensityStyle">+ <ObjectSourceDialog+ v-if="triggerSourceTarget"+ :key="JSON.stringify(triggerSourceTarget.target)"+ ref="triggerSourceDialog"+ v-model:open="triggerSourceOpen"+ :connection-id="triggerSourceTarget.target.connectionId"+ :database="triggerSourceTarget.target.database"+ :catalog="triggerSourceTarget.target.catalog"+ :schema="triggerSourceTarget.target.owner"+ :execution-schema="triggerSourceTarget.target.executionSchema"+ :name="triggerSourceTarget.target.name"+ object-type="TRIGGER"+ trigger-identity-mode="exact"+ :database-type="databaseType"+ :dialect="codeMirrorSqlDialect(databaseType)"+ :format-dialect="sqlFormatDialectForDbType(databaseType)"+ initial-editing+ @trigger-read="mergeTriggerSourceSnapshot"+ @trigger-result="recordTriggerSourceResult"+ /><DangerConfirmDialog v-model:open="primaryKeyResultOpen" :title="t(primaryKeyResultTitle)" :message="primaryKeyResultMessage" :confirm-label="t('common.close')"><template #options><details class="rounded border p-2 text-xs">@@ -9199,6 +9632,7 @@ watch(:class="[trigger.id === selectedTriggerId ? 'bg-accent text-accent-foreground' : '', trigger.markedForDrop ? 'bg-destructive/5 opacity-60' : '']"@click="selectTrigger(trigger)">+ <span v-if="exactOracleTriggerMetadata(trigger.original)" class="max-w-[35%] truncate whitespace-pre font-mono text-muted-foreground" :title="trigger.original?.oracle_metadata?.owner">{{ trigger.original?.oracle_metadata?.owner }}.</span><template v-if="renamingTriggerId === trigger.id"><Inputv-model="trigger.name"@@ -9262,7 +9696,13 @@ watch(<!-- Statement editor (detail): title + SQL sized to its content --><div v-if="selectedTrigger" class="flex min-h-0 flex-1 flex-col rounded-md border px-[var(--structure-cell-px)] py-[var(--structure-header-py)] text-[length:var(--structure-font-size)]" :class="selectedTrigger.markedForDrop ? 'bg-destructive/5 opacity-60' : ''"><div class="flex min-w-0 items-center gap-1.5 font-mono font-medium" :title="selectedTrigger.name">+ <span v-if="exactOracleTriggerMetadata(selectedTrigger.original)" class="max-w-[35%] truncate whitespace-pre text-muted-foreground" :title="selectedTrigger.original?.oracle_metadata?.owner">{{ selectedTrigger.original?.oracle_metadata?.owner }}.</span><span class="truncate">{{ selectedTrigger.name || t("structureEditor.triggerName") }}</span>+ <span v-if="exactOracleTriggerMetadata(selectedTrigger.original)" class="text-sm font-normal">{{+ selectedTrigger.original?.oracle_metadata?.reads.validity?.state === "available" && typeof selectedTrigger.original?.valid === "boolean" ? (selectedTrigger.original.valid ? "VALID" : "INVALID") : t("oracleTrigger.unknown")+ }}</span>+ <Button v-if="exactOracleTriggerMetadata(selectedTrigger.original)" variant="outline" size="sm" class="ml-auto shrink-0 font-sans" :disabled="saving || triggersLoading" @click="openTriggerFullSource(selectedTrigger)">{{ t("oracleTrigger.editFullSource") }}</Button>+ <Button v-if="triggerSourceRefreshRequired.has(selectedTrigger.id)" variant="outline" size="sm" class="shrink-0 font-sans" :disabled="saving || triggersLoading" @click="reloadTriggerDraftAfterSource(selectedTrigger)">{{ t("oracleTrigger.refreshDraft") }}</Button></div><textareav-model="selectedTrigger.statement"@@ -9522,6 +9962,11 @@ watch({{ errorMessage || draftHydrationError }}</div>+ <div v-if="triggerStructureRecovery" class="flex shrink-0 items-center gap-2 rounded-md border border-amber-500/30 bg-amber-500/10 p-2 text-sm" role="status">+ <span class="min-w-0 flex-1">{{ t("oracleTrigger.reloadBaseline") }}</span>+ <Button variant="outline" size="sm" :disabled="saving || loading" @click="reconcileTriggerStructure">{{ t("oracleTrigger.reconcileStructure") }}</Button>+ </div>+<div class="flex shrink-0 items-center justify-end gap-2"><Button :class="structureToolbarButtonClass" :disabled="!canApply" @click="applyChanges"><Loader2 v-if="saving" :class="[structureIconClass, 'mr-1.5 animate-spin']" />diff --git a/apps/desktop/src/components/structure/__tests__/TableStructureEditor.columnNameWhitespace.spec.ts b/apps/desktop/src/components/structure/__tests__/TableStructureEditor.columnNameWhitespace.spec.tsindex b84314af70..742290ee3a 100644--- a/apps/desktop/src/components/structure/__tests__/TableStructureEditor.columnNameWhitespace.spec.ts+++ b/apps/desktop/src/components/structure/__tests__/TableStructureEditor.columnNameWhitespace.spec.ts@@ -27,7 +27,7 @@ const mocks = vi.hoisted(() => ({toast: vi.fn(),}));-vi.mock("vue-i18n", () => ({ useI18n: () => ({ t: (key: string) => key }) }));+vi.mock("vue-i18n", async (original) => ({ ...(await original<typeof import("vue-i18n")>()), useI18n: () => ({ t: (key: string) => key }) }));vi.mock("@lucide/vue", async () => {const { defineComponent, h } = await import("vue");diff --git a/apps/desktop/src/components/structure/__tests__/TableStructureEditor.columnSelectionCopy.spec.ts b/apps/desktop/src/components/structure/__tests__/TableStructureEditor.columnSelectionCopy.spec.tsindex 7ca66f7487..a1ecf197aa 100644--- a/apps/desktop/src/components/structure/__tests__/TableStructureEditor.columnSelectionCopy.spec.ts+++ b/apps/desktop/src/components/structure/__tests__/TableStructureEditor.columnSelectionCopy.spec.ts@@ -28,7 +28,7 @@ const mocks = vi.hoisted(() => ({toast: vi.fn(),}));-vi.mock("vue-i18n", () => ({ useI18n: () => ({ t: (key: string) => key }) }));+vi.mock("vue-i18n", async (original) => ({ ...(await original<typeof import("vue-i18n")>()), useI18n: () => ({ t: (key: string) => key }) }));vi.mock("@lucide/vue", async () => {const { defineComponent, h } = await import("vue");diff --git a/apps/desktop/src/components/structure/__tests__/TableStructureEditor.concurrentTransition.spec.ts b/apps/desktop/src/components/structure/__tests__/TableStructureEditor.concurrentTransition.spec.tsindex 2f54ff6654..13667751db 100644--- a/apps/desktop/src/components/structure/__tests__/TableStructureEditor.concurrentTransition.spec.ts+++ b/apps/desktop/src/components/structure/__tests__/TableStructureEditor.concurrentTransition.spec.ts@@ -27,7 +27,7 @@ const mocks = vi.hoisted(() => ({toast: vi.fn(),}));-vi.mock("vue-i18n", () => ({ useI18n: () => ({ t: (key: string) => key }) }));+vi.mock("vue-i18n", async (original) => ({ ...(await original<typeof import("vue-i18n")>()), useI18n: () => ({ t: (key: string) => key }) }));vi.mock("@lucide/vue", async () => {const { defineComponent, h } = await import("vue");diff --git a/apps/desktop/src/components/structure/__tests__/TableStructureEditor.createModeSavedName.spec.ts b/apps/desktop/src/components/structure/__tests__/TableStructureEditor.createModeSavedName.spec.tsindex 0f11a2deb4..96b35e7772 100644--- a/apps/desktop/src/components/structure/__tests__/TableStructureEditor.createModeSavedName.spec.ts+++ b/apps/desktop/src/components/structure/__tests__/TableStructureEditor.createModeSavedName.spec.ts@@ -46,7 +46,7 @@ const mocks = vi.hoisted(() => ({toast: vi.fn(),}));-vi.mock("vue-i18n", () => ({ useI18n: () => ({ t: (key: string) => key }) }));+vi.mock("vue-i18n", async (original) => ({ ...(await original<typeof import("vue-i18n")>()), useI18n: () => ({ t: (key: string) => key }) }));// Render rows without browser layout measurements so drag controls can be exercised.vi.mock("vue-virtual-scroller", async () => {diff --git a/apps/desktop/src/components/structure/__tests__/TableStructureEditor.ddlTab.spec.ts b/apps/desktop/src/components/structure/__tests__/TableStructureEditor.ddlTab.spec.tsindex d91dcd1a35..80d807b908 100644--- a/apps/desktop/src/components/structure/__tests__/TableStructureEditor.ddlTab.spec.ts+++ b/apps/desktop/src/components/structure/__tests__/TableStructureEditor.ddlTab.spec.ts@@ -41,7 +41,7 @@ const mocks = vi.hoisted(() => ({toast: vi.fn(),}));-vi.mock("vue-i18n", () => ({ useI18n: () => ({ t: (key: string) => key }) }));+vi.mock("vue-i18n", async (original) => ({ ...(await original<typeof import("vue-i18n")>()), useI18n: () => ({ t: (key: string) => key }) }));vi.mock("@lucide/vue", async () => {const { defineComponent, h } = await import("vue");diff --git a/apps/desktop/src/components/structure/__tests__/TableStructureEditor.ddlTabLifecycle.spec.ts b/apps/desktop/src/components/structure/__tests__/TableStructureEditor.ddlTabLifecycle.spec.tsindex e6673b04b7..783b923111 100644--- a/apps/desktop/src/components/structure/__tests__/TableStructureEditor.ddlTabLifecycle.spec.ts+++ b/apps/desktop/src/components/structure/__tests__/TableStructureEditor.ddlTabLifecycle.spec.ts@@ -28,7 +28,7 @@ const mocks = vi.hoisted(() => ({copyToClipboard: vi.fn(),}));-vi.mock("vue-i18n", () => ({ useI18n: () => ({ t: (key: string) => key }) }));+vi.mock("vue-i18n", async (original) => ({ ...(await original<typeof import("vue-i18n")>()), useI18n: () => ({ t: (key: string) => key }) }));vi.mock("@lucide/vue", async () => {const { defineComponent, h } = await import("vue");diff --git a/apps/desktop/src/components/structure/__tests__/TableStructureEditor.initialTab.spec.ts b/apps/desktop/src/components/structure/__tests__/TableStructureEditor.initialTab.spec.tsindex b913f3dd88..d2237792aa 100644--- a/apps/desktop/src/components/structure/__tests__/TableStructureEditor.initialTab.spec.ts+++ b/apps/desktop/src/components/structure/__tests__/TableStructureEditor.initialTab.spec.ts@@ -31,7 +31,7 @@ const mocks = vi.hoisted(() => ({toast: vi.fn(),}));-vi.mock("vue-i18n", () => ({ useI18n: () => ({ t: (key: string) => key }) }));+vi.mock("vue-i18n", async (original) => ({ ...(await original<typeof import("vue-i18n")>()), useI18n: () => ({ t: (key: string) => key }) }));vi.mock("@lucide/vue", async () => {const { defineComponent, h } = await import("vue");diff --git a/apps/desktop/src/components/structure/__tests__/TableStructureEditor.metadataRevalidation.spec.ts b/apps/desktop/src/components/structure/__tests__/TableStructureEditor.metadataRevalidation.spec.tsindex b6ec7a5d47..7fe71c3ca0 100644--- a/apps/desktop/src/components/structure/__tests__/TableStructureEditor.metadataRevalidation.spec.ts+++ b/apps/desktop/src/components/structure/__tests__/TableStructureEditor.metadataRevalidation.spec.ts@@ -37,7 +37,7 @@ const mocks = vi.hoisted(() => ({toast: vi.fn(),}));-vi.mock("vue-i18n", () => ({ useI18n: () => ({ t: (key: string) => key }) }));+vi.mock("vue-i18n", async (original) => ({ ...(await original<typeof import("vue-i18n")>()), useI18n: () => ({ t: (key: string) => key }) }));vi.mock("@lucide/vue", async () => {const { defineComponent, h } = await import("vue");diff --git a/apps/desktop/src/components/structure/__tests__/TableStructureEditor.mysqlGenerated.spec.ts b/apps/desktop/src/components/structure/__tests__/TableStructureEditor.mysqlGenerated.spec.tsindex 262cf30ff8..9be9965d35 100644--- a/apps/desktop/src/components/structure/__tests__/TableStructureEditor.mysqlGenerated.spec.ts+++ b/apps/desktop/src/components/structure/__tests__/TableStructureEditor.mysqlGenerated.spec.ts@@ -27,7 +27,7 @@ const mocks = vi.hoisted(() => ({toast: vi.fn(),}));-vi.mock("vue-i18n", () => ({ useI18n: () => ({ t: (key: string) => key }) }));+vi.mock("vue-i18n", async (original) => ({ ...(await original<typeof import("vue-i18n")>()), useI18n: () => ({ t: (key: string) => key }) }));vi.mock("@lucide/vue", async () => {const { defineComponent, h } = await import("vue");diff --git a/apps/desktop/src/components/structure/__tests__/TableStructureEditor.oracleForeignKey.spec.ts b/apps/desktop/src/components/structure/__tests__/TableStructureEditor.oracleForeignKey.spec.tsindex 9c10af9769..2566ba652f 100644--- a/apps/desktop/src/components/structure/__tests__/TableStructureEditor.oracleForeignKey.spec.ts+++ b/apps/desktop/src/components/structure/__tests__/TableStructureEditor.oracleForeignKey.spec.ts@@ -7,8 +7,9 @@ import i18n from "@/i18n";import { TooltipProvider } from "@/components/ui/tooltip";import LightTooltip from "@/components/ui/LightTooltip.vue";import { useConnectionStore } from "@/stores/connectionStore";+import { useSqlExecutionDangerStore } from "@/stores/sqlExecutionDangerStore";import { invalidateObjectMetadataCache } from "@/lib/metadata/objectMetadataCache";-import type { ConnectionConfig } from "@/types/database";+import type { ConnectionConfig, ObjectSource, TableStructureEditorDraft } from "@/types/database";import * as api from "@/lib/backend/api";vi.mock("@/lib/backend/api", async (importOriginal) => ({@@ -31,25 +32,31 @@ vi.mock("@/lib/backend/api", async (importOriginal) => ({getTablePartitioning: vi.fn().mockResolvedValue(null),buildTableStructureChangeSql: vi.fn().mockResolvedValue({ statements: [], warnings: [] }),buildCreateTableSql: vi.fn().mockResolvedValue({ statements: [], warnings: [] }),+ getObjectSource: vi.fn(),+ prepareOracleTriggerSql: vi.fn(),saveHistory: vi.fn().mockResolvedValue(undefined),disconnectDb: vi.fn().mockResolvedValue(undefined),- executeQuery: vi.fn(async (_id, _database, sql: string) => ({- columns: [],- rows: sql.includes("SELECT USER")- ? [["APP"]]- : sql.includes("SYS.ALL_TABLES")- ? [["APP", "SOURCE"]]- : sql.includes("SYS.ALL_CONSTRAINTS") || sql.includes("SYS.USER_CONSTRAINTS")- ? [["FK_SOURCE", "ENABLED", "VALIDATED", "NOT DEFERRABLE", "IMMEDIATE", null, "PARENT_OWNER", "PK_PARENT", "CASCADE"]]- : [['ALTER TABLE "APP"."SOURCE" ADD CONSTRAINT "FK_SOURCE" FOREIGN KEY ("A", "B") REFERENCES "PARENT_OWNER"."PARENT" ("ID", "V") ON DELETE CASCADE ENABLE VALIDATE']],- execution_time_ms: 0,- rows_affected: 0,- })),+ executeQuery: vi.fn(),}));let app: App | undefined;beforeEach(() => {vi.clearAllMocks();+ vi.mocked(api.executeQuery).mockImplementation(+ async (_id, _database, sql: string) =>+ ({+ columns: [],+ rows: sql.includes("SELECT USER")+ ? [["APP"]]+ : sql.includes("SYS.ALL_TABLES")+ ? [["APP", "SOURCE"]]+ : sql.includes("SYS.ALL_CONSTRAINTS") || sql.includes("SYS.USER_CONSTRAINTS")+ ? [["FK_SOURCE", "ENABLED", "VALIDATED", "NOT DEFERRABLE", "IMMEDIATE", null, "PARENT_OWNER", "PK_PARENT", "CASCADE"]]+ : [['ALTER TABLE "APP"."SOURCE" ADD CONSTRAINT "FK_SOURCE" FOREIGN KEY ("A", "B") REFERENCES "PARENT_OWNER"."PARENT" ("ID", "V") ON DELETE CASCADE ENABLE VALIDATE']],+ execution_time_ms: 0,+ rows_affected: 0,+ }) as never,+ );i18n.global.locale.value = "en";vi.stubGlobal("fetch",@@ -67,6 +74,143 @@ afterEach(() => {});describe("Oracle family foreign key editing entry", () => {+ it.each([false, true])("keeps new-table FK preflight and readback around the exact trigger sequence (readback fails=%s)", async (failReadback) => {+ const pinia = createPinia();+ setActivePinia(pinia);+ const store = useConnectionStore(),+ id = `foreign-key-trigger-create-${failReadback}`;+ store.connections = [{ id, name: "Create trigger fixture", db_type: "oracle", username: "APP", database: "APP" } as ConnectionConfig];+ store.connectedIds.add(id);+ const createSql = 'CREATE TABLE "APP"."NEW_TABLE" ("ID" NUMBER PRIMARY KEY);';+ const addSql = 'ALTER TABLE "APP"."NEW_TABLE" ADD CONSTRAINT "FK_SELF" FOREIGN KEY ("ID") REFERENCES "APP"."NEW_TABLE" ("ID") ENABLE VALIDATE;';+ const triggerSql = 'CREATE TRIGGER "APP"."NEW_TRIGGER" BEFORE INSERT ON "APP"."NEW_TABLE" DISABLE BEGIN NULL; END;';+ let tableExists = false,+ triggerExists = false;+ vi.mocked(api.buildCreateTableSql).mockResolvedValue({ statements: [createSql, addSql, triggerSql], warnings: [], triggerOperations: [{ draftId: "new:trigger", action: "create", owner: "APP", name: "NEW_TRIGGER", statementIndex: 2, statementCount: 1, enabled: false }] });+ vi.mocked(api.getObjectSource).mockImplementation(+ async () =>+ ({+ name: "NEW_TRIGGER",+ schema: "APP",+ object_type: "TRIGGER",+ source: triggerExists ? triggerSql : "",+ trigger: {+ name: "NEW_TRIGGER",+ timing: "BEFORE",+ event: "INSERT",+ statement: "BEGIN NULL; END;",+ enabled: false,+ valid: true,+ oracle_metadata: {+ contractVersion: 1,+ identityMode: "exact",+ engine: "oracle",+ engineVersion: "19.0.0.0",+ owner: "APP",+ name: "NEW_TRIGGER",+ scope: triggerExists ? "TABLE" : "UNKNOWN",+ objectId: triggerExists ? "trigger-id" : null,+ parent: triggerExists ? { owner: "APP", name: "NEW_TABLE", objectType: "TABLE" } : null,+ definition: { origin: "ALL_SOURCE", format: "ddl", complete: triggerExists },+ errors: [],+ reads: {+ identity: { state: triggerExists ? "available" : "empty" },+ scope: { state: "available" },+ parent: { state: "available" },+ enabled: { state: "available" },+ validity: { state: "available" },+ definition: { state: triggerExists ? "available" : "empty" },+ errors: { state: "available" },+ },+ },+ },+ }) as ObjectSource,+ );+ vi.mocked(api.prepareOracleTriggerSql).mockImplementation(async (input) => ({ definition: input.source, comparisonSource: input.source, header: { scope: "RELATION", owner: "APP", name: "NEW_TABLE", viewOnly: false, pluggable: false }, requiresStateRestore: false }));+ const result = (rows: unknown[][] = []) => ({ columns: [], rows, execution_time_ms: 0, affected_rows: 0 });+ vi.mocked(api.executeQuery).mockImplementation(async (_id, _db, sql) => {+ if (sql.includes("SELECT USER, SYS_CONTEXT")) return result([["APP", "APP"]]) as never;+ if (sql.includes("FROM ALL_OBJECTS")) {+ if (!tableExists) throw new Error("No parent before CREATE TABLE");+ return result([["APP", "NEW_TABLE", "TABLE", "parent-id"]]) as never;+ }+ if (sql.includes("SYS.ALL_TABLES")) {+ if (failReadback) throw new Error("FK dictionary unavailable after write");+ return result([["APP", "NEW_TABLE"]]) as never;+ }+ if (sql.includes("SYS.ALL_CONSTRAINTS")) return result([["FK_SELF", "ENABLED", "VALIDATED", "NOT DEFERRABLE", "IMMEDIATE", null, "APP", "PK_SELF", "NO ACTION"]]) as never;+ if (sql.includes("DBMS_METADATA.GET_DDL")) return result([[addSql]]) as never;+ if (sql === createSql) tableExists = true;+ else if (sql === triggerSql) triggerExists = true;+ else if (sql !== addSql) throw new Error(`Unexpected fixture SQL: ${sql}`);+ return result() as never;+ });+ const container = document.createElement("div");+ document.body.append(container);+ const drafts: (TableStructureEditorDraft | undefined)[] = [],+ saved: unknown[][] = [];+ const editor = ref<InstanceType<typeof TableStructureEditor>>();+ app = createApp({+ render: () =>+ h(+ TooltipProvider,+ {},+ {+ default: () =>+ h(TableStructureEditor, {+ connectionId: id,+ originTabId: id,+ database: "APP",+ schema: "APP",+ tableName: "",+ initialTab: "foreignKeys",+ draft: {+ dirty: true,+ activeTab: "foreignKeys",+ newTableName: "NEW_TABLE",+ tableComment: "",+ originalTableComment: "",+ columns: [{ id: "new:id", name: "ID", dataType: "NUMBER", isNullable: false, defaultValue: "", comment: "", isPrimaryKey: true, extra: {}, markedForDrop: false }],+ indexes: [],+ foreignKeys: [{ id: "new:fk", name: "FK_SELF", column: "ID", columns: ["ID"], refSchema: "APP", refTable: "NEW_TABLE", refColumn: "ID", refColumns: ["ID"], onUpdate: "", onDelete: "NO ACTION", markedForDrop: false }],+ triggers: [{ id: "new:trigger", name: "NEW_TRIGGER", timing: "BEFORE", event: "INSERT", statement: "BEGIN NULL; END;", enabled: false, markedForDrop: false }],+ initialized: true,+ },+ ref: editor,+ "onUpdate:draft": (draft?: TableStructureEditorDraft) => drafts.push(draft && JSON.parse(JSON.stringify(draft))),+ onSaved: (...args: unknown[]) => saved.push(args),+ }),+ },+ ),+ });+ app.use(pinia);+ app.use(i18n);+ app.component("LightTooltip", LightTooltip);+ app.mount(container);+ const apply = () => [...container.querySelectorAll<HTMLButtonElement>("button")].find((button) => button.textContent?.trim() === i18n.global.t("structureEditor.apply"));+ await vi.waitFor(() => expect(apply()?.disabled).toBe(false));+ const applying = editor.value!.applyChanges();+ const danger = useSqlExecutionDangerStore();+ await vi.waitFor(() => expect(danger.pending).toBeDefined());+ expect(danger.pending!.sql).toContain(addSql);+ expect(danger.pending!.sql).toContain(triggerSql);+ danger.confirm();+ expect(await applying).toBe(!failReadback);+ expect(+ vi+ .mocked(api.executeQuery)+ .mock.calls.filter((call) => !call[2].startsWith("SELECT"))+ .map((call) => call[2]),+ ).toEqual([createSql, addSql, triggerSql]);+ expect(vi.mocked(api.executeQuery).mock.calls.filter((call) => call[2].includes("SELECT USER, SYS_CONTEXT")).length).toBeGreaterThanOrEqual(2);+ if (failReadback) {+ expect(saved).toEqual([]);+ expect(drafts.at(-1)?.oracleTriggerStructureRecovery?.details).toContain("FK dictionary unavailable");+ expect(drafts.at(-1)?.triggers[0]?.name).toBe("NEW_TRIGGER");+ expect(await editor.value!.applyChanges()).toBe(false);+ expect(vi.mocked(api.executeQuery).mock.calls.filter((call) => !call[2].startsWith("SELECT"))).toHaveLength(3);+ } else expect(saved).toEqual([[false, "NEW_TABLE", id]]);+ });it.each([{ databaseType: "oracle", readable: true },{ databaseType: "oceanbase-oracle", readable: true },diff --git a/apps/desktop/src/components/structure/__tests__/TableStructureEditor.oracleTriggerSource.spec.ts b/apps/desktop/src/components/structure/__tests__/TableStructureEditor.oracleTriggerSource.spec.tsnew file mode 100644index 0000000000..c23b7323fc--- /dev/null+++ b/apps/desktop/src/components/structure/__tests__/TableStructureEditor.oracleTriggerSource.spec.ts@@ -0,0 +1,553 @@+// @vitest-environment happy-dom+import { createApp, h, nextTick, type App } from "vue";+import { createPinia, setActivePinia } from "pinia";+import { afterEach, beforeEach, expect, it, vi } from "vitest";+import { EditorView } from "@codemirror/view";+import TableStructureEditor from "../TableStructureEditor.vue";+import { TooltipProvider } from "@/components/ui/tooltip";+import LightTooltip from "@/components/ui/LightTooltip.vue";+import i18n from "@/i18n";+import { useConnectionStore } from "@/stores/connectionStore";+import { useSqlExecutionDangerStore } from "@/stores/sqlExecutionDangerStore";+import type { ConnectionConfig, ObjectSource, TableStructureEditorDraft, TriggerInfo } from "@/types/database";+import type { BuildTableStructureChangeSqlOptions, TableStructureChangeSql } from "@/lib/table/tableStructureEditorSql";+import { invalidateObjectMetadataCache } from "@/lib/metadata/objectMetadataCache";+import { invalidateObjectDdl } from "@/lib/metadata/objectDdlCache";+import { createColumnDrafts, createTriggerDrafts } from "@/lib/table/tableStructureEditorState";++const rpc = vi.hoisted(() => ({+ listPlugins: vi.fn(async () => []),+ listInstalledAgents: vi.fn(async () => []),+ checkConnectionHealth: vi.fn(async () => undefined),+ loadSchemaCache: vi.fn(async () => null),+ saveSchemaCache: vi.fn(async () => undefined),+ deleteSchemaCachePrefix: vi.fn(async () => undefined),+ listDataTypes: vi.fn(async () => ["NUMBER"]),+ getColumns: vi.fn(async () => [{ name: "ID", data_type: "NUMBER", is_nullable: true, is_primary_key: false, column_default: null }]),+ listIndexes: vi.fn(async () => []),+ listForeignKeys: vi.fn(async () => []),+ listConstraints: vi.fn(async () => []),+ getTableComment: vi.fn(async () => ""),+ getTablePartitionStatus: vi.fn(async () => ({ isPartitionedParent: false, isPartition: false, isForeign: false })),+ getTablePartitioning: vi.fn(async () => null),+ buildTableStructureChangeSql: vi.fn(async (_options: BuildTableStructureChangeSqlOptions): Promise<TableStructureChangeSql> => ({ statements: [], warnings: [] })),+ listTriggers: vi.fn(),+ getObjectSource: vi.fn(),+ prepareOracleTriggerSql: vi.fn(),+ executeQuery: vi.fn(),+ executeBatch: vi.fn(),+ buildDropObjectSql: vi.fn(),+ saveHistory: vi.fn(async () => undefined),+ saveOpenTabsState: vi.fn(async () => undefined),+}));+vi.mock("@/lib/backend/api", async (original) => ({ ...(await original<typeof import("@/lib/backend/api")>()), ...rpc }));+const owner = "Trigger.Owner",+ parent = "Parent.Owner",+ name = "Complex Trigger";+const definition = `CREATE OR REPLACE TRIGGER "${owner}"."${name}" BEFORE INSERT ON "${parent}"."T" FOR EACH ROW WHEN (NEW.ID > 0) DISABLE BEGIN NULL; END;`;+let raw: ObjectSource;+let app: App | undefined;+const drafts: TableStructureEditorDraft[] = [];+beforeEach(async () => {+ vi.clearAllMocks();+ vi.stubGlobal(+ "confirm",+ vi.fn(() => true),+ );+ await invalidateObjectMetadataCache({ connectionId: "trigger-structure-source" });+ await invalidateObjectDdl({ connectionId: "trigger-structure-source" });+ rpc.buildTableStructureChangeSql.mockReset().mockResolvedValue({ statements: [], warnings: [] });+ rpc.getColumns.mockReset().mockResolvedValue([{ name: "ID", data_type: "NUMBER", is_nullable: true, is_primary_key: false, column_default: null }]);+ drafts.length = 0;+ i18n.global.locale.value = "en";+ const info: TriggerInfo = {+ name,+ timing: "BEFORE EACH ROW",+ event: "INSERT",+ statement: definition,+ condition: "NEW.ID > 0",+ enabled: false,+ valid: true,+ oracle_metadata: {+ contractVersion: 1,+ identityMode: "exact",+ engine: "oceanbase-oracle",+ engineVersion: "4.2.5.7_107",+ owner,+ name,+ objectId: "trigger-id",+ scope: "TABLE",+ parent: { owner: parent, name: "T", objectType: "TABLE" },+ definition: { origin: "DBMS_METADATA", format: "ddl", complete: true },+ errors: [],+ reads: { identity: { state: "available" }, scope: { state: "available" }, parent: { state: "available" }, enabled: { state: "available" }, validity: { state: "available" }, definition: { state: "available" }, errors: { state: "available" } },+ },+ };+ raw = { name, schema: owner, object_type: "TRIGGER", source: definition, trigger: info };+ rpc.listTriggers.mockImplementation(async () => [JSON.parse(JSON.stringify(raw.trigger))]);+ rpc.getObjectSource.mockImplementation(async () => JSON.parse(JSON.stringify(raw)));+ rpc.prepareOracleTriggerSql.mockImplementation(async (input) => ({ definition: input.source, comparisonSource: input.source, structuredEditable: false, header: { scope: "RELATION", owner: parent, name: "T", viewOnly: false, pluggable: false }, requiresStateRestore: false }));+ rpc.executeQuery.mockImplementation(async (_id, _db, sql) => {+ if (sql.startsWith("SELECT")) return { columns: ["OWNER", "OBJECT_NAME", "OBJECT_TYPE", "OBJECT_ID"], rows: [[parent, "T", "TABLE", "parent-id"]] };+ raw.source = sql;+ raw.trigger!.statement = sql;+ return { columns: [], rows: [], affected_rows: 0 };+ });+});+afterEach(() => {+ app?.unmount();+ app = undefined;+ document.body.innerHTML = "";+ vi.restoreAllMocks();+ vi.unstubAllGlobals();+});+function button(label: string) {+ return [...document.querySelectorAll<HTMLButtonElement>("button")].find((button) => button.textContent?.trim() === label);+}++async function mountStructure(draft?: TableStructureEditorDraft, catalog?: string, databaseType: "oracle" | "oceanbase-oracle" = "oceanbase-oracle") {+ let structure: InstanceType<typeof TableStructureEditor> | null = null;+ const pinia = createPinia();+ setActivePinia(pinia);+ const connections = useConnectionStore();+ connections.connections = [{ id: "trigger-structure-source", name: "Trigger structure", db_type: databaseType, username: "Execution.Owner", database: "service" } as ConnectionConfig];+ connections.connectedIds.add("trigger-structure-source");+ const host = document.createElement("div");+ document.body.append(host);+ app = createApp({+ render: () =>+ h(+ TooltipProvider,+ {},+ {+ default: () =>+ h(TableStructureEditor, {+ ref: (instance) => {+ structure = instance as InstanceType<typeof TableStructureEditor> | null;+ },+ connectionId: "trigger-structure-source",+ database: "service",+ catalog,+ schema: parent,+ tableName: "T",+ initialTab: "columns",+ draft,+ "onUpdate:draft": (draft?: TableStructureEditorDraft) => {+ if (draft) drafts.push(JSON.parse(JSON.stringify(draft)));+ },+ }),+ },+ ),+ });+ app.use(pinia);+ app.use(i18n);+ app.component("LightTooltip", LightTooltip);+ app.mount(host);+ await vi.waitFor(() => expect(host.querySelector("[data-column-name-input]")).not.toBeNull());+ return { host, structure: structure! };+}++it("distinguishes and selects same-name triggers from different owners in the actual structure panel", async () => {+ const second = structuredClone(raw);+ second.schema = "Other.Trigger.Owner";+ second.source = definition.replace(`"${owner}"`, '"Other.Trigger.Owner"');+ second.trigger!.statement = second.source;+ second.trigger!.oracle_metadata!.owner = second.schema;+ second.trigger!.oracle_metadata!.objectId = "other-trigger-id";+ rpc.listTriggers.mockResolvedValue([structuredClone(raw.trigger), second.trigger]);+ rpc.getObjectSource.mockImplementation(async (_id, _db, requestedOwner) => structuredClone(requestedOwner === second.schema ? second : raw));+ const { host } = await mountStructure();+ button(i18n.global.t("structureEditor.triggers"))!.dispatchEvent(new MouseEvent("mousedown", { bubbles: true, button: 0 }));+ const names = () => [...host.querySelectorAll<HTMLElement>(`span[title="${name}"]`)];+ await vi.waitFor(() => expect(names()).toHaveLength(2));+ expect(names()[0].parentElement!.textContent).toContain(owner);+ expect(names()[1].parentElement!.textContent).toContain(second.schema);+ names()[1].parentElement!.click();+ await vi.waitFor(() => expect(rpc.getObjectSource.mock.calls.some((call) => call[2] === second.schema)).toBe(true));+ expect(host.querySelector<HTMLTextAreaElement>("textarea")!.value).toBe(second.source);+ expect(new Set(drafts.at(-1)!.triggers.map((trigger) => trigger.id)).size).toBe(2);+ expect(rpc.executeQuery.mock.calls.filter((call) => !call[2].startsWith("SELECT"))).toHaveLength(0);+});++it.each(["FOLLOWS OTHER_TRIGGER", "REFERENCING NEW AS N OLD AS O"])("keeps %s definitions out of the structured editor even when a provider supplies a plain body", async (clause) => {+ raw.trigger!.condition = null;+ raw.trigger!.statement = "BEGIN NULL; END;";+ raw.source = `CREATE OR REPLACE TRIGGER "${owner}"."${name}" BEFORE INSERT ON "${parent}"."T" ${clause} FOR EACH ROW DISABLE BEGIN NULL; END;`;+ rpc.prepareOracleTriggerSql.mockImplementation(async (input) => ({ definition: input.source, comparisonSource: input.source, structuredEditable: false, header: { scope: "RELATION", owner: parent, name: "T", viewOnly: false, pluggable: false }, requiresStateRestore: false }));+ const { host } = await mountStructure();+ button(i18n.global.t("structureEditor.triggers"))!.dispatchEvent(new MouseEvent("mousedown", { bubbles: true, button: 0 }));+ await vi.waitFor(() => expect(drafts.at(-1)?.triggers[0]?.loadedOracleSource).toBe(raw.source));+ expect(host.querySelector<HTMLTextAreaElement>("textarea")!.disabled).toBe(true);+ expect(button(i18n.global.t("oracleTrigger.editFullSource"))).toBeDefined();+ expect(button(i18n.global.t("damengJobAdmin.disabled"))!.disabled).toBe(false);+ expect(rpc.executeQuery.mock.calls.filter((call) => !call[2].startsWith("SELECT"))).toHaveLength(0);+});++it.each(["applied", "unknown", "cancelled", "closed"])("serializes an originally allowed column/trigger draft without opaque batch (%s)", async (outcome) => {+ const columnSql = 'ALTER TABLE "Parent.Owner"."T" RENAME COLUMN "ID" TO "ID_LOCAL_DRAFT"';+ const expectedColumnSql = 'ALTER TABLE "T" RENAME COLUMN "ID" TO "ID_LOCAL_DRAFT"';+ const toggleSql = 'ALTER TRIGGER "Trigger.Owner"."Complex Trigger" ENABLE;';+ const disableSql = 'ALTER TRIGGER "Trigger.Owner"."Complex Trigger" DISABLE;';+ let offline = false;+ let columnName = "ID";+ rpc.getColumns.mockImplementation(async () => [{ name: columnName, data_type: "NUMBER", is_nullable: true, is_primary_key: false, column_default: null }]);+ rpc.buildTableStructureChangeSql.mockImplementation(async (options) => {+ const statements = options.columns.some((column) => column.name !== column.original?.name) ? [columnSql] : [];+ const trigger = options.triggers?.[0];+ if (!trigger || trigger.enabled === trigger.original?.enabled) return { statements, warnings: [] };+ return { statements: [...statements, trigger.enabled ? toggleSql : disableSql], warnings: [], triggerOperations: [{ draftId: trigger.id, action: trigger.enabled ? "enable" : "disable", owner, name, statementIndex: statements.length, statementCount: 1, enabled: trigger.enabled }] };+ });+ rpc.getObjectSource.mockImplementation(async () => {+ if (offline) throw new Error("readback offline");+ return JSON.parse(JSON.stringify(raw));+ });+ rpc.executeQuery.mockImplementation(async (_id, _db, sql) => {+ if (sql.startsWith("SELECT")) return { columns: ["OWNER", "OBJECT_NAME", "OBJECT_TYPE", "OBJECT_ID"], rows: [[parent, "T", "TABLE", "parent-id"]] };+ if (sql.includes("RENAME COLUMN")) columnName = "ID_LOCAL_DRAFT";+ if (sql === toggleSql) {+ raw.trigger!.enabled = true;+ if (outcome === "unknown") {+ offline = true;+ throw new Error("reply lost");+ }+ }+ if (sql === disableSql) raw.trigger!.enabled = false;+ return { columns: [], rows: [], affected_rows: 0 };+ });+ const { host, structure } = await mountStructure(undefined, outcome === "unknown" ? "Recovery.Catalog" : undefined);+ const input = host.querySelector<HTMLInputElement>("[data-column-name-input]")!;+ input.value = "ID_LOCAL_DRAFT";+ input.dispatchEvent(new Event("input", { bubbles: true }));+ button(i18n.global.t("structureEditor.triggers"))!.dispatchEvent(new MouseEvent("mousedown", { bubbles: true, button: 0 }));+ await vi.waitFor(() => expect(button(i18n.global.t("damengJobAdmin.disabled"))).toBeDefined());+ button(i18n.global.t("damengJobAdmin.disabled"))!.click();+ await vi.waitFor(() => expect(button(i18n.global.t("structureEditor.apply"))!.disabled).toBe(false));+ const applying = structure.applyChanges();+ if (outcome === "closed") {+ const danger = useSqlExecutionDangerStore();+ await vi.waitFor(() => expect(danger.pending).toBeDefined());+ app!.unmount();+ app = undefined;+ } else if (outcome === "cancelled") {+ const danger = useSqlExecutionDangerStore();+ await vi.waitFor(() => expect(danger.pending).toBeDefined());+ danger.cancel();+ } else {+ const danger = useSqlExecutionDangerStore();+ await vi.waitFor(() => expect(danger.pending).toBeDefined());+ expect(danger.pending!.sql).toContain(toggleSql);+ danger.confirm();+ }+ expect(await applying).toBe(outcome === "applied");+ expect(rpc.executeBatch).not.toHaveBeenCalled();+ const writes = () => rpc.executeQuery.mock.calls.filter((call) => !call[2].startsWith("SELECT")).map((call) => call[2]);+ expect(writes()).toEqual(outcome === "cancelled" || outcome === "closed" ? [] : [expectedColumnSql, toggleSql]);+ expect(rpc.buildTableStructureChangeSql.mock.calls.at(-1)![0].triggers![0].oracleExact).toEqual({ owner, parentType: "TABLE" });+ if (outcome === "unknown") {+ expect(drafts.at(-1)?.columns[0]?.name).toBe("ID_LOCAL_DRAFT");+ expect(drafts.at(-1)?.triggers[0]?.original?.enabled).toBe(false);+ await structure.applyChanges();+ expect(writes()).toEqual([expectedColumnSql, toggleSql]);+ offline = false;+ button(i18n.global.t("common.close"))!.click();+ button(i18n.global.t("oracleTrigger.reconcileStructure"))!.click();+ await vi.waitFor(() => expect(drafts.at(-1)?.oracleTriggerStructureRecovery).toBeUndefined());+ const identityRead = rpc.executeQuery.mock.calls.filter((call) => call[2].startsWith("SELECT") && call[5]?.maxRows === 2).at(-1)!;+ expect(identityRead[4]).toBeUndefined();+ expect(identityRead[5]).toEqual({ catalog: "Recovery.Catalog", maxRows: 2 });+ expect(drafts.at(-1)?.columns[0]?.original?.name).toBe("ID_LOCAL_DRAFT");+ expect(drafts.at(-1)?.triggers[0]?.original?.enabled).toBe(true);+ expect(writes()).toEqual([expectedColumnSql, toggleSql]);+ button(i18n.global.t("damengJobAdmin.enabled"))!.click();+ await vi.waitFor(() => expect(button(i18n.global.t("structureEditor.apply"))!.disabled).toBe(false));+ const remaining = structure.applyChanges();+ const danger = useSqlExecutionDangerStore();+ await vi.waitFor(() => expect(danger.pending).toBeDefined());+ expect(danger.pending!.sql).toContain(disableSql);+ expect(danger.pending!.sql).not.toContain("RENAME COLUMN");+ danger.confirm();+ expect(await remaining).toBe(true);+ expect(writes()).toEqual([expectedColumnSql, toggleSql, disableSql]);+ }+});++it("still refuses an Oracle index/trigger mixed draft before either specialized or general writes", async () => {+ rpc.buildTableStructureChangeSql.mockImplementation(async (options) => ({+ statements: ['CREATE INDEX "IDX_T" ON "Parent.Owner"."T" ("ID")', 'ALTER TRIGGER "Trigger.Owner"."Complex Trigger" ENABLE;'],+ warnings: [],+ triggerOperations: [{ draftId: options.triggers![0].id, action: "enable", owner, name, statementIndex: 1, statementCount: 1, enabled: true }],+ }));+ const draft: TableStructureEditorDraft = {+ activeTab: "columns",+ newTableName: "",+ tableComment: "",+ originalTableComment: "",+ columns: createColumnDrafts(await rpc.getColumns(), "oceanbase-oracle"),+ indexes: [{ id: "new:index", name: "IDX_T", columns: ["ID"], isUnique: false, isPrimary: false, filter: "", indexType: "NORMAL", includedColumns: [], comment: "", markedForDrop: false }],+ foreignKeys: [],+ triggers: createTriggerDrafts([raw.trigger!]).map((trigger) => ({ ...trigger, enabled: true })),+ constraints: [],+ constraintsLoaded: false,+ triggersLoaded: true,+ loadedMetadataFacets: ["columns", "indexes", "foreign-keys", "triggers"],+ initialized: true,+ };+ const { structure, host } = await mountStructure(draft);+ await vi.waitFor(() => expect(button(i18n.global.t("structureEditor.apply"))!.disabled).toBe(false));+ expect(await structure.applyChanges()).toBe(false);+ expect(host.textContent).toContain(i18n.global.t("oracleIndex.mixedDraft"));+ expect(rpc.executeBatch).not.toHaveBeenCalled();+ expect(rpc.executeQuery.mock.calls.filter((call) => !call[2].startsWith("SELECT"))).toEqual([]);+ expect(useSqlExecutionDangerStore().pending).toBeUndefined();+ expect(drafts.at(-1)?.indexes[0]?.name).toBe("IDX_T");+ expect(drafts.at(-1)?.triggers[0]?.enabled).toBe(true);+});++it.each(["primary-key", "constraint"])("does not route a mixed %s/trigger draft through the new general sequence", async (kind) => {+ const state = { enabled: true, validated: true, deferrable: false, initiallyDeferred: false, rely: false };+ const originalCheck = { kind: "check" as const, definition: { name: "CK_T", expression: "ID > 0", state } };+ const draft: TableStructureEditorDraft = {+ activeTab: "columns",+ newTableName: "",+ tableComment: "",+ originalTableComment: "",+ columns: createColumnDrafts(+ [+ { name: "ID", data_type: "NUMBER", is_nullable: false, is_primary_key: true, column_default: null },+ { name: "V", data_type: "NUMBER", is_nullable: true, is_primary_key: false, column_default: null },+ ],+ "oceanbase-oracle",+ ),+ indexes: [],+ foreignKeys: [],+ constraints: [{ name: "PK_T", constraint_type: "PRIMARY KEY", columns: ["ID"], definition: "", ref_columns: [], enabled: true, valid: true, deferrable: false, initially_deferred: false }],+ constraintsLoaded: true,+ triggers: createTriggerDrafts([raw.trigger!]).map((trigger) => ({ ...trigger, enabled: true })),+ triggersLoaded: true,+ loadedMetadataFacets: ["columns", "constraints", "triggers"],+ initialized: true,+ ...(kind === "primary-key" ? { existingPrimaryKey: { name: "PK_T", originalColumns: ["ID"], columns: ["ID", "V"] } } : { oracleConstraintChange: { original: originalCheck, target: { kind: "check" as const, definition: { ...originalCheck.definition, expression: "ID > 1" } } } }),+ };+ const { structure, host } = await mountStructure(draft);+ await vi.waitFor(() => expect(host.textContent).toContain(kind === "primary-key" ? i18n.global.t("oceanbasePrimaryKey.mixedDraft") : "Apply CHECK/UNIQUE changes separately"));+ expect(await structure.applyChanges()).toBe(false);+ expect(rpc.executeBatch).not.toHaveBeenCalled();+ expect(rpc.executeQuery.mock.calls.filter((call) => !call[2].startsWith("SELECT"))).toEqual([]);+ expect(drafts.at(-1)?.triggers[0]?.enabled).toBe(true);+});++it("saves an ordinary structured body through the complete loaded baseline and exact replacement plan", async () => {+ rpc.prepareOracleTriggerSql.mockImplementation(async (input) => ({ definition: input.source, comparisonSource: input.source, structuredEditable: true, header: { scope: "RELATION", owner: parent, name: "T", viewOnly: false, pluggable: false }, requiresStateRestore: false }));+ const body = "BEGIN :NEW.ID := 7; END;";+ const oldSource = `CREATE OR REPLACE TRIGGER "${owner}"."${name}" BEFORE INSERT ON "${parent}"."T" FOR EACH ROW DISABLE BEGIN NULL; END;`;+ const candidate = oldSource.replace("BEGIN NULL; END;", body);+ raw.source = oldSource;+ raw.trigger!.statement = "BEGIN NULL; END;";+ raw.trigger!.condition = undefined;+ rpc.buildTableStructureChangeSql.mockImplementation(async (options) => {+ const trigger = options.triggers?.[0];+ if (trigger?.statement !== body) return { statements: [], warnings: [] };+ return { statements: [candidate], warnings: [], triggerOperations: [{ draftId: trigger.id, action: "replace", owner, name, statementIndex: 0, statementCount: 1, enabled: false }] };+ });+ rpc.executeQuery.mockImplementation(async (_id, _db, sql) => {+ if (sql.startsWith("SELECT")) return { columns: ["OWNER", "OBJECT_NAME", "OBJECT_TYPE", "OBJECT_ID"], rows: [[parent, "T", "TABLE", "parent-id"]] };+ raw.source = sql;+ raw.trigger!.statement = body;+ return { columns: [], rows: [], affected_rows: 0 };+ });+ const { host, structure } = await mountStructure();+ button(i18n.global.t("structureEditor.triggers"))!.dispatchEvent(new MouseEvent("mousedown", { bubbles: true, button: 0 }));+ await vi.waitFor(() => expect(host.querySelector<HTMLTextAreaElement>("textarea")?.disabled).toBe(false));+ const input = host.querySelector<HTMLTextAreaElement>("textarea")!;+ input.value = body;+ input.dispatchEvent(new Event("input", { bubbles: true }));+ await vi.waitFor(() => expect(button(i18n.global.t("structureEditor.apply"))!.disabled).toBe(false));+ const applying = structure.applyChanges(),+ danger = useSqlExecutionDangerStore();+ await vi.waitFor(() => expect(danger.pending).toBeDefined());+ expect(danger.pending!.sql).toBe(candidate);+ danger.confirm();+ expect(await applying).toBe(true);+ expect(rpc.executeQuery.mock.calls.filter((call) => !call[2].startsWith("SELECT")).map((call) => call[2])).toEqual([candidate]);+ expect(drafts.at(-1)?.triggers[0]?.original?.statement).toBe(body);+ expect(rpc.executeBatch).not.toHaveBeenCalled();+});++it.each(["NewTrigger", "new"])("retains the exact rename target %s after DROP succeeds but CREATE is rejected", async (newName) => {+ raw.trigger!.oracle_metadata!.engine = "oracle";+ rpc.prepareOracleTriggerSql.mockImplementation(async (input) => ({ definition: input.source, comparisonSource: input.source, structuredEditable: true, header: { scope: "RELATION", owner: parent, name: "T", viewOnly: false, pluggable: false }, requiresStateRestore: false }));+ const oldSource = `CREATE OR REPLACE TRIGGER "${owner}"."${name}" BEFORE INSERT ON "${parent}"."T" FOR EACH ROW DISABLE BEGIN NULL; END;`;+ raw.source = oldSource;+ raw.trigger!.statement = "BEGIN NULL; END;";+ raw.trigger!.condition = undefined;+ let oldExists = true;+ const neighbor = JSON.parse(JSON.stringify(raw.trigger)) as TriggerInfo;+ neighbor.name = "NEW";+ neighbor.enabled = true;+ Object.assign(neighbor.oracle_metadata!, { name: "NEW", objectId: "neighbor-id" });+ const neighbors = newName === "new" ? [neighbor] : [];+ const dropSql = `DROP TRIGGER "${owner}"."${name}";`;+ const newSql = (triggerOwner: string) => `CREATE TRIGGER "${triggerOwner}"."${newName}" BEFORE INSERT ON "${parent}"."T" FOR EACH ROW DISABLE BEGIN NULL; END;`;+ rpc.listTriggers.mockImplementation(async () => [...(oldExists ? [JSON.parse(JSON.stringify(raw.trigger))] : []), ...structuredClone(neighbors)]);+ rpc.buildDropObjectSql.mockResolvedValue(dropSql);+ rpc.getObjectSource.mockImplementation(async (_id, _db, requestedOwner, requestedName) => {+ if (requestedName === name && requestedOwner === owner && oldExists) return JSON.parse(JSON.stringify(raw));+ const absent: ObjectSource = JSON.parse(JSON.stringify(raw));+ absent.name = requestedName;+ absent.schema = requestedOwner;+ absent.source = "";+ absent.trigger!.name = requestedName;+ absent.trigger!.statement = "";+ Object.assign(absent.trigger!.oracle_metadata!, { name: requestedName, owner: requestedOwner, objectId: null, scope: "UNKNOWN", parent: null });+ absent.trigger!.oracle_metadata!.reads.identity = { state: "empty" };+ return absent;+ });+ rpc.buildTableStructureChangeSql.mockImplementation(async (options) => {+ const trigger = options.triggers?.[0];+ if (!trigger || trigger.name === trigger.original?.name) return { statements: [], warnings: [] };+ const actualOwner = trigger.oracleExact!.owner;+ const creating = { draftId: trigger.id, action: "create" as const, owner: actualOwner, name: newName, statementIndex: trigger.original ? 1 : 0, statementCount: 1, enabled: false };+ return { statements: [...(trigger.original ? [dropSql] : []), newSql(actualOwner)], warnings: [], triggerOperations: [...(trigger.original ? [{ ...creating, action: "delete" as const, name, statementIndex: 0 }] : []), creating] };+ });+ rpc.executeQuery.mockImplementation(async (_id, _db, sql) => {+ if (sql.startsWith("SELECT USER")) return { columns: ["SESSION_USER"], rows: [["Execution.Owner"]] };+ if (sql.includes("FROM DBA_OBJECTS")) return { columns: ["OWNER", "OBJECT_NAME"], rows: [] };+ if (sql.startsWith("SELECT")) return { columns: ["OWNER", "OBJECT_NAME", "OBJECT_TYPE", "OBJECT_ID"], rows: [[parent, "T", "TABLE", "parent-id"]] };+ if (sql === dropSql) {+ oldExists = false;+ return { columns: [], rows: [], affected_rows: 0 };+ }+ return {+ columns: [],+ rows: [],+ execution_error: true,+ error: {+ version: 1,+ code: "DBX-JDBC-4001",+ messageKey: "backendErrors.jdbc.sqlFailed",+ messageParams: {},+ source: "jdbc-agent",+ operationOutcome: "unknown",+ detail: "ORA-01031: insufficient privileges",+ origin: { subsystem: "database", adapter: "jdbc-agent" },+ diagnostics: { category: "sql", stage: "execute", vendorCode: 1031 },+ },+ } as never;+ });+ const { host, structure } = await mountStructure(undefined, undefined, "oracle");+ button(i18n.global.t("structureEditor.triggers"))!.dispatchEvent(new MouseEvent("mousedown", { bubbles: true, button: 0 }));+ await vi.waitFor(() => expect(host.querySelector<HTMLTextAreaElement>("textarea")?.disabled).toBe(false));+ host.querySelector<HTMLButtonElement>(`button[title="${i18n.global.t("structureEditor.triggerName")}"]`)!.click();+ await nextTick();+ const nameInput = host.querySelector<HTMLInputElement>(`input[placeholder="${i18n.global.t("structureEditor.triggerName")}"]`)!;+ nameInput.value = newName;+ nameInput.dispatchEvent(new Event("input", { bubbles: true }));+ await vi.waitFor(() => expect(button(i18n.global.t("structureEditor.apply"))!.disabled).toBe(false));+ const applying = structure.applyChanges(),+ danger = useSqlExecutionDangerStore();+ await vi.waitFor(() => expect(danger.pending).toBeDefined());+ danger.confirm();+ expect(await applying).toBe(false);+ const writes = () => rpc.executeQuery.mock.calls.filter((call) => !call[2].startsWith("SELECT")).map((call) => call[2]);+ expect(writes()).toEqual([dropSql, newSql(owner)]);+ expect(drafts.at(-1)?.triggers[0]?.loadedOracleSource).toBe(oldSource);+ expect(drafts.at(-1)?.oracleTriggerStructureRecovery?.steps.map((step) => step.state)).toEqual(["committed", "rejected"]);+ expect(await structure.applyChanges()).toBe(false);+ button(i18n.global.t("common.close"))!.click();+ button(i18n.global.t("oracleTrigger.reconcileStructure"))!.click();+ await vi.waitFor(() => expect(drafts.at(-1)?.oracleTriggerStructureRecovery).toBeUndefined());+ await vi.waitFor(() => expect(rpc.buildTableStructureChangeSql.mock.calls.at(-1)?.[0].triggers?.[0]?.original).toBeUndefined());+ expect(rpc.buildTableStructureChangeSql.mock.calls.at(-1)![0].triggers![0].oracleExact?.owner).toBe(owner);+ expect(rpc.buildTableStructureChangeSql.mock.calls.at(-1)![0].triggers![0].name.trim()).toBe(newName);+ if (neighbors.length) expect(drafts.at(-1)?.triggers.find((trigger) => trigger.name === "NEW")).toMatchObject({ enabled: true, original: { oracle_metadata: { objectId: "neighbor-id" } } });+ expect(writes()).toEqual([dropSql, newSql(owner)]);+});++it.each([false, true])("repairs a protected exact trigger without discarding a column draft (lost reply=%s)", async (lostReply) => {+ let offline = false;+ if (lostReply) {+ rpc.buildTableStructureChangeSql.mockResolvedValue({ statements: ['ALTER TABLE "Parent.Owner"."T" RENAME COLUMN "ID" TO "ID_LOCAL_DRAFT"'], warnings: [] });+ rpc.getObjectSource.mockImplementation(async () => {+ if (offline) throw new Error("readback offline");+ return JSON.parse(JSON.stringify(raw));+ });+ rpc.executeQuery.mockImplementation(async (_id, _db, sql) => {+ if (sql.startsWith("SELECT")) return { columns: ["OWNER", "OBJECT_NAME", "OBJECT_TYPE", "OBJECT_ID"], rows: [[parent, "T", "TABLE", "parent-id"]] };+ raw.source = sql;+ raw.trigger!.statement = sql;+ offline = true;+ throw new Error("reply lost");+ });+ }+ let structure: InstanceType<typeof TableStructureEditor> | null = null;+ const pinia = createPinia();+ setActivePinia(pinia);+ const connections = useConnectionStore();+ connections.connections = [{ id: "trigger-structure-source", name: "Trigger structure", db_type: "oceanbase-oracle", username: "Execution.Owner", database: "service" } as ConnectionConfig];+ connections.connectedIds.add("trigger-structure-source");+ const host = document.createElement("div");+ document.body.append(host);+ app = createApp({+ render: () =>+ h(+ TooltipProvider,+ {},+ {+ default: () =>+ h(TableStructureEditor, {+ ref: (instance) => {+ structure = instance as InstanceType<typeof TableStructureEditor> | null;+ },+ connectionId: "trigger-structure-source",+ database: "service",+ schema: parent,+ tableName: "T",+ initialTab: "columns",+ "onUpdate:draft": (draft?: TableStructureEditorDraft) => {+ if (draft) drafts.push(JSON.parse(JSON.stringify(draft)));+ },+ }),+ },+ ),+ });+ app.use(pinia);+ app.use(i18n);+ app.component("LightTooltip", LightTooltip);+ app.mount(host);+ await vi.waitFor(() => expect(host.querySelector("[data-column-name-input]")).not.toBeNull());+ const column = host.querySelector<HTMLInputElement>("[data-column-name-input]")!;+ column.value = "ID_LOCAL_DRAFT";+ column.dispatchEvent(new Event("input", { bubbles: true }));+ await nextTick();+ button(i18n.global.t("structureEditor.triggers"))!.dispatchEvent(new MouseEvent("mousedown", { bubbles: true, button: 0 }));+ await vi.waitFor(() => expect(host.textContent).toContain(name));+ expect(host.querySelector<HTMLTextAreaElement>("textarea")!.disabled).toBe(true);+ const edit = button(i18n.global.t("oracleTrigger.editFullSource"));+ expect(edit).toBeDefined();+ edit!.click();+ await vi.waitFor(() => expect(document.querySelector("[data-object-source-editor] .cm-editor")).not.toBeNull(), { timeout: 10_000 });+ const view = EditorView.findFromDOM(document.querySelector<HTMLElement>("[data-object-source-editor] .cm-editor")!)!;+ view.dispatch({ changes: { from: view.state.doc.toString().indexOf("NULL;"), to: view.state.doc.toString().indexOf("NULL;") + 5, insert: "NULL; -- corrected\n" } });+ await nextTick();+ const candidate = view.state.doc.toString();+ button(i18n.global.t("objects.saveSource"))!.click();+ const danger = useSqlExecutionDangerStore();+ await vi.waitFor(() => expect(danger.pending).toBeDefined());+ danger.confirm();+ if (lostReply) {+ await vi.waitFor(() => expect(document.body.textContent).toContain("readback offline"));+ expect(drafts.at(-1)?.triggers[0]?.original?.statement).toBe(definition);+ expect(drafts.at(-1)?.columns[0]?.name).toBe("ID_LOCAL_DRAFT");+ button(i18n.global.t("common.close"))!.click();+ await nextTick();+ await vi.waitFor(() => expect(button(i18n.global.t("structureEditor.apply"))!.disabled).toBe(false));+ expect(await structure!.applyChanges()).toBe(false);+ expect(rpc.executeBatch).not.toHaveBeenCalled();+ offline = false;+ button(i18n.global.t("oracleTrigger.refreshDraft"))!.click();+ }+ await vi.waitFor(() => expect(drafts.at(-1)?.triggers[0]?.original?.statement).toBe(candidate));+ expect(drafts.at(-1)?.columns[0]?.name).toBe("ID_LOCAL_DRAFT");+ expect(rpc.executeQuery.mock.calls.filter((call) => !call[2].startsWith("SELECT")).map((call) => call[2])).toEqual([candidate]);+ expect(rpc.listTriggers).toHaveBeenCalledWith("trigger-structure-source", "service", parent, "T", undefined, { identityMode: "exact" });+});diff --git a/apps/desktop/src/components/structure/__tests__/TableStructureEditor.partitionsTab.spec.ts b/apps/desktop/src/components/structure/__tests__/TableStructureEditor.partitionsTab.spec.tsindex f81695a9fb..73fd254044 100644--- a/apps/desktop/src/components/structure/__tests__/TableStructureEditor.partitionsTab.spec.ts+++ b/apps/desktop/src/components/structure/__tests__/TableStructureEditor.partitionsTab.spec.ts@@ -33,7 +33,7 @@ const mocks = vi.hoisted(() => ({toast: vi.fn(),}));-vi.mock("vue-i18n", () => ({ useI18n: () => ({ t: (key: string) => key }) }));+vi.mock("vue-i18n", async (original) => ({ ...(await original<typeof import("vue-i18n")>()), useI18n: () => ({ t: (key: string) => key }) }));vi.mock("@lucide/vue", async () => {const { defineComponent, h } = await import("vue");diff --git a/apps/desktop/src/components/structure/__tests__/TableStructureEditor.presetFields.spec.ts b/apps/desktop/src/components/structure/__tests__/TableStructureEditor.presetFields.spec.tsindex 34c151120d..9c5af8ec78 100644--- a/apps/desktop/src/components/structure/__tests__/TableStructureEditor.presetFields.spec.ts+++ b/apps/desktop/src/components/structure/__tests__/TableStructureEditor.presetFields.spec.ts@@ -33,7 +33,7 @@ const mocks = vi.hoisted(() => ({},}));-vi.mock("vue-i18n", () => ({ useI18n: () => ({ t: (key: string) => key }) }));+vi.mock("vue-i18n", async (original) => ({ ...(await original<typeof import("vue-i18n")>()), useI18n: () => ({ t: (key: string) => key }) }));vi.mock("vue-virtual-scroller", async () => {const { defineComponent, h } = await import("vue");diff --git a/apps/desktop/src/composables/__tests__/useNativeJobExecution.spec.ts b/apps/desktop/src/composables/__tests__/useNativeJobExecution.spec.tsnew file mode 100644index 0000000000..58da46d21b--- /dev/null+++ b/apps/desktop/src/composables/__tests__/useNativeJobExecution.spec.ts@@ -0,0 +1,320 @@+import { effectScope, ref } from "vue";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import type { NativeJobMutation, NativeJobOperationStatus, NativeJobPreparedPlan, NativeJobRef, NativeJobScope } from "@/lib/database/nativeJobs";+import type { ConnectionConfig } from "@/types/database";++const rpc = vi.hoisted(() => ({ prepare: vi.fn(), apply: vi.fn(), status: vi.fn(), cancel: vi.fn(), guard: vi.fn() }));+vi.mock("@/lib/backend/api", () => ({ nativeJobPrepare: rpc.prepare, nativeJobApply: rpc.apply, nativeJobStatus: rpc.status, nativeJobCancel: rpc.cancel }));+vi.mock("@/lib/database/productionExecutionGuard", () => ({ executeWithProductionContextGuard: rpc.guard }));++import { useNativeJobExecution } from "@/composables/useNativeJobExecution";++const scope: NativeJobScope = { connectionId: "c", database: "", contextId: "original" };+const target: NativeJobRef = { scope, kind: "scheduler", owner: "Owner", name: "A,B" };+const mutation: NativeJobMutation = { target, baseline: "revision", action: "run" };+const plan: NativeJobPreparedPlan = { scope, target, planId: "plan", operationId: "operation", steps: [{ id: "run", label: "Run", sql: "native reviewed SQL" }] };++function status(state: NativeJobOperationStatus["state"] = "finished", outcome: NativeJobOperationStatus["outcome"] = "accepted"): NativeJobOperationStatus {+ return { operationId: plan.operationId, target, state, outcome, cancelRequested: false, steps: [{ id: "run", state: "accepted", reason: null, vendorCode: null }], reason: null };+}++function deferred<T>() {+ let resolve!: (value: T) => void;+ const promise = new Promise<T>((done) => (resolve = done));+ return { promise, resolve };+}++const scopes: ReturnType<typeof effectScope>[] = [];+function setup() {+ const connection = ref<ConnectionConfig>({ id: "c", name: "Original", db_type: "oracle", host: "localhost", port: 1521, username: "Owner", password: "" });+ const selected = ref<NativeJobRef | undefined>(target);+ const context = ref<NativeJobScope | undefined>(scope);+ const onFinished = vi.fn();+ const onTargetObserved = vi.fn();+ const owner = effectScope();+ scopes.push(owner);+ const execution = owner.run(() => useNativeJobExecution({ connection: () => connection.value, database: () => "", scope: () => context.value, selected: () => selected.value, source: () => "admin", onFinished, onTargetObserved }))!;+ return { execution, connection, selected, context, onFinished, onTargetObserved, owner };+}++beforeEach(() => {+ vi.resetAllMocks();+ vi.useFakeTimers();+ rpc.guard.mockImplementation((options: { execute: () => Promise<unknown> }) => options.execute());+ rpc.prepare.mockResolvedValue(plan);+ rpc.apply.mockResolvedValue(status());+});+afterEach(() => {+ for (const scope of scopes.splice(0)) scope.stop();+ vi.useRealTimers();+});++describe("native job page execution", () => {+ it("observes dispatch while the apply receipt waits and never replaces newer status with the late receipt", async () => {+ const { execution, onFinished } = setup();+ const receipt = deferred<NativeJobOperationStatus>();+ rpc.apply.mockReturnValueOnce(receipt.promise);+ rpc.status.mockResolvedValue({ ...status("running"), steps: [{ id: "run", state: "dispatching", reason: null, vendorCode: null }] });+ await execution.prepare(mutation);+ const applying = execution.apply();+ await Promise.resolve();+ await vi.advanceTimersByTimeAsync(400);+ expect(execution.execution.value?.status.steps[0]?.state).toBe("dispatching");+ expect(rpc.status).toHaveBeenCalledExactlyOnceWith("operation");+ rpc.status.mockResolvedValue(status());+ await vi.advanceTimersByTimeAsync(400);+ expect(execution.execution.value?.status.state).toBe("finished");+ receipt.resolve(status("queued", "not_started"));+ await applying;+ expect(execution.execution.value?.status.state).toBe("finished");+ expect(onFinished).toHaveBeenCalledTimes(1);+ expect(rpc.apply).toHaveBeenCalledTimes(1);+ });+ it("revokes old UI callbacks across explicit refresh even if Core returns the same scope", async () => {+ const { execution, onFinished, onTargetObserved } = setup();+ const receipt = deferred<NativeJobOperationStatus>();+ rpc.apply.mockReturnValueOnce(receipt.promise);+ await execution.prepare(mutation);+ const applying = execution.apply();+ await Promise.resolve();+ execution.invalidateContext();+ receipt.resolve(status("finished", "verified"));+ await applying;+ expect(execution.previousExecution.value?.status).toEqual(status("finished", "verified"));+ expect(onFinished).not.toHaveBeenCalled();+ expect(onTargetObserved).not.toHaveBeenCalled();+ expect(rpc.apply).toHaveBeenCalledExactlyOnceWith("plan");+ rpc.prepare.mockResolvedValue({ ...plan, planId: "new-plan", operationId: "new-operation" });+ rpc.apply.mockResolvedValue({ ...status(), operationId: "new-operation" });+ await execution.prepare(mutation);+ await execution.apply();+ expect(onFinished).toHaveBeenCalledExactlyOnceWith(expect.objectContaining({ operationId: "new-operation" }));+ expect(execution.previousExecution.value).toBeUndefined();+ });+ it("keeps prior-context receipts observable without rebinding their target or reviving late previews", async () => {+ const { execution, context, selected, connection } = setup();+ await execution.prepare(mutation);+ await execution.apply();+ const preview = deferred<NativeJobPreparedPlan>();+ rpc.prepare.mockReturnValueOnce(preview.promise);+ const preparing = execution.prepare(mutation);+ execution.invalidateContext();+ const next = { ...scope, contextId: "new-context" };+ context.value = next;+ selected.value = { ...target, scope: next } as NativeJobRef;+ preview.resolve(plan);+ await preparing;+ expect(execution.preview.value).toBeUndefined();+ expect(execution.execution.value).toBeUndefined();+ expect(execution.previousExecution.value?.status.target).toEqual(target);+ rpc.status.mockResolvedValue(status("finished", "unknown"));+ await execution.observe();+ expect(rpc.status).toHaveBeenCalledExactlyOnceWith("operation", true);+ expect(execution.previousExecution.value?.status.outcome).toBe("unknown");+ expect(rpc.apply).toHaveBeenCalledTimes(1);+ connection.value = { ...connection.value, username: "Other" };+ expect(execution.previousExecution.value).toBeUndefined();+ });+ it("delivers a later effective target without repeating completion or moving a different selection", async () => {+ const { execution, selected, onFinished, onTargetObserved } = setup();+ const original = { kind: "dameng-native" as const, scope, jobId: "41", name: "Old Job" };+ const renamed = { ...original, name: "New Job" };+ selected.value = original;+ rpc.prepare.mockResolvedValue({ ...plan, target: original, steps: [{ id: "rename", label: "rename", sql: "reviewed rename" }] });+ rpc.apply.mockResolvedValue({ ...status("finished", "unknown"), target: original });+ onTargetObserved.mockImplementation((value: NativeJobOperationStatus) => {+ if (value.observedIdentity) selected.value = value.target!;+ });+ await execution.prepare({ action: "update", target: original, baseline: "revision", attributes: [{ name: "NAME", change: { kind: "set", value: "New Job" } }], arguments: [] });+ await execution.apply();+ rpc.status.mockResolvedValue({ ...status("finished", "unknown"), target: renamed, observedIdentity: { DBX_JOB_ID: "41", DBX_CREATED_AT: "creation", NAME: "New Job" } });+ await execution.observe();+ expect(selected.value).toEqual(renamed);+ expect(execution.execution.value?.status.outcome).toBe("unknown");+ expect(onFinished).toHaveBeenCalledTimes(1);+ expect(onTargetObserved).toHaveBeenCalledTimes(2);+ const late = deferred<NativeJobOperationStatus>();+ rpc.status.mockReturnValueOnce(late.promise);+ const observing = execution.observe();+ selected.value = { ...original, jobId: "99", name: "Another Job" };+ late.resolve({ ...status("finished", "unknown"), target: renamed, observedIdentity: { DBX_JOB_ID: "41", DBX_CREATED_AT: "creation", NAME: "New Job" } });+ await observing;+ expect(selected.value).toMatchObject({ jobId: "99" });+ expect(onTargetObserved).toHaveBeenCalledTimes(2);+ expect(rpc.apply).toHaveBeenCalledTimes(1);+ });+ it("refreshes native observations manually after the request has finished without replay or permanent busy", async () => {+ const { execution, selected, onFinished } = setup();+ await execution.prepare(mutation);+ await execution.apply();+ const pending = deferred<NativeJobOperationStatus>();+ rpc.status.mockReturnValueOnce(pending.promise);+ const observing = execution.observe();+ expect(execution.observing.value).toBe(true);+ expect(execution.busy.value).toBe(false);+ expect(rpc.status).toHaveBeenCalledExactlyOnceWith("operation", true);+ selected.value = { ...target, name: "different job" } as NativeJobRef;+ pending.resolve({ ...status(), executionObservation: { observedAt: "first", association: "uncertain", reason: "request_uncertain", running: { status: "empty" }, history: { status: "empty" }, sources: {}, candidates: [] } });+ await observing;+ expect(execution.execution.value).toBeUndefined();+ expect(execution.observing.value).toBe(false);+ selected.value = target;+ expect(execution.execution.value?.status.outcome).toBe("accepted");+ expect(execution.execution.value?.status.executionObservation?.association).toBe("uncertain");+ expect(onFinished).toHaveBeenCalledTimes(1);+ await vi.advanceTimersByTimeAsync(1000);+ expect(rpc.status).toHaveBeenCalledTimes(1);+ expect(rpc.apply).toHaveBeenCalledTimes(1);+ });++ it("does not let an older observation overwrite the latest explicit refresh", async () => {+ const { execution } = setup();+ await execution.prepare(mutation);+ await execution.apply();+ const older = deferred<NativeJobOperationStatus>();+ const newer = deferred<NativeJobOperationStatus>();+ rpc.status.mockReturnValueOnce(older.promise).mockReturnValueOnce(newer.promise);+ const first = execution.observe();+ const second = execution.observe();+ newer.resolve({ ...status(), reason: "newer observation" });+ await second;+ older.resolve({ ...status(), reason: "older observation" });+ await first;+ expect(execution.execution.value?.status.reason).toBe("newer observation");+ expect(execution.execution.value?.status.outcome).toBe("accepted");+ });++ it("reviews the immutable backend preview through the existing context guard and applies only its plan ID", async () => {+ const { execution, onFinished } = setup();+ await execution.prepare(mutation);+ expect(execution.preview.value).toEqual(plan);+ await execution.apply();+ expect(rpc.guard).toHaveBeenCalledWith(expect.objectContaining({ connection: expect.objectContaining({ id: "c" }), database: "", reviewText: "native reviewed SQL", source: "admin" }));+ expect(rpc.apply).toHaveBeenCalledExactlyOnceWith("plan");+ expect(execution.execution.value?.status.outcome).toBe("accepted");+ expect(onFinished).toHaveBeenCalledExactlyOnceWith(status());+ await execution.apply();+ expect(rpc.apply).toHaveBeenCalledTimes(1);+ });++ it("rejects another selection or scope before requesting preview", async () => {+ const { execution } = setup();+ await expect(execution.prepare({ ...mutation, target: { ...target, name: "other" } as NativeJobRef })).rejects.toThrow("native_job_identity_mismatch");+ await expect(execution.prepare({ ...mutation, target: { ...target, scope: { ...scope, contextId: "other" } } })).rejects.toThrow("native_job_context_changed");+ expect(rpc.prepare).not.toHaveBeenCalled();+ });++ it("ignores a late preview after changing selection and retains the new selection's preview", async () => {+ const pending = deferred<NativeJobPreparedPlan>();+ rpc.prepare.mockReturnValueOnce(pending.promise);+ const { execution, selected } = setup();+ const first = execution.prepare(mutation);+ selected.value = { ...target, name: "other" } as NativeJobRef;+ const other = { ...plan, target: selected.value, planId: "other-plan" };+ rpc.prepare.mockResolvedValueOnce(other);+ await execution.prepare({ ...mutation, target: selected.value });+ pending.resolve(plan);+ await first;+ expect(execution.preview.value?.planId).toBe("other-plan");+ });++ it.each(["selection", "connection", "context"])("does not apply after %s changes while production confirmation is open", async (change) => {+ const confirmation = deferred<void>();+ rpc.guard.mockImplementation(async (options: { execute: () => Promise<unknown> }) => {+ await confirmation.promise;+ return options.execute();+ });+ const { execution, selected, connection, context } = setup();+ await execution.prepare(mutation);+ const applying = execution.apply();+ if (change === "selection") selected.value = { ...target, name: "other" } as NativeJobRef;+ if (change === "connection") connection.value.host = "different-host";+ if (change === "context") context.value = { ...scope, contextId: "new-context" };+ confirmation.resolve();+ await applying;+ expect(rpc.apply).not.toHaveBeenCalled();+ expect(execution.preview.value).toBeUndefined();+ });++ it("keeps a canceled confirmation available for review without sending a request", async () => {+ rpc.guard.mockResolvedValue(undefined);+ const { execution } = setup();+ await execution.prepare(mutation);+ await execution.apply();+ expect(execution.preview.value?.planId).toBe("plan");+ expect(rpc.apply).not.toHaveBeenCalled();+ });++ it("continues observing the original operation after dispatch without refreshing a different selection", async () => {+ const applied = deferred<NativeJobOperationStatus>();+ rpc.apply.mockReturnValue(applied.promise);+ rpc.status.mockResolvedValue(status());+ const { execution, selected, onFinished } = setup();+ await execution.prepare(mutation);+ const applying = execution.apply();+ selected.value = { ...target, name: "other" } as NativeJobRef;+ applied.resolve(status("running", "not_started"));+ await applying;+ expect(execution.execution.value).toBeUndefined();+ await vi.advanceTimersByTimeAsync(400);+ expect(rpc.status).toHaveBeenCalledExactlyOnceWith("operation");+ expect(onFinished).not.toHaveBeenCalled();+ selected.value = target;+ expect(execution.execution.value?.status.outcome).toBe("accepted");+ expect(rpc.apply).toHaveBeenCalledTimes(1);+ });++ it("looks up a lost apply receipt and allows a read-only recheck after transport loss, never replay", async () => {+ rpc.apply.mockRejectedValue(new Error("apply response lost"));+ rpc.status.mockRejectedValueOnce(new Error("status transport unavailable"));+ const { execution } = setup();+ await execution.prepare(mutation);+ await execution.apply();+ expect(execution.execution.value?.status.outcome).toBe("unknown");+ expect(execution.execution.value?.error).toBe("status transport unavailable");+ rpc.status.mockResolvedValue(status("finished", "verified"));+ await execution.refresh();+ expect(execution.execution.value?.status.outcome).toBe("verified");+ expect(rpc.apply).toHaveBeenCalledTimes(1);+ expect(rpc.status).toHaveBeenCalledTimes(2);+ });++ it("uses operation cancellation instead of submitting native STOP and stops polling on page disposal", async () => {+ rpc.apply.mockResolvedValue(status("running", "not_started"));+ rpc.cancel.mockResolvedValue({ ...status("running", "not_started"), cancelRequested: true });+ const { execution, owner } = setup();+ await execution.prepare(mutation);+ await execution.apply();+ await execution.cancel();+ expect(rpc.cancel).toHaveBeenCalledExactlyOnceWith("operation");+ expect(rpc.prepare).toHaveBeenCalledTimes(1);+ expect(execution.execution.value?.status.cancelRequested).toBe(true);+ owner.stop();+ await vi.advanceTimersByTimeAsync(1000);+ expect(rpc.status).not.toHaveBeenCalled();+ expect(rpc.cancel).toHaveBeenCalledTimes(1);+ });++ it("previews creation with its scope and does not invent a target before OUT returns", async () => {+ rpc.prepare.mockResolvedValue({ ...plan, target: null });+ const { execution } = setup();+ await execution.prepare({ action: "create", scope, definition: { kind: "legacy", what: "BEGIN NULL; END;", nextDate: "2026-10-21 00:00:00", interval: "null", enabled: false } });+ expect(execution.preview.value?.target).toBeNull();+ expect(rpc.prepare).toHaveBeenCalledTimes(1);+ expect(rpc.apply).not.toHaveBeenCalled();+ });++ it("keeps creation results beside the returned OUT identity when the page selects the new job", async () => {+ rpc.prepare.mockResolvedValue({ ...plan, target: null });+ const created: NativeJobRef = { scope, kind: "legacy", jobId: "900719925474099312345" };+ rpc.apply.mockResolvedValue({ ...status("finished", "verified"), target: created });+ const { execution, selected, onFinished } = setup();+ onFinished.mockImplementation(() => {+ selected.value = created;+ });+ await execution.prepare({ action: "create", scope, definition: { kind: "legacy", what: "BEGIN NULL; END;", nextDate: "2026-10-21 00:00:00", interval: "null", enabled: false } });+ await execution.apply();+ expect(execution.execution.value?.status.target).toEqual(created);+ expect(execution.execution.value?.status.outcome).toBe("verified");+ });+});diff --git a/apps/desktop/src/composables/useNativeJobExecution.ts b/apps/desktop/src/composables/useNativeJobExecution.tsnew file mode 100644index 0000000000..6d5d2e2a0a--- /dev/null+++ b/apps/desktop/src/composables/useNativeJobExecution.ts@@ -0,0 +1,212 @@+import { computed, onScopeDispose, ref, shallowRef, watch } from "vue";+import * as api from "@/lib/backend/api";+import { connectionConfigFingerprint } from "@/lib/connection/connectionDatabaseInfo";+import { executeWithProductionContextGuard } from "@/lib/database/productionExecutionGuard";+import { nativeJobRefKey, type NativeJobOperationStatus, type NativeJobPreparedPlan, type NativeJobRef, type NativeJobRequest, type NativeJobScope } from "@/lib/database/nativeJobs";+import type { ConnectionConfig } from "@/types/database";++interface JobExecutionOptions {+ connection: () => ConnectionConfig;+ database: () => string;+ scope: () => NativeJobScope | undefined;+ selected: () => NativeJobRef | undefined;+ source: () => string;+ onFinished?: (status: NativeJobOperationStatus) => Promise<void> | void;+ onTargetObserved?: (status: NativeJobOperationStatus, originalTarget: NativeJobRef) => Promise<void> | void;+}++interface PreparedJob {+ plan: NativeJobPreparedPlan;+ identity: string;+ sourceIdentity: string;+ connection: ConnectionConfig;+ database: string;+}++interface JobExecution {+ prepared: PreparedJob;+ status: NativeJobOperationStatus;+ error: string;+ notified: boolean;+ callbackGeneration: number;+}++function errorMessage(error: unknown): string {+ return error instanceof Error ? error.message : String(error);+}++function sameScope(left: NativeJobScope, right: NativeJobScope | undefined): boolean {+ return !!right && left.connectionId === right.connectionId && left.database === right.database && left.contextId === right.contextId;+}++/** One management page's preview/confirmation/result lifecycle; native execution stays in Core. */+export function useNativeJobExecution(options: JobExecutionOptions) {+ const prepared = shallowRef<PreparedJob>();+ const execution = shallowRef<JobExecution>();+ const preparing = ref(false);+ const confirming = ref(false);+ const observing = ref(false);+ const error = ref("");+ const callbackGeneration = ref(0);+ let generation = 0;+ let refreshGeneration = 0;+ let disposed = false;+ let timer: ReturnType<typeof setTimeout> | undefined;++ const sourceIdentity = computed(() => JSON.stringify([connectionConfigFingerprint(options.connection()), options.database(), options.scope()]));+ const identity = computed(() => JSON.stringify([sourceIdentity.value, options.selected() ? nativeJobRefKey(options.selected()!) : null]));+ const busy = computed(() => confirming.value || (!!execution.value && execution.value.status.state !== "finished"));+ const preview = computed(() => prepared.value?.plan);+ function isVisible(current: JobExecution) {+ return current.prepared.sourceIdentity === sourceIdentity.value && (current.prepared.identity === identity.value || (!!current.status.target && !!options.selected() && nativeJobRefKey(current.status.target) === nativeJobRefKey(options.selected()!)));+ }+ const visibleExecution = computed(() => (execution.value && isVisible(execution.value) ? execution.value : undefined));+ const previousExecution = computed(() => {+ const current = execution.value;+ return current && current.callbackGeneration !== callbackGeneration.value && connectionConfigFingerprint(current.prepared.connection) === connectionConfigFingerprint(options.connection()) && current.prepared.database === options.database() ? current : undefined;+ });++ function invalidatePreview() {+ generation += 1;+ prepared.value = undefined;+ preparing.value = false;+ error.value = "";+ }++ watch(identity, invalidatePreview, { flush: "sync" });++ async function prepare(request: NativeJobRequest) {+ const requestedScope = request.action === "create" ? request.scope : request.target.scope;+ if (!sameScope(requestedScope, options.scope())) throw new Error("native_job_context_changed");+ if (request.action !== "create" && (!options.selected() || nativeJobRefKey(request.target) !== nativeJobRefKey(options.selected()!))) throw new Error("native_job_identity_mismatch");+ const current = ++generation;+ const expectedIdentity = identity.value;+ const connection = { ...options.connection() };+ const database = options.database();+ prepared.value = undefined;+ preparing.value = true;+ error.value = "";+ try {+ const plan = await api.nativeJobPrepare(request);+ if (disposed || current !== generation || expectedIdentity !== identity.value) return;+ if (!sameScope(plan.scope, requestedScope) || (request.action !== "create" && (!plan.target || nativeJobRefKey(plan.target) !== nativeJobRefKey(request.target)))) throw new Error("native_job_identity_mismatch");+ prepared.value = { plan, identity: expectedIdentity, sourceIdentity: sourceIdentity.value, connection, database };+ return plan;+ } catch (failure) {+ if (!disposed && current === generation && expectedIdentity === identity.value) error.value = errorMessage(failure);+ } finally {+ if (current === generation) preparing.value = false;+ }+ }++ function schedulePoll(current: JobExecution) {+ if (disposed || execution.value !== current || current.status.state === "finished") return;+ if (timer) clearTimeout(timer);+ timer = setTimeout(() => void refreshExecution(current), 400);+ }++ async function acceptStatus(current: JobExecution, status: NativeJobOperationStatus) {+ if (disposed || execution.value !== current) return;+ if (status.operationId !== current.prepared.plan.operationId) throw new Error("native_job_identity_mismatch");+ current.status = status;+ current.error = "";+ execution.value = { ...current };+ // Keep this request's identity even if the page now displays another job.+ const updated = execution.value;+ if (status.state === "finished") {+ if (current.callbackGeneration === callbackGeneration.value && current.prepared.plan.target && isVisible(updated)) {+ await options.onTargetObserved?.(status, current.prepared.plan.target);+ if (disposed || execution.value !== updated) return;+ }+ if (updated.callbackGeneration === callbackGeneration.value && !updated.notified) {+ updated.notified = true;+ if (isVisible(updated)) await options.onFinished?.(status);+ }+ } else {+ schedulePoll(updated);+ }+ }++ async function refreshExecution(current = execution.value, observe = false) {+ if (!current || disposed || execution.value !== current) return;+ if (timer) clearTimeout(timer);+ timer = undefined;+ const requested = ++refreshGeneration;+ if (observe) observing.value = true;+ try {+ const status = observe ? await api.nativeJobStatus(current.prepared.plan.operationId, true) : await api.nativeJobStatus(current.prepared.plan.operationId);+ if (requested !== refreshGeneration) return;+ await acceptStatus(current, status);+ } catch (failure) {+ if (!disposed && requested === refreshGeneration && execution.value === current) execution.value = { ...current, error: errorMessage(failure) };+ } finally {+ if (requested === refreshGeneration) observing.value = false;+ }+ }++ async function apply() {+ const selected = prepared.value;+ if (!selected || busy.value) return;+ confirming.value = true;+ error.value = "";+ try {+ return await executeWithProductionContextGuard({+ connection: selected.connection,+ database: selected.database,+ reviewText: selected.plan.steps.map((step) => step.sql).join("\n\n"),+ source: options.source(),+ execute: async () => {+ if (disposed || prepared.value !== selected || identity.value !== selected.identity) throw new Error("native_job_context_changed");+ const plan = selected.plan;+ const current: JobExecution = {+ prepared: selected,+ status: { operationId: plan.operationId, target: plan.target, state: "running", outcome: "unknown", cancelRequested: false, steps: plan.steps.map((step) => ({ id: step.id, state: "pending", reason: null, vendorCode: null })), reason: "native_job_apply_receipt_unknown" },+ error: "",+ notified: false,+ callbackGeneration: callbackGeneration.value,+ };+ prepared.value = undefined;+ execution.value = current;+ schedulePoll(current);+ try {+ await acceptStatus(current, await api.nativeJobApply(plan.planId));+ } catch {+ // A missing apply receipt authorizes only status lookup, never another apply.+ await refreshExecution(current);+ }+ return execution.value?.status;+ },+ });+ } catch (failure) {+ if (!disposed && identity.value === selected.identity) error.value = errorMessage(failure);+ } finally {+ confirming.value = false;+ }+ }++ async function cancel() {+ const current = execution.value;+ if (!current || current.status.state === "finished") return;+ if (timer) clearTimeout(timer);+ timer = undefined;+ try {+ await acceptStatus(current, await api.nativeJobCancel(current.prepared.plan.operationId));+ } catch (failure) {+ if (!disposed && execution.value === current) execution.value = { ...current, error: errorMessage(failure) };+ }+ }++ onScopeDispose(() => {+ disposed = true;+ generation += 1;+ if (timer) clearTimeout(timer);+ // Closing the page stops observation, not a native operation already dispatched.+ });++ function invalidateContext() {+ callbackGeneration.value++;+ invalidatePreview();+ }++ return { preview, execution: visibleExecution, previousExecution, preparing, confirming, observing, busy, error, prepare, apply, cancel, refresh: () => refreshExecution(), observe: () => refreshExecution(execution.value, true), invalidatePreview, invalidateContext };+}diff --git a/apps/desktop/src/composables/useSidebarRemoteSearch.ts b/apps/desktop/src/composables/useSidebarRemoteSearch.tsindex 5386e6d491..3be1325e45 100644--- a/apps/desktop/src/composables/useSidebarRemoteSearch.ts+++ b/apps/desktop/src/composables/useSidebarRemoteSearch.ts@@ -1,5 +1,6 @@import { onScopeDispose, ref, shallowRef, watch, type Ref, type WatchSource } from "vue";-import type { SidebarRemoteSearchResult } from "@/lib/sidebar/sidebarRemoteSearch";+import { removeVerifiedSidebarTriggerSearchResult, type SidebarRemoteSearchResult } from "@/lib/sidebar/sidebarRemoteSearch";+import type { TreeNode } from "@/types/database";export function useSidebarRemoteSearch(options: {query: Ref<string>;@@ -86,5 +87,10 @@ export function useSidebarRemoteSearch(options: {);onScopeDispose(reset);- return { results, isLoading };+ const removeVerifiedTriggerNode = (node: TreeNode) => {+ abortPending();+ results.value = removeVerifiedSidebarTriggerSearchResult(results.value, node);+ schedule();+ };+ return { results, isLoading, removeVerifiedTriggerNode };}diff --git a/apps/desktop/src/composables/useSqlExecution.ts b/apps/desktop/src/composables/useSqlExecution.tsindex 269f091beb..b30512f1d8 100644--- a/apps/desktop/src/composables/useSqlExecution.ts+++ b/apps/desktop/src/composables/useSqlExecution.ts@@ -32,6 +32,7 @@ import type { SqlExecutionDangerRequest } from "@/stores/sqlExecutionDangerStoreimport type { ConnectionConfig, DatabaseType, QueryResult, QueryTab } from "@/types/database";import type { MultiDbExecutionTarget, MultiDbResultRunExecution, MultiDbTargetExecutionResult, MultiDbManualTransaction } from "@/types/sqlExecution";import { effectiveDatabaseTypeForConnection, kingbaseSqlDatabaseType } from "@/lib/database/jdbcDialect";+import { oracleTriggerReadOptions } from "@/lib/database/oracleTriggerIdentity";import type { SqlExecutionTargetContext } from "@/lib/database/sqlExecutionTargetRegistry";import { MULTI_SOURCE_MAX_ROWS_PER_SOURCE } from "@/lib/query/multiSourceResult";import { translateBackendError } from "@/i18n/backend-errors";@@ -332,6 +333,13 @@ export function useSqlExecution(deps: {cancelEditorViewportRequest(editorViewportRequestId);return notStarted("missing-database", context.tabId);}+ if (tab.objectSource?.objectType === "TRIGGER" && oracleTriggerReadOptions(effectiveDatabaseTypeForConnection(context.connection))) {+ const previousResult = queryStore.oracleTriggerSourceState(tab.id)?.result;+ const ok = await queryStore.runOracleTriggerSourceAction(tab.id, "replace", sql);+ cancelEditorViewportRequest(editorViewportRequestId);+ const state = queryStore.oracleTriggerSourceState(tab.id);+ return ok || (state?.result !== previousResult && state?.result?.steps.some((step) => step.receipt !== undefined)) ? { status: "started", ok, tabId: tab.id, errorMessage: state?.error } : notStarted("blocked", tab.id);+ }if (supportsSqlTemplateParameters(context.connection, sql) && prepareSqlParameterDialog(sql, sourceOffset, executionOptions)) {return deferred("parameters", context.tabId);}diff --git a/apps/desktop/src/i18n/locales/en.ts b/apps/desktop/src/i18n/locales/en.tsindex 1b3c101ac4..9e110a112b 100644--- a/apps/desktop/src/i18n/locales/en.ts+++ b/apps/desktop/src/i18n/locales/en.ts@@ -65,6 +65,27 @@ const consul = {};export default {+ oracleTrigger: {+ errorPositionUnavailable: "Source opened. The error location could not be verified; check the reported line and column.",+ reconcileStructure: "Reconcile applied changes",+ reconcileConfirm: "Reread the current table structure, keep the desired edits, and reconcile completed steps without replaying old SQL?",+ editFullSource: "Edit full source",+ refreshDraft: "Reload this trigger",+ refreshDraftConfirm: "Reload and discard only this trigger's structured draft? Other table structure drafts will be kept.",+ discardSourceConfirm: "Discard unsaved changes to this source?",+ scope: "Trigger scope",+ parentOwner: "Owning table/view schema",+ parentName: "Owning table/view",+ scopeOwner: "Event scope schema",+ obSchemaUnsupported: "No Schema trigger template is offered for this OB version: the tested template was rejected.",+ obDatabaseUnknown: "DATABASE trigger capability has not been verified.",+ nonAtomic: "DDL statements commit separately. The trigger may be enabled between creation and disablement. Failure stops later steps; nothing is retried automatically.",+ unknown: "Unknown",+ verifyReadOnly: "Verify without writing",+ reloadBaseline: "Keep the draft and reload the complete trigger before previewing again.",+ runFullDefinition: "This trigger tab can run only this object's complete definition. Use a normal query tab for other SQL.",+ executionSchema: "Execution schema",+ },objectRelations: {title: "Relations",foreignKeys: "Foreign keys",@@ -5207,6 +5228,7 @@ export default {manage: "Manage database links",},tree: {+ nativeJobs: "Native jobs",savedSql: "SQL Library",queries: "Queries",userAdmin: "Users & Privileges",@@ -6061,6 +6083,199 @@ export default {operationFailed: "Operation failed",operationFailedWithMessage: "Operation failed: {message}",},+ nativeJobs: {+ datePrecisionMicroseconds: "Job dates in this OceanBase version support microsecond precision only. Set fractional-second digits 7–9 to 0 and preview again; your original input has been retained.",+ previousContext: "Operation result from the previous context",+ detachedDraft: "The original draft was retained and is not bound to the current object.",+ viewRetainedDraft: "View original draft",+ damengIntervalAccepted: "The interval call succeeded; the original expression cannot be verified by reading it back from the catalog.",+ damengInterval: "Interval in seconds or native expression",+ damengIntervalHint: "A positive integer sets a fixed interval in seconds; all other input is passed as a native expression and is not evaluated during preview.",+ executionObservation: "Native execution observations",+ observeExecution: "Refresh run results",+ associationUncertain: "The association between native instances and this request is uncertain.",+ observationUnavailable: "The execution instance cannot be reliably associated; refresh run results or view the native record.",+ newlyObserved: "Newly observed since before the request",+ observedInstance: "Observed instance",+ instanceNotObserved: "This instance is not currently observed",+ observationEmpty: "There are currently no reliably identifiable candidate instances.",+ observationReadStatus: "Current runs: {running}; history: {history}",+ observationNativeDetails: "Native record",+ observationTimestamp: "Observed at: {time}",+ scalarStorage: "Value storage type",+ scalarText: "Plain text",+ scalarNull: "NULL for this type",+ scalarCivilDate: "Date",+ scalarCivilHint: "YYYY-MM-DD; use a negative year for BCE, with no year 0",+ scalarDateClock: "Time (HH:MM:SS, whole seconds)",+ scalarClock: "Time (HH:MM:SS, up to 9 decimal places)",+ scalarUtc: "Edit in UTC; saved as a timestamp in the database local time zone",+ scalarRegion: "Time zone region",+ scalarOffset: "UTC offset (±HH:MM)",+ scalarAbbreviation: "Time zone abbreviation (optional)",+ scalarMonths: "Total months (signed integer)",+ scalarNanoseconds: "Total nanoseconds (signed integer)",+ scalarHex: "RAW bytes (hexadecimal)",+ scalarFloatHex: "IEEE 754 bit pattern (8 hexadecimal digits, big-endian)",+ scalarDoubleHex: "IEEE 754 bit pattern (16 hexadecimal digits, big-endian)",+ scalarUrowid: "Full UROWID",+ finalEnabledHint: "This enabled state is applied only after the definition and arguments are verified.",+ transitionPreviewHint: "Pause future scheduling first; apply the selected enabled state after all checks pass.",+ legacyRunRestoresScheduling: "This foreground run also resumes future scheduling and lets the database recalculate the next run time.",+ legacyRuntimeUpdateRequired: "The current runtime lacks the OceanBase traditional Job protocol. Update this connection's Agent or JDBC plugin, then try again.",+ title: "Native jobs",+ unsupported: "This connection does not support native job management.",+ kind: "Job type",+ createKind: "New job type",+ owner: "Owner",+ ownerFilter: "Filter by owner",+ definition: "Definition",+ arguments: "Arguments",+ advanced: "Advanced attributes",+ restoreDefinitionDraft: "Restore original definition draft",+ addArgument: "Add argument",+ argumentPosition: "Argument {position}",+ argumentType: "Type of argument {position}",+ argumentState: "State of argument {position}",+ argumentValue: "Value of argument {position}",+ scheduleMode: "Trigger",+ scheduleModes: { inline: "Date or repeat rule", named: "Named schedule or window", queue: "Queue event", fileWatcher: "File arrival event" },+ destinationMode: "Execution target",+ destinationModes: { local: "Run locally", legacy: "Legacy remote host (host[:port])", named: "Named destination or group" },+ eventCondition: "Event condition",+ eventQueueOwner: "Queue owner",+ eventQueueName: "Queue name",+ eventQueueAgent: "AQ agent (optional)",+ fileWatcherOwner: "File watcher owner",+ fileWatcherName: "File watcher name",+ chooseReference: "Choose {kind}",+ inactiveInlineDraft: "A named reference is selected. Inline fields remain in the draft and will not be written.",+ referenceFilter: "Search owner or name",+ emptyReferences: "No matching objects in the readable scope.",+ referenceCatalogUnavailable: "Cannot read the referenced-object list ({status}). You can still enter the exact owner and name.",+ catalogCoverage: { database: "Database-wide", accessible: "Accessible to this account", current_user: "Owned by this account", unknown: "Unknown scope" },+ opaqueArgument: "This native value cannot be safely rewritten as text; keep its original value.",+ programDefault: "Program default",+ programDefaultUnknown: "The default value could not be determined. Keep the original value.",+ metadataArgument: "Provided by the database: {attribute}",+ argumentCatalogUnavailable: "This version only provides placeholder argument views. They cannot identify existing arguments or values.",+ obSchedulerDefinitionReadOnly: "Existing job base definitions are read-only in this OceanBase version. Edit run limits and the execution zone under Advanced.",+ runForeground: "Run in foreground",+ forceStop: "Force stop",+ legacyNoStop: "Traditional DBMS_JOB has no native stop operation. Killing a session is not the same as stopping a job.",+ baselineUnavailable: "The object identity or consistency baseline is unreadable. Read again before making changes.",+ kinds: { scheduler: "Scheduler job", legacy: "Traditional Job", "dameng-native": "Dameng agent job" },+ argumentStates: { unset: "Unset", inherit: "Inherit default", null: "SQL NULL", value: "Explicit value", opaque: "Native value" },+ referenceKinds: { program: "Program", schedule: "Schedule", chain: "Chain", credential: "Credential", destination: "Destination", window: "Window", "window-group": "Window group", "file-watcher": "File watcher", "destination-group": "Destination group" },+ jobTypes: { PLSQL_BLOCK: "PL/SQL block", STORED_PROCEDURE: "Stored procedure", CHAIN: "Chain", EXECUTABLE: "Executable", EXTERNAL_SCRIPT: "External script", SQL_SCRIPT: "SQL script", BACKUP_SCRIPT: "Backup script" },+ loggingLevels: { OFF: "Off", RUNS: "Runs", FAILED_RUNS: "Failed runs only", FULL: "Full" },+ definitionFields: {+ ENABLED: "Enable when ready",+ WHAT: "Job body",+ NEXT_DATE: "Next run date",+ INTERVAL: "Repeat expression",+ INSTANCE: "Instance",+ ZONE: "Zone",+ JOB_TYPE: "Job type",+ JOB_ACTION: "Job action",+ NUMBER_OF_ARGUMENTS: "Argument count",+ PROGRAM_OWNER: "Program owner",+ PROGRAM_NAME: "Program name",+ SCHEDULE_OWNER: "Schedule owner",+ SCHEDULE_NAME: "Schedule name",+ START_DATE: "Start date with UTC offset",+ END_DATE: "End date with UTC offset",+ REPEAT_INTERVAL: "Repeat interval",+ AUTO_DROP: "Auto-drop on completion",+ COMMENTS: "Comments",+ LOG_USER: "Login user",+ PRIV_USER: "Privilege user",+ SCHEMA_USER: "Execution schema",+ JOB_CLASS: "Job class",+ JOB_PRIORITY: "Priority",+ MAX_RUNS: "Maximum runs",+ MAX_FAILURES: "Maximum failures",+ MAX_RUN_DURATION: "Maximum run duration",+ SCHEDULE_LIMIT: "Scheduling delay limit",+ RESTARTABLE: "Allow restart",+ STOP_ON_WINDOW_CLOSE: "Stop when the window closes",+ STORE_OUTPUT: "Store run output",+ ALLOW_RUNS_IN_RESTRICTED_MODE: "Allow runs in restricted mode",+ INSTANCE_STICKINESS: "Instance affinity",+ FOLLOW_DEFAULT_TIMEZONE: "Follow default timezone",+ INSTANCE_ID: "Execution instance",+ JOB_WEIGHT: "Job weight",+ RAISE_EVENTS: "Raised event mask",+ CONNECT_CREDENTIAL_NAME: "Connection credential",+ CREDENTIAL_NAME: "Run credential",+ DESTINATION_NAME: "Named destination",+ DESTINATION: "Remote host (host[:port])",+ JOB_STYLE: "Job style",+ LOGGING_LEVEL: "Logging level",+ },+ editJob: "Edit job",+ editSections: "Job configuration",+ add: "Add",+ attributes: "Job properties",+ steps: "Steps",+ schedules: "Schedules",+ running: "Current runs",+ unknown: "Unknown",+ emptyJobs: "No jobs in the current scope.",+ noMatches: "No matching jobs.",+ previousPage: "Previous",+ nextPage: "Next",+ pendingDrop: "Pending deletion",+ pendingAdd: "New",+ undoDrop: "Undo deletion",+ keepOriginal: "Keep original",+ explicitNull: "Set to NULL after confirmation",+ partitionUnavailable: "This section is {status} and cannot be edited as complete data.",+ generatedCommandHint: "This is database-generated SQL. To modify a backup or DTS definition, enter its original native configuration above. Changing only the next step does not require it.",+ runningUnknownHint: "Running state is unavailable. A native stop can still be requested with the required permission.",+ cancelFollowing: "Stop remaining steps",+ readAgain: "Read again",+ correctDraft: "Correct draft",+ operationStatusUnavailable: "Unable to confirm the latest operation status. Please check the operation result.",+ checkResult: "Check operation result",+ keepOperator: "Keep operator ID {id}; enter a name to replace it.",+ nextStepHint: "Used only by actions that continue execution. NULL follows the native step order.",+ stepTypes: { "0": "SQL or block", "1": "Backup/restore V1", "2": "Reorganize database", "3": "Update statistics", "4": "DTS migration", "5": "Backup/restore V1 (extended)", "6": "Backup/restore V2" },+ scheduleTypes: { "0": "Once", "1": "Daily", "2": "Weekly", "3": "Monthly date", "4": "First week of month", "5": "Second week of month", "6": "Third week of month", "7": "Fourth week of month", "8": "Last week of month" },+ actions: { "0": "End without reporting", "1": "Report and end", "2": "Continue without reporting", "3": "Report and continue" },+ notificationTypes: { "0": "On success", "1": "On failure", "2": "On completion" },+ outcomes: { running: "Executing operation", not_started: "Not started", not_applied: "Not applied", partial: "Some steps were applied", unknown: "Outcome unknown; inspect before preparing again", verified: "Operation verified", accepted: "Request accepted; run outcome not yet confirmed" },+ stepStates: { pending: "Pending", dispatching: "Dispatched", applied: "Executed", accepted: "Accepted", failed: "Not applied", unknown: "Unknown", skipped: "Not executed" },+ fields: {+ NAME: "Name",+ ENABLE: "Final enabled state",+ DESCRIBE: "Description",+ ENABLE_EMAIL: "Email notification",+ EMAIL_OPERATOR_NAME: "Email operator name",+ EMAIL_TYPE: "Email condition",+ ENABLE_NETSEND: "Network notification",+ NETSEND_OPERATOR_NAME: "Network operator name",+ NETSEND_TYPE: "Network condition",+ EP_SEQNO: "Execution node (0–15)",+ RAFT_NAME: "RAFT group",+ TYPE: "Type",+ COMMAND_INPUT: "SQL body or native configuration",+ SUCC_ACTION: "Action after success",+ SUCC_NEXT_STEP: "Next step on success",+ FAIL_ACTION: "Action after failure",+ FAIL_NEXT_STEP: "Next step on failure",+ RETRY_ATTEMPTS: "Retry attempts",+ RETRY_INTERVAL: "Retry interval (seconds)",+ APPEND_FLAG: "Append output",+ FREQ_INTERVAL: "Frequency interval",+ FREQ_SUB_INTERVAL: "Week/month condition",+ FREQ_MINUTE_INTERVAL: "Daily interval (minutes; 0 runs once)",+ STARTTIME: "Start time",+ ENDTIME: "End time",+ DURING_START_DATE: "Valid from",+ DURING_END_DATE: "Valid until",+ },+ },damengJobAdmin: {title: "Dameng Agent Jobs",unsupported: "This page only supports Dameng connections.",diff --git a/apps/desktop/src/i18n/locales/es.ts b/apps/desktop/src/i18n/locales/es.tsindex b23eecf01f..f16666498a 100644--- a/apps/desktop/src/i18n/locales/es.ts+++ b/apps/desktop/src/i18n/locales/es.ts@@ -67,6 +67,27 @@ const consul = {};export default withEnglishFallback({+ oracleTrigger: {+ errorPositionUnavailable: "Código fuente abierto. No se pudo verificar la ubicación del error; consulte la línea y la columna indicadas.",+ reconcileStructure: "Reconciliar cambios aplicados",+ reconcileConfirm: "¿Volver a leer la estructura actual, conservar los cambios deseados y reconciliar los pasos completados sin repetir el SQL anterior?",+ editFullSource: "Editar fuente completa",+ refreshDraft: "Recargar este disparador",+ refreshDraftConfirm: "¿Recargar y descartar solo el borrador estructurado de este disparador? Se conservarán los demás borradores de la estructura de tabla.",+ discardSourceConfirm: "¿Descartar los cambios sin guardar de este código fuente?",+ scope: "Ámbito del disparador",+ parentOwner: "Esquema de la tabla/vista",+ parentName: "Tabla/vista asociada",+ scopeOwner: "Esquema de los eventos",+ obSchemaUnsupported: "Esta versión de OB no ofrece una plantilla de disparador de Schema: la plantilla probada fue rechazada.",+ obDatabaseUnknown: "No se ha verificado la capacidad de disparadores DATABASE.",+ nonAtomic: "Las sentencias DDL se confirman por separado. El disparador puede estar habilitado entre su creación y desactivación. Un fallo detiene los pasos posteriores; no hay reintentos automáticos.",+ unknown: "Desconocido",+ verifyReadOnly: "Verificar sin escribir",+ reloadBaseline: "Conserve el borrador y vuelva a cargar el disparador completo antes de generar otra vista previa.",+ runFullDefinition: "Esta pestaña solo puede ejecutar la definición completa de este disparador. Use una pestaña de consulta normal para otro SQL.",+ executionSchema: "Esquema de ejecución",+ },objectRelations: {title: "Relaciones",foreignKeys: "Claves externas",@@ -4964,6 +4985,7 @@ export default withEnglishFallback({manage: "Manage database links",},tree: {+ nativeJobs: "Trabajos nativos",databaseLinks: "Database Links",savedSql: "Biblioteca SQL",queries: "Consultas",@@ -5138,6 +5160,207 @@ export default withEnglishFallback({scopeFunctions: "funciones",stepSkipped: "Omitido porque falló un paso anterior requerido.",},+ nativeJobs: {+ datePrecisionMicroseconds: "Las fechas de los trabajos en esta versión de OceanBase solo admiten precisión de microsegundos. Cambie a 0 los dígitos 7–9 de los segundos fraccionarios y vuelva a generar la vista previa; se conservó la entrada original.",+ previousContext: "Resultado de la operación del contexto anterior",+ detachedDraft: "Se conservó el borrador original; no está vinculado al objeto actual.",+ viewRetainedDraft: "Ver borrador original",+ damengIntervalAccepted: "La llamada de intervalo se realizó correctamente; no se puede verificar la expresión original leyéndola de nuevo del catálogo.",+ damengInterval: "Intervalo en segundos o expresión nativa",+ damengIntervalHint: "Un entero positivo establece un intervalo fijo en segundos; cualquier otro contenido se pasa como expresión nativa y no se evalúa durante la vista previa.",+ executionObservation: "Observaciones de ejecución nativa",+ observeExecution: "Actualizar resultados de ejecución",+ associationUncertain: "La relación entre las instancias nativas y esta solicitud es incierta.",+ observationUnavailable: "No se puede asociar la instancia de ejecución de forma fiable; actualice los resultados de ejecución o consulte el registro nativo.",+ newlyObserved: "Observado recientemente respecto a antes de la solicitud",+ observedInstance: "Instancia observada",+ instanceNotObserved: "Esta instancia no se observa actualmente",+ observationEmpty: "Actualmente no hay instancias candidatas que puedan identificarse de forma fiable.",+ observationReadStatus: "Ejecuciones actuales: {running}; historial: {history}",+ observationNativeDetails: "Registro nativo",+ observationTimestamp: "Hora de observación: {time}",+ scalarStorage: "Tipo de almacenamiento del valor",+ scalarText: "Texto sin formato",+ scalarNull: "NULL de este tipo",+ scalarCivilDate: "Fecha",+ scalarCivilHint: "YYYY-MM-DD; use un año negativo para fechas a. C.; no existe el año 0",+ scalarDateClock: "Hora (HH:MM:SS, segundos enteros)",+ scalarClock: "Hora (HH:MM:SS, hasta 9 decimales)",+ scalarUtc: "Edite en UTC; se guarda como marca de tiempo en la zona horaria local de la base de datos",+ scalarRegion: "Región de zona horaria",+ scalarOffset: "Desfase UTC (±HH:MM)",+ scalarAbbreviation: "Abreviatura de zona horaria (opcional)",+ scalarMonths: "Meses totales (entero con signo)",+ scalarNanoseconds: "Nanosegundos totales (entero con signo)",+ scalarHex: "Bytes RAW (hexadecimal)",+ scalarFloatHex: "Patrón de bits IEEE 754 (8 dígitos hexadecimales, big-endian)",+ scalarDoubleHex: "Patrón de bits IEEE 754 (16 dígitos hexadecimales, big-endian)",+ scalarUrowid: "UROWID completo",+ finalEnabledHint: "Este estado de activación solo se aplica tras verificar la definición y los argumentos.",+ transitionPreviewHint: "Pause primero la programación futura; aplique el estado de activación elegido cuando se hayan superado todas las verificaciones.",+ legacyRunRestoresScheduling: "Esta ejecución en primer plano también reanuda la programación futura y hace que la base de datos recalcule la próxima ejecución.",+ legacyRuntimeUpdateRequired: "El entorno actual no incluye el protocolo de tareas tradicionales de OceanBase. Actualice el Agent o el complemento JDBC de esta conexión y vuelva a intentarlo.",+ title: "Trabajos nativos",+ unsupported: "Esta conexión no admite la gestión de trabajos nativos.",+ kind: "Tipo de trabajo",+ createKind: "Tipo del nuevo trabajo",+ owner: "Propietario",+ ownerFilter: "Filtrar por propietario",+ definition: "Definición",+ arguments: "Argumentos",+ advanced: "Atributos avanzados",+ restoreDefinitionDraft: "Restaurar borrador de la definición original",+ addArgument: "Añadir argumento",+ argumentPosition: "Argumento {position}",+ argumentType: "Tipo del argumento {position}",+ argumentState: "Estado del argumento {position}",+ argumentValue: "Valor del argumento {position}",+ scheduleMode: "Modo de activación",+ scheduleModes: { inline: "Fecha o regla de repetición", named: "Programación o ventana con nombre", queue: "Evento de cola", fileWatcher: "Evento de llegada de archivo" },+ destinationMode: "Destino de ejecución",+ destinationModes: { local: "Ejecutar localmente", legacy: "Host remoto heredado (host[:port])", named: "Destino o grupo con nombre" },+ eventCondition: "Condición del evento",+ eventQueueOwner: "Propietario de la cola",+ eventQueueName: "Nombre de la cola",+ eventQueueAgent: "Agente AQ (opcional)",+ fileWatcherOwner: "Propietario de File watcher",+ fileWatcherName: "Nombre de File watcher",+ chooseReference: "Elegir {kind}",+ inactiveInlineDraft: "Se ha seleccionado una referencia con nombre. Los campos en línea se conservan en el borrador y no se escribirán.",+ referenceFilter: "Buscar propietario o nombre",+ emptyReferences: "No hay objetos coincidentes en el ámbito legible.",+ referenceCatalogUnavailable: "No se puede leer la lista de objetos referenciados ({status}). Puede introducir el propietario y el nombre exactos.",+ catalogCoverage: { database: "Toda la base de datos", accessible: "Accesible para esta cuenta", current_user: "Propiedad de esta cuenta", unknown: "Ámbito desconocido" },+ opaqueArgument: "Este valor nativo no puede reescribirse de forma segura como texto; conserve su valor original.",+ programDefault: "Valor predeterminado del programa",+ programDefaultUnknown: "No se pudo determinar el valor predeterminado. Conserve el valor original.",+ metadataArgument: "Proporcionado por la base de datos: {attribute}",+ argumentCatalogUnavailable: "Esta versión solo proporciona vistas de argumentos de compatibilidad vacías. No permiten identificar argumentos ni valores existentes.",+ obSchedulerDefinitionReadOnly: "En esta versión de OceanBase, la definición básica de los trabajos existentes es de solo lectura. Edite los límites de ejecución y la zona en Opciones avanzadas.",+ runForeground: "Ejecutar en primer plano",+ forceStop: "Forzar detención",+ legacyNoStop: "DBMS_JOB tradicional no dispone de una operación nativa de detención. Terminar una sesión no equivale a detener un trabajo.",+ baselineUnavailable: "No se puede leer la identidad del objeto o la base de coherencia. Vuelva a leer antes de modificar.",+ kinds: { scheduler: "Trabajo Scheduler", legacy: "Job tradicional", "dameng-native": "Trabajo de agente Dameng" },+ argumentStates: { unset: "Sin establecer", inherit: "Heredar valor predeterminado", null: "SQL NULL", value: "Valor explícito", opaque: "Valor nativo" },+ referenceKinds: { program: "Programa", schedule: "Programación", chain: "Cadena", credential: "Credencial", destination: "Destino", window: "Ventana", "window-group": "Grupo de ventanas", "file-watcher": "Monitor de archivos", "destination-group": "Grupo de destinos" },+ jobTypes: { PLSQL_BLOCK: "Bloque PL/SQL", STORED_PROCEDURE: "Procedimiento almacenado", CHAIN: "Cadena", EXECUTABLE: "Programa ejecutable", EXTERNAL_SCRIPT: "Script externo", SQL_SCRIPT: "Script SQL", BACKUP_SCRIPT: "Script de copia de seguridad" },+ loggingLevels: { OFF: "Sin registro", RUNS: "Ejecuciones", FAILED_RUNS: "Solo ejecuciones fallidas", FULL: "Registro completo" },+ definitionFields: {+ ENABLED: "Activar al finalizar",+ WHAT: "Contenido del trabajo",+ NEXT_DATE: "Próxima ejecución",+ INTERVAL: "Expresión de repetición",+ INSTANCE: "Instancia",+ ZONE: "Zona",+ JOB_TYPE: "Tipo de trabajo",+ JOB_ACTION: "Acción del trabajo",+ NUMBER_OF_ARGUMENTS: "Número de argumentos",+ PROGRAM_OWNER: "Propietario de Program",+ PROGRAM_NAME: "Nombre de Program",+ SCHEDULE_OWNER: "Propietario de Schedule",+ SCHEDULE_NAME: "Nombre de Schedule",+ START_DATE: "Inicio con desfase UTC",+ END_DATE: "Fin con desfase UTC",+ REPEAT_INTERVAL: "Intervalo de repetición",+ AUTO_DROP: "Eliminar automáticamente al finalizar",+ COMMENTS: "Comentarios",+ LOG_USER: "Usuario de inicio de sesión",+ PRIV_USER: "Usuario de privilegios",+ SCHEMA_USER: "Esquema de ejecución",+ JOB_CLASS: "Clase de trabajo",+ JOB_PRIORITY: "Prioridad",+ MAX_RUNS: "Máximo de ejecuciones",+ MAX_FAILURES: "Máximo de fallos",+ MAX_RUN_DURATION: "Duración máxima de ejecución",+ SCHEDULE_LIMIT: "Límite de retraso de programación",+ RESTARTABLE: "Permitir reinicio",+ STOP_ON_WINDOW_CLOSE: "Detener al cerrar la ventana",+ STORE_OUTPUT: "Guardar salida de ejecución",+ ALLOW_RUNS_IN_RESTRICTED_MODE: "Permitir ejecuciones en modo restringido",+ INSTANCE_STICKINESS: "Afinidad de instancia",+ FOLLOW_DEFAULT_TIMEZONE: "Seguir zona horaria predeterminada",+ INSTANCE_ID: "Instancia de ejecución",+ JOB_WEIGHT: "Peso del trabajo",+ RAISE_EVENTS: "Máscara de eventos generados",+ CONNECT_CREDENTIAL_NAME: "Credencial de conexión",+ CREDENTIAL_NAME: "Credencial de ejecución",+ DESTINATION_NAME: "Destino con nombre",+ DESTINATION: "Host remoto (host[:port])",+ JOB_STYLE: "Estilo de trabajo",+ LOGGING_LEVEL: "Nivel de registro",+ },+ editJob: "Editar trabajo",+ editSections: "Configuración del trabajo",+ add: "Añadir",+ attributes: "Propiedades del trabajo",+ steps: "Pasos",+ schedules: "Programaciones",+ running: "Ejecuciones actuales",+ unknown: "Desconocido",+ emptyJobs: "No hay trabajos en el ámbito actual.",+ noMatches: "No hay trabajos coincidentes.",+ previousPage: "Anterior",+ nextPage: "Siguiente",+ pendingDrop: "Pendiente de eliminación",+ pendingAdd: "Nuevo",+ undoDrop: "Deshacer eliminación",+ keepOriginal: "Conservar original",+ explicitNull: "Establecer NULL tras confirmar",+ partitionUnavailable: "Esta sección tiene el estado {status} y no se puede editar como datos completos.",+ generatedCommandHint: "Esta sentencia la genera la base de datos. Para modificar una copia de seguridad o DTS, introduce arriba la configuración nativa original. No es necesario si solo cambias el paso siguiente.",+ runningUnknownHint: "El estado de ejecución no está disponible. Aún puedes solicitar la detención nativa con los permisos necesarios.",+ cancelFollowing: "Detener pasos restantes",+ readAgain: "Volver a leer",+ correctDraft: "Corregir borrador",+ operationStatusUnavailable: "No se puede confirmar el estado más reciente de la operación. Consulte el resultado de la operación.",+ checkResult: "Consultar resultado",+ keepOperator: "Conservar el ID de operador {id}; introduce un nombre para sustituirlo.",+ nextStepHint: "Solo se usa en acciones que continúan la ejecución. NULL sigue el orden nativo de pasos.",+ stepTypes: { "0": "SQL o bloque", "1": "Copia/restauración V1", "2": "Reorganizar base de datos", "3": "Actualizar estadísticas", "4": "Migración DTS", "5": "Copia/restauración V1 (ampliada)", "6": "Copia/restauración V2" },+ scheduleTypes: { "0": "Una vez", "1": "Diaria", "2": "Semanal", "3": "Fecha mensual", "4": "Primera semana del mes", "5": "Segunda semana del mes", "6": "Tercera semana del mes", "7": "Cuarta semana del mes", "8": "Última semana del mes" },+ actions: { "0": "Terminar sin informar", "1": "Informar y terminar", "2": "Continuar sin informar", "3": "Informar y continuar" },+ notificationTypes: { "0": "Al tener éxito", "1": "Al fallar", "2": "Al terminar" },+ outcomes: {+ running: "Ejecutando operación",+ not_started: "Sin iniciar",+ not_applied: "No aplicada",+ partial: "Algunos pasos se han aplicado",+ unknown: "Resultado desconocido; comprueba antes de generar otra vista previa",+ verified: "Resultado verificado",+ accepted: "Solicitud aceptada; resultado de ejecución pendiente",+ },+ stepStates: { pending: "Pendiente", dispatching: "Enviado", applied: "Ejecutado", accepted: "Aceptado", failed: "No aplicado", unknown: "Desconocido", skipped: "No ejecutado" },+ fields: {+ NAME: "Nombre",+ ENABLE: "Estado habilitado final",+ DESCRIBE: "Descripción",+ ENABLE_EMAIL: "Notificación por correo",+ EMAIL_OPERATOR_NAME: "Operador de correo",+ EMAIL_TYPE: "Condición de correo",+ ENABLE_NETSEND: "Notificación de red",+ NETSEND_OPERATOR_NAME: "Operador de red",+ NETSEND_TYPE: "Condición de red",+ EP_SEQNO: "Nodo de ejecución (0–15)",+ RAFT_NAME: "Grupo RAFT",+ TYPE: "Tipo",+ COMMAND_INPUT: "SQL o configuración nativa",+ SUCC_ACTION: "Acción tras el éxito",+ SUCC_NEXT_STEP: "Paso siguiente tras éxito",+ FAIL_ACTION: "Acción tras el fallo",+ FAIL_NEXT_STEP: "Paso siguiente tras fallo",+ RETRY_ATTEMPTS: "Número de reintentos",+ RETRY_INTERVAL: "Intervalo de reintentos (segundos)",+ APPEND_FLAG: "Añadir salida",+ FREQ_INTERVAL: "Frecuencia",+ FREQ_SUB_INTERVAL: "Condición semanal/mensual",+ FREQ_MINUTE_INTERVAL: "Intervalo diario (minutos; 0 ejecuta una vez al día)",+ STARTTIME: "Hora de inicio",+ ENDTIME: "Hora de fin",+ DURING_START_DATE: "Válido desde",+ DURING_END_DATE: "Válido hasta",+ },+ },damengJobAdmin: {title: "Trabajos del agente Dameng",unsupported: "Esta página solo admite conexiones Dameng.",diff --git a/apps/desktop/src/i18n/locales/it.ts b/apps/desktop/src/i18n/locales/it.tsindex b056867dda..9769ee772f 100644--- a/apps/desktop/src/i18n/locales/it.ts+++ b/apps/desktop/src/i18n/locales/it.ts@@ -65,6 +65,27 @@ const consul = {};export default withEnglishFallback({+ oracleTrigger: {+ errorPositionUnavailable: "Sorgente aperto. Impossibile verificare la posizione dell'errore; controllare la riga e la colonna indicate.",+ reconcileStructure: "Riconcilia le modifiche applicate",+ reconcileConfirm: "Rileggere la struttura attuale, conservare le modifiche desiderate e riconciliare i passaggi completati senza rieseguire il vecchio SQL?",+ editFullSource: "Modifica sorgente completo",+ refreshDraft: "Ricarica questo trigger",+ refreshDraftConfirm: "Ricaricare scartando solo la bozza strutturata di questo trigger? Le altre bozze della struttura della tabella verranno conservate.",+ discardSourceConfirm: "Scartare le modifiche non salvate a questo sorgente?",+ scope: "Ambito del trigger",+ parentOwner: "Schema della tabella/vista",+ parentName: "Tabella/vista associata",+ scopeOwner: "Schema degli eventi",+ obSchemaUnsupported: "Questa versione di OB non offre un modello di trigger Schema: il modello provato è stato rifiutato.",+ obDatabaseUnknown: "Il supporto dei trigger DATABASE non è stato verificato.",+ nonAtomic: "Le istruzioni DDL vengono confermate separatamente. Il trigger può essere attivo tra la creazione e la disattivazione. Un errore interrompe i passaggi successivi, senza tentativi automatici.",+ unknown: "Sconosciuto",+ verifyReadOnly: "Verifica senza scrivere",+ reloadBaseline: "Conserva la bozza e ricarica il trigger completo prima di visualizzare una nuova anteprima.",+ runFullDefinition: "Questa scheda può eseguire solo la definizione completa del trigger. Usa una normale scheda di query per altro SQL.",+ executionSchema: "Schema di esecuzione",+ },objectRelations: {title: "Relazioni",foreignKeys: "Chiavi esterne",@@ -4785,6 +4806,7 @@ export default withEnglishFallback({manage: "Manage database links",},tree: {+ nativeJobs: "Job nativi",databaseLinks: "Database Links",savedSql: "Libreria SQL",queries: "Query",@@ -4958,6 +4980,207 @@ export default withEnglishFallback({scopeFunctions: "funzioni",stepSkipped: "Ignorato perché un passaggio precedente richiesto non è riuscito.",},+ nativeJobs: {+ datePrecisionMicroseconds: "Le date dei job in questa versione di OceanBase supportano solo la precisione al microsecondo. Imposta a 0 le cifre 7–9 dei secondi frazionari e genera di nuovo l'anteprima; l'input originale è stato conservato.",+ previousContext: "Risultato dell'operazione del contesto precedente",+ detachedDraft: "La bozza originale è stata conservata e non è associata all'oggetto corrente.",+ viewRetainedDraft: "Visualizza la bozza originale",+ damengIntervalAccepted: "La chiamata dell'intervallo è riuscita; non è possibile verificare l'espressione originale rileggendola dal catalogo.",+ damengInterval: "Intervallo in secondi o espressione nativa",+ damengIntervalHint: "Un intero positivo imposta un intervallo fisso in secondi; qualsiasi altro contenuto viene passato come espressione nativa e non viene valutato nell'anteprima.",+ executionObservation: "Osservazioni dell'esecuzione nativa",+ observeExecution: "Aggiorna i risultati dell'esecuzione",+ associationUncertain: "L'associazione tra le istanze native e questa richiesta è incerta.",+ observationUnavailable: "Impossibile associare in modo affidabile l'istanza di esecuzione; aggiorna i risultati dell'esecuzione o consulta il record nativo.",+ newlyObserved: "Osservato di recente rispetto a prima della richiesta",+ observedInstance: "Istanza osservata",+ instanceNotObserved: "Questa istanza non è attualmente osservata",+ observationEmpty: "Al momento non ci sono istanze candidate identificabili in modo affidabile.",+ observationReadStatus: "Esecuzioni correnti: {running}; cronologia: {history}",+ observationNativeDetails: "Record nativo",+ observationTimestamp: "Ora dell'osservazione: {time}",+ scalarStorage: "Tipo di memorizzazione del valore",+ scalarText: "Testo normale",+ scalarNull: "NULL di questo tipo",+ scalarCivilDate: "Data",+ scalarCivilHint: "YYYY-MM-DD; usare un anno negativo per gli anni a.C.; l'anno 0 non esiste",+ scalarDateClock: "Ora (HH:MM:SS, secondi interi)",+ scalarClock: "Ora (HH:MM:SS, fino a 9 cifre decimali)",+ scalarUtc: "Modifica in UTC; salvato come timestamp nel fuso orario locale del database",+ scalarRegion: "Area del fuso orario",+ scalarOffset: "Offset UTC (±HH:MM)",+ scalarAbbreviation: "Abbreviazione del fuso orario (facoltativa)",+ scalarMonths: "Mesi totali (intero con segno)",+ scalarNanoseconds: "Nanosecondi totali (intero con segno)",+ scalarHex: "Byte RAW (esadecimale)",+ scalarFloatHex: "Modello di bit IEEE 754 (8 cifre esadecimali, big-endian)",+ scalarDoubleHex: "Modello di bit IEEE 754 (16 cifre esadecimali, big-endian)",+ scalarUrowid: "UROWID completo",+ finalEnabledHint: "Questo stato di abilitazione viene applicato solo dopo la verifica della definizione e degli argomenti.",+ transitionPreviewHint: "Sospendi prima la pianificazione futura; applica lo stato di abilitazione scelto dopo il superamento di tutte le verifiche.",+ legacyRunRestoresScheduling: "Questa esecuzione in primo piano riprende anche la pianificazione futura e fa ricalcolare al database la prossima esecuzione.",+ legacyRuntimeUpdateRequired: "Il runtime attuale non include il protocollo dei job tradizionali OceanBase. Aggiornare l'Agent o il plugin JDBC della connessione e riprovare.",+ title: "Job nativi",+ unsupported: "Questa connessione non supporta la gestione dei job nativi.",+ kind: "Tipo di job",+ createKind: "Tipo del nuovo job",+ owner: "Proprietario",+ ownerFilter: "Filtra per proprietario",+ definition: "Definizione",+ arguments: "Argomenti",+ advanced: "Attributi avanzati",+ restoreDefinitionDraft: "Ripristina la bozza della definizione originale",+ addArgument: "Aggiungi argomento",+ argumentPosition: "Argomento {position}",+ argumentType: "Tipo dell'argomento {position}",+ argumentState: "Stato dell'argomento {position}",+ argumentValue: "Valore dell'argomento {position}",+ scheduleMode: "Modalità di attivazione",+ scheduleModes: { inline: "Data o regola di ripetizione", named: "Pianificazione o finestra con nome", queue: "Evento di coda", fileWatcher: "Evento di arrivo di file" },+ destinationMode: "Destinazione di esecuzione",+ destinationModes: { local: "Esegui localmente", legacy: "Host remoto legacy (host[:port])", named: "Destinazione o gruppo con nome" },+ eventCondition: "Condizione dell'evento",+ eventQueueOwner: "Proprietario della coda",+ eventQueueName: "Nome della coda",+ eventQueueAgent: "Agente AQ (facoltativo)",+ fileWatcherOwner: "Proprietario di File watcher",+ fileWatcherName: "Nome di File watcher",+ chooseReference: "Scegli {kind}",+ inactiveInlineDraft: "È selezionato un riferimento con nome. I campi in linea restano nella bozza e non verranno scritti.",+ referenceFilter: "Cerca proprietario o nome",+ emptyReferences: "Nessun oggetto corrispondente nell'ambito leggibile.",+ referenceCatalogUnavailable: "Impossibile leggere l'elenco degli oggetti referenziati ({status}). Puoi inserire il proprietario e il nome esatti.",+ catalogCoverage: { database: "Intero database", accessible: "Accessibile a questo account", current_user: "Di proprietà di questo account", unknown: "Ambito sconosciuto" },+ opaqueArgument: "Questo valore nativo non può essere riscritto in sicurezza come testo; mantieni il valore originale.",+ programDefault: "Valore predefinito del programma",+ programDefaultUnknown: "Impossibile determinare il valore predefinito. Mantieni il valore originale.",+ metadataArgument: "Fornito dal database: {attribute}",+ argumentCatalogUnavailable: "Questa versione offre solo viste degli argomenti vuote per compatibilità. Non consentono di identificare gli argomenti o i valori esistenti.",+ obSchedulerDefinitionReadOnly: "In questa versione di OceanBase le definizioni di base dei job esistenti sono di sola lettura. Modifica i limiti di esecuzione e la zona in Avanzate.",+ runForeground: "Esegui in primo piano",+ forceStop: "Arresta forzatamente",+ legacyNoStop: "DBMS_JOB tradizionale non dispone di un arresto nativo. Terminare una sessione non equivale ad arrestare un job.",+ baselineUnavailable: "L'identità dell'oggetto o la base di coerenza non è leggibile. Rileggi prima di modificare.",+ kinds: { scheduler: "Job Scheduler", legacy: "Job tradizionale", "dameng-native": "Job agente Dameng" },+ argumentStates: { unset: "Non impostato", inherit: "Eredita valore predefinito", null: "SQL NULL", value: "Valore esplicito", opaque: "Valore nativo" },+ referenceKinds: { program: "Programma", schedule: "Pianificazione", chain: "Catena", credential: "Credenziale", destination: "Destinazione", window: "Finestra", "window-group": "Gruppo di finestre", "file-watcher": "Monitor di file", "destination-group": "Gruppo di destinazioni" },+ jobTypes: { PLSQL_BLOCK: "Blocco PL/SQL", STORED_PROCEDURE: "Procedura memorizzata", CHAIN: "Catena", EXECUTABLE: "Eseguibile", EXTERNAL_SCRIPT: "Script esterno", SQL_SCRIPT: "Script SQL", BACKUP_SCRIPT: "Script di backup" },+ loggingLevels: { OFF: "Nessuna registrazione", RUNS: "Esecuzioni", FAILED_RUNS: "Solo esecuzioni non riuscite", FULL: "Registrazione completa" },+ definitionFields: {+ ENABLED: "Abilita al termine",+ WHAT: "Corpo del job",+ NEXT_DATE: "Prossima esecuzione",+ INTERVAL: "Espressione di ripetizione",+ INSTANCE: "Istanza",+ ZONE: "Zona",+ JOB_TYPE: "Tipo di job",+ JOB_ACTION: "Azione del job",+ NUMBER_OF_ARGUMENTS: "Numero di argomenti",+ PROGRAM_OWNER: "Proprietario Program",+ PROGRAM_NAME: "Nome Program",+ SCHEDULE_OWNER: "Proprietario Schedule",+ SCHEDULE_NAME: "Nome Schedule",+ START_DATE: "Inizio con offset UTC",+ END_DATE: "Fine con offset UTC",+ REPEAT_INTERVAL: "Intervallo di ripetizione",+ AUTO_DROP: "Elimina automaticamente al termine",+ COMMENTS: "Commenti",+ LOG_USER: "Utente di accesso",+ PRIV_USER: "Utente dei privilegi",+ SCHEMA_USER: "Schema di esecuzione",+ JOB_CLASS: "Classe del job",+ JOB_PRIORITY: "Priorità",+ MAX_RUNS: "Numero massimo di esecuzioni",+ MAX_FAILURES: "Numero massimo di errori",+ MAX_RUN_DURATION: "Durata massima di esecuzione",+ SCHEDULE_LIMIT: "Limite di ritardo della pianificazione",+ RESTARTABLE: "Consenti riavvio",+ STOP_ON_WINDOW_CLOSE: "Arresta alla chiusura della finestra",+ STORE_OUTPUT: "Salva output di esecuzione",+ ALLOW_RUNS_IN_RESTRICTED_MODE: "Consenti esecuzioni in modalità limitata",+ INSTANCE_STICKINESS: "Affinità dell'istanza",+ FOLLOW_DEFAULT_TIMEZONE: "Segui il fuso orario predefinito",+ INSTANCE_ID: "Istanza di esecuzione",+ JOB_WEIGHT: "Peso del job",+ RAISE_EVENTS: "Maschera degli eventi generati",+ CONNECT_CREDENTIAL_NAME: "Credenziale di connessione",+ CREDENTIAL_NAME: "Credenziale di esecuzione",+ DESTINATION_NAME: "Destinazione con nome",+ DESTINATION: "Host remoto (host[:port])",+ JOB_STYLE: "Stile del job",+ LOGGING_LEVEL: "Livello di registrazione",+ },+ editJob: "Modifica job",+ editSections: "Configurazione job",+ add: "Aggiungi",+ attributes: "Proprietà job",+ steps: "Passi",+ schedules: "Pianificazioni",+ running: "Esecuzioni attuali",+ unknown: "Sconosciuto",+ emptyJobs: "Nessun job nell'ambito corrente.",+ noMatches: "Nessun job corrispondente.",+ previousPage: "Precedente",+ nextPage: "Successiva",+ pendingDrop: "Da eliminare",+ pendingAdd: "Nuovo",+ undoDrop: "Annulla eliminazione",+ keepOriginal: "Mantieni originale",+ explicitNull: "Imposta NULL dopo la conferma",+ partitionUnavailable: "Questa sezione è nello stato {status} e non può essere modificata come dati completi.",+ generatedCommandHint: "Questa istruzione è generata dal database. Per modificare un backup o DTS, inserisci sopra la configurazione nativa originale. Non serve se cambi solo il passo successivo.",+ runningUnknownHint: "Lo stato di esecuzione non è disponibile. Puoi comunque richiedere l'arresto nativo con i permessi necessari.",+ cancelFollowing: "Ferma passi rimanenti",+ readAgain: "Rileggi",+ correctDraft: "Correggi bozza",+ operationStatusUnavailable: "Impossibile confermare lo stato più recente dell'operazione. Controlla il risultato dell'operazione.",+ checkResult: "Controlla risultato",+ keepOperator: "Mantieni l'ID operatore {id}; inserisci un nome per sostituirlo.",+ nextStepHint: "Usato solo dalle azioni che continuano l'esecuzione. NULL segue l'ordine nativo dei passi.",+ stepTypes: { "0": "SQL o blocco", "1": "Backup/ripristino V1", "2": "Riorganizza database", "3": "Aggiorna statistiche", "4": "Migrazione DTS", "5": "Backup/ripristino V1 (esteso)", "6": "Backup/ripristino V2" },+ scheduleTypes: { "0": "Una volta", "1": "Giornaliera", "2": "Settimanale", "3": "Data mensile", "4": "Prima settimana del mese", "5": "Seconda settimana del mese", "6": "Terza settimana del mese", "7": "Quarta settimana del mese", "8": "Ultima settimana del mese" },+ actions: { "0": "Termina senza segnalare", "1": "Segnala e termina", "2": "Continua senza segnalare", "3": "Segnala e continua" },+ notificationTypes: { "0": "In caso di successo", "1": "In caso di errore", "2": "Al termine" },+ outcomes: {+ running: "Operazione in esecuzione",+ not_started: "Non iniziata",+ not_applied: "Non applicata",+ partial: "Alcuni passi sono stati applicati",+ unknown: "Esito sconosciuto; controlla prima di generare una nuova anteprima",+ verified: "Esito verificato",+ accepted: "Richiesta accettata; esito dell'esecuzione da confermare",+ },+ stepStates: { pending: "In attesa", dispatching: "Inviato", applied: "Eseguito", accepted: "Accettato", failed: "Non applicato", unknown: "Sconosciuto", skipped: "Non eseguito" },+ fields: {+ NAME: "Nome",+ ENABLE: "Stato di abilitazione finale",+ DESCRIBE: "Descrizione",+ ENABLE_EMAIL: "Notifica email",+ EMAIL_OPERATOR_NAME: "Nome operatore email",+ EMAIL_TYPE: "Condizione email",+ ENABLE_NETSEND: "Notifica di rete",+ NETSEND_OPERATOR_NAME: "Nome operatore di rete",+ NETSEND_TYPE: "Condizione di rete",+ EP_SEQNO: "Nodo di esecuzione (0–15)",+ RAFT_NAME: "Gruppo RAFT",+ TYPE: "Tipo",+ COMMAND_INPUT: "SQL o configurazione nativa",+ SUCC_ACTION: "Azione dopo il successo",+ SUCC_NEXT_STEP: "Passo successivo dopo successo",+ FAIL_ACTION: "Azione dopo l'errore",+ FAIL_NEXT_STEP: "Passo successivo dopo errore",+ RETRY_ATTEMPTS: "Tentativi di ripetizione",+ RETRY_INTERVAL: "Intervallo tentativi (secondi)",+ APPEND_FLAG: "Accoda output",+ FREQ_INTERVAL: "Frequenza",+ FREQ_SUB_INTERVAL: "Condizione settimanale/mensile",+ FREQ_MINUTE_INTERVAL: "Intervallo giornaliero (minuti; 0 esegue una volta al giorno)",+ STARTTIME: "Ora di inizio",+ ENDTIME: "Ora di fine",+ DURING_START_DATE: "Valido dal",+ DURING_END_DATE: "Valido fino al",+ },+ },damengJobAdmin: {title: "Job agente Dameng",unsupported: "Questa pagina supporta solo connessioni Dameng.",diff --git a/apps/desktop/src/i18n/locales/ja.ts b/apps/desktop/src/i18n/locales/ja.tsindex e55b358b59..0a203e09d6 100644--- a/apps/desktop/src/i18n/locales/ja.ts+++ b/apps/desktop/src/i18n/locales/ja.ts@@ -66,6 +66,27 @@ const consul = {};export default withEnglishFallback({+ oracleTrigger: {+ errorPositionUnavailable: "ソースを開きました。エラー位置を確認できないため、表示された行と列を確認してください。",+ reconcileStructure: "実行済みの変更を照合",+ reconcileConfirm: "現在のテーブル構造を再読み込みし、編集内容を保持して実行済みの手順を照合しますか? 以前の SQL は再実行しません。",+ editFullSource: "完全なソースを編集",+ refreshDraft: "このトリガーを再読み込み",+ refreshDraftConfirm: "このトリガーの構造化編集の下書きだけを破棄して再読み込みしますか?他のテーブル構造の下書きは保持されます。",+ discardSourceConfirm: "このソースの未保存の変更を破棄しますか?",+ scope: "トリガーのスコープ",+ parentOwner: "所属テーブル/ビューのスキーマ",+ parentName: "所属テーブル/ビュー",+ scopeOwner: "イベント対象スキーマ",+ obSchemaUnsupported: "この OB バージョンでは、検証したテンプレートが拒否されたため Schema トリガーのテンプレートを提供しません。",+ obDatabaseUnknown: "DATABASE トリガーの対応状況は未確認です。",+ nonAtomic: "DDL は個別にコミットされます。作成から無効化までの間、トリガーが一時的に有効になる場合があります。失敗すると後続の手順は停止し、自動再試行はしません。",+ unknown: "不明",+ verifyReadOnly: "読み取りのみで確認",+ reloadBaseline: "下書きを保持したままトリガーの完全な定義を再読み込みし、再度プレビューしてください。",+ runFullDefinition: "このタブでは、このトリガーの完全な定義のみ実行できます。他の SQL は通常のクエリタブで実行してください。",+ executionSchema: "実行スキーマ",+ },objectRelations: {title: "関連",foreignKeys: "外部キー",@@ -4808,6 +4829,7 @@ export default withEnglishFallback({manage: "Manage database links",},tree: {+ nativeJobs: "ネイティブジョブ",databaseLinks: "Database Links",savedSql: "SQLライブラリ",queries: "クエリ",@@ -5022,6 +5044,199 @@ export default withEnglishFallback({scopeFunctions: "関数",stepSkipped: "必要な前のステップが失敗したためスキップしました。",},+ nativeJobs: {+ datePrecisionMicroseconds: "この OceanBase バージョンのジョブ日付はマイクロ秒精度のみ対応しています。小数秒の 7~9 桁目を 0 にして、もう一度プレビューしてください。元の入力は保持されています。",+ previousContext: "前のコンテキストでの操作結果",+ detachedDraft: "元の下書きは保持されており、現在のオブジェクトには紐付いていません。",+ viewRetainedDraft: "元の下書きを表示",+ damengIntervalAccepted: "間隔の呼び出しは成功しました。元の式はカタログから読み戻して検証できません。",+ damengInterval: "秒単位の間隔またはネイティブ式",+ damengIntervalHint: "正の整数は秒単位の固定間隔として設定します。それ以外の入力はネイティブ式として渡され、プレビュー時には評価されません。",+ executionObservation: "ネイティブ実行の観測結果",+ observeExecution: "実行結果を更新",+ associationUncertain: "ネイティブインスタンスと今回のリクエストとの関連は不確かです。",+ observationUnavailable: "実行インスタンスを確実に関連付けられません。実行結果を更新するか、ネイティブレコードを確認してください。",+ newlyObserved: "リクエスト前と比べ新たに観測",+ observedInstance: "観測したインスタンス",+ instanceNotObserved: "このインスタンスは現在観測されていません",+ observationEmpty: "現在、確実に識別できる候補インスタンスはありません。",+ observationReadStatus: "現在の実行:{running};履歴:{history}",+ observationNativeDetails: "ネイティブレコード",+ observationTimestamp: "観測時刻:{time}",+ scalarStorage: "値の保存形式",+ scalarText: "通常のテキスト",+ scalarNull: "この型の NULL",+ scalarCivilDate: "日付",+ scalarCivilHint: "YYYY-MM-DD;紀元前は年にマイナスを付け、紀元 0 年はありません",+ scalarDateClock: "時刻(HH:MM:SS、秒単位)",+ scalarClock: "時刻(HH:MM:SS、小数点以下最大 9 桁)",+ scalarUtc: "UTC で編集;データベースのローカルタイムゾーンのタイムスタンプとして保存",+ scalarRegion: "タイムゾーン地域",+ scalarOffset: "UTC オフセット(±HH:MM)",+ scalarAbbreviation: "タイムゾーン略称(任意)",+ scalarMonths: "合計月数(符号付き整数)",+ scalarNanoseconds: "合計ナノ秒(符号付き整数)",+ scalarHex: "RAW バイト(16 進数)",+ scalarFloatHex: "IEEE 754 ビットパターン(16 進数 8 桁、ビッグエンディアン)",+ scalarDoubleHex: "IEEE 754 ビットパターン(16 進数 16 桁、ビッグエンディアン)",+ scalarUrowid: "完全な UROWID",+ finalEnabledHint: "定義と引数の検証がすべて完了してから、この有効状態を適用します。",+ transitionPreviewHint: "まず今後のスケジュールを一時停止し、すべての検証に合格した後で選択した有効状態を適用します。",+ legacyRunRestoresScheduling: "このフォアグラウンド実行では今後のスケジュールも再開され、次回実行時刻がデータベースによって再計算されます。",+ legacyRuntimeUpdateRequired: "現在のランタイムには OceanBase の従来型ジョブプロトコルがありません。この接続の Agent または JDBC プラグインを更新してから再試行してください。",+ title: "ネイティブジョブ",+ unsupported: "この接続はネイティブジョブ管理に対応していません。",+ kind: "ジョブの種類",+ createKind: "新規ジョブの種類",+ owner: "所有者",+ ownerFilter: "所有者で絞り込み",+ definition: "定義",+ arguments: "引数",+ advanced: "詳細属性",+ restoreDefinitionDraft: "元の定義を下書きに戻す",+ addArgument: "引数を追加",+ argumentPosition: "引数 {position}",+ argumentType: "引数 {position} の型",+ argumentState: "引数 {position} の状態",+ argumentValue: "引数 {position} の値",+ scheduleMode: "トリガー方式",+ scheduleModes: { inline: "日時または繰り返しルール", named: "名前付きスケジュールまたはウィンドウ", queue: "キューイベント", fileWatcher: "ファイル到着イベント" },+ destinationMode: "実行先",+ destinationModes: { local: "ローカルで実行", legacy: "従来のリモートホスト (host[:port])", named: "名前付き実行先またはグループ" },+ eventCondition: "イベント条件",+ eventQueueOwner: "キューの所有者",+ eventQueueName: "キュー名",+ eventQueueAgent: "AQ エージェント(任意)",+ fileWatcherOwner: "File watcher の所有者",+ fileWatcherName: "File watcher 名",+ chooseReference: "{kind} を選択",+ inactiveInlineDraft: "名前付き参照が選択されています。インライン項目は下書きに保持され、今回は書き込まれません。",+ referenceFilter: "所有者または名前で検索",+ emptyReferences: "読み取り可能な範囲に一致するオブジェクトがありません。",+ referenceCatalogUnavailable: "参照オブジェクトの一覧を読み取れません({status})。正確な所有者と名前を入力することもできます。",+ catalogCoverage: { database: "データベース全体", accessible: "このアカウントがアクセス可能", current_user: "このアカウントが所有", unknown: "範囲不明" },+ opaqueArgument: "このネイティブ値はテキストとして安全に書き換えられません。元の値を保持できます。",+ programDefault: "Program の既定値",+ programDefaultUnknown: "既定値を確認できません。元の値を保持します。",+ metadataArgument: "データベースが提供:{attribute}",+ argumentCatalogUnavailable: "このバージョンの引数ビューは互換性のための空のビューです。既存の引数や値を判定できません。",+ obSchedulerDefinitionReadOnly: "この OceanBase バージョンでは既存ジョブの基本定義は読み取り専用です。実行制限と実行 Zone は「詳細設定」で編集できます。",+ runForeground: "フォアグラウンドで実行",+ forceStop: "強制停止",+ legacyNoStop: "従来の DBMS_JOB にネイティブの停止操作はありません。セッションの終了とジョブの停止は異なります。",+ baselineUnavailable: "オブジェクト識別情報または整合性の基準を読み取れません。変更前に再読み込みしてください。",+ kinds: { scheduler: "Scheduler ジョブ", legacy: "従来の Job", "dameng-native": "Dameng エージェントジョブ" },+ argumentStates: { unset: "未設定", inherit: "既定値を継承", null: "SQL NULL", value: "明示的な値", opaque: "ネイティブ値" },+ referenceKinds: { program: "プログラム", schedule: "スケジュール", chain: "チェーン", credential: "資格情報", destination: "実行先", window: "ウィンドウ", "window-group": "ウィンドウグループ", "file-watcher": "ファイルウォッチャー", "destination-group": "実行先グループ" },+ jobTypes: { PLSQL_BLOCK: "PL/SQL ブロック", STORED_PROCEDURE: "ストアドプロシージャ", CHAIN: "チェーン", EXECUTABLE: "実行可能プログラム", EXTERNAL_SCRIPT: "外部スクリプト", SQL_SCRIPT: "SQL スクリプト", BACKUP_SCRIPT: "バックアップスクリプト" },+ loggingLevels: { OFF: "記録しない", RUNS: "実行を記録", FAILED_RUNS: "失敗した実行のみ", FULL: "すべて記録" },+ definitionFields: {+ ENABLED: "完了後に有効化",+ WHAT: "実行内容",+ NEXT_DATE: "次回実行日時",+ INTERVAL: "繰り返し式",+ INSTANCE: "インスタンス",+ ZONE: "ゾーン",+ JOB_TYPE: "ジョブの種類",+ JOB_ACTION: "ジョブアクション",+ NUMBER_OF_ARGUMENTS: "引数の数",+ PROGRAM_OWNER: "Program 所有者",+ PROGRAM_NAME: "Program 名",+ SCHEDULE_OWNER: "Schedule 所有者",+ SCHEDULE_NAME: "Schedule 名",+ START_DATE: "開始日時(UTC オフセット付き)",+ END_DATE: "終了日時(UTC オフセット付き)",+ REPEAT_INTERVAL: "繰り返し間隔",+ AUTO_DROP: "完了後に自動削除",+ COMMENTS: "コメント",+ LOG_USER: "ログインユーザー",+ PRIV_USER: "権限ユーザー",+ SCHEMA_USER: "実行スキーマ",+ JOB_CLASS: "ジョブクラス",+ JOB_PRIORITY: "優先度",+ MAX_RUNS: "最大実行回数",+ MAX_FAILURES: "最大失敗回数",+ MAX_RUN_DURATION: "最大実行時間",+ SCHEDULE_LIMIT: "スケジュール遅延の上限",+ RESTARTABLE: "再起動を許可",+ STOP_ON_WINDOW_CLOSE: "ウィンドウ終了時に停止",+ STORE_OUTPUT: "実行出力を保存",+ ALLOW_RUNS_IN_RESTRICTED_MODE: "制限モードでの実行を許可",+ INSTANCE_STICKINESS: "インスタンス親和性",+ FOLLOW_DEFAULT_TIMEZONE: "デフォルトのタイムゾーンに従う",+ INSTANCE_ID: "実行インスタンス",+ JOB_WEIGHT: "ジョブの重み",+ RAISE_EVENTS: "発生イベントのマスク",+ CONNECT_CREDENTIAL_NAME: "接続資格情報",+ CREDENTIAL_NAME: "実行資格情報",+ DESTINATION_NAME: "名前付き実行先",+ DESTINATION: "リモートホスト (host[:port])",+ JOB_STYLE: "ジョブスタイル",+ LOGGING_LEVEL: "ログ記録レベル",+ },+ editJob: "ジョブを編集",+ editSections: "ジョブ設定",+ add: "追加",+ attributes: "ジョブ属性",+ steps: "ステップ",+ schedules: "スケジュール",+ running: "現在の実行",+ unknown: "不明",+ emptyJobs: "現在の範囲にジョブはありません。",+ noMatches: "一致するジョブはありません。",+ previousPage: "前へ",+ nextPage: "次へ",+ pendingDrop: "削除予定",+ pendingAdd: "新規",+ undoDrop: "削除を取り消す",+ keepOriginal: "元の値を保持",+ explicitNull: "確認後に NULL を設定",+ partitionUnavailable: "このセクションは {status} のため、完全なデータとして編集できません。",+ generatedCommandHint: "これはデータベースが生成した文です。バックアップまたは DTS の定義を変更するには、上に元のネイティブ設定を入力してください。次のステップのみの変更では不要です。",+ runningUnknownHint: "実行状態を読み取れません。必要な権限があればネイティブ停止を要求できます。",+ cancelFollowing: "残りのステップを停止",+ readAgain: "再読み込み",+ correctDraft: "下書きを修正",+ operationStatusUnavailable: "最新の操作状態を確認できません。操作結果を確認してください。",+ checkResult: "操作結果を確認",+ keepOperator: "操作員 ID {id} を保持します。置き換える場合は名前を入力してください。",+ nextStepHint: "実行を継続するアクションでのみ使用します。NULL はネイティブのステップ順に従います。",+ stepTypes: { "0": "SQL またはブロック", "1": "バックアップ/復元 V1", "2": "データベースを再編成", "3": "統計情報を更新", "4": "DTS 移行", "5": "バックアップ/復元 V1(拡張)", "6": "バックアップ/復元 V2" },+ scheduleTypes: { "0": "1回", "1": "毎日", "2": "毎週", "3": "毎月の指定日", "4": "毎月第1週", "5": "毎月第2週", "6": "毎月第3週", "7": "毎月第4週", "8": "毎月最終週" },+ actions: { "0": "結果を報告せず終了", "1": "結果を報告して終了", "2": "結果を報告せず継続", "3": "結果を報告して継続" },+ notificationTypes: { "0": "成功時", "1": "失敗時", "2": "終了時" },+ outcomes: { running: "操作を実行中", not_started: "未開始", not_applied: "未反映", partial: "一部のステップが反映済み", unknown: "結果不明。確認してから再プレビューしてください", verified: "操作結果を検証済み", accepted: "要求を受理済み。実行結果は未確認です" },+ stepStates: { pending: "待機中", dispatching: "送信済み", applied: "実行済み", accepted: "受理済み", failed: "未反映", unknown: "結果不明", skipped: "未実行" },+ fields: {+ NAME: "名前",+ ENABLE: "最終的に有効化",+ DESCRIBE: "説明",+ ENABLE_EMAIL: "メール通知",+ EMAIL_OPERATOR_NAME: "メール操作員名",+ EMAIL_TYPE: "メール通知条件",+ ENABLE_NETSEND: "ネットワーク通知",+ NETSEND_OPERATOR_NAME: "ネットワーク操作員名",+ NETSEND_TYPE: "ネットワーク通知条件",+ EP_SEQNO: "実行ノード(0–15)",+ RAFT_NAME: "RAFT グループ",+ TYPE: "種類",+ COMMAND_INPUT: "SQL 本文またはネイティブ設定",+ SUCC_ACTION: "成功後のアクション",+ SUCC_NEXT_STEP: "成功時の次のステップ",+ FAIL_ACTION: "失敗後のアクション",+ FAIL_NEXT_STEP: "失敗時の次のステップ",+ RETRY_ATTEMPTS: "再試行回数",+ RETRY_INTERVAL: "再試行間隔(秒)",+ APPEND_FLAG: "出力を追記",+ FREQ_INTERVAL: "実行頻度",+ FREQ_SUB_INTERVAL: "週/月の条件",+ FREQ_MINUTE_INTERVAL: "1日の実行間隔(分。0 は1日1回)",+ STARTTIME: "開始時刻",+ ENDTIME: "終了時刻",+ DURING_START_DATE: "有効開始日",+ DURING_END_DATE: "有効終了日",+ },+ },damengJobAdmin: {title: "Dameng エージェントジョブ",unsupported: "このページは Dameng 接続のみ対応しています。",diff --git a/apps/desktop/src/i18n/locales/ko.ts b/apps/desktop/src/i18n/locales/ko.tsindex 0da7181529..c3be6fc737 100644--- a/apps/desktop/src/i18n/locales/ko.ts+++ b/apps/desktop/src/i18n/locales/ko.ts@@ -65,6 +65,27 @@ const consul = {};export default withEnglishFallback({+ oracleTrigger: {+ errorPositionUnavailable: "소스를 열었습니다. 오류 위치를 확인할 수 없으므로 표시된 행과 열을 확인하세요.",+ reconcileStructure: "적용된 변경 사항 대조",+ reconcileConfirm: "현재 테이블 구조를 다시 읽고 원하는 수정 사항을 유지하며 완료된 단계를 대조할까요? 이전 SQL은 다시 실행하지 않습니다.",+ editFullSource: "전체 소스 편집",+ refreshDraft: "이 트리거 다시 읽기",+ refreshDraftConfirm: "이 트리거의 구조화된 초안만 버리고 다시 읽으시겠습니까? 다른 테이블 구조 초안은 유지됩니다.",+ discardSourceConfirm: "이 소스의 저장하지 않은 변경 사항을 버리시겠습니까?",+ scope: "트리거 범위",+ parentOwner: "소유 테이블/뷰 스키마",+ parentName: "소유 테이블/뷰",+ scopeOwner: "이벤트 대상 스키마",+ obSchemaUnsupported: "이 OB 버전에서는 테스트한 템플릿이 거부되어 Schema 트리거 템플릿을 제공하지 않습니다.",+ obDatabaseUnknown: "DATABASE 트리거 지원 여부는 확인되지 않았습니다.",+ nonAtomic: "DDL 문은 각각 커밋됩니다. 생성부터 비활성화까지 트리거가 잠시 활성화될 수 있습니다. 실패하면 후속 단계가 중단되며 자동 재시도하지 않습니다.",+ unknown: "알 수 없음",+ verifyReadOnly: "읽기 전용으로 확인",+ reloadBaseline: "초안을 유지하고 트리거 전체 정의를 다시 읽은 후 미리 보기를 생성하세요.",+ runFullDefinition: "이 탭에서는 해당 트리거의 전체 정의만 실행할 수 있습니다. 다른 SQL은 일반 쿼리 탭을 사용하세요.",+ executionSchema: "실행 스키마",+ },objectRelations: {title: "관계",foreignKeys: "외래 키",@@ -4720,6 +4741,7 @@ export default withEnglishFallback({manage: "Manage database links",},tree: {+ nativeJobs: "네이티브 작업",databaseLinks: "Database Links",savedSql: "SQL 라이브러리",queries: "쿼리",@@ -5252,6 +5274,199 @@ export default withEnglishFallback({scopeFunctions: "함수",stepSkipped: "필요한 이전 단계가 실패하여 건너뜁니다.",},+ nativeJobs: {+ datePrecisionMicroseconds: "이 OceanBase 버전의 작업 날짜는 마이크로초 정밀도만 지원합니다. 소수 초의 7~9번째 자리를 0으로 바꾸고 다시 미리 보세요. 원래 입력은 보존되었습니다.",+ previousContext: "이전 컨텍스트의 작업 결과",+ detachedDraft: "원래 초안은 보존되었으며 현재 객체에 연결되어 있지 않습니다.",+ viewRetainedDraft: "원래 초안 보기",+ damengIntervalAccepted: "간격 호출은 성공했지만 원래 표현식은 카탈로그에서 다시 읽어 검증할 수 없습니다.",+ damengInterval: "초 단위 간격 또는 네이티브 표현식",+ damengIntervalHint: "양의 정수는 초 단위의 고정 간격으로 설정됩니다. 그 외 입력은 네이티브 표현식으로 전달되며 미리 보기에서 평가되지 않습니다.",+ executionObservation: "네이티브 실행 관찰 결과",+ observeExecution: "실행 결과 새로고침",+ associationUncertain: "네이티브 인스턴스와 이번 요청의 관련 여부는 확실하지 않습니다.",+ observationUnavailable: "실행 인스턴스를 신뢰할 수 있게 연결할 수 없습니다. 실행 결과를 새로고침하거나 네이티브 기록을 확인하세요.",+ newlyObserved: "요청 전과 비교해 새로 관찰됨",+ observedInstance: "관찰된 인스턴스",+ instanceNotObserved: "현재 이 인스턴스가 관찰되지 않음",+ observationEmpty: "현재 신뢰할 수 있게 식별할 수 있는 후보 인스턴스가 없습니다.",+ observationReadStatus: "현재 실행: {running}; 기록: {history}",+ observationNativeDetails: "네이티브 기록",+ observationTimestamp: "관찰 시각: {time}",+ scalarStorage: "값 저장 유형",+ scalarText: "일반 텍스트",+ scalarNull: "이 유형의 NULL",+ scalarCivilDate: "날짜",+ scalarCivilHint: "YYYY-MM-DD; 기원전은 연도 앞에 음수 기호를 붙이며 0년은 없습니다",+ scalarDateClock: "시간(HH:MM:SS, 정수 초)",+ scalarClock: "시간(HH:MM:SS, 소수점 이하 최대 9자리)",+ scalarUtc: "UTC로 편집하고 데이터베이스 현지 시간대의 타임스탬프로 저장",+ scalarRegion: "시간대 지역",+ scalarOffset: "UTC 오프셋(±HH:MM)",+ scalarAbbreviation: "시간대 약어(선택 사항)",+ scalarMonths: "총 개월 수(부호 있는 정수)",+ scalarNanoseconds: "총 나노초(부호 있는 정수)",+ scalarHex: "RAW 바이트(16진수)",+ scalarFloatHex: "IEEE 754 비트 패턴(16진수 8자리, 빅 엔디언)",+ scalarDoubleHex: "IEEE 754 비트 패턴(16진수 16자리, 빅 엔디언)",+ scalarUrowid: "전체 UROWID",+ finalEnabledHint: "정의와 인수를 모두 검증한 후에만 이 활성화 상태를 적용합니다.",+ transitionPreviewHint: "먼저 향후 예약을 일시 중지하고, 모든 검증을 통과한 후 선택한 활성화 상태를 적용합니다.",+ legacyRunRestoresScheduling: "이번 포그라운드 실행은 향후 예약도 다시 활성화하며 데이터베이스가 다음 실행 시간을 다시 계산합니다.",+ legacyRuntimeUpdateRequired: "현재 런타임에 OceanBase 기존 작업 프로토콜이 없습니다. 이 연결의 Agent 또는 JDBC 플러그인을 업데이트한 뒤 다시 시도하세요.",+ title: "네이티브 작업",+ unsupported: "이 연결은 네이티브 작업 관리를 지원하지 않습니다.",+ kind: "작업 유형",+ createKind: "새 작업 유형",+ owner: "소유자",+ ownerFilter: "소유자로 필터링",+ definition: "정의",+ arguments: "인수",+ advanced: "고급 속성",+ restoreDefinitionDraft: "원래 정의를 초안으로 복원",+ addArgument: "인수 추가",+ argumentPosition: "인수 {position}",+ argumentType: "인수 {position}의 유형",+ argumentState: "인수 {position}의 상태",+ argumentValue: "인수 {position}의 값",+ scheduleMode: "트리거 방식",+ scheduleModes: { inline: "날짜 또는 반복 규칙", named: "이름이 있는 일정 또는 윈도우", queue: "큐 이벤트", fileWatcher: "파일 도착 이벤트" },+ destinationMode: "실행 대상",+ destinationModes: { local: "로컬에서 실행", legacy: "기존 원격 호스트 (host[:port])", named: "이름이 있는 대상 또는 그룹" },+ eventCondition: "이벤트 조건",+ eventQueueOwner: "큐 소유자",+ eventQueueName: "큐 이름",+ eventQueueAgent: "AQ 에이전트(선택 사항)",+ fileWatcherOwner: "File watcher 소유자",+ fileWatcherName: "File watcher 이름",+ chooseReference: "{kind} 선택",+ inactiveInlineDraft: "이름이 있는 참조가 선택되었습니다. 인라인 필드는 초안에 유지되며 이번에는 저장되지 않습니다.",+ referenceFilter: "소유자 또는 이름 검색",+ emptyReferences: "읽을 수 있는 범위에 일치하는 객체가 없습니다.",+ referenceCatalogUnavailable: "참조 객체 목록을 읽을 수 없습니다({status}). 정확한 소유자와 이름을 직접 입력할 수 있습니다.",+ catalogCoverage: { database: "전체 데이터베이스", accessible: "현재 계정에서 접근 가능", current_user: "현재 계정 소유", unknown: "범위 알 수 없음" },+ opaqueArgument: "이 네이티브 값은 텍스트로 안전하게 변경할 수 없습니다. 원래 값을 유지할 수 있습니다.",+ programDefault: "Program 기본값",+ programDefaultUnknown: "기본값을 확인할 수 없습니다. 원래 값을 유지합니다.",+ metadataArgument: "데이터베이스 제공: {attribute}",+ argumentCatalogUnavailable: "이 버전의 인수 뷰는 호환성용 빈 뷰입니다. 기존 인수나 값을 확인할 수 없습니다.",+ obSchedulerDefinitionReadOnly: "이 OceanBase 버전에서 기존 작업의 기본 정의는 읽기 전용입니다. 실행 제한과 실행 Zone은 고급 설정에서 편집하세요.",+ runForeground: "포그라운드 실행",+ forceStop: "강제 중지",+ legacyNoStop: "기존 DBMS_JOB에는 네이티브 중지 작업이 없습니다. 세션 종료는 작업 중지와 다릅니다.",+ baselineUnavailable: "객체 식별 정보 또는 일관성 기준을 읽을 수 없습니다. 변경 전에 다시 읽으세요.",+ kinds: { scheduler: "Scheduler 작업", legacy: "기존 Job", "dameng-native": "Dameng 에이전트 작업" },+ argumentStates: { unset: "미설정", inherit: "기본값 상속", null: "SQL NULL", value: "명시적 값", opaque: "네이티브 값" },+ referenceKinds: { program: "프로그램", schedule: "일정", chain: "체인", credential: "자격 증명", destination: "대상", window: "윈도우", "window-group": "윈도우 그룹", "file-watcher": "파일 감시기", "destination-group": "대상 그룹" },+ jobTypes: { PLSQL_BLOCK: "PL/SQL 블록", STORED_PROCEDURE: "저장 프로시저", CHAIN: "체인", EXECUTABLE: "실행 파일", EXTERNAL_SCRIPT: "외부 스크립트", SQL_SCRIPT: "SQL 스크립트", BACKUP_SCRIPT: "백업 스크립트" },+ loggingLevels: { OFF: "기록 안 함", RUNS: "실행 기록", FAILED_RUNS: "실패한 실행만", FULL: "전체 기록" },+ definitionFields: {+ ENABLED: "완료 후 활성화",+ WHAT: "실행 내용",+ NEXT_DATE: "다음 실행 시각",+ INTERVAL: "반복 식",+ INSTANCE: "인스턴스",+ ZONE: "영역",+ JOB_TYPE: "작업 유형",+ JOB_ACTION: "작업 동작",+ NUMBER_OF_ARGUMENTS: "인수 개수",+ PROGRAM_OWNER: "Program 소유자",+ PROGRAM_NAME: "Program 이름",+ SCHEDULE_OWNER: "Schedule 소유자",+ SCHEDULE_NAME: "Schedule 이름",+ START_DATE: "시작 시각(UTC 오프셋 포함)",+ END_DATE: "종료 시각(UTC 오프셋 포함)",+ REPEAT_INTERVAL: "반복 간격",+ AUTO_DROP: "완료 후 자동 삭제",+ COMMENTS: "설명",+ LOG_USER: "로그인 사용자",+ PRIV_USER: "권한 사용자",+ SCHEMA_USER: "실행 스키마",+ JOB_CLASS: "작업 클래스",+ JOB_PRIORITY: "우선순위",+ MAX_RUNS: "최대 실행 횟수",+ MAX_FAILURES: "최대 실패 횟수",+ MAX_RUN_DURATION: "최대 실행 시간",+ SCHEDULE_LIMIT: "예약 지연 한도",+ RESTARTABLE: "다시 시작 허용",+ STOP_ON_WINDOW_CLOSE: "윈도우가 닫히면 중지",+ STORE_OUTPUT: "실행 출력 저장",+ ALLOW_RUNS_IN_RESTRICTED_MODE: "제한 모드에서 실행 허용",+ INSTANCE_STICKINESS: "인스턴스 선호도",+ FOLLOW_DEFAULT_TIMEZONE: "기본 시간대 따르기",+ INSTANCE_ID: "실행 인스턴스",+ JOB_WEIGHT: "작업 가중치",+ RAISE_EVENTS: "발생 이벤트 마스크",+ CONNECT_CREDENTIAL_NAME: "연결 자격 증명",+ CREDENTIAL_NAME: "실행 자격 증명",+ DESTINATION_NAME: "이름이 있는 대상",+ DESTINATION: "원격 호스트 (host[:port])",+ JOB_STYLE: "작업 스타일",+ LOGGING_LEVEL: "로깅 수준",+ },+ editJob: "작업 편집",+ editSections: "작업 구성",+ add: "추가",+ attributes: "작업 속성",+ steps: "단계",+ schedules: "일정",+ running: "현재 실행",+ unknown: "알 수 없음",+ emptyJobs: "현재 범위에 작업이 없습니다.",+ noMatches: "일치하는 작업이 없습니다.",+ previousPage: "이전",+ nextPage: "다음",+ pendingDrop: "삭제 예정",+ pendingAdd: "새 항목",+ undoDrop: "삭제 취소",+ keepOriginal: "원래 값 유지",+ explicitNull: "확인 후 NULL로 설정",+ partitionUnavailable: "이 부분은 {status} 상태이므로 완전한 데이터로 편집할 수 없습니다.",+ generatedCommandHint: "데이터베이스가 생성한 구문입니다. 백업 또는 DTS 정의를 변경하려면 위에 원래 네이티브 구성 값을 입력하세요. 다음 단계만 변경할 때는 필요하지 않습니다.",+ runningUnknownHint: "실행 상태를 읽을 수 없습니다. 필요한 권한이 있으면 네이티브 중지를 요청할 수 있습니다.",+ cancelFollowing: "나머지 단계 중지",+ readAgain: "다시 읽기",+ correctDraft: "초안 수정",+ operationStatusUnavailable: "최신 작업 상태를 확인할 수 없습니다. 작업 결과를 확인하세요.",+ checkResult: "작업 결과 확인",+ keepOperator: "운영자 ID {id}을(를) 유지합니다. 바꾸려면 이름을 입력하세요.",+ nextStepHint: "계속 실행하는 동작에서만 사용합니다. NULL은 네이티브 단계 순서를 따릅니다.",+ stepTypes: { "0": "SQL 또는 블록", "1": "백업/복원 V1", "2": "데이터베이스 재구성", "3": "통계 갱신", "4": "DTS 마이그레이션", "5": "백업/복원 V1 (확장)", "6": "백업/복원 V2" },+ scheduleTypes: { "0": "한 번", "1": "매일", "2": "매주", "3": "매월 지정일", "4": "매월 첫째 주", "5": "매월 둘째 주", "6": "매월 셋째 주", "7": "매월 넷째 주", "8": "매월 마지막 주" },+ actions: { "0": "결과 보고 없이 종료", "1": "결과 보고 후 종료", "2": "결과 보고 없이 계속", "3": "결과 보고 후 계속" },+ notificationTypes: { "0": "성공 시", "1": "실패 시", "2": "완료 시" },+ outcomes: { running: "작업 실행 중", not_started: "시작하지 않음", not_applied: "적용되지 않음", partial: "일부 단계가 적용됨", unknown: "결과를 알 수 없습니다. 확인 후 다시 미리 보세요", verified: "작업 결과 검증됨", accepted: "요청이 수락됨; 실행 결과는 확인 대기 중" },+ stepStates: { pending: "대기 중", dispatching: "전송됨", applied: "실행됨", accepted: "수락됨", failed: "적용되지 않음", unknown: "알 수 없음", skipped: "실행하지 않음" },+ fields: {+ NAME: "이름",+ ENABLE: "최종 활성화 상태",+ DESCRIBE: "설명",+ ENABLE_EMAIL: "이메일 알림",+ EMAIL_OPERATOR_NAME: "이메일 운영자 이름",+ EMAIL_TYPE: "이메일 조건",+ ENABLE_NETSEND: "네트워크 알림",+ NETSEND_OPERATOR_NAME: "네트워크 운영자 이름",+ NETSEND_TYPE: "네트워크 조건",+ EP_SEQNO: "실행 노드 (0–15)",+ RAFT_NAME: "RAFT 그룹",+ TYPE: "유형",+ COMMAND_INPUT: "SQL 본문 또는 네이티브 구성",+ SUCC_ACTION: "성공 후 동작",+ SUCC_NEXT_STEP: "성공 시 다음 단계",+ FAIL_ACTION: "실패 후 동작",+ FAIL_NEXT_STEP: "실패 시 다음 단계",+ RETRY_ATTEMPTS: "재시도 횟수",+ RETRY_INTERVAL: "재시도 간격 (초)",+ APPEND_FLAG: "출력 추가",+ FREQ_INTERVAL: "실행 빈도",+ FREQ_SUB_INTERVAL: "주/월 조건",+ FREQ_MINUTE_INTERVAL: "일중 간격 (분; 0은 하루 한 번)",+ STARTTIME: "시작 시간",+ ENDTIME: "종료 시간",+ DURING_START_DATE: "유효 시작일",+ DURING_END_DATE: "유효 종료일",+ },+ },damengJobAdmin: {title: "Dameng 에이전트 작업",unsupported: "이 페이지는 Dameng 연결만 지원합니다.",diff --git a/apps/desktop/src/i18n/locales/pt-BR.ts b/apps/desktop/src/i18n/locales/pt-BR.tsindex c76b746aad..96258e2b69 100644--- a/apps/desktop/src/i18n/locales/pt-BR.ts+++ b/apps/desktop/src/i18n/locales/pt-BR.ts@@ -66,6 +66,27 @@ const consul = {};export default withEnglishFallback({+ oracleTrigger: {+ errorPositionUnavailable: "Código-fonte aberto. Não foi possível verificar a posição do erro; confira a linha e a coluna indicadas.",+ reconcileStructure: "Reconciliar alterações aplicadas",+ reconcileConfirm: "Reler a estrutura atual, manter as edições desejadas e reconciliar as etapas concluídas sem repetir o SQL anterior?",+ editFullSource: "Editar código-fonte completo",+ refreshDraft: "Recarregar este gatilho",+ refreshDraftConfirm: "Recarregar e descartar apenas o rascunho estruturado deste gatilho? Os outros rascunhos da estrutura da tabela serão mantidos.",+ discardSourceConfirm: "Descartar as alterações não salvas deste código-fonte?",+ scope: "Escopo do gatilho",+ parentOwner: "Esquema da tabela/visão",+ parentName: "Tabela/visão associada",+ scopeOwner: "Esquema dos eventos",+ obSchemaUnsupported: "Esta versão do OB não oferece um modelo de gatilho Schema: o modelo testado foi rejeitado.",+ obDatabaseUnknown: "O suporte a gatilhos DATABASE não foi verificado.",+ nonAtomic: "As instruções DDL são confirmadas separadamente. O gatilho pode ficar ativo entre a criação e a desativação. Uma falha interrompe as etapas seguintes; não há novas tentativas automáticas.",+ unknown: "Desconhecido",+ verifyReadOnly: "Verificar sem gravar",+ reloadBaseline: "Mantenha o rascunho e recarregue a definição completa do gatilho antes de gerar outra prévia.",+ runFullDefinition: "Esta aba só pode executar a definição completa deste gatilho. Use uma aba de consulta comum para outros SQL.",+ executionSchema: "Esquema de execução",+ },objectRelations: {title: "Relações",foreignKeys: "Chaves estrangeiras",@@ -4785,6 +4806,7 @@ export default withEnglishFallback({manage: "Manage database links",},tree: {+ nativeJobs: "Jobs nativos",databaseLinks: "Database Links",savedSql: "Biblioteca SQL",queries: "Consultas",@@ -4958,6 +4980,207 @@ export default withEnglishFallback({scopeFunctions: "funções",stepSkipped: "Ignorado porque uma etapa anterior obrigatória falhou.",},+ nativeJobs: {+ datePrecisionMicroseconds: "As datas de jobs nesta versão do OceanBase aceitam apenas precisão de microssegundos. Defina como 0 os dígitos 7–9 dos segundos fracionários e gere a prévia novamente; a entrada original foi mantida.",+ previousContext: "Resultado da operação do contexto anterior",+ detachedDraft: "O rascunho original foi mantido e não está vinculado ao objeto atual.",+ viewRetainedDraft: "Ver rascunho original",+ damengIntervalAccepted: "A chamada do intervalo foi bem-sucedida; não é possível verificar a expressão original relendo-a no catálogo.",+ damengInterval: "Intervalo em segundos ou expressão nativa",+ damengIntervalHint: "Um número inteiro positivo define um intervalo fixo em segundos; qualquer outra entrada é passada como expressão nativa e não é avaliada na prévia.",+ executionObservation: "Observações de execução nativa",+ observeExecution: "Atualizar resultados da execução",+ associationUncertain: "A associação entre as instâncias nativas e esta solicitação é incerta.",+ observationUnavailable: "Não é possível associar a instância de execução com segurança; atualize os resultados da execução ou consulte o registro nativo.",+ newlyObserved: "Observado recentemente em relação ao período anterior à solicitação",+ observedInstance: "Instância observada",+ instanceNotObserved: "Esta instância não está sendo observada no momento",+ observationEmpty: "No momento, não há instâncias candidatas que possam ser identificadas com segurança.",+ observationReadStatus: "Execuções atuais: {running}; histórico: {history}",+ observationNativeDetails: "Registro nativo",+ observationTimestamp: "Horário da observação: {time}",+ scalarStorage: "Tipo de armazenamento do valor",+ scalarText: "Texto simples",+ scalarNull: "NULL deste tipo",+ scalarCivilDate: "Data",+ scalarCivilHint: "YYYY-MM-DD; use um ano negativo para a.C.; não existe ano 0",+ scalarDateClock: "Horário (HH:MM:SS, segundos inteiros)",+ scalarClock: "Horário (HH:MM:SS, até 9 casas decimais)",+ scalarUtc: "Edite em UTC; salvo como timestamp no fuso horário local do banco de dados",+ scalarRegion: "Região do fuso horário",+ scalarOffset: "Deslocamento UTC (±HH:MM)",+ scalarAbbreviation: "Abreviação do fuso horário (opcional)",+ scalarMonths: "Total de meses (inteiro com sinal)",+ scalarNanoseconds: "Total de nanossegundos (inteiro com sinal)",+ scalarHex: "Bytes RAW (hexadecimal)",+ scalarFloatHex: "Padrão de bits IEEE 754 (8 dígitos hexadecimais, big-endian)",+ scalarDoubleHex: "Padrão de bits IEEE 754 (16 dígitos hexadecimais, big-endian)",+ scalarUrowid: "UROWID completo",+ finalEnabledHint: "Este estado de ativação só é aplicado após a verificação da definição e dos argumentos.",+ transitionPreviewHint: "Pause primeiro os agendamentos futuros; aplique o estado de ativação escolhido após todas as verificações serem aprovadas.",+ legacyRunRestoresScheduling: "Esta execução em primeiro plano também retoma o agendamento futuro e faz o banco de dados recalcular a próxima execução.",+ legacyRuntimeUpdateRequired: "O runtime atual não inclui o protocolo de jobs tradicionais do OceanBase. Atualize o Agent ou o plugin JDBC desta conexão e tente novamente.",+ title: "Jobs nativos",+ unsupported: "Esta conexão não oferece gerenciamento de jobs nativos.",+ kind: "Tipo de job",+ createKind: "Tipo do novo job",+ owner: "Proprietário",+ ownerFilter: "Filtrar por proprietário",+ definition: "Definição",+ arguments: "Argumentos",+ advanced: "Atributos avançados",+ restoreDefinitionDraft: "Restaurar rascunho da definição original",+ addArgument: "Adicionar argumento",+ argumentPosition: "Argumento {position}",+ argumentType: "Tipo do argumento {position}",+ argumentState: "Estado do argumento {position}",+ argumentValue: "Valor do argumento {position}",+ scheduleMode: "Modo de acionamento",+ scheduleModes: { inline: "Data ou regra de repetição", named: "Agendamento ou janela nomeada", queue: "Evento de fila", fileWatcher: "Evento de chegada de arquivo" },+ destinationMode: "Destino de execução",+ destinationModes: { local: "Executar localmente", legacy: "Host remoto legado (host[:port])", named: "Destino ou grupo nomeado" },+ eventCondition: "Condição do evento",+ eventQueueOwner: "Proprietário da fila",+ eventQueueName: "Nome da fila",+ eventQueueAgent: "Agente AQ (opcional)",+ fileWatcherOwner: "Proprietário do File watcher",+ fileWatcherName: "Nome do File watcher",+ chooseReference: "Selecionar {kind}",+ inactiveInlineDraft: "Uma referência nomeada está selecionada. Os campos em linha permanecem no rascunho e não serão gravados.",+ referenceFilter: "Pesquisar proprietário ou nome",+ emptyReferences: "Nenhum objeto correspondente no escopo legível.",+ referenceCatalogUnavailable: "Não foi possível ler a lista de objetos referenciados ({status}). Você ainda pode informar o proprietário e o nome exatos.",+ catalogCoverage: { database: "Todo o banco de dados", accessible: "Acessível a esta conta", current_user: "Pertencente a esta conta", unknown: "Escopo desconhecido" },+ opaqueArgument: "Este valor nativo não pode ser reescrito com segurança como texto; mantenha o valor original.",+ programDefault: "Padrão do programa",+ programDefaultUnknown: "Não foi possível determinar o valor padrão. Mantenha o valor original.",+ metadataArgument: "Fornecido pelo banco de dados: {attribute}",+ argumentCatalogUnavailable: "Esta versão fornece apenas visões de argumentos vazias para compatibilidade. Elas não permitem identificar argumentos ou valores existentes.",+ obSchedulerDefinitionReadOnly: "Nesta versão do OceanBase, a definição básica dos trabalhos existentes é somente leitura. Edite os limites de execução e a zona em Avançado.",+ runForeground: "Executar em primeiro plano",+ forceStop: "Forçar parada",+ legacyNoStop: "O DBMS_JOB tradicional não tem uma operação nativa de parada. Encerrar uma sessão não é o mesmo que parar um job.",+ baselineUnavailable: "Não é possível ler a identidade do objeto ou a base de consistência. Leia novamente antes de alterar.",+ kinds: { scheduler: "Job Scheduler", legacy: "Job tradicional", "dameng-native": "Job do agente Dameng" },+ argumentStates: { unset: "Não definido", inherit: "Herdar padrão", null: "SQL NULL", value: "Valor explícito", opaque: "Valor nativo" },+ referenceKinds: { program: "Programa", schedule: "Agendamento", chain: "Cadeia", credential: "Credencial", destination: "Destino", window: "Janela", "window-group": "Grupo de janelas", "file-watcher": "Monitor de arquivos", "destination-group": "Grupo de destinos" },+ jobTypes: { PLSQL_BLOCK: "Bloco PL/SQL", STORED_PROCEDURE: "Procedimento armazenado", CHAIN: "Cadeia", EXECUTABLE: "Executável", EXTERNAL_SCRIPT: "Script externo", SQL_SCRIPT: "Script SQL", BACKUP_SCRIPT: "Script de backup" },+ loggingLevels: { OFF: "Sem registro", RUNS: "Execuções", FAILED_RUNS: "Somente execuções com falha", FULL: "Registro completo" },+ definitionFields: {+ ENABLED: "Ativar ao concluir",+ WHAT: "Corpo do job",+ NEXT_DATE: "Próxima execução",+ INTERVAL: "Expressão de repetição",+ INSTANCE: "Instância",+ ZONE: "Zona",+ JOB_TYPE: "Tipo de job",+ JOB_ACTION: "Ação do job",+ NUMBER_OF_ARGUMENTS: "Número de argumentos",+ PROGRAM_OWNER: "Proprietário de Program",+ PROGRAM_NAME: "Nome de Program",+ SCHEDULE_OWNER: "Proprietário de Schedule",+ SCHEDULE_NAME: "Nome de Schedule",+ START_DATE: "Início com deslocamento UTC",+ END_DATE: "Fim com deslocamento UTC",+ REPEAT_INTERVAL: "Intervalo de repetição",+ AUTO_DROP: "Excluir automaticamente ao concluir",+ COMMENTS: "Comentários",+ LOG_USER: "Usuário de login",+ PRIV_USER: "Usuário de privilégios",+ SCHEMA_USER: "Esquema de execução",+ JOB_CLASS: "Classe do job",+ JOB_PRIORITY: "Prioridade",+ MAX_RUNS: "Máximo de execuções",+ MAX_FAILURES: "Máximo de falhas",+ MAX_RUN_DURATION: "Duração máxima de execução",+ SCHEDULE_LIMIT: "Limite de atraso do agendamento",+ RESTARTABLE: "Permitir reinício",+ STOP_ON_WINDOW_CLOSE: "Parar quando a janela fechar",+ STORE_OUTPUT: "Armazenar saída da execução",+ ALLOW_RUNS_IN_RESTRICTED_MODE: "Permitir execuções em modo restrito",+ INSTANCE_STICKINESS: "Afinidade de instância",+ FOLLOW_DEFAULT_TIMEZONE: "Seguir fuso horário padrão",+ INSTANCE_ID: "Instância de execução",+ JOB_WEIGHT: "Peso do job",+ RAISE_EVENTS: "Máscara de eventos gerados",+ CONNECT_CREDENTIAL_NAME: "Credencial de conexão",+ CREDENTIAL_NAME: "Credencial de execução",+ DESTINATION_NAME: "Destino nomeado",+ DESTINATION: "Host remoto (host[:port])",+ JOB_STYLE: "Estilo do job",+ LOGGING_LEVEL: "Nível de registro",+ },+ editJob: "Editar job",+ editSections: "Configuração do job",+ add: "Adicionar",+ attributes: "Propriedades do job",+ steps: "Etapas",+ schedules: "Agendamentos",+ running: "Execuções atuais",+ unknown: "Desconhecido",+ emptyJobs: "Nenhum job no escopo atual.",+ noMatches: "Nenhum job correspondente.",+ previousPage: "Anterior",+ nextPage: "Próxima",+ pendingDrop: "Exclusão pendente",+ pendingAdd: "Novo",+ undoDrop: "Desfazer exclusão",+ keepOriginal: "Manter original",+ explicitNull: "Definir NULL após confirmar",+ partitionUnavailable: "Esta seção está no estado {status} e não pode ser editada como dados completos.",+ generatedCommandHint: "Esta instrução é gerada pelo banco de dados. Para alterar uma definição de backup ou DTS, informe acima a configuração nativa original. Isso não é necessário ao alterar apenas a próxima etapa.",+ runningUnknownHint: "O estado de execução está indisponível. Ainda é possível solicitar a parada nativa com a permissão necessária.",+ cancelFollowing: "Parar etapas restantes",+ readAgain: "Ler novamente",+ correctDraft: "Corrigir rascunho",+ operationStatusUnavailable: "Não foi possível confirmar o status mais recente da operação. Consulte o resultado da operação.",+ checkResult: "Consultar resultado",+ keepOperator: "Manter o ID de operador {id}; informe um nome para substituí-lo.",+ nextStepHint: "Usado apenas por ações que continuam a execução. NULL segue a ordem nativa das etapas.",+ stepTypes: { "0": "SQL ou bloco", "1": "Backup/restauração V1", "2": "Reorganizar banco de dados", "3": "Atualizar estatísticas", "4": "Migração DTS", "5": "Backup/restauração V1 (estendido)", "6": "Backup/restauração V2" },+ scheduleTypes: { "0": "Uma vez", "1": "Diário", "2": "Semanal", "3": "Data mensal", "4": "Primeira semana do mês", "5": "Segunda semana do mês", "6": "Terceira semana do mês", "7": "Quarta semana do mês", "8": "Última semana do mês" },+ actions: { "0": "Encerrar sem relatar", "1": "Relatar e encerrar", "2": "Continuar sem relatar", "3": "Relatar e continuar" },+ notificationTypes: { "0": "Em caso de sucesso", "1": "Em caso de falha", "2": "Ao concluir" },+ outcomes: {+ running: "Executando operação",+ not_started: "Não iniciada",+ not_applied: "Não aplicada",+ partial: "Algumas etapas foram aplicadas",+ unknown: "Resultado desconhecido; confira antes de gerar outra prévia",+ verified: "Resultado verificado",+ accepted: "Solicitação aceita; resultado da execução ainda não confirmado",+ },+ stepStates: { pending: "Pendente", dispatching: "Enviada", applied: "Executada", accepted: "Aceita", failed: "Não aplicada", unknown: "Desconhecido", skipped: "Não executada" },+ fields: {+ NAME: "Nome",+ ENABLE: "Estado final de ativação",+ DESCRIBE: "Descrição",+ ENABLE_EMAIL: "Notificação por email",+ EMAIL_OPERATOR_NAME: "Nome do operador de email",+ EMAIL_TYPE: "Condição do email",+ ENABLE_NETSEND: "Notificação de rede",+ NETSEND_OPERATOR_NAME: "Nome do operador de rede",+ NETSEND_TYPE: "Condição da rede",+ EP_SEQNO: "Nó de execução (0–15)",+ RAFT_NAME: "Grupo RAFT",+ TYPE: "Tipo",+ COMMAND_INPUT: "SQL ou configuração nativa",+ SUCC_ACTION: "Ação após o sucesso",+ SUCC_NEXT_STEP: "Próxima etapa após sucesso",+ FAIL_ACTION: "Ação após a falha",+ FAIL_NEXT_STEP: "Próxima etapa após falha",+ RETRY_ATTEMPTS: "Número de tentativas",+ RETRY_INTERVAL: "Intervalo entre tentativas (segundos)",+ APPEND_FLAG: "Acrescentar saída",+ FREQ_INTERVAL: "Frequência",+ FREQ_SUB_INTERVAL: "Condição semanal/mensal",+ FREQ_MINUTE_INTERVAL: "Intervalo diário (minutos; 0 executa uma vez por dia)",+ STARTTIME: "Hora de início",+ ENDTIME: "Hora de término",+ DURING_START_DATE: "Válido a partir de",+ DURING_END_DATE: "Válido até",+ },+ },damengJobAdmin: {title: "Jobs do agente Dameng",unsupported: "Esta página oferece suporte apenas a conexões Dameng.",diff --git a/apps/desktop/src/i18n/locales/ru.ts b/apps/desktop/src/i18n/locales/ru.tsindex 51f087f6a0..2bb31568b3 100644--- a/apps/desktop/src/i18n/locales/ru.ts+++ b/apps/desktop/src/i18n/locales/ru.ts@@ -8,6 +8,27 @@ import { meilisearchManagementRu } from "./meilisearchManagement";// Russian locale. Entries omitted here fall back to English at runtime.export default withEnglishFallback({+ oracleTrigger: {+ errorPositionUnavailable: "Исходный код открыт. Не удалось проверить позицию ошибки; проверьте указанные строку и столбец.",+ reconcileStructure: "Сверить применённые изменения",+ reconcileConfirm: "Перечитать текущую структуру таблицы, сохранить желаемые правки и сверить выполненные шаги без повторного запуска прежнего SQL?",+ editFullSource: "Изменить полный исходный код",+ refreshDraft: "Перечитать этот триггер",+ refreshDraftConfirm: "Перечитать триггер и отменить только его структурированный черновик? Остальные черновики структуры таблицы будут сохранены.",+ discardSourceConfirm: "Отменить несохранённые изменения этого исходного кода?",+ scope: "Область триггера",+ parentOwner: "Схема таблицы/представления",+ parentName: "Таблица/представление",+ scopeOwner: "Схема событий",+ obSchemaUnsupported: "Для этой версии OB шаблон триггера Schema не предлагается: проверенный шаблон был отклонён.",+ obDatabaseUnknown: "Поддержка триггеров DATABASE не проверена.",+ nonAtomic: "Операторы DDL фиксируются отдельно. Между созданием и отключением триггер может быть включён. Ошибка останавливает последующие шаги; автоматических повторов нет.",+ unknown: "Неизвестно",+ verifyReadOnly: "Проверить без записи",+ reloadBaseline: "Сохраните черновик и загрузите полное определение триггера перед новым предпросмотром.",+ runFullDefinition: "На этой вкладке можно выполнить только полное определение данного триггера. Для другого SQL используйте обычную вкладку запроса.",+ executionSchema: "Схема выполнения",+ },objectRelations: {title: "Связи",foreignKeys: "Внешние ключи",@@ -4905,6 +4926,7 @@ export default withEnglishFallback({manage: "Управление ссылками на базы данных",},tree: {+ nativeJobs: "Нативные задания",savedSql: "Библиотека SQL",queries: "Запросы",userAdmin: "Пользователи и права",@@ -5706,6 +5728,207 @@ export default withEnglishFallback({scopeFunctions: "функции",stepSkipped: "Пропущено из-за сбоя необходимого предыдущего шага.",},+ nativeJobs: {+ datePrecisionMicroseconds: "Даты заданий в этой версии OceanBase поддерживают только микросекундную точность. Установите цифры 7–9 дробной части секунды в 0 и повторите предварительный просмотр; исходный ввод сохранён.",+ previousContext: "Результат операции из предыдущего контекста",+ detachedDraft: "Исходный черновик сохранён и не связан с текущим объектом.",+ viewRetainedDraft: "Просмотреть исходный черновик",+ damengIntervalAccepted: "Вызов интервала выполнен успешно; исходное выражение нельзя проверить, прочитав его из каталога.",+ damengInterval: "Интервал в секундах или нативное выражение",+ damengIntervalHint: "Положительное целое число задаёт фиксированный интервал в секундах; любой другой ввод передаётся как нативное выражение и не вычисляется при предварительном просмотре.",+ executionObservation: "Наблюдения за нативным выполнением",+ observeExecution: "Обновить результаты запуска",+ associationUncertain: "Связь нативных экземпляров с этим запросом неясна.",+ observationUnavailable: "Не удаётся надёжно сопоставить экземпляр выполнения; обновите результаты запуска или просмотрите нативную запись.",+ newlyObserved: "Впервые обнаружено после отправки запроса",+ observedInstance: "Наблюдаемый экземпляр",+ instanceNotObserved: "Этот экземпляр сейчас не наблюдается",+ observationEmpty: "Сейчас нет экземпляров-кандидатов, которые можно надёжно идентифицировать.",+ observationReadStatus: "Текущие запуски: {running}; история: {history}",+ observationNativeDetails: "Нативная запись",+ observationTimestamp: "Время наблюдения: {time}",+ scalarStorage: "Тип хранения значения",+ scalarText: "Обычный текст",+ scalarNull: "NULL этого типа",+ scalarCivilDate: "Дата",+ scalarCivilHint: "YYYY-MM-DD; для лет до н. э. укажите отрицательный год; нулевого года нет",+ scalarDateClock: "Время (HH:MM:SS, целые секунды)",+ scalarClock: "Время (HH:MM:SS, до 9 знаков после запятой)",+ scalarUtc: "Редактирование в UTC; сохраняется как временная метка в местном часовом поясе базы данных",+ scalarRegion: "Регион часового пояса",+ scalarOffset: "Смещение UTC (±HH:MM)",+ scalarAbbreviation: "Аббревиатура часового пояса (необязательно)",+ scalarMonths: "Всего месяцев (целое число со знаком)",+ scalarNanoseconds: "Всего наносекунд (целое число со знаком)",+ scalarHex: "Байты RAW (шестнадцатеричный формат)",+ scalarFloatHex: "Битовое представление IEEE 754 (8 шестнадцатеричных цифр, от старшего к младшему байту)",+ scalarDoubleHex: "Битовое представление IEEE 754 (16 шестнадцатеричных цифр, от старшего к младшему байту)",+ scalarUrowid: "Полный UROWID",+ finalEnabledHint: "Это состояние включения применяется только после проверки определения и аргументов.",+ transitionPreviewHint: "Сначала приостановите будущее выполнение по расписанию; выбранное состояние включения примените после успешного прохождения всех проверок.",+ legacyRunRestoresScheduling: "Этот запуск на переднем плане также возобновит дальнейшее выполнение по расписанию, а база данных пересчитает время следующего запуска.",+ legacyRuntimeUpdateRequired: "В текущей среде нет протокола традиционных заданий OceanBase. Обновите Agent или JDBC-плагин этого подключения и повторите попытку.",+ title: "Нативные задания",+ unsupported: "Это подключение не поддерживает управление нативными заданиями.",+ kind: "Тип задания",+ createKind: "Тип нового задания",+ owner: "Владелец",+ ownerFilter: "Фильтр по владельцу",+ definition: "Определение",+ arguments: "Аргументы",+ advanced: "Дополнительные атрибуты",+ restoreDefinitionDraft: "Восстановить черновик исходного определения",+ addArgument: "Добавить аргумент",+ argumentPosition: "Аргумент {position}",+ argumentType: "Тип аргумента {position}",+ argumentState: "Состояние аргумента {position}",+ argumentValue: "Значение аргумента {position}",+ scheduleMode: "Способ запуска",+ scheduleModes: { inline: "Дата или правило повтора", named: "Именованное расписание или окно", queue: "Событие очереди", fileWatcher: "Событие поступления файла" },+ destinationMode: "Цель выполнения",+ destinationModes: { local: "Выполнять локально", legacy: "Устаревший удалённый узел (host[:port])", named: "Именованное назначение или группа" },+ eventCondition: "Условие события",+ eventQueueOwner: "Владелец очереди",+ eventQueueName: "Имя очереди",+ eventQueueAgent: "Агент AQ (необязательно)",+ fileWatcherOwner: "Владелец File watcher",+ fileWatcherName: "Имя File watcher",+ chooseReference: "Выбрать {kind}",+ inactiveInlineDraft: "Выбрана именованная ссылка. Встроенные поля остаются в черновике и не будут записаны.",+ referenceFilter: "Поиск по владельцу или имени",+ emptyReferences: "В доступной для чтения области нет подходящих объектов.",+ referenceCatalogUnavailable: "Не удалось прочитать список объектов ссылок ({status}). Можно указать точные имя владельца и имя объекта.",+ catalogCoverage: { database: "Вся база данных", accessible: "Доступно этой учётной записи", current_user: "Принадлежит этой учётной записи", unknown: "Область неизвестна" },+ opaqueArgument: "Это нативное значение нельзя безопасно переписать как текст; сохраните исходное значение.",+ programDefault: "Значение Program по умолчанию",+ programDefaultUnknown: "Не удалось определить значение по умолчанию. Сохраните исходное значение.",+ metadataArgument: "Предоставляется базой данных: {attribute}",+ argumentCatalogUnavailable: "В этой версии представления аргументов являются пустыми заглушками совместимости. По ним нельзя определить существующие аргументы или значения.",+ obSchedulerDefinitionReadOnly: "В этой версии OceanBase базовое определение существующих заданий доступно только для чтения. Ограничения выполнения и зону можно изменить в разделе расширенных настроек.",+ runForeground: "Запустить на переднем плане",+ forceStop: "Принудительно остановить",+ legacyNoStop: "В традиционном DBMS_JOB нет нативной операции остановки. Завершение сеанса не равнозначно остановке задания.",+ baselineUnavailable: "Невозможно прочитать идентификатор объекта или основу согласованности. Перед изменением прочитайте данные снова.",+ kinds: { scheduler: "Задание Scheduler", legacy: "Традиционное Job", "dameng-native": "Задание агента Dameng" },+ argumentStates: { unset: "Не задано", inherit: "Наследовать значение по умолчанию", null: "SQL NULL", value: "Явное значение", opaque: "Нативное значение" },+ referenceKinds: { program: "Программа", schedule: "Расписание", chain: "Цепочка", credential: "Учётные данные", destination: "Назначение", window: "Окно", "window-group": "Группа окон", "file-watcher": "Наблюдатель файлов", "destination-group": "Группа назначений" },+ jobTypes: { PLSQL_BLOCK: "Блок PL/SQL", STORED_PROCEDURE: "Хранимая процедура", CHAIN: "Цепочка", EXECUTABLE: "Исполняемая программа", EXTERNAL_SCRIPT: "Внешний скрипт", SQL_SCRIPT: "Скрипт SQL", BACKUP_SCRIPT: "Скрипт резервного копирования" },+ loggingLevels: { OFF: "Не записывать", RUNS: "Запуски", FAILED_RUNS: "Только неудачные запуски", FULL: "Полное журналирование" },+ definitionFields: {+ ENABLED: "Включить по завершении",+ WHAT: "Тело задания",+ NEXT_DATE: "Следующий запуск",+ INTERVAL: "Выражение повтора",+ INSTANCE: "Экземпляр",+ ZONE: "Зона",+ JOB_TYPE: "Тип задания",+ JOB_ACTION: "Действие задания",+ NUMBER_OF_ARGUMENTS: "Количество аргументов",+ PROGRAM_OWNER: "Владелец Program",+ PROGRAM_NAME: "Имя Program",+ SCHEDULE_OWNER: "Владелец Schedule",+ SCHEDULE_NAME: "Имя Schedule",+ START_DATE: "Начало со смещением UTC",+ END_DATE: "Конец со смещением UTC",+ REPEAT_INTERVAL: "Интервал повтора",+ AUTO_DROP: "Автоудаление по завершении",+ COMMENTS: "Комментарии",+ LOG_USER: "Пользователь входа",+ PRIV_USER: "Пользователь привилегий",+ SCHEMA_USER: "Схема выполнения",+ JOB_CLASS: "Класс задания",+ JOB_PRIORITY: "Приоритет",+ MAX_RUNS: "Максимум запусков",+ MAX_FAILURES: "Максимум ошибок",+ MAX_RUN_DURATION: "Максимальная длительность запуска",+ SCHEDULE_LIMIT: "Предельная задержка запуска по расписанию",+ RESTARTABLE: "Разрешить перезапуск",+ STOP_ON_WINDOW_CLOSE: "Останавливать при закрытии окна",+ STORE_OUTPUT: "Сохранять вывод запуска",+ ALLOW_RUNS_IN_RESTRICTED_MODE: "Разрешить запуск в ограниченном режиме",+ INSTANCE_STICKINESS: "Привязка к экземпляру",+ FOLLOW_DEFAULT_TIMEZONE: "Использовать часовой пояс по умолчанию",+ INSTANCE_ID: "Экземпляр выполнения",+ JOB_WEIGHT: "Вес задания",+ RAISE_EVENTS: "Маска генерируемых событий",+ CONNECT_CREDENTIAL_NAME: "Учётные данные подключения",+ CREDENTIAL_NAME: "Учётные данные запуска",+ DESTINATION_NAME: "Именованное назначение",+ DESTINATION: "Удалённый узел (host[:port])",+ JOB_STYLE: "Стиль задания",+ LOGGING_LEVEL: "Уровень журналирования",+ },+ editJob: "Изменить задание",+ editSections: "Настройка задания",+ add: "Добавить",+ attributes: "Свойства задания",+ steps: "Шаги",+ schedules: "Расписания",+ running: "Текущие запуски",+ unknown: "Неизвестно",+ emptyJobs: "В текущей области нет заданий.",+ noMatches: "Совпадающих заданий нет.",+ previousPage: "Назад",+ nextPage: "Далее",+ pendingDrop: "Будет удалено",+ pendingAdd: "Новое",+ undoDrop: "Отменить удаление",+ keepOriginal: "Сохранить исходное",+ explicitNull: "Установить NULL после подтверждения",+ partitionUnavailable: "Этот раздел имеет состояние {status}; его нельзя редактировать как полные данные.",+ generatedCommandHint: "Эта команда сгенерирована базой данных. Для изменения резервного копирования или DTS введите выше исходные параметры. При изменении только следующего шага это не требуется.",+ runningUnknownHint: "Состояние запуска недоступно. При наличии нужных прав можно запросить штатную остановку.",+ cancelFollowing: "Остановить оставшиеся шаги",+ readAgain: "Прочитать повторно",+ correctDraft: "Исправить черновик",+ operationStatusUnavailable: "Не удалось подтвердить последнее состояние операции. Проверьте результат операции.",+ checkResult: "Проверить результат",+ keepOperator: "Сохранить ID оператора {id}; для замены укажите имя.",+ nextStepHint: "Используется только действиями с продолжением выполнения. NULL означает штатный порядок шагов.",+ stepTypes: { "0": "SQL или блок", "1": "Копирование/восстановление V1", "2": "Реорганизация базы данных", "3": "Обновление статистики", "4": "Миграция DTS", "5": "Копирование/восстановление V1 (расширенное)", "6": "Копирование/восстановление V2" },+ scheduleTypes: { "0": "Однократно", "1": "Ежедневно", "2": "Еженедельно", "3": "Дата месяца", "4": "Первая неделя месяца", "5": "Вторая неделя месяца", "6": "Третья неделя месяца", "7": "Четвёртая неделя месяца", "8": "Последняя неделя месяца" },+ actions: { "0": "Завершить без отчёта", "1": "Сообщить и завершить", "2": "Продолжить без отчёта", "3": "Сообщить и продолжить" },+ notificationTypes: { "0": "При успехе", "1": "При ошибке", "2": "При завершении" },+ outcomes: {+ running: "Операция выполняется",+ not_started: "Не начата",+ not_applied: "Не применена",+ partial: "Часть шагов применена",+ unknown: "Результат неизвестен; проверьте перед новым предпросмотром",+ verified: "Результат проверен",+ accepted: "Запрос принят; результат запуска ещё не подтверждён",+ },+ stepStates: { pending: "Ожидает", dispatching: "Отправлен", applied: "Выполнен", accepted: "Принят", failed: "Не применён", unknown: "Неизвестно", skipped: "Не выполнен" },+ fields: {+ NAME: "Имя",+ ENABLE: "Итоговое состояние включения",+ DESCRIBE: "Описание",+ ENABLE_EMAIL: "Уведомление по почте",+ EMAIL_OPERATOR_NAME: "Имя почтового оператора",+ EMAIL_TYPE: "Условие отправки письма",+ ENABLE_NETSEND: "Сетевое уведомление",+ NETSEND_OPERATOR_NAME: "Имя сетевого оператора",+ NETSEND_TYPE: "Условие сетевого уведомления",+ EP_SEQNO: "Узел выполнения (0–15)",+ RAFT_NAME: "Группа RAFT",+ TYPE: "Тип",+ COMMAND_INPUT: "Текст SQL или штатные параметры",+ SUCC_ACTION: "Действие после успеха",+ SUCC_NEXT_STEP: "Следующий шаг при успехе",+ FAIL_ACTION: "Действие после ошибки",+ FAIL_NEXT_STEP: "Следующий шаг при ошибке",+ RETRY_ATTEMPTS: "Число повторов",+ RETRY_INTERVAL: "Интервал повторов (секунды)",+ APPEND_FLAG: "Дописывать вывод",+ FREQ_INTERVAL: "Частота",+ FREQ_SUB_INTERVAL: "Условие недели/месяца",+ FREQ_MINUTE_INTERVAL: "Дневной интервал (минуты; 0 — раз в день)",+ STARTTIME: "Время начала",+ ENDTIME: "Время окончания",+ DURING_START_DATE: "Действует с",+ DURING_END_DATE: "Действует до",+ },+ },damengJobAdmin: {title: "Задания агента Dameng",unsupported: "Эта страница поддерживает только подключения Dameng.",diff --git a/apps/desktop/src/i18n/locales/th.ts b/apps/desktop/src/i18n/locales/th.tsindex eb19b9158c..cd8f27bf54 100644--- a/apps/desktop/src/i18n/locales/th.ts+++ b/apps/desktop/src/i18n/locales/th.ts@@ -50,6 +50,27 @@ const damengDump = {};export default withEnglishFallback({+ oracleTrigger: {+ errorPositionUnavailable: "เปิดซอร์สแล้ว แต่ไม่สามารถยืนยันตำแหน่งข้อผิดพลาดได้ โปรดตรวจสอบบรรทัดและคอลัมน์ที่แสดง",+ reconcileStructure: "ตรวจสอบการเปลี่ยนแปลงที่ใช้แล้ว",+ reconcileConfirm: "อ่านโครงสร้างตารางปัจจุบันอีกครั้ง เก็บการแก้ไขที่ต้องการไว้ และตรวจสอบขั้นตอนที่เสร็จแล้วโดยไม่เรียกใช้ SQL เดิมซ้ำหรือไม่?",+ editFullSource: "แก้ไขซอร์สฉบับเต็ม",+ refreshDraft: "โหลดทริกเกอร์นี้ใหม่",+ refreshDraftConfirm: "โหลดใหม่และละทิ้งเฉพาะแบบร่างเชิงโครงสร้างของทริกเกอร์นี้หรือไม่? แบบร่างโครงสร้างตารางอื่นจะยังคงอยู่",+ discardSourceConfirm: "ต้องการละทิ้งการแก้ไขซอร์สโค้ดนี้ที่ยังไม่ได้บันทึกหรือไม่?",+ scope: "ขอบเขตทริกเกอร์",+ parentOwner: "สคีมาของตาราง/วิว",+ parentName: "ตาราง/วิวที่เกี่ยวข้อง",+ scopeOwner: "สคีมาของเหตุการณ์",+ obSchemaUnsupported: "OB เวอร์ชันนี้ไม่มีเทมเพลตทริกเกอร์ Schema เนื่องจากเทมเพลตที่ทดสอบถูกปฏิเสธ",+ obDatabaseUnknown: "ยังไม่ได้ตรวจสอบความสามารถของทริกเกอร์ DATABASE",+ nonAtomic: "คำสั่ง DDL จะคอมมิตแยกกัน ทริกเกอร์อาจเปิดใช้งานชั่วคราวระหว่างการสร้างและการปิดใช้งาน หากล้มเหลว ขั้นตอนถัดไปจะหยุดและไม่มีการลองซ้ำอัตโนมัติ",+ unknown: "ไม่ทราบ",+ verifyReadOnly: "ตรวจสอบโดยไม่เขียนข้อมูล",+ reloadBaseline: "เก็บแบบร่างไว้และโหลดนิยามทริกเกอร์ฉบับเต็มอีกครั้งก่อนดูตัวอย่างใหม่",+ runFullDefinition: "แท็บนี้เรียกใช้ได้เฉพาะนิยามฉบับเต็มของทริกเกอร์นี้เท่านั้น สำหรับ SQL อื่นให้ใช้แท็บคิวรีปกติ",+ executionSchema: "สคีมาที่ใช้รัน",+ },objectRelations: {title: "ความสัมพันธ์",foreignKeys: "คีย์นอก",@@ -5090,6 +5111,7 @@ export default withEnglishFallback({manage: "จัดการลิงก์ฐานข้อมูล",},tree: {+ nativeJobs: "งานเนทีฟ",savedSql: "ไลบรารี SQL",queries: "Queries",userAdmin: "ผู้ใช้และสิทธิ์",@@ -5993,6 +6015,199 @@ export default withEnglishFallback({operationFailed: "Operation ล้มเหลว",operationFailedWithMessage: "Operation ล้มเหลว: {message}",},+ nativeJobs: {+ datePrecisionMicroseconds: "วันที่ของงานใน OceanBase รุ่นนี้รองรับความละเอียดระดับไมโครวินาทีเท่านั้น โปรดเปลี่ยนหลักที่ 7–9 ของวินาทีเศษให้เป็น 0 แล้วดูตัวอย่างอีกครั้ง โดยเก็บข้อมูลที่ป้อนเดิมไว้แล้ว",+ previousContext: "ผลการดำเนินการจากบริบทก่อนหน้า",+ detachedDraft: "เก็บฉบับร่างเดิมไว้แล้ว และไม่ได้ผูกกับออบเจ็กต์ปัจจุบัน",+ viewRetainedDraft: "ดูฉบับร่างเดิม",+ damengIntervalAccepted: "เรียกใช้ช่วงเวลาสำเร็จ แต่ไม่สามารถตรวจสอบนิพจน์เดิมด้วยการอ่านกลับจากแค็ตตาล็อกได้",+ damengInterval: "ช่วงเวลาเป็นวินาทีหรือนิพจน์เนทีฟ",+ damengIntervalHint: "จำนวนเต็มบวกจะกำหนดช่วงเวลาคงที่เป็นวินาที ส่วนข้อมูลอื่นจะส่งเป็นนิพจน์เนทีฟโดยไม่ประเมินค่าในตัวอย่างก่อนใช้",+ executionObservation: "ผลการสังเกตการทำงานแบบเนทีฟ",+ observeExecution: "รีเฟรชผลการรัน",+ associationUncertain: "ยังไม่แน่ชัดว่าอินสแตนซ์เนทีฟเกี่ยวข้องกับคำขอนี้หรือไม่",+ observationUnavailable: "ไม่สามารถระบุความเชื่อมโยงกับอินสแตนซ์การทำงานได้อย่างน่าเชื่อถือ โปรดรีเฟรชผลการรันหรือดูระเบียนเนทีฟ",+ newlyObserved: "พบใหม่เมื่อเทียบกับก่อนส่งคำขอ",+ observedInstance: "อินสแตนซ์ที่สังเกตพบ",+ instanceNotObserved: "ขณะนี้ไม่พบอินสแตนซ์นี้",+ observationEmpty: "ขณะนี้ไม่มีอินสแตนซ์ที่เป็นไปได้ซึ่งระบุได้อย่างน่าเชื่อถือ",+ observationReadStatus: "การทำงานปัจจุบัน: {running}; ประวัติ: {history}",+ observationNativeDetails: "ระเบียนเนทีฟ",+ observationTimestamp: "เวลาที่สังเกต: {time}",+ scalarStorage: "ชนิดการจัดเก็บค่า",+ scalarText: "ข้อความทั่วไป",+ scalarNull: "ค่า NULL ของชนิดนี้",+ scalarCivilDate: "วันที่",+ scalarCivilHint: "YYYY-MM-DD; ใช้ปีติดลบสำหรับปีก่อนคริสตกาล และไม่มีปี 0",+ scalarDateClock: "เวลา (HH:MM:SS, วินาทีเต็ม)",+ scalarClock: "เวลา (HH:MM:SS, ทศนิยมได้สูงสุด 9 หลัก)",+ scalarUtc: "แก้ไขเป็น UTC; บันทึกเป็น timestamp ในเขตเวลาท้องถิ่นของฐานข้อมูล",+ scalarRegion: "ภูมิภาคเขตเวลา",+ scalarOffset: "ออฟเซ็ต UTC (±HH:MM)",+ scalarAbbreviation: "ตัวย่อเขตเวลา (ไม่บังคับ)",+ scalarMonths: "จำนวนเดือนทั้งหมด (จำนวนเต็มมีเครื่องหมาย)",+ scalarNanoseconds: "จำนวนนาโนวินาทีทั้งหมด (จำนวนเต็มมีเครื่องหมาย)",+ scalarHex: "ไบต์ RAW (เลขฐานสิบหก)",+ scalarFloatHex: "รูปแบบบิต IEEE 754 (เลขฐานสิบหก 8 หลัก, big-endian)",+ scalarDoubleHex: "รูปแบบบิต IEEE 754 (เลขฐานสิบหก 16 หลัก, big-endian)",+ scalarUrowid: "UROWID แบบเต็ม",+ finalEnabledHint: "สถานะเปิดใช้งานนี้จะมีผลหลังจากตรวจสอบข้อกำหนดและอาร์กิวเมนต์ทั้งหมดแล้วเท่านั้น",+ transitionPreviewHint: "พักกำหนดการในอนาคตก่อน แล้วใช้สถานะเปิดใช้งานที่เลือกหลังผ่านการตรวจสอบทั้งหมด",+ legacyRunRestoresScheduling: "การรันแบบเบื้องหน้าครั้งนี้จะเปิดการทำงานตามกำหนดการในอนาคตอีกครั้ง และให้ฐานข้อมูลคำนวณเวลารันครั้งถัดไปใหม่",+ legacyRuntimeUpdateRequired: "รันไทม์ปัจจุบันไม่มีโปรโตคอล Job แบบเดิมของ OceanBase โปรดอัปเดต Agent หรือปลั๊กอิน JDBC ของการเชื่อมต่อนี้แล้วลองอีกครั้ง",+ title: "งานเนทีฟ",+ unsupported: "การเชื่อมต่อนี้ไม่รองรับการจัดการงานเนทีฟ",+ kind: "ประเภทงาน",+ createKind: "ประเภทงานใหม่",+ owner: "เจ้าของ",+ ownerFilter: "กรองตามเจ้าของ",+ definition: "ข้อกำหนด",+ arguments: "อาร์กิวเมนต์",+ advanced: "คุณสมบัติขั้นสูง",+ restoreDefinitionDraft: "คืนค่าฉบับร่างข้อกำหนดเดิม",+ addArgument: "เพิ่มอาร์กิวเมนต์",+ argumentPosition: "อาร์กิวเมนต์ {position}",+ argumentType: "ชนิดของอาร์กิวเมนต์ {position}",+ argumentState: "สถานะของอาร์กิวเมนต์ {position}",+ argumentValue: "ค่าของอาร์กิวเมนต์ {position}",+ scheduleMode: "วิธีเรียกใช้",+ scheduleModes: { inline: "วันที่หรือกฎการทำซ้ำ", named: "กำหนดการหรือหน้าต่างเวลาที่มีชื่อ", queue: "เหตุการณ์คิว", fileWatcher: "เหตุการณ์เมื่อไฟล์มาถึง" },+ destinationMode: "เป้าหมายการทำงาน",+ destinationModes: { local: "ทำงานในเครื่อง", legacy: "โฮสต์ระยะไกลแบบเดิม (host[:port])", named: "ปลายทางหรือกลุ่มที่มีชื่อ" },+ eventCondition: "เงื่อนไขเหตุการณ์",+ eventQueueOwner: "เจ้าของคิว",+ eventQueueName: "ชื่อคิว",+ eventQueueAgent: "เอเจนต์ AQ (ไม่บังคับ)",+ fileWatcherOwner: "เจ้าของ File watcher",+ fileWatcherName: "ชื่อ File watcher",+ chooseReference: "เลือก {kind}",+ inactiveInlineDraft: "เลือกการอ้างอิงที่มีชื่อแล้ว ฟิลด์อินไลน์จะยังอยู่ในฉบับร่างและจะไม่ถูกเขียนในครั้งนี้",+ referenceFilter: "ค้นหาเจ้าของหรือชื่อ",+ emptyReferences: "ไม่พบออบเจ็กต์ที่ตรงกันในขอบเขตที่อ่านได้",+ referenceCatalogUnavailable: "ไม่สามารถอ่านรายการออบเจ็กต์ที่อ้างอิงได้ ({status}) คุณยังสามารถป้อนเจ้าของและชื่อที่ตรงกันได้",+ catalogCoverage: { database: "ทั้งฐานข้อมูล", accessible: "บัญชีนี้เข้าถึงได้", current_user: "บัญชีนี้เป็นเจ้าของ", unknown: "ไม่ทราบขอบเขต" },+ opaqueArgument: "ค่าเนทีฟนี้ไม่สามารถเขียนใหม่เป็นข้อความได้อย่างปลอดภัย ให้คงค่าเดิมไว้",+ programDefault: "ค่าเริ่มต้นของ Program",+ programDefaultUnknown: "ไม่สามารถระบุค่าเริ่มต้นได้ ให้คงค่าเดิมไว้",+ metadataArgument: "ฐานข้อมูลเป็นผู้ระบุ: {attribute}",+ argumentCatalogUnavailable: "มุมมองอาร์กิวเมนต์ในรุ่นนี้เป็นมุมมองว่างเพื่อความเข้ากันได้ จึงใช้ระบุอาร์กิวเมนต์หรือค่าที่มีอยู่ไม่ได้",+ obSchedulerDefinitionReadOnly: "นิยามพื้นฐานของงานที่มีอยู่เป็นแบบอ่านอย่างเดียวใน OceanBase รุ่นนี้ แก้ไขขีดจำกัดการทำงานและ Zone ได้ในขั้นสูง",+ runForeground: "เรียกใช้เบื้องหน้า",+ forceStop: "บังคับหยุด",+ legacyNoStop: "DBMS_JOB แบบเดิมไม่มีคำสั่งหยุดงานเนทีฟ การยุติเซสชันไม่เหมือนกับการหยุดงาน",+ baselineUnavailable: "ไม่สามารถอ่านข้อมูลระบุตัวตนหรือฐานความสอดคล้องของวัตถุได้ โปรดอ่านใหม่ก่อนแก้ไข",+ kinds: { scheduler: "งาน Scheduler", legacy: "Job แบบเดิม", "dameng-native": "งานเอเจนต์ Dameng" },+ argumentStates: { unset: "ยังไม่ตั้งค่า", inherit: "สืบทอดค่าเริ่มต้น", null: "SQL NULL", value: "ค่าที่ระบุ", opaque: "ค่าเนทีฟ" },+ referenceKinds: { program: "โปรแกรม", schedule: "กำหนดการ", chain: "เชน", credential: "ข้อมูลรับรอง", destination: "ปลายทาง", window: "หน้าต่างเวลา", "window-group": "กลุ่มหน้าต่างเวลา", "file-watcher": "ตัวเฝ้าดูไฟล์", "destination-group": "กลุ่มปลายทาง" },+ jobTypes: { PLSQL_BLOCK: "บล็อก PL/SQL", STORED_PROCEDURE: "โพรซีเยอร์ที่จัดเก็บ", CHAIN: "เชน", EXECUTABLE: "โปรแกรมที่เรียกใช้งานได้", EXTERNAL_SCRIPT: "สคริปต์ภายนอก", SQL_SCRIPT: "สคริปต์ SQL", BACKUP_SCRIPT: "สคริปต์สำรองข้อมูล" },+ loggingLevels: { OFF: "ไม่บันทึก", RUNS: "บันทึกการรัน", FAILED_RUNS: "บันทึกเฉพาะการรันที่ล้มเหลว", FULL: "บันทึกทั้งหมด" },+ definitionFields: {+ ENABLED: "เปิดใช้งานเมื่อพร้อม",+ WHAT: "เนื้อหางาน",+ NEXT_DATE: "เวลาทำงานครั้งถัดไป",+ INTERVAL: "นิพจน์การทำซ้ำ",+ INSTANCE: "อินสแตนซ์",+ ZONE: "โซน",+ JOB_TYPE: "ประเภทงาน",+ JOB_ACTION: "การทำงานของงาน",+ NUMBER_OF_ARGUMENTS: "จำนวนอาร์กิวเมนต์",+ PROGRAM_OWNER: "เจ้าของ Program",+ PROGRAM_NAME: "ชื่อ Program",+ SCHEDULE_OWNER: "เจ้าของ Schedule",+ SCHEDULE_NAME: "ชื่อ Schedule",+ START_DATE: "เวลาเริ่มพร้อมออฟเซ็ต UTC",+ END_DATE: "เวลาสิ้นสุดพร้อมออฟเซ็ต UTC",+ REPEAT_INTERVAL: "ช่วงเวลาทำซ้ำ",+ AUTO_DROP: "ลบอัตโนมัติเมื่อเสร็จ",+ COMMENTS: "ความคิดเห็น",+ LOG_USER: "ผู้ใช้ที่เข้าสู่ระบบ",+ PRIV_USER: "ผู้ใช้สำหรับสิทธิ์",+ SCHEMA_USER: "สคีมาที่ใช้รัน",+ JOB_CLASS: "คลาสงาน",+ JOB_PRIORITY: "ลำดับความสำคัญ",+ MAX_RUNS: "จำนวนครั้งรันสูงสุด",+ MAX_FAILURES: "จำนวนครั้งล้มเหลวสูงสุด",+ MAX_RUN_DURATION: "ระยะเวลารันสูงสุด",+ SCHEDULE_LIMIT: "ขีดจำกัดความล่าช้าตามกำหนดการ",+ RESTARTABLE: "อนุญาตให้เริ่มใหม่",+ STOP_ON_WINDOW_CLOSE: "หยุดเมื่อหน้าต่างเวลาปิด",+ STORE_OUTPUT: "เก็บเอาต์พุตการรัน",+ ALLOW_RUNS_IN_RESTRICTED_MODE: "อนุญาตให้รันในโหมดจำกัด",+ INSTANCE_STICKINESS: "ความผูกพันกับอินสแตนซ์",+ FOLLOW_DEFAULT_TIMEZONE: "ใช้เขตเวลาเริ่มต้น",+ INSTANCE_ID: "อินสแตนซ์ที่รัน",+ JOB_WEIGHT: "น้ำหนักงาน",+ RAISE_EVENTS: "มาสก์เหตุการณ์ที่ส่ง",+ CONNECT_CREDENTIAL_NAME: "ข้อมูลรับรองการเชื่อมต่อ",+ CREDENTIAL_NAME: "ข้อมูลรับรองการรัน",+ DESTINATION_NAME: "ปลายทางที่มีชื่อ",+ DESTINATION: "โฮสต์ระยะไกล (host[:port])",+ JOB_STYLE: "รูปแบบงาน",+ LOGGING_LEVEL: "ระดับการบันทึก",+ },+ editJob: "แก้ไข Job",+ editSections: "การตั้งค่า Job",+ add: "เพิ่ม",+ attributes: "คุณสมบัติ Job",+ steps: "ขั้นตอน",+ schedules: "กำหนดเวลา",+ running: "การทำงานปัจจุบัน",+ unknown: "ไม่ทราบ",+ emptyJobs: "ไม่มี Job ในขอบเขตปัจจุบัน",+ noMatches: "ไม่มี Job ที่ตรงกัน",+ previousPage: "ก่อนหน้า",+ nextPage: "ถัดไป",+ pendingDrop: "รอลบ",+ pendingAdd: "รายการใหม่",+ undoDrop: "ยกเลิกการลบ",+ keepOriginal: "คงค่าเดิม",+ explicitNull: "ตั้งเป็น NULL หลังยืนยัน",+ partitionUnavailable: "ข้อมูลส่วนนี้มีสถานะ {status} จึงไม่สามารถแก้ไขเป็นข้อมูลที่ครบถ้วนได้",+ generatedCommandHint: "คำสั่งนี้สร้างโดยฐานข้อมูล หากต้องการแก้ไขการสำรองข้อมูลหรือ DTS ให้กรอกค่าตั้งค่าดั้งเดิมด้านบน ไม่จำเป็นเมื่อเปลี่ยนเฉพาะขั้นตอนถัดไป",+ runningUnknownHint: "อ่านสถานะการทำงานไม่ได้ แต่ยังขอหยุดผ่านคำสั่งของฐานข้อมูลได้หากมีสิทธิ์",+ cancelFollowing: "หยุดขั้นตอนที่เหลือ",+ readAgain: "อ่านอีกครั้ง",+ correctDraft: "แก้ไขฉบับร่าง",+ operationStatusUnavailable: "ไม่สามารถยืนยันสถานะล่าสุดของการดำเนินการได้ โปรดตรวจสอบผลการดำเนินการ",+ checkResult: "ตรวจสอบผลการดำเนินการ",+ keepOperator: "คง ID ผู้ดำเนินการ {id} หรือกรอกชื่อเพื่อเปลี่ยน",+ nextStepHint: "ใช้เฉพาะการดำเนินการที่ทำงานต่อ NULL จะทำตามลำดับขั้นตอนของฐานข้อมูล",+ stepTypes: { "0": "SQL หรือบล็อกคำสั่ง", "1": "สำรอง/กู้คืน V1", "2": "จัดระเบียบฐานข้อมูลใหม่", "3": "อัปเดตสถิติ", "4": "ย้ายข้อมูล DTS", "5": "สำรอง/กู้คืน V1 (เพิ่มเติม)", "6": "สำรอง/กู้คืน V2" },+ scheduleTypes: { "0": "ครั้งเดียว", "1": "ทุกวัน", "2": "ทุกสัปดาห์", "3": "วันที่ระบุของเดือน", "4": "สัปดาห์แรกของเดือน", "5": "สัปดาห์ที่สองของเดือน", "6": "สัปดาห์ที่สามของเดือน", "7": "สัปดาห์ที่สี่ของเดือน", "8": "สัปดาห์สุดท้ายของเดือน" },+ actions: { "0": "จบโดยไม่รายงานผล", "1": "รายงานผลแล้วจบ", "2": "ทำต่อโดยไม่รายงานผล", "3": "รายงานผลแล้วทำต่อ" },+ notificationTypes: { "0": "เมื่อสำเร็จ", "1": "เมื่อล้มเหลว", "2": "เมื่อจบการทำงาน" },+ outcomes: { running: "กำลังดำเนินการ", not_started: "ยังไม่เริ่ม", not_applied: "ยังไม่มีผล", partial: "บางขั้นตอนมีผลแล้ว", unknown: "ไม่ทราบผล โปรดตรวจสอบก่อนสร้างตัวอย่างใหม่", verified: "ตรวจสอบผลแล้ว", accepted: "รับคำขอแล้ว ยังไม่ยืนยันผลการทำงาน" },+ stepStates: { pending: "รอดำเนินการ", dispatching: "ส่งแล้ว", applied: "ดำเนินการแล้ว", accepted: "ยอมรับแล้ว", failed: "ยังไม่มีผล", unknown: "ไม่ทราบผล", skipped: "ไม่ได้ดำเนินการ" },+ fields: {+ NAME: "ชื่อ",+ ENABLE: "สถานะเปิดใช้งานสุดท้าย",+ DESCRIBE: "คำอธิบาย",+ ENABLE_EMAIL: "แจ้งเตือนทางอีเมล",+ EMAIL_OPERATOR_NAME: "ชื่อผู้ดำเนินการอีเมล",+ EMAIL_TYPE: "เงื่อนไขอีเมล",+ ENABLE_NETSEND: "แจ้งเตือนทางเครือข่าย",+ NETSEND_OPERATOR_NAME: "ชื่อผู้ดำเนินการเครือข่าย",+ NETSEND_TYPE: "เงื่อนไขเครือข่าย",+ EP_SEQNO: "โหนดทำงาน (0–15)",+ RAFT_NAME: "กลุ่ม RAFT",+ TYPE: "ประเภท",+ COMMAND_INPUT: "คำสั่ง SQL หรือค่าตั้งค่าดั้งเดิม",+ SUCC_ACTION: "การดำเนินการหลังสำเร็จ",+ SUCC_NEXT_STEP: "ขั้นตอนถัดไปเมื่อสำเร็จ",+ FAIL_ACTION: "การดำเนินการหลังล้มเหลว",+ FAIL_NEXT_STEP: "ขั้นตอนถัดไปเมื่อล้มเหลว",+ RETRY_ATTEMPTS: "จำนวนครั้งที่ลองใหม่",+ RETRY_INTERVAL: "ช่วงเวลาลองใหม่ (วินาที)",+ APPEND_FLAG: "ต่อท้ายผลลัพธ์",+ FREQ_INTERVAL: "ความถี่",+ FREQ_SUB_INTERVAL: "เงื่อนไขสัปดาห์/เดือน",+ FREQ_MINUTE_INTERVAL: "ช่วงเวลาระหว่างวัน (นาที; 0 คือวันละครั้ง)",+ STARTTIME: "เวลาเริ่ม",+ ENDTIME: "เวลาสิ้นสุด",+ DURING_START_DATE: "วันที่เริ่มมีผล",+ DURING_END_DATE: "วันที่สิ้นสุดผล",+ },+ },damengJobAdmin: {title: "Agent Jobs ของ Dameng",unsupported: "หน้านี้รองรับเฉพาะการเชื่อมต่อ Dameng",diff --git a/apps/desktop/src/i18n/locales/zh-CN.ts b/apps/desktop/src/i18n/locales/zh-CN.tsindex 1fb3272f55..756f19a429 100644--- a/apps/desktop/src/i18n/locales/zh-CN.ts+++ b/apps/desktop/src/i18n/locales/zh-CN.ts@@ -11,6 +11,27 @@ import { mongodbDatabaseDumpZhCN as mongoDump } from "./mongodbDatabaseDump";import { damengDumpZhCN as damengDump } from "./damengDump";export default withEnglishFallback({+ oracleTrigger: {+ errorPositionUnavailable: "源码已打开,但无法核实错误位置,请按原行列检查。",+ reconcileStructure: "核对已执行改动",+ reconcileConfirm: "重新读取当前表结构,保留期望修改并核对已执行步骤,不重放旧 SQL。继续吗?",+ editFullSource: "编辑完整源码",+ refreshDraft: "重读此触发器",+ refreshDraftConfirm: "重读将放弃此触发器的结构化草稿,其他表结构草稿保留。继续吗?",+ discardSourceConfirm: "放弃尚未保存的源码修改吗?",+ scope: "触发范围",+ parentOwner: "所属表/视图 Schema",+ parentName: "所属表/视图",+ scopeOwner: "事件范围 Schema",+ obSchemaUnsupported: "当前 OB 版本不提供 Schema 触发器模板(已测试模板被拒绝)。",+ obDatabaseUnknown: "DATABASE 触发器能力未核实。",+ nonAtomic: "多条 DDL 分别提交。创建后到停用前可能短暂启用;失败会停止后续步骤,不自动重试。",+ unknown: "未知",+ verifyReadOnly: "只读核实",+ reloadBaseline: "保留草稿,重新读取完整触发器后再预览。",+ runFullDefinition: "此触发器标签仅可运行本对象的完整定义。其他 SQL 请使用普通查询标签。",+ executionSchema: "执行模式",+ },objectRelations: {title: "关系",foreignKeys: "外键引用",@@ -5134,6 +5155,7 @@ export default withEnglishFallback({manage: "管理数据库链接",},tree: {+ nativeJobs: "原生作业",savedSql: "SQL 库",queries: "查询",userAdmin: "用户与权限",@@ -6036,6 +6058,199 @@ export default withEnglishFallback({operationFailed: "操作执行失败",operationFailedWithMessage: "操作执行失败:{message}",},+ nativeJobs: {+ datePrecisionMicroseconds: "此 OceanBase 版本的作业日期只支持微秒精度。请将小数秒第 7–9 位改为 0,再重新预览;原输入已保留。",+ previousContext: "原上下文的操作结果",+ detachedDraft: "原草稿已保留,未绑定当前对象。",+ viewRetainedDraft: "查看原草稿",+ damengIntervalAccepted: "间隔调用已成功,原表达式无法从目录读回验证。",+ damengInterval: "间隔秒数或原生表达式",+ damengIntervalHint: "正整数按秒设置固定间隔;其他内容作为原生表达式传入,不会在预览时求值。",+ executionObservation: "原生执行观测",+ observeExecution: "刷新运行结果",+ associationUncertain: "原生实例与本次请求的关联不确定。",+ observationUnavailable: "无法可靠关联执行实例;可刷新运行结果或查看原生记录。",+ newlyObserved: "相对请求前新观察到",+ observedInstance: "已观察实例",+ instanceNotObserved: "当前未观察到该实例",+ observationEmpty: "当前没有可可靠识别的候选实例。",+ observationReadStatus: "当前运行:{running};历史:{history}",+ observationNativeDetails: "原生记录",+ observationTimestamp: "观测时间:{time}",+ scalarStorage: "值的存储类型",+ scalarText: "普通文本",+ scalarNull: "此类型的 NULL",+ scalarCivilDate: "日期",+ scalarCivilHint: "YYYY-MM-DD;公元前年份加负号,无公元 0 年",+ scalarDateClock: "时间(HH:MM:SS,整秒)",+ scalarClock: "时间(HH:MM:SS,最多 9 位小数)",+ scalarUtc: "以 UTC 编辑;保存为数据库本地时区时间戳",+ scalarRegion: "时区区域",+ scalarOffset: "UTC 偏移(±HH:MM)",+ scalarAbbreviation: "时区缩写(可选)",+ scalarMonths: "月数合计(带符号整数)",+ scalarNanoseconds: "纳秒合计(带符号整数)",+ scalarHex: "RAW 字节(十六进制)",+ scalarFloatHex: "IEEE 754 位模式(8 位十六进制,大端)",+ scalarDoubleHex: "IEEE 754 位模式(16 位十六进制,大端)",+ scalarUrowid: "完整 UROWID",+ finalEnabledHint: "定义和参数全部验证通过后,才应用此启用状态。",+ transitionPreviewHint: "先暂停未来调度,全部验证通过后再应用所选启用状态。",+ legacyRunRestoresScheduling: "此次前台运行也会恢复未来调度,并由数据库重新计算下次运行时间。",+ legacyRuntimeUpdateRequired: "当前运行包缺少 OceanBase 传统作业协议。请更新此连接使用的 Agent 或 JDBC 插件后重试。",+ title: "原生作业",+ unsupported: "此连接不支持原生作业管理。",+ kind: "作业类型",+ createKind: "新建作业类型",+ owner: "所有者",+ ownerFilter: "按所有者筛选",+ definition: "作业定义",+ restoreDefinitionDraft: "恢复原定义草稿",+ arguments: "参数",+ advanced: "高级属性",+ addArgument: "添加参数",+ argumentPosition: "参数 {position}",+ argumentType: "参数 {position} 的类型",+ argumentState: "参数 {position} 的状态",+ argumentValue: "参数 {position} 的值",+ scheduleMode: "触发方式",+ scheduleModes: { inline: "日期或重复规则", named: "命名调度或窗口", queue: "队列事件", fileWatcher: "文件到达事件" },+ destinationMode: "执行目标",+ destinationModes: { local: "本地执行", legacy: "传统远程主机 (host[:port])", named: "命名目的地或目标组" },+ eventCondition: "事件条件",+ eventQueueOwner: "队列所有者",+ eventQueueName: "队列名称",+ eventQueueAgent: "AQ 代理(可选)",+ fileWatcherOwner: "文件监视器所有者",+ fileWatcherName: "文件监视器名称",+ chooseReference: "选择{kind}",+ inactiveInlineDraft: "命名引用已选中;内联字段保留在草稿中,本次不写入。",+ referenceFilter: "搜索所有者或名称",+ emptyReferences: "当前可读范围内没有匹配对象。",+ referenceCatalogUnavailable: "暂时无法读取引用对象列表({status});仍可填写精确的所有者和名称。",+ catalogCoverage: { database: "全库范围", accessible: "当前账号可访问", current_user: "当前账号所有", unknown: "范围未知" },+ opaqueArgument: "此原生值不能按文本安全改写,可保持原值。",+ programDefault: "程序默认值",+ programDefaultUnknown: "默认值未能确定,保留原值。",+ metadataArgument: "由数据库提供:{attribute}",+ argumentCatalogUnavailable: "当前版本的参数视图仅为兼容占位,无法据此读取或判断已有参数。",+ obSchedulerDefinitionReadOnly: "此 OceanBase 版本的已有作业基础定义只读。运行限制和执行 Zone 可在“高级属性”中编辑。",+ runForeground: "前台运行",+ forceStop: "强制停止",+ legacyNoStop: "传统 DBMS_JOB 没有原生停止入口;停止会话不等同于停止作业。",+ baselineUnavailable: "对象身份或一致性基线不可读,请重新读取后操作。",+ kinds: { scheduler: "Scheduler 作业", legacy: "传统 Job", "dameng-native": "达梦代理作业" },+ argumentStates: { unset: "未设置", inherit: "继承默认值", null: "SQL NULL", value: "显式值", opaque: "原生值" },+ referenceKinds: { program: "程序", schedule: "调度", chain: "链", credential: "凭据", destination: "目的地", window: "窗口", "window-group": "窗口组", "file-watcher": "文件监视器", "destination-group": "目的地组" },+ jobTypes: { PLSQL_BLOCK: "PL/SQL 块", STORED_PROCEDURE: "存储过程", CHAIN: "链", EXECUTABLE: "可执行程序", EXTERNAL_SCRIPT: "外部脚本", SQL_SCRIPT: "SQL 脚本", BACKUP_SCRIPT: "备份脚本" },+ loggingLevels: { OFF: "不记录", RUNS: "运行记录", FAILED_RUNS: "仅记录失败", FULL: "完整记录" },+ definitionFields: {+ ENABLED: "最终启用",+ WHAT: "执行内容",+ NEXT_DATE: "下次执行时间",+ INTERVAL: "重复表达式",+ INSTANCE: "运行实例",+ ZONE: "运行区域",+ JOB_TYPE: "作业类型",+ JOB_ACTION: "执行内容",+ NUMBER_OF_ARGUMENTS: "参数数量",+ PROGRAM_OWNER: "程序所有者",+ PROGRAM_NAME: "程序名称",+ SCHEDULE_OWNER: "调度所有者",+ SCHEDULE_NAME: "调度名称",+ START_DATE: "开始时间(含时区偏移)",+ END_DATE: "结束时间(含时区偏移)",+ REPEAT_INTERVAL: "重复规则",+ AUTO_DROP: "完成后自动删除",+ COMMENTS: "备注",+ LOG_USER: "登录用户",+ PRIV_USER: "权限用户",+ SCHEMA_USER: "执行模式",+ JOB_CLASS: "作业类",+ JOB_PRIORITY: "优先级",+ MAX_RUNS: "最多运行次数",+ MAX_FAILURES: "最多失败次数",+ MAX_RUN_DURATION: "最长运行时长",+ SCHEDULE_LIMIT: "调度延迟上限",+ RESTARTABLE: "允许重新启动",+ STOP_ON_WINDOW_CLOSE: "窗口关闭时停止",+ STORE_OUTPUT: "保存运行输出",+ ALLOW_RUNS_IN_RESTRICTED_MODE: "允许在受限模式运行",+ INSTANCE_STICKINESS: "实例亲和性",+ FOLLOW_DEFAULT_TIMEZONE: "跟随默认时区",+ INSTANCE_ID: "执行实例",+ JOB_WEIGHT: "作业权重",+ RAISE_EVENTS: "触发事件掩码",+ CONNECT_CREDENTIAL_NAME: "连接凭据",+ CREDENTIAL_NAME: "运行凭据",+ DESTINATION_NAME: "命名目的地",+ DESTINATION: "远程主机 (host[:port])",+ JOB_STYLE: "作业样式",+ LOGGING_LEVEL: "日志记录级别",+ },+ editJob: "编辑作业",+ editSections: "作业配置",+ add: "新增",+ attributes: "作业属性",+ steps: "步骤",+ schedules: "调度",+ running: "当前运行",+ unknown: "未知",+ emptyJobs: "当前范围内没有作业。",+ noMatches: "没有匹配的作业。",+ previousPage: "上一页",+ nextPage: "下一页",+ pendingDrop: "待删除",+ pendingAdd: "待新增",+ undoDrop: "撤销删除",+ keepOriginal: "保持原值",+ explicitNull: "确认后设为 NULL",+ partitionUnavailable: "此部分数据的状态为 {status},不能按完整数据编辑。",+ generatedCommandHint: "这里显示的是数据库生成的语句。修改备份或 DTS 步骤时,请在上方填写原生配置参数;只修改下一步骤无需重新填写。",+ runningUnknownHint: "当前运行状态不可读,仍可按原生权限请求停止。",+ cancelFollowing: "停止后续步骤",+ readAgain: "重新读取",+ correctDraft: "修正草稿",+ operationStatusUnavailable: "无法确认最新操作状态,请查询操作结果。",+ checkResult: "查询操作结果",+ keepOperator: "保持当前操作员 ID {id};填写名称可替换。",+ nextStepHint: "仅继续执行的动作使用此跳转;NULL 按原生步骤顺序继续。",+ stepTypes: { "0": "SQL 或语句块", "1": "备份还原 V1", "2": "重组数据库", "3": "更新统计信息", "4": "DTS 数据迁移", "5": "备份还原 V1(扩展)", "6": "备份还原 V2" },+ scheduleTypes: { "0": "执行一次", "1": "按天", "2": "按周", "3": "每月指定日期", "4": "每月第一周", "5": "每月第二周", "6": "每月第三周", "7": "每月第四周", "8": "每月最后一周" },+ actions: { "0": "不报告结果并结束", "1": "报告结果并结束", "2": "不报告结果并继续", "3": "报告结果并继续" },+ notificationTypes: { "0": "成功时", "1": "失败时", "2": "结束时" },+ outcomes: { running: "正在执行操作", not_started: "尚未开始", not_applied: "未生效", partial: "部分步骤已生效", unknown: "结果未知,请核对后重新预览", verified: "操作结果已验证", accepted: "请求已接受,运行结果待确认" },+ stepStates: { pending: "待执行", dispatching: "已发送", applied: "已执行", accepted: "已接受", failed: "未生效", unknown: "结果未知", skipped: "未执行" },+ fields: {+ NAME: "名称",+ ENABLE: "最终启用",+ DESCRIBE: "描述",+ ENABLE_EMAIL: "启用邮件通知",+ EMAIL_OPERATOR_NAME: "邮件操作员名称",+ EMAIL_TYPE: "邮件通知条件",+ ENABLE_NETSEND: "启用网络通知",+ NETSEND_OPERATOR_NAME: "网络通知操作员名称",+ NETSEND_TYPE: "网络通知条件",+ EP_SEQNO: "执行节点(0–15)",+ RAFT_NAME: "RAFT 组",+ TYPE: "类型",+ COMMAND_INPUT: "SQL 正文或原生配置参数",+ SUCC_ACTION: "成功后的动作",+ SUCC_NEXT_STEP: "成功时跳转到步骤",+ FAIL_ACTION: "失败后的动作",+ FAIL_NEXT_STEP: "失败时跳转到步骤",+ RETRY_ATTEMPTS: "失败重试次数",+ RETRY_INTERVAL: "重试间隔(秒)",+ APPEND_FLAG: "追加输出",+ FREQ_INTERVAL: "发生频率",+ FREQ_SUB_INTERVAL: "周/月内发生条件",+ FREQ_MINUTE_INTERVAL: "日内间隔(分钟,0 为每天一次)",+ STARTTIME: "开始时间",+ ENDTIME: "结束时间",+ DURING_START_DATE: "有效起始日期",+ DURING_END_DATE: "有效结束日期",+ },+ },damengJobAdmin: {title: "达梦代理作业",unsupported: "当前页面仅支持达梦数据库连接。",diff --git a/apps/desktop/src/i18n/locales/zh-TW.ts b/apps/desktop/src/i18n/locales/zh-TW.tsindex 88f476c597..a572ba323f 100644--- a/apps/desktop/src/i18n/locales/zh-TW.ts+++ b/apps/desktop/src/i18n/locales/zh-TW.ts@@ -67,6 +67,27 @@ const consul = {};export default withEnglishFallback({+ oracleTrigger: {+ errorPositionUnavailable: "原始碼已開啟,但無法核實錯誤位置,請依原行列檢查。",+ reconcileStructure: "核對已執行變更",+ reconcileConfirm: "重新讀取目前資料表結構,保留預期修改並核對已執行步驟,不重播舊 SQL。繼續嗎?",+ editFullSource: "編輯完整原始碼",+ refreshDraft: "重新讀取此觸發器",+ refreshDraftConfirm: "重新讀取將捨棄此觸發器的結構化草稿,其他資料表結構草稿會保留。繼續嗎?",+ discardSourceConfirm: "要捨棄尚未儲存的原始碼修改嗎?",+ scope: "觸發範圍",+ parentOwner: "所屬資料表/檢視 Schema",+ parentName: "所屬資料表/檢視",+ scopeOwner: "事件範圍 Schema",+ obSchemaUnsupported: "目前 OB 版本不提供 Schema 觸發器範本(已測試範本遭拒絕)。",+ obDatabaseUnknown: "DATABASE 觸發器能力尚未核實。",+ nonAtomic: "多條 DDL 分別提交。建立後到停用前可能短暫啟用;失敗會停止後續步驟,不自動重試。",+ unknown: "未知",+ verifyReadOnly: "唯讀核實",+ reloadBaseline: "保留草稿,重新讀取完整觸發器後再預覽。",+ runFullDefinition: "此觸發器分頁僅可執行本物件的完整定義。其他 SQL 請使用一般查詢分頁。",+ executionSchema: "執行綱要",+ },objectRelations: {title: "關係",foreignKeys: "外鍵參照",@@ -4784,6 +4805,7 @@ export default withEnglishFallback({manage: "Manage database links",},tree: {+ nativeJobs: "原生作業",databaseLinks: "Database Links",savedSql: "SQL 庫",queries: "查詢",@@ -9752,6 +9774,199 @@ export default withEnglishFallback({scopeFunctions: "函式",stepSkipped: "因相依的前置步驟失敗而略過。",},+ nativeJobs: {+ datePrecisionMicroseconds: "此 OceanBase 版本的作業日期只支援微秒精度。請將小數秒第 7–9 位改為 0,再重新預覽;原輸入已保留。",+ previousContext: "原脈絡的操作結果",+ detachedDraft: "原草稿已保留,未綁定目前物件。",+ viewRetainedDraft: "查看原草稿",+ damengIntervalAccepted: "間隔呼叫已成功,原運算式無法從目錄讀回驗證。",+ damengInterval: "間隔秒數或原生運算式",+ damengIntervalHint: "正整數會設定以秒為單位的固定間隔;其他內容會作為原生運算式傳入,且不會在預覽時求值。",+ executionObservation: "原生執行觀測",+ observeExecution: "重新整理執行結果",+ associationUncertain: "原生執行個體與本次要求的關聯性不確定。",+ observationUnavailable: "無法可靠關聯執行個體;可重新整理執行結果或查看原生紀錄。",+ newlyObserved: "相較要求前新觀測到",+ observedInstance: "已觀測執行個體",+ instanceNotObserved: "目前未觀測到此執行個體",+ observationEmpty: "目前沒有可可靠識別的候選執行個體。",+ observationReadStatus: "目前執行:{running};歷史紀錄:{history}",+ observationNativeDetails: "原生紀錄",+ observationTimestamp: "觀測時間:{time}",+ scalarStorage: "值的儲存類型",+ scalarText: "一般文字",+ scalarNull: "此類型的 NULL",+ scalarCivilDate: "日期",+ scalarCivilHint: "YYYY-MM-DD;西元前年份加負號,沒有西元 0 年",+ scalarDateClock: "時間(HH:MM:SS,整秒)",+ scalarClock: "時間(HH:MM:SS,最多 9 位小數)",+ scalarUtc: "以 UTC 編輯;儲存為資料庫本地時區時間戳記",+ scalarRegion: "時區區域",+ scalarOffset: "UTC 偏移(±HH:MM)",+ scalarAbbreviation: "時區縮寫(選填)",+ scalarMonths: "月數總計(帶正負號的整數)",+ scalarNanoseconds: "奈秒總計(帶正負號的整數)",+ scalarHex: "RAW 位元組(十六進位)",+ scalarFloatHex: "IEEE 754 位元模式(8 位十六進位,大端序)",+ scalarDoubleHex: "IEEE 754 位元模式(16 位十六進位,大端序)",+ scalarUrowid: "完整 UROWID",+ finalEnabledHint: "定義與引數全部驗證通過後,才套用此啟用狀態。",+ transitionPreviewHint: "先暫停未來排程,全部驗證通過後再套用所選啟用狀態。",+ legacyRunRestoresScheduling: "此次前景執行也會恢復未來排程,並由資料庫重新計算下次執行時間。",+ legacyRuntimeUpdateRequired: "目前的執行套件缺少 OceanBase 傳統作業協定。請更新此連線使用的 Agent 或 JDBC 外掛後重試。",+ title: "原生作業",+ unsupported: "此連線不支援原生作業管理。",+ kind: "作業類型",+ createKind: "新增作業類型",+ owner: "擁有者",+ ownerFilter: "依擁有者篩選",+ definition: "作業定義",+ restoreDefinitionDraft: "還原原始定義草稿",+ arguments: "引數",+ advanced: "進階屬性",+ addArgument: "新增引數",+ argumentPosition: "引數 {position}",+ argumentType: "引數 {position} 的類型",+ argumentState: "引數 {position} 的狀態",+ argumentValue: "引數 {position} 的值",+ scheduleMode: "觸發方式",+ scheduleModes: { inline: "日期或重複規則", named: "命名排程或視窗", queue: "佇列事件", fileWatcher: "檔案到達事件" },+ destinationMode: "執行目標",+ destinationModes: { local: "本機執行", legacy: "傳統遠端主機 (host[:port])", named: "具名目的地或目標群組" },+ eventCondition: "事件條件",+ eventQueueOwner: "佇列擁有者",+ eventQueueName: "佇列名稱",+ eventQueueAgent: "AQ 代理(選填)",+ fileWatcherOwner: "檔案監視器擁有者",+ fileWatcherName: "檔案監視器名稱",+ chooseReference: "選擇{kind}",+ inactiveInlineDraft: "已選取命名引用;內聯欄位保留在草稿中,本次不寫入。",+ referenceFilter: "搜尋擁有者或名稱",+ emptyReferences: "目前可讀範圍內沒有符合的物件。",+ referenceCatalogUnavailable: "暫時無法讀取引用物件清單({status});仍可填寫精確的擁有者和名稱。",+ catalogCoverage: { database: "全庫範圍", accessible: "目前帳號可存取", current_user: "目前帳號擁有", unknown: "範圍未知" },+ opaqueArgument: "此原生值無法以文字安全改寫,可保留原值。",+ programDefault: "程式預設值",+ programDefaultUnknown: "無法確定預設值,保留原值。",+ metadataArgument: "由資料庫提供:{attribute}",+ argumentCatalogUnavailable: "目前版本的引數檢視僅為相容佔位,無法據此讀取或判斷既有引數。",+ obSchedulerDefinitionReadOnly: "此 OceanBase 版本的既有作業基本定義為唯讀。執行限制與執行 Zone 可在「進階屬性」中編輯。",+ runForeground: "前景執行",+ forceStop: "強制停止",+ legacyNoStop: "傳統 DBMS_JOB 沒有原生停止操作;終止工作階段不等於停止作業。",+ baselineUnavailable: "無法讀取物件身分或一致性基準,請重新讀取後操作。",+ kinds: { scheduler: "Scheduler 作業", legacy: "傳統 Job", "dameng-native": "達夢代理作業" },+ argumentStates: { unset: "未設定", inherit: "繼承預設值", null: "SQL NULL", value: "明確值", opaque: "原生值" },+ referenceKinds: { program: "程式", schedule: "排程", chain: "鏈", credential: "認證資料", destination: "目的地", window: "視窗", "window-group": "視窗群組", "file-watcher": "檔案監視器", "destination-group": "目的地群組" },+ jobTypes: { PLSQL_BLOCK: "PL/SQL 區塊", STORED_PROCEDURE: "預存程序", CHAIN: "鏈", EXECUTABLE: "可執行程式", EXTERNAL_SCRIPT: "外部指令碼", SQL_SCRIPT: "SQL 指令碼", BACKUP_SCRIPT: "備份指令碼" },+ loggingLevels: { OFF: "不記錄", RUNS: "執行記錄", FAILED_RUNS: "僅記錄失敗", FULL: "完整記錄" },+ definitionFields: {+ ENABLED: "完成後啟用",+ WHAT: "執行內容",+ NEXT_DATE: "下次執行時間",+ INTERVAL: "重複運算式",+ INSTANCE: "執行個體",+ ZONE: "執行區域",+ JOB_TYPE: "作業類型",+ JOB_ACTION: "執行內容",+ NUMBER_OF_ARGUMENTS: "引數數量",+ PROGRAM_OWNER: "程式擁有者",+ PROGRAM_NAME: "程式名稱",+ SCHEDULE_OWNER: "排程擁有者",+ SCHEDULE_NAME: "排程名稱",+ START_DATE: "開始時間(含時區偏移)",+ END_DATE: "結束時間(含時區偏移)",+ REPEAT_INTERVAL: "重複規則",+ AUTO_DROP: "完成後自動刪除",+ COMMENTS: "備註",+ LOG_USER: "登入使用者",+ PRIV_USER: "權限使用者",+ SCHEMA_USER: "執行綱要",+ JOB_CLASS: "作業類別",+ JOB_PRIORITY: "優先順序",+ MAX_RUNS: "最多執行次數",+ MAX_FAILURES: "最多失敗次數",+ MAX_RUN_DURATION: "最長執行時間",+ SCHEDULE_LIMIT: "排程延遲上限",+ RESTARTABLE: "允許重新啟動",+ STOP_ON_WINDOW_CLOSE: "視窗關閉時停止",+ STORE_OUTPUT: "儲存執行輸出",+ ALLOW_RUNS_IN_RESTRICTED_MODE: "允許在受限模式執行",+ INSTANCE_STICKINESS: "執行個體親和性",+ FOLLOW_DEFAULT_TIMEZONE: "跟隨預設時區",+ INSTANCE_ID: "執行個體",+ JOB_WEIGHT: "作業權重",+ RAISE_EVENTS: "觸發事件遮罩",+ CONNECT_CREDENTIAL_NAME: "連線認證資料",+ CREDENTIAL_NAME: "執行認證資料",+ DESTINATION_NAME: "具名目的地",+ DESTINATION: "遠端主機 (host[:port])",+ JOB_STYLE: "作業樣式",+ LOGGING_LEVEL: "日誌記錄層級",+ },+ editJob: "編輯作業",+ editSections: "作業設定",+ add: "新增",+ attributes: "作業屬性",+ steps: "步驟",+ schedules: "排程",+ running: "目前執行",+ unknown: "未知",+ emptyJobs: "目前範圍內沒有作業。",+ noMatches: "沒有符合的作業。",+ previousPage: "上一頁",+ nextPage: "下一頁",+ pendingDrop: "待刪除",+ pendingAdd: "待新增",+ undoDrop: "復原刪除",+ keepOriginal: "保持原值",+ explicitNull: "確認後設為 NULL",+ partitionUnavailable: "此部分資料的狀態為 {status},不能當作完整資料編輯。",+ generatedCommandHint: "這裡顯示的是資料庫產生的敘述。修改備份或 DTS 步驟時,請在上方填寫原生設定參數;只修改下一步驟時不必重新填寫。",+ runningUnknownHint: "無法讀取目前執行狀態,仍可依原生權限要求停止。",+ cancelFollowing: "停止後續步驟",+ readAgain: "重新讀取",+ correctDraft: "修正草稿",+ operationStatusUnavailable: "無法確認最新操作狀態,請查詢操作結果。",+ checkResult: "查詢操作結果",+ keepOperator: "保持目前操作員 ID {id};填寫名稱可取代。",+ nextStepHint: "僅繼續執行的動作使用此跳轉;NULL 依原生步驟順序繼續。",+ stepTypes: { "0": "SQL 或敘述區塊", "1": "備份還原 V1", "2": "重組資料庫", "3": "更新統計資訊", "4": "DTS 資料移轉", "5": "備份還原 V1(擴充)", "6": "備份還原 V2" },+ scheduleTypes: { "0": "執行一次", "1": "按天", "2": "按週", "3": "每月指定日期", "4": "每月第一週", "5": "每月第二週", "6": "每月第三週", "7": "每月第四週", "8": "每月最後一週" },+ actions: { "0": "不回報結果並結束", "1": "回報結果並結束", "2": "不回報結果並繼續", "3": "回報結果並繼續" },+ notificationTypes: { "0": "成功時", "1": "失敗時", "2": "結束時" },+ outcomes: { running: "正在執行操作", not_started: "尚未開始", not_applied: "未生效", partial: "部分步驟已生效", unknown: "結果未知,請核對後重新預覽", verified: "操作結果已驗證", accepted: "要求已接受,執行結果待確認" },+ stepStates: { pending: "待執行", dispatching: "已傳送", applied: "已執行", accepted: "已接受", failed: "未生效", unknown: "結果未知", skipped: "未執行" },+ fields: {+ NAME: "名稱",+ ENABLE: "最終啟用",+ DESCRIBE: "描述",+ ENABLE_EMAIL: "啟用郵件通知",+ EMAIL_OPERATOR_NAME: "郵件操作員名稱",+ EMAIL_TYPE: "郵件通知條件",+ ENABLE_NETSEND: "啟用網路通知",+ NETSEND_OPERATOR_NAME: "網路通知操作員名稱",+ NETSEND_TYPE: "網路通知條件",+ EP_SEQNO: "執行節點(0–15)",+ RAFT_NAME: "RAFT 群組",+ TYPE: "類型",+ COMMAND_INPUT: "SQL 本文或原生設定參數",+ SUCC_ACTION: "成功後的動作",+ SUCC_NEXT_STEP: "成功時跳轉到步驟",+ FAIL_ACTION: "失敗後的動作",+ FAIL_NEXT_STEP: "失敗時跳轉到步驟",+ RETRY_ATTEMPTS: "失敗重試次數",+ RETRY_INTERVAL: "重試間隔(秒)",+ APPEND_FLAG: "附加輸出",+ FREQ_INTERVAL: "發生頻率",+ FREQ_SUB_INTERVAL: "週/月內發生條件",+ FREQ_MINUTE_INTERVAL: "日內間隔(分鐘,0 為每天一次)",+ STARTTIME: "開始時間",+ ENDTIME: "結束時間",+ DURING_START_DATE: "有效起始日期",+ DURING_END_DATE: "有效結束日期",+ },+ },damengJobAdmin: {title: "達夢代理作業",unsupported: "目前頁面僅支援達夢資料庫連線。",diff --git a/apps/desktop/src/lib/__tests__/database/DamengJobAdmin.component.spec.ts b/apps/desktop/src/lib/__tests__/database/DamengJobAdmin.component.spec.tsnew file mode 100644index 0000000000..6c4b9b0fce--- /dev/null+++ b/apps/desktop/src/lib/__tests__/database/DamengJobAdmin.component.spec.ts@@ -0,0 +1,1724 @@+// @vitest-environment happy-dom+import { createApp, defineComponent, h, nextTick, reactive, type Component } from "vue";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import type { NativeJobDetails, NativeJobRequest } from "@/lib/database/nativeJobs";+import type { ConnectionConfig } from "@/types/database";+import type { NativeJobAdminSelection } from "@/lib/database/nativeJobAdmin";++const mocks = vi.hoisted(() => ({+ ensureConnected: vi.fn(),+ executeQuery: vi.fn(),+ executeMulti: vi.fn(),+ nativeJobOpenContext: vi.fn(),+ nativeJobList: vi.fn(),+ nativeJobRead: vi.fn(),+ nativeJobReferences: vi.fn(),+ nativeJobPrepare: vi.fn(),+ nativeJobApply: vi.fn(),+ nativeJobStatus: vi.fn(),+ nativeJobCancel: vi.fn(),+ toast: vi.fn(),+ track: vi.fn(),+}));+function passthrough(tag: string): Component {+ return defineComponent({+ inheritAttrs: false,+ setup(_, { attrs, slots }) {+ return () => h(tag, attrs, slots.default?.());+ },+ });+}+function modelDialog() {+ return defineComponent({+ inheritAttrs: false,+ setup(_, { attrs, slots }) {+ return () => (attrs.open ? h("div", { "data-dialog": "true" }, slots.default?.()) : null);+ },+ });+}+function modelInput() {+ return defineComponent({+ inheritAttrs: false,+ setup(_, { attrs }) {+ return () => h("input", { ...attrs, value: attrs.modelValue, onInput: (event: Event) => (attrs["onUpdate:modelValue"] as (value: string) => void)?.((event.target as HTMLInputElement).value) });+ },+ });+}+vi.mock("vue-i18n", () => ({ useI18n: () => ({ t: (key: string) => key }) }));+vi.mock("@/components/ui/button", () => ({ Button: passthrough("button") }));+vi.mock("@/components/ui/badge", () => ({ Badge: passthrough("span") }));+vi.mock("@/components/ui/input", () => ({ Input: modelInput() }));+vi.mock("@/components/ui/dialog", () => ({ Dialog: modelDialog(), DialogContent: passthrough("div"), DialogFooter: passthrough("div"), DialogHeader: passthrough("div"), DialogTitle: passthrough("div") }));+vi.mock("@/stores/connectionStore", () => ({ useConnectionStore: () => ({ ensureConnected: mocks.ensureConnected }) }));+vi.mock("@/composables/useToast", () => ({ useToast: () => ({ toast: mocks.toast }) }));+vi.mock("@/lib/tabs/tabUiState", () => ({ useTabUiState: () => ({ initialState: { selectedJobName: "Job_1", detailTab: "steps" }, track: mocks.track }) }));+vi.mock("@/lib/backend/api", () => mocks);+vi.mock("@/lib/database/productionExecutionGuard", () => ({ executeWithProductionContextGuard: async (options: { execute: () => Promise<unknown> }) => options.execute(), executeWithProductionSqlGuard: async (options: { execute: () => Promise<unknown> }) => options.execute() }));+import DamengJobAdmin from "@/components/admin/DamengJobAdmin.vue";++const scope = { connectionId: "c", database: "", contextId: "context" };+const target = { kind: "dameng-native" as const, scope, jobId: "900719925474099312345", name: "Job_1" };+const connection: ConnectionConfig = { id: "c", name: "DM test", db_type: "dameng", host: "localhost", port: 5236, username: "Owner", password: "" };+let details: NativeJobDetails;+let request: NativeJobRequest | undefined;+const mounted: { app: ReturnType<typeof createApp>; root: HTMLDivElement }[] = [];+async function flush() {+ for (let index = 0; index < 24; index++) {+ await Promise.resolve();+ await nextTick();+ }+}+async function mount(config: ConnectionConfig = connection, initialSelection?: NativeJobAdminSelection) {+ const root = document.createElement("div");+ document.body.append(root);+ const app = createApp(DamengJobAdmin, { connection: config, initialSelection });+ app.mount(root);+ mounted.push({ app, root });+ await flush();+ return root;+}+function button(root: Element, label: string) {+ const active = root.querySelector('[data-dialog="true"]') ?? root;+ const result = [...active.querySelectorAll("button")].find((element) => element.textContent?.trim() === label);+ if (!result) throw new Error(`Missing button ${label}`);+ return result;+}+function input(root: Element, label: string, value: string) {+ const element = root.querySelector<HTMLInputElement | HTMLTextAreaElement>(`[aria-label="${label}"]`);+ if (!element) throw new Error(`Missing input ${label}`);+ element.value = value;+ element.dispatchEvent(new Event("input", { bubbles: true }));+}+beforeEach(() => {+ vi.resetAllMocks();+ request = undefined;+ details = {+ snapshot: {+ ref: target,+ revision: "baseline",+ definition: { status: "available", value: { ID: target.jobId, NAME: "Job_1", USERNAME: "Owner", ENABLE: false, DESCRIBE: "old description", ENABLE_EMAIL: false, EMAIL_TYPE: 2, ENABLE_NETSEND: false, NETSEND_TYPE: 2, EP_SEQNO: 0, RAFT_NAME: null } },+ arguments: { status: "empty" },+ },+ nativeIdentity: { status: "available", value: { DBX_JOB_ID: target.jobId, DBX_CREATED_AT: "creation" } },+ consistency: { status: "available", value: null },+ parameterMetadata: { status: "unsupported", reason: "not_applicable" },+ steps: { status: "available", value: [{ ID: 11, JOBID: target.jobId, NAME: "sql", TYPE: 0, COMMAND: "SELECT 1;", SUCC_ACTION: 1, FAIL_ACTION: 1, RETRY_ATTEMPTS: 0, RETRY_INTERVAL: 0, APPEND_FLAG: 0, DESCRIBE: null, SUCC_NEXT_STEP: null, FAIL_NEXT_STEP: null }] },+ schedules: { status: "empty" },+ running: { status: "unknown", reason: "not_readable" },+ history: { status: "denied", reason: "privilege_missing" },+ sources: {},+ };+ mocks.executeQuery.mockResolvedValue({ columns: ["CNT"], rows: [[1]], affected_rows: 0, execution_time_ms: 0 });+ mocks.nativeJobOpenContext.mockResolvedValue({ scope, engine: "dameng", sessionUser: "Owner", actualDatabase: "DB", productVersion: "8" });+ mocks.nativeJobList.mockImplementation(async () => ({+ jobs: { status: "available", value: [{ ref: target, name: "Job_1", owner: "Owner", enabled: false, jobType: "native", state: null, nextRun: null, comments: "old description", aliases: [], logUser: null, privUser: null, schemaUser: null }] },+ source: { source: "SYSJOB.USER_JOBS_VIEW", coverage: "current_user" },+ offset: 0,+ limit: 100,+ }));+ mocks.nativeJobRead.mockImplementation(async () => structuredClone(details));+ mocks.nativeJobPrepare.mockImplementation(async (value: NativeJobRequest) => {+ request = value;+ return { planId: "immutable-plan", operationId: "operation", scope, target, steps: [{ id: "definition", label: "native_job_step_definition", sql: "native reviewed SQL" }] };+ });+ mocks.nativeJobApply.mockResolvedValue({ operationId: "operation", target, state: "finished", outcome: "verified", cancelRequested: false, steps: [{ id: "definition", state: "applied", reason: null, vendorCode: null }], reason: null });+});+afterEach(() => {+ for (const { app, root } of mounted.splice(0)) {+ app.unmount();+ root.remove();+ }+ vi.useRealTimers();+});++function schedulerRefreshFixture(options: { sameScope?: boolean; replaced?: boolean; unknownIdentity?: boolean; sessionUser?: string; actualDatabase?: string } = {}) {+ const nextScope = options.sameScope ? scope : { ...scope, contextId: "reconnected" };+ const ref = { kind: "scheduler" as const, scope, owner: "Owner", name: "Job_1" };+ let opened = 0;+ mocks.nativeJobOpenContext.mockImplementation(async () => {+ opened++;+ return { scope: opened === 1 ? scope : nextScope, engine: "oceanbase-oracle", sessionUser: opened === 1 ? "Owner" : (options.sessionUser ?? "Owner"), actualDatabase: opened === 1 ? "DB" : (options.actualDatabase ?? "DB"), productVersion: "4.2.5.7" };+ });+ mocks.nativeJobList.mockImplementation(async ({ scope: requested }) => ({ jobs: { status: "available", value: [{ ref: { ...ref, scope: requested }, name: ref.name, owner: ref.owner, enabled: false, aliases: [] }] }, source: { coverage: "current_user" }, offset: 0, limit: 100 }));+ const read = (requested: typeof ref) => {+ const value = structuredClone(details);+ value.snapshot.ref = requested;+ value.snapshot.revision = opened === 1 ? "baseline" : "fresh-baseline";+ value.snapshot.definition = { status: "available", value: { JOB_TYPE: "STORED_PROCEDURE", JOB_ACTION: "work_proc", NUMBER_OF_ARGUMENTS: 0, JOB_STYLE: "REGULAR", ENABLED: false, AUTO_DROP: false, JOB_CLASS: "DEFAULT_JOB_CLASS", MAX_FAILURES: 0, MAX_RUN_DURATION: "0 0:0:0.0" } };+ value.nativeIdentity = opened > 1 && options.unknownIdentity ? { status: "unknown", reason: "identity_unavailable" } : { status: "available", value: { DBX_JOB_ID: "41", DBX_CREATED_AT: opened > 1 && options.replaced ? "replacement" : "creation" } };+ value.snapshot.arguments = { status: "empty" };+ return value;+ };+ mocks.nativeJobRead.mockImplementation(async (requested) => read(requested));+ mocks.nativeJobPrepare.mockImplementation(async (value: NativeJobRequest) => {+ request = value;+ if (!("target" in value)) throw new Error("Expected an existing target");+ return { planId: "immutable-plan", operationId: "operation", scope: value.target.scope, target: value.target, steps: [{ id: "attributes", label: "attributes", sql: "reviewed effective native attribute" }] };+ });+ return { ref, nextScope, read, config: { ...connection, db_type: "oceanbase-oracle" as const } };+}++describe("native Job explicit context recovery", () => {+ it("keeps a dispatched Run and independent Stop separate while a late Run receipt cannot close Stop confirmation", async () => {+ vi.useFakeTimers();+ const fixture = schedulerRefreshFixture();+ details.running = { status: "empty" };+ let finishRun!: (status: unknown) => void;+ const runReceipt = new Promise((resolve) => (finishRun = resolve));+ let runFinished = false;+ const operation = (action: "run" | "stop", finished = false) => ({+ operationId: `${action}-operation`,+ target: fixture.ref,+ state: finished ? "finished" : "running",+ outcome: finished ? "accepted" : "unknown",+ cancelRequested: false,+ steps: [{ id: action, state: finished ? "accepted" : "dispatching", reason: null, vendorCode: null }],+ reason: null,+ });+ mocks.nativeJobPrepare.mockImplementation(async (value: NativeJobRequest) => ({ planId: `${value.action}-plan`, operationId: `${value.action}-operation`, scope, target: fixture.ref, steps: [{ id: value.action, label: value.action, sql: `reviewed ${value.action}` }] }));+ mocks.nativeJobApply.mockImplementation(async (planId: string) => (planId === "run-plan" ? runReceipt : operation("stop", true)));+ mocks.nativeJobStatus.mockImplementation(async (id: string) => operation(id === "run-operation" ? "run" : "stop", id === "run-operation" ? runFinished : true));+ const root = await mount(fixture.config);+ expect(button(root, "damengJobAdmin.stopRunning").disabled).toBe(true);+ button(root, "damengJobAdmin.runAsync").click();+ await flush();+ button(root, "damengJobAdmin.applySql").click();+ await flush();+ await vi.advanceTimersByTimeAsync(400);+ await flush();+ expect(button(root, "damengJobAdmin.stopRunning").disabled).toBe(false);+ expect(button(root, "nativeJobs.editJob").disabled).toBe(true);+ button(root, "damengJobAdmin.stopRunning").click();+ await flush();+ expect(root.querySelector('[data-dialog="true"]')?.textContent).toContain("reviewed stop");+ expect(button(root, "damengJobAdmin.applySql").disabled).toBe(false);+ finishRun(operation("run", true));+ await flush();+ expect(root.querySelector('[data-dialog="true"]')?.textContent).toContain("reviewed stop");+ button(root, "damengJobAdmin.applySql").click();+ await flush();+ expect(mocks.nativeJobApply.mock.calls.map(([id]) => id)).toEqual(["run-plan", "stop-plan"]);+ expect(root.textContent).toContain("nativeJobs.outcomes.running");+ expect(root.textContent).toContain("nativeJobs.outcomes.accepted");+ runFinished = true;+ await vi.advanceTimersByTimeAsync(400);+ await flush();+ expect(mocks.nativeJobStatus.mock.calls.every(([id]) => id === "run-operation" || id === "stop-operation")).toBe(true);+ expect(mocks.nativeJobApply).toHaveBeenCalledTimes(2);+ });+ it("keeps rejected precision inputs editable and allows a corrected creation preview without applying", async () => {+ const fixture = schedulerRefreshFixture();+ const root = await mount(fixture.config);+ button(root, "damengJobAdmin.newJob").click();+ await flush();+ input(root, "damengJobAdmin.jobName", "Precision_job");+ input(root, "nativeJobs.definitionFields.START_DATE", "2032-01-01T23:54:25.123456789Z");+ input(root, "nativeJobs.definitionFields.END_DATE", "2032-01-02T00:04:25.987654321Z");+ mocks.nativeJobPrepare.mockRejectedValueOnce(new Error("native_job_timestamp_precision_microseconds"));+ button(root, "damengJobAdmin.previewSql").click();+ await flush();+ expect(root.textContent).toContain("nativeJobs.datePrecisionMicroseconds");+ expect(root.querySelector<HTMLInputElement>('[aria-label="nativeJobs.definitionFields.START_DATE"]')!.value).toBe("2032-01-01T23:54:25.123456789Z");+ expect(root.querySelector<HTMLInputElement>('[aria-label="nativeJobs.definitionFields.END_DATE"]')!.value).toBe("2032-01-02T00:04:25.987654321Z");+ mocks.nativeJobPrepare.mockResolvedValueOnce({ planId: "corrected-plan", operationId: "corrected-operation", scope, target: { ...fixture.ref, name: "Precision_job" }, steps: [{ id: "create", label: "create", sql: "reviewed create" }] });+ input(root, "nativeJobs.definitionFields.START_DATE", "2032-01-01T23:54:25.123456000Z");+ input(root, "nativeJobs.definitionFields.END_DATE", "2032-01-02T00:04:25.987654000Z");+ button(root, "damengJobAdmin.previewSql").click();+ await flush();+ expect(root.textContent).toContain("reviewed create");+ expect(mocks.nativeJobPrepare).toHaveBeenLastCalledWith(expect.objectContaining({ action: "create", definition: expect.objectContaining({ startDate: "2032-01-01T23:54:25.123456000Z", endDate: "2032-01-02T00:04:25.987654000Z" }) }));+ expect(mocks.nativeJobApply).not.toHaveBeenCalled();+ });++ it("keeps a failed refresh draft readable without reusing its previous baseline", async () => {+ const fixture = schedulerRefreshFixture();+ const root = await mount(fixture.config);+ button(root, "nativeJobs.editJob").click();+ await flush();+ button(root, "nativeJobs.advanced").click();+ await flush();+ input(root, "nativeJobs.definitionFields.MAX_FAILURES", "2");+ button(root, "common.cancel").click();+ await flush();+ mocks.nativeJobOpenContext.mockRejectedValueOnce(new Error("refresh_connection_failed"));+ button(root, "contextMenu.refreshChildren").click();+ await flush();+ expect(root.textContent).toContain("refresh_connection_failed");+ button(root, "nativeJobs.viewRetainedDraft").click();+ await flush();+ button(root, "nativeJobs.advanced").click();+ await flush();+ const retained = root.querySelector<HTMLInputElement>('[aria-label="nativeJobs.definitionFields.MAX_FAILURES"]')!;+ expect(retained.value).toBe("2");+ expect(retained.disabled).toBe(true);+ expect(mocks.nativeJobPrepare).not.toHaveBeenCalled();+ expect(mocks.nativeJobApply).not.toHaveBeenCalled();+ });++ it("discards an old detail read after installing a fresh context", async () => {+ const fixture = schedulerRefreshFixture();+ let finish!: (value: NativeJobDetails) => void;+ mocks.nativeJobRead.mockImplementationOnce(+ () =>+ new Promise((resolve) => {+ finish = resolve;+ }),+ );+ const root = await mount(fixture.config);+ button(root, "contextMenu.refreshChildren").click();+ await flush();+ const old = fixture.read(fixture.ref);+ old.snapshot.revision = "late-old-baseline";+ finish(old);+ await flush();+ button(root, "nativeJobs.editJob").click();+ await flush();+ button(root, "nativeJobs.advanced").click();+ await flush();+ input(root, "nativeJobs.definitionFields.MAX_FAILURES", "2");+ button(root, "damengJobAdmin.previewSql").click();+ await flush();+ expect(request).toMatchObject({ target: { scope: fixture.nextScope }, baseline: "fresh-baseline" });+ expect(mocks.nativeJobApply).not.toHaveBeenCalled();+ });++ it("loads a cold Generic OceanBase page only after mode discovery and rejects late context after withdrawal", async () => {+ const fixture = schedulerRefreshFixture();+ const config = reactive({ ...fixture.config, db_type: "jdbc" as const, database_info: { productName: "OceanBase" } });+ let finish!: (value: unknown) => void;+ mocks.nativeJobOpenContext.mockImplementationOnce(+ () =>+ new Promise((resolve) => {+ finish = resolve;+ }),+ );+ const root = await mount(config);+ expect(mocks.nativeJobOpenContext).not.toHaveBeenCalled();+ config.database_info = { productName: "OceanBase", compatibilityMode: "oracle" };+ await flush();+ expect(mocks.nativeJobOpenContext).toHaveBeenCalledTimes(1);+ config.database_info = { productName: "OceanBase", compatibilityMode: "mysql" };+ await flush();+ finish({ scope, engine: "oceanbase-oracle", sessionUser: "Owner", actualDatabase: "DB" });+ await flush();+ expect(root.textContent).toContain("nativeJobs.unsupported");+ expect(mocks.nativeJobList).not.toHaveBeenCalled();+ expect(mocks.executeQuery).not.toHaveBeenCalled();+ expect(mocks.nativeJobPrepare).not.toHaveBeenCalled();+ });++ it("reconnects with a fresh scope and baseline while retaining the same object's MAX_FAILURES draft", async () => {+ const fixture = schedulerRefreshFixture();+ const root = await mount(fixture.config);+ button(root, "nativeJobs.editJob").click();+ await flush();+ button(root, "nativeJobs.advanced").click();+ await flush();+ input(root, "nativeJobs.definitionFields.MAX_FAILURES", "2");+ mocks.nativeJobPrepare.mockRejectedValueOnce(new Error("native_job_context_changed"));+ button(root, "damengJobAdmin.previewSql").click();+ await flush();+ expect(root.querySelector<HTMLInputElement>('[aria-label="nativeJobs.definitionFields.MAX_FAILURES"]')!.value).toBe("2");+ button(root, "common.cancel").click();+ await flush();+ button(root, "contextMenu.refreshChildren").click();+ await flush();+ expect(mocks.nativeJobOpenContext).toHaveBeenCalledTimes(2);+ button(root, "nativeJobs.editJob").click();+ await flush();+ button(root, "nativeJobs.advanced").click();+ await flush();+ expect(root.querySelector<HTMLInputElement>('[aria-label="nativeJobs.definitionFields.MAX_FAILURES"]')!.value).toBe("2");+ button(root, "damengJobAdmin.previewSql").click();+ await flush();+ expect(request).toMatchObject({ action: "update", target: { ...fixture.ref, scope: fixture.nextScope }, baseline: "fresh-baseline", attributes: [{ name: "MAX_FAILURES", change: { kind: "set", value: 2 } }] });+ expect(mocks.nativeJobApply).not.toHaveBeenCalled();+ });++ it.each([{ replaced: true }, { unknownIdentity: true }, { sessionUser: "Other" }, { actualDatabase: "OTHER_DB" }])("retains an unbound read-only draft rather than applying it after identity changes: %j", async (options) => {+ const fixture = schedulerRefreshFixture(options);+ const root = await mount(fixture.config);+ button(root, "nativeJobs.editJob").click();+ await flush();+ button(root, "nativeJobs.advanced").click();+ await flush();+ input(root, "nativeJobs.definitionFields.MAX_FAILURES", "2");+ button(root, "common.cancel").click();+ await flush();+ button(root, "contextMenu.refreshChildren").click();+ await flush();+ expect(root.textContent).toContain("nativeJobs.detachedDraft");+ button(root, "nativeJobs.viewRetainedDraft").click();+ await flush();+ button(root, "nativeJobs.advanced").click();+ await flush();+ const retained = root.querySelector<HTMLInputElement>('[aria-label="nativeJobs.definitionFields.MAX_FAILURES"]')!;+ expect(retained.value).toBe("2");+ expect(retained.disabled).toBe(true);+ expect([...root.querySelectorAll("button")].some((item) => item.textContent?.trim() === "damengJobAdmin.previewSql")).toBe(false);+ expect(mocks.nativeJobPrepare).not.toHaveBeenCalled();+ expect(mocks.nativeJobApply).not.toHaveBeenCalled();+ });++ it("does not clear fresh same-scope drafts when a pre-refresh operation finishes late", async () => {+ const fixture = schedulerRefreshFixture({ sameScope: true });+ let finish!: (value: unknown) => void;+ mocks.nativeJobApply.mockImplementation(+ () =>+ new Promise((resolve) => {+ finish = resolve;+ }),+ );+ const root = await mount(fixture.config);+ button(root, "nativeJobs.editJob").click();+ await flush();+ button(root, "nativeJobs.advanced").click();+ await flush();+ input(root, "nativeJobs.definitionFields.MAX_FAILURES", "2");+ button(root, "damengJobAdmin.previewSql").click();+ await flush();+ button(root, "damengJobAdmin.applySql").click();+ await flush();+ const refresh = [...root.querySelectorAll("button")].find((element) => element.textContent?.trim() === "contextMenu.refreshChildren")!;+ refresh.click();+ await flush();+ finish({ operationId: "operation", target: fixture.ref, state: "finished", outcome: "verified", cancelRequested: false, steps: [{ id: "attributes", state: "applied", reason: null, vendorCode: null }], reason: null });+ await flush();+ expect(root.textContent).toContain("nativeJobs.previousContext");+ expect(mocks.nativeJobApply).toHaveBeenCalledTimes(1);+ button(root, "nativeJobs.editJob").click();+ await flush();+ button(root, "nativeJobs.advanced").click();+ await flush();+ expect(root.querySelector<HTMLInputElement>('[aria-label="nativeJobs.definitionFields.MAX_FAILURES"]')!.value).toBe("2");+ expect(mocks.toast).not.toHaveBeenCalledWith("damengJobAdmin.applySuccess", 2500);+ });+});++describe("existing Dameng Job management entry", () => {+ it.each(["partial", "unknown"] as const)("follows a verified renamed identity and retains remaining edits after %s", async (outcome) => {+ const renamed = { ...target, name: "Renamed Job" };+ let changed = false;+ mocks.nativeJobList.mockImplementation(async () => ({+ jobs: { status: "available", value: [{ ref: changed ? renamed : target, name: changed ? renamed.name : target.name, owner: "Owner", enabled: false, aliases: [] }] },+ source: { source: "SYSJOB.SYSJOBS", coverage: "database" },+ offset: 0,+ limit: 100,+ }));+ mocks.nativeJobRead.mockImplementation(async (requested) => {+ const value = structuredClone(details);+ value.snapshot.ref = requested;+ if (changed && requested.name === target.name) {+ value.snapshot.definition = { status: "empty" };+ value.nativeIdentity = { status: "empty" };+ } else if (changed && value.snapshot.definition.status === "available") value.snapshot.definition.value.NAME = renamed.name;+ return value;+ });+ mocks.nativeJobPrepare.mockImplementation(async (value: NativeJobRequest) => {+ request = value;+ if (value.action !== "configure-dameng") throw new Error("expected native edit");+ const rename = value.configuration.attributes?.some((attribute) => attribute.name === "NAME");+ return {+ planId: "rename-plan",+ operationId: "rename-operation",+ scope,+ target: value.target,+ steps: rename+ ? [+ { id: "rename", label: "rename", sql: "reviewed rename and commit" },+ { id: "enable", label: "enable", sql: "reviewed activation" },+ ]+ : [{ id: "enable", label: "enable", sql: "remaining activation" }],+ };+ });+ const observed = { DBX_JOB_ID: target.jobId, DBX_CREATED_AT: "creation", NAME: renamed.name };+ const result = {+ operationId: "rename-operation",+ target: outcome === "partial" ? renamed : target,+ observedIdentity: outcome === "partial" ? observed : undefined,+ state: "finished",+ outcome,+ cancelRequested: false,+ steps: [+ { id: "rename", state: outcome === "partial" ? "applied" : "unknown", reason: null, vendorCode: null },+ { id: "enable", state: "skipped", reason: null, vendorCode: null },+ ],+ reason: outcome === "unknown" ? "native_job_rename_commit_unknown" : "native_job_step_not_applied",+ };+ mocks.nativeJobApply.mockImplementation(async () => {+ changed = true;+ return result;+ });+ const root = await mount();+ button(root, "nativeJobs.editJob").click();+ await flush();+ input(root, "nativeJobs.fields.NAME", renamed.name);+ const enabled = root.querySelector<HTMLInputElement>('[aria-label="nativeJobs.fields.ENABLE"]')!;+ enabled.checked = true;+ enabled.dispatchEvent(new Event("change", { bubbles: true }));+ button(root, "damengJobAdmin.previewSql").click();+ await flush();+ button(root, "damengJobAdmin.applySql").click();+ await flush();+ if (outcome === "unknown") {+ expect(mocks.nativeJobRead).toHaveBeenLastCalledWith(target);+ mocks.nativeJobStatus.mockResolvedValue({ ...result, target: renamed, observedIdentity: observed });+ button(root, "nativeJobs.checkResult").click();+ await flush();+ expect(mocks.nativeJobStatus).toHaveBeenCalledExactlyOnceWith("rename-operation", true);+ }+ expect(mocks.nativeJobRead).toHaveBeenLastCalledWith(renamed);+ expect(root.textContent).toContain(renamed.name);+ button(root, "nativeJobs.correctDraft").click();+ await flush();+ expect(root.querySelector<HTMLInputElement>('[aria-label="nativeJobs.fields.NAME"]')!.value).toBe(renamed.name);+ expect(root.querySelector<HTMLInputElement>('[aria-label="nativeJobs.fields.ENABLE"]')!.checked).toBe(true);+ button(root, "damengJobAdmin.previewSql").click();+ await flush();+ expect(request).toMatchObject({ target: renamed, configuration: { attributes: [{ name: "ENABLE", change: { kind: "set", value: true } }] } });+ expect(mocks.nativeJobApply).toHaveBeenCalledTimes(1);+ });+ it("reports a committed custom Legacy interval without implying a pending business run", async () => {+ const legacy = { kind: "legacy" as const, scope, jobId: target.jobId };+ details.snapshot.ref = legacy;+ details.legacyDefinition = { status: "available", value: { DBX_JOB_ID: target.jobId, WHAT: "work();", NEXT_DATE: "native date", INTERVAL: "86400", INSTANCE: 1 } };+ mocks.nativeJobList.mockResolvedValue({ jobs: { status: "available", value: [{ ref: legacy, name: "Job_1", owner: "Owner", enabled: false, aliases: [] }] }, source: { source: "SYSJOB.SYSJOBS", coverage: "database" }, offset: 0, limit: 100 });+ mocks.nativeJobPrepare.mockImplementation(async (value: NativeJobRequest) => {+ request = value;+ return { planId: "interval-plan", operationId: "interval-operation", scope, target: legacy, steps: [{ id: "legacy_interval", label: "native_job_step_attribute", sql: "reviewed interval and commit" }] };+ });+ mocks.nativeJobApply.mockResolvedValue({+ operationId: "interval-operation",+ target: legacy,+ state: "finished",+ outcome: "accepted",+ cancelRequested: false,+ steps: [{ id: "legacy_interval", state: "accepted", reason: "native_job_legacy_interval_expression_not_readable", vendorCode: null }],+ reason: "native_job_legacy_interval_expression_not_readable",+ });+ const root = await mount(connection, { kind: "legacy", jobId: target.jobId });+ button(root, "nativeJobs.editJob").click();+ await flush();+ input(root, "nativeJobs.damengInterval", "SYSDATE + custom_next()");+ button(root, "damengJobAdmin.previewSql").click();+ await flush();+ button(root, "damengJobAdmin.applySql").click();+ await flush();+ expect(request).toMatchObject({ target: legacy, attributes: [{ name: "INTERVAL", change: { kind: "set", value: "SYSDATE + custom_next()" } }] });+ expect(root.textContent).toContain("nativeJobs.damengIntervalAccepted");+ expect(root.textContent).not.toContain("nativeJobs.outcomes.accepted");+ expect(mocks.nativeJobApply).toHaveBeenCalledTimes(1);+ expect(mocks.nativeJobStatus).not.toHaveBeenCalled();+ });+ it.each(["available", "denied"] as const)("preserves old DM Legacy child tabs and history clearing when DBMS_JOB metadata is %s", async (status) => {+ const legacy = { kind: "legacy" as const, scope, jobId: target.jobId };+ details.snapshot.ref = legacy;+ details.legacyDefinition = status === "available" ? { status, value: { WHAT: "work();", NEXT_DATE: "native date", INTERVAL: "86400" } } : { status, reason: "privilege_missing" };+ details.schedules = { status: "available", value: [{ ID: 12, JOBID: target.jobId, NAME: "old_schedule" }] };+ mocks.nativeJobList.mockResolvedValue({ jobs: { status: "available", value: [{ ref: legacy, name: "Job_1", owner: "Owner", enabled: false, aliases: [] }] }, source: { source: "SYSJOB.SYSJOBS", coverage: "database" }, offset: 0, limit: 100 });+ mocks.nativeJobPrepare.mockImplementation(async (value: NativeJobRequest) => {+ request = value;+ return { planId: "clear-history-plan", operationId: "clear-history-operation", scope, target: legacy, steps: [{ id: "clear_history", label: "clear_history", sql: "reviewed exact Legacy history clear" }] };+ });+ mocks.nativeJobApply.mockResolvedValue({ operationId: "clear-history-operation", target: legacy, state: "finished", outcome: "verified", cancelRequested: false, steps: [{ id: "clear_history", state: "applied", reason: null, vendorCode: null }], reason: null });+ const root = await mount(connection, { kind: "legacy", jobId: target.jobId });+ button(root, "damengJobAdmin.steps").click();+ await flush();+ expect(root.textContent).toContain("SELECT 1;");+ button(root, "damengJobAdmin.schedules").click();+ await flush();+ expect(root.textContent).toContain("old_schedule");+ expect(button(root, "damengJobAdmin.clearHistories").disabled).toBe(false);+ button(root, "damengJobAdmin.clearHistories").click();+ await flush();+ expect(request).toMatchObject({ action: "clear-history", target: legacy, baseline: "baseline" });+ expect(mocks.nativeJobApply).not.toHaveBeenCalled();+ expect(root.querySelector('[data-dialog="true"]')?.textContent).toContain("reviewed exact Legacy history clear");+ button(root, "damengJobAdmin.applySql").click();+ await flush();+ expect(mocks.nativeJobApply).toHaveBeenCalledExactlyOnceWith("clear-history-plan");+ expect(root.textContent).toContain("nativeJobs.outcomes.verified");+ });+ it.each(["available", "denied"] as const)("edits Legacy body and next date only when their independent definition is %s", async (status) => {+ const legacy = { kind: "legacy" as const, scope, jobId: target.jobId };+ details.snapshot.ref = legacy;+ details.legacyDefinition = status === "available" ? { status, value: { WHAT: "old();", NEXT_DATE: "2032-01-02 03:04:05", NEXT_SEC: "03:04:05", INTERVAL: "86400", INSTANCE: 1 } } : { status, reason: "privilege_missing" };+ mocks.nativeJobList.mockResolvedValue({ jobs: { status: "available", value: [{ ref: legacy, name: "Job_1", owner: "Owner", enabled: false, aliases: [] }] }, source: { source: "SYSJOB.SYSJOBS", coverage: "database" }, offset: 0, limit: 100 });+ mocks.nativeJobPrepare.mockImplementation(async (value: NativeJobRequest) => {+ request = value;+ return { planId: "legacy-edit-plan", operationId: "legacy-edit-operation", scope, target: legacy, steps: [{ id: "legacy_definition", label: "definition", sql: "reviewed Legacy definition change" }] };+ });+ mocks.nativeJobApply.mockResolvedValue({ operationId: "legacy-edit-operation", target: legacy, state: "finished", outcome: "verified", cancelRequested: false, steps: [{ id: "legacy_definition", state: "applied", reason: null, vendorCode: null }], reason: null });+ const root = await mount(connection, { kind: "legacy", jobId: target.jobId });+ button(root, "nativeJobs.editJob").click();+ await flush();+ const body = root.querySelector<HTMLTextAreaElement>('[aria-label="nativeJobs.definitionFields.WHAT"]')!;+ const date = root.querySelector<HTMLInputElement>('[aria-label="nativeJobs.definitionFields.NEXT_DATE"]')!;+ expect(body.disabled).toBe(status !== "available");+ expect(date.disabled).toBe(status !== "available");+ if (status === "available") {+ input(root, "nativeJobs.definitionFields.WHAT", "BEGIN work('O''ne'); END; ");+ input(root, "nativeJobs.definitionFields.NEXT_DATE", "2032-02-03 04:05:06");+ button(root, "damengJobAdmin.previewSql").click();+ await flush();+ expect(request).toMatchObject({+ target: legacy,+ baseline: "baseline",+ attributes: [+ { name: "WHAT", change: { kind: "set", value: "BEGIN work('O''ne'); END; " } },+ { name: "NEXT_DATE", change: { kind: "set", value: "2032-02-03 04:05:06" } },+ ],+ });+ expect(mocks.nativeJobApply).not.toHaveBeenCalled();+ button(root, "damengJobAdmin.applySql").click();+ await flush();+ expect(mocks.nativeJobApply).toHaveBeenCalledExactlyOnceWith("legacy-edit-plan");+ expect(root.textContent).toContain("nativeJobs.outcomes.verified");+ }+ });+ it.each(["available", "denied", "empty"] as const)("keeps native Legacy properties and controls when the independent DBMS_JOB partition is %s", async (status) => {+ const legacy = { kind: "legacy" as const, scope, jobId: target.jobId };+ details.snapshot.ref = legacy;+ details.legacyDefinition = status === "available" ? { status, value: { DBX_JOB_ID: target.jobId, WHAT: "begin\n work('多字节');\nend; ", NEXT_DATE: "native date text", INTERVAL: "86400", INSTANCE: 2 } } : status === "denied" ? { status, reason: "privilege_missing" } : { status };+ mocks.nativeJobList.mockResolvedValue({ jobs: { status: "available", value: [{ ref: legacy, name: "Job_1", owner: "Owner", enabled: false, aliases: [] }] }, source: { source: "SYSJOB.SYSJOBS", coverage: "database" }, offset: 0, limit: 100 });+ const root = await mount(connection, { kind: "legacy", jobId: target.jobId });+ button(root, "nativeJobs.attributes").click();+ await flush();+ expect(root.textContent).toContain("old description");+ expect(root.textContent).toContain("DBMS_JOB");+ expect(button(root, "damengJobAdmin.enable").disabled).toBe(false);+ expect(button(root, "damengJobAdmin.runAsync").disabled).toBe(false);+ if (status === "available") {+ expect(root.textContent).toContain("begin\n work('多字节');\nend; ");+ expect(root.textContent).toContain("native date text");+ expect(root.textContent).toContain("86400");+ button(root, "nativeJobs.editJob").click();+ await flush();+ expect(root.querySelector<HTMLTextAreaElement>('[aria-label="nativeJobs.definitionFields.WHAT"]')!.disabled).toBe(false);+ expect(root.querySelector<HTMLInputElement>('[aria-label="nativeJobs.definitionFields.NEXT_DATE"]')!.disabled).toBe(true);+ expect(root.querySelector<HTMLInputElement>('[aria-label="nativeJobs.definitionFields.INSTANCE"]')!.disabled).toBe(true);+ input(root, "nativeJobs.damengInterval", "900719925474099312345");+ button(root, "damengJobAdmin.previewSql").click();+ await flush();+ expect(request).toMatchObject({ target: legacy, attributes: [{ name: "INTERVAL", change: { kind: "set", value: "900719925474099312345" } }] });+ expect(details.snapshot.definition.status === "available" && details.snapshot.definition.value).not.toHaveProperty("WHAT");+ } else {+ expect(root.textContent).toContain(status === "empty" ? "damengJobAdmin.emptyDetails" : "nativeJobs.partitionUnavailable");+ }+ expect(mocks.nativeJobApply).not.toHaveBeenCalled();+ });+ it("selects exact Program and Schedule references from the shared creation editor without changing retained inline values", async () => {+ mocks.nativeJobOpenContext.mockResolvedValue({ scope, engine: "oracle", sessionUser: "Owner", actualDatabase: "DB", productVersion: "19" });+ mocks.nativeJobList.mockResolvedValue({ jobs: { status: "empty" }, source: { source: "SYS.DBA_SCHEDULER_JOBS", coverage: "database" }, offset: 0, limit: 100 });+ mocks.nativeJobReferences.mockImplementation(async ({ kind }) => ({+ objects: { status: "available", value: [{ DBX_OWNER: 'Own.er"One', DBX_NAME: kind === "program" ? "Pro,g.One" : "Sch.ed,One" }] },+ source: { source: "SYS.ALL_SCHEDULER_PROGRAMS", coverage: "accessible" },+ offset: 0,+ limit: 100,+ }));+ const root = await mount({ ...connection, db_type: "oracle" });+ button(root, "damengJobAdmin.newJob").click();+ await flush();+ input(root, "damengJobAdmin.jobName", "New_scheduler");+ button(root, "nativeJobs.chooseReference").click();+ await flush();+ root.querySelector<HTMLButtonElement>("[data-native-reference]")!.click();+ await flush();+ expect(root.querySelector<HTMLInputElement>('[aria-label="nativeJobs.definitionFields.PROGRAM_OWNER"]')!.value).toBe('Own.er"One');+ expect(root.querySelector<HTMLInputElement>('[aria-label="nativeJobs.definitionFields.PROGRAM_NAME"]')!.value).toBe("Pro,g.One");+ expect(root.querySelector<HTMLInputElement>('[aria-label="nativeJobs.definitionFields.JOB_ACTION"]')!.value).toBe("BEGIN NULL; END;");+ expect(root.querySelector<HTMLInputElement>('[aria-label="nativeJobs.definitionFields.JOB_ACTION"]')!.disabled).toBe(true);+ input(root, "nativeJobs.definitionFields.PROGRAM_NAME", "");+ await flush();+ expect(root.querySelector<HTMLInputElement>('[aria-label="nativeJobs.definitionFields.JOB_ACTION"]')!.disabled).toBe(false);+ expect(root.querySelector<HTMLInputElement>('[aria-label="nativeJobs.definitionFields.JOB_ACTION"]')!.value).toBe("BEGIN NULL; END;");+ input(root, "nativeJobs.definitionFields.PROGRAM_NAME", "Pro,g.One");+ await flush();+ const choices = [...root.querySelectorAll<HTMLButtonElement>("button")].filter((element) => element.textContent === "nativeJobs.chooseReference");+ choices.at(-1)!.click();+ await flush();+ root.querySelector<HTMLButtonElement>("[data-native-reference]")!.click();+ await flush();+ expect(root.querySelector<HTMLInputElement>('[aria-label="nativeJobs.definitionFields.SCHEDULE_NAME"]')!.value).toBe("Sch.ed,One");+ button(root, "damengJobAdmin.previewSql").click();+ await flush();+ expect(request).toMatchObject({ action: "create", scope, definition: { kind: "scheduler", program: { owner: 'Own.er"One', name: "Pro,g.One" }, schedule: { owner: 'Own.er"One', name: "Sch.ed,One" } } });+ expect(mocks.nativeJobReferences.mock.calls.filter(([value]) => value.name === undefined).map(([value]) => value.kind)).toEqual(["program", "schedule"]);+ expect(mocks.executeMulti).not.toHaveBeenCalled();+ });+ it("selects a Chain and external references without splitting names on dots or commas", async () => {+ mocks.nativeJobOpenContext.mockResolvedValue({ scope, engine: "oracle", sessionUser: "Owner", actualDatabase: "DB", productVersion: "19" });+ mocks.nativeJobList.mockResolvedValue({ jobs: { status: "empty" }, source: { source: "SYS.DBA_SCHEDULER_JOBS", coverage: "database" }, offset: 0, limit: 100 });+ mocks.nativeJobReferences.mockImplementation(async ({ kind }) => ({+ objects: { status: "available", value: [{ DBX_OWNER: 'Own.er"One', DBX_NAME: `${kind},One` }] },+ source: { source: "catalog", coverage: "accessible" },+ offset: 0,+ limit: 100,+ }));+ const root = await mount({ ...connection, db_type: "oracle" });+ button(root, "damengJobAdmin.newJob").click();+ await flush();+ input(root, "damengJobAdmin.jobName", "Reference_job");+ const jobType = root.querySelector<HTMLSelectElement>('[aria-label="nativeJobs.definitionFields.JOB_TYPE"]')!;+ jobType.value = "CHAIN";+ jobType.dispatchEvent(new Event("change", { bubbles: true }));+ await flush();+ root.querySelector('[aria-label="nativeJobs.definitionFields.JOB_ACTION"]')!.parentElement!.querySelector<HTMLButtonElement>("button")!.click();+ await flush();+ root.querySelector<HTMLButtonElement>("[data-native-reference]")!.click();+ await flush();+ button(root, "nativeJobs.advanced").click();+ await flush();+ for (const field of ["CREDENTIAL_NAME", "DESTINATION_NAME"]) {+ const input = root.querySelector<HTMLInputElement>(`[aria-label="nativeJobs.definitionFields.${field}"]`)!;+ [...input.parentElement!.querySelectorAll<HTMLButtonElement>("button")].at(-1)!.click();+ await flush();+ root.querySelector<HTMLButtonElement>("[data-native-reference]")!.click();+ await flush();+ }+ button(root, "damengJobAdmin.previewSql").click();+ await flush();+ expect(request).toMatchObject({+ definition: {+ jobType: "CHAIN",+ jobAction: '"Own.er""One"."chain,One"',+ credentialName: '"Own.er""One"."credential,One"',+ destinationName: '"Own.er""One"."destination,One"',+ },+ });+ expect(mocks.nativeJobReferences.mock.calls.map(([value]) => value.kind)).toEqual(["chain", "credential", "destination"]);+ });+ it("previews only activation when acknowledged Scheduler creation completed every earlier step", async () => {+ const created = { kind: "scheduler" as const, scope, owner: "Owner", name: "New_scheduler" };+ mocks.nativeJobOpenContext.mockResolvedValue({ scope, engine: "oracle", sessionUser: "Owner", actualDatabase: "DB", productVersion: "19" });+ mocks.nativeJobList.mockResolvedValue({ jobs: { status: "empty" }, source: { source: "SYS.DBA_SCHEDULER_JOBS", coverage: "database" }, offset: 0, limit: 100 });+ mocks.nativeJobRead.mockResolvedValue({ ...details, snapshot: { ...details.snapshot, ref: created, revision: "created", definition: { status: "available", value: { JOB_TYPE: "PLSQL_BLOCK", JOB_ACTION: "BEGIN NULL; END;", ENABLED: "FALSE", NUMBER_OF_ARGUMENTS: 0, AUTO_DROP: true } } } });+ mocks.nativeJobApply.mockResolvedValue({+ operationId: "operation",+ target: created,+ state: "finished",+ outcome: "partial",+ cancelRequested: false,+ steps: [+ { id: "create", state: "applied", reason: null, vendorCode: null },+ { id: "enable", state: "failed", reason: "native_failure", vendorCode: -1 },+ ],+ reason: "native_failure",+ });+ const root = await mount({ ...connection, db_type: "oracle" });+ button(root, "damengJobAdmin.newJob").click();+ await flush();+ input(root, "damengJobAdmin.jobName", "New_scheduler");+ const enabled = root.querySelector<HTMLInputElement>('[aria-label="nativeJobs.definitionFields.ENABLED"]')!;+ enabled.checked = true;+ enabled.dispatchEvent(new Event("change", { bubbles: true }));+ button(root, "damengJobAdmin.previewSql").click();+ await flush();+ button(root, "damengJobAdmin.applySql").click();+ await flush();+ button(root, "nativeJobs.correctDraft").click();+ await flush();+ expect(request).toEqual({ action: "enable", target: created, baseline: "created" });+ expect(mocks.nativeJobApply).toHaveBeenCalledTimes(1);+ });+ it("creates inline Scheduler arguments from the actual editor and keeps their count in the definition", async () => {+ mocks.nativeJobOpenContext.mockResolvedValue({ scope, engine: "oracle", sessionUser: "Owner", actualDatabase: "DB", productVersion: "19" });+ mocks.nativeJobList.mockResolvedValue({ jobs: { status: "empty" }, source: { source: "SYS.DBA_SCHEDULER_JOBS", coverage: "database" }, offset: 0, limit: 100 });+ const root = await mount({ ...connection, db_type: "oracle" });+ button(root, "damengJobAdmin.newJob").click();+ await flush();+ input(root, "damengJobAdmin.jobName", "New_scheduler");+ input(root, "nativeJobs.definitionFields.JOB_ACTION", "work_proc");+ const jobType = root.querySelector<HTMLSelectElement>('[aria-label="nativeJobs.definitionFields.JOB_TYPE"]')!;+ jobType.value = "STORED_PROCEDURE";+ jobType.dispatchEvent(new Event("change", { bubbles: true }));+ button(root, "nativeJobs.arguments").click();+ await flush();+ button(root, "nativeJobs.addArgument").click();+ await flush();+ const state = root.querySelector<HTMLSelectElement>('[aria-label="nativeJobs.argumentState"]')!;+ state.value = "value";+ state.dispatchEvent(new Event("change", { bubbles: true }));+ await flush();+ input(root, "nativeJobs.argumentValue", "a,b'c");+ button(root, "nativeJobs.definition").click();+ await flush();+ expect(root.querySelector<HTMLInputElement>('[aria-label="nativeJobs.definitionFields.NUMBER_OF_ARGUMENTS"]')?.value).toBe("1");+ expect(root.querySelector<HTMLTextAreaElement>('[aria-label="nativeJobs.definitionFields.JOB_ACTION"]')?.value).toBe("work_proc");+ button(root, "damengJobAdmin.previewSql").click();+ await flush();+ expect(request).toMatchObject({+ action: "create",+ scope,+ definition: { kind: "scheduler", owner: "Owner", name: "New_scheduler", jobType: "STORED_PROCEDURE", jobAction: "work_proc", numberOfArguments: 1, arguments: [{ position: 1, dataType: "VARCHAR2", value: { kind: "value", value: "a,b'c" } }] },+ });+ expect(mocks.executeMulti).not.toHaveBeenCalled();+ });+ it("loads Program defaults in the creation form, ignores stale metadata and only submits the chosen override", async () => {+ mocks.nativeJobOpenContext.mockResolvedValue({ scope, engine: "oracle", sessionUser: "Owner", actualDatabase: "DB", productVersion: "19" });+ mocks.nativeJobList.mockResolvedValue({ jobs: { status: "empty" }, source: { source: "SYS.DBA_SCHEDULER_JOBS", coverage: "database" }, offset: 0, limit: 100 });+ const old: Array<(value: unknown) => void> = [];+ const catalog = (kind: string, name: string) => ({+ objects: {+ status: "available",+ value:+ kind === "program"+ ? [{ DBX_OWNER: "Owner", DBX_NAME: name, PROGRAM_TYPE: "STORED_PROCEDURE", PROGRAM_ACTION: "program_procedure", NUMBER_OF_ARGUMENTS: 2 }]+ : [+ { DBX_OWNER: "Owner", DBX_NAME: name, ARGUMENT_POSITION: 1, ARGUMENT_NAME: "TEXT", ARGUMENT_TYPE: "VARCHAR2", DEFAULT_VALUE: `${name} native default`, OUT_ARGUMENT: "FALSE" },+ { DBX_OWNER: "Owner", DBX_NAME: name, ARGUMENT_POSITION: 2, ARGUMENT_NAME: "OPTIONAL", ARGUMENT_TYPE: "NUMBER", DEFAULT_VALUE: null, OUT_ARGUMENT: "FALSE" },+ ],+ },+ source: { source: "SYS.ALL_SCHEDULER_PROGRAMS", coverage: "accessible" },+ offset: 0,+ limit: 100,+ });+ mocks.nativeJobReferences.mockImplementation(({ kind, name }) =>+ name === "Old.Program"+ ? new Promise((resolve) => {+ old.push((value) => resolve(value));+ })+ : Promise.resolve(catalog(kind, name)),+ );+ const root = await mount({ ...connection, db_type: "oracle" });+ button(root, "damengJobAdmin.newJob").click();+ await flush();+ input(root, "damengJobAdmin.jobName", "Program_job");+ input(root, "nativeJobs.definitionFields.PROGRAM_NAME", "Old.Program");+ await flush();+ input(root, "nativeJobs.definitionFields.PROGRAM_NAME", "New.Program");+ await flush();+ old.forEach((resolve, index) => resolve(catalog(index === 0 ? "program" : "program-arguments", "Old.Program")));+ await flush();+ button(root, "nativeJobs.arguments").click();+ await flush();+ const defaults = [...root.querySelectorAll<HTMLTextAreaElement>('[aria-label="nativeJobs.programDefault"]')];+ expect(defaults.map((field) => field.value)).toContain("New.Program native default");+ expect(defaults.map((field) => field.value)).not.toContain("Old.Program native default");+ expect(defaults.every((field) => field.readOnly)).toBe(true);+ expect(root.textContent).toContain("nativeJobs.programDefaultUnknown");+ const states = root.querySelectorAll<HTMLSelectElement>('[aria-label="nativeJobs.argumentState"]');+ expect(states).toHaveLength(2);+ expect(states[0]!.value).toBe("inherit");+ states[0]!.value = "value";+ states[0]!.dispatchEvent(new Event("change", { bubbles: true }));+ await flush();+ input(root, "nativeJobs.argumentValue", "chosen override");+ button(root, "damengJobAdmin.previewSql").click();+ await flush();+ expect(request).toMatchObject({ action: "create", definition: { program: { owner: "Owner", name: "New.Program" }, arguments: [{ position: 1, dataType: "VARCHAR2", value: { kind: "value", value: "chosen override" } }] } });+ });+ it("shows Program defaults separately and preserves unmodified overrides and database-supplied arguments", async () => {+ const ref = { kind: "scheduler" as const, scope, owner: "Owner", name: "Program_job" };+ mocks.nativeJobOpenContext.mockResolvedValue({ scope, engine: "oracle", sessionUser: "Owner", actualDatabase: "DB", productVersion: "19" });+ mocks.nativeJobList.mockResolvedValue({+ jobs: { status: "available", value: [{ ref, name: ref.name, owner: ref.owner, enabled: false, jobType: "STORED_PROCEDURE", state: "DISABLED", nextRun: null, comments: null, aliases: [], logUser: null, privUser: null, schemaUser: null }] },+ source: { source: "SYS.DBA_SCHEDULER_JOBS", coverage: "database" },+ offset: 0,+ limit: 100,+ });+ details.snapshot.ref = ref;+ details.snapshot.definition = { status: "available", value: { PROGRAM_OWNER: "Shared.Owner", PROGRAM_NAME: "Program,One", NUMBER_OF_ARGUMENTS: null, JOB_TYPE: null, JOB_ACTION: null, COMMENTS: "unchanged" } };+ details.program = { status: "available", value: { PROGRAM_TYPE: "STORED_PROCEDURE", PROGRAM_ACTION: "original_program_procedure", NUMBER_OF_ARGUMENTS: 3 } };+ details.snapshot.arguments = {+ status: "available",+ value: [+ { position: 1, dataType: "VARCHAR2", value: { kind: "value", value: "keep override" }, defaultValue: { status: "available", value: { kind: "value", value: "original default" } }, editable: true },+ { position: 2, dataType: "VARCHAR2", value: { kind: "inherit" }, defaultValue: { status: "unknown", reason: "native_job_program_default_ambiguous" }, editable: true },+ { position: 3, dataType: "VARCHAR2", value: { kind: "inherit" }, metadataAttribute: "JOB_NAME", editable: false },+ ],+ };+ const root = await mount({ ...connection, db_type: "oracle" });+ button(root, "nativeJobs.editJob").click();+ await flush();+ expect(root.querySelector<HTMLInputElement>('[aria-label="nativeJobs.definitionFields.NUMBER_OF_ARGUMENTS"]')!.disabled).toBe(true);+ expect(root.textContent).toContain("original_program_procedure");+ button(root, "nativeJobs.arguments").click();+ await flush();+ const originalDefault = root.querySelector<HTMLTextAreaElement>('[aria-label="nativeJobs.programDefault"]')!;+ expect(originalDefault.value).toBe("original default");+ expect(originalDefault.readOnly).toBe(true);+ expect(root.textContent).toContain("nativeJobs.programDefaultUnknown");+ expect(root.textContent).toContain("nativeJobs.metadataArgument");+ const states = root.querySelectorAll<HTMLSelectElement>('[aria-label="nativeJobs.argumentState"]');+ expect(states[2]!.disabled).toBe(true);+ states[1]!.value = "value";+ states[1]!.dispatchEvent(new Event("change", { bubbles: true }));+ await flush();+ const fields = root.querySelectorAll<HTMLTextAreaElement>('[aria-label="nativeJobs.argumentValue"]');+ expect(fields[0]!.value).toBe("keep override");+ fields[1]!.value = "only changed argument";+ fields[1]!.dispatchEvent(new Event("input", { bubbles: true }));+ button(root, "damengJobAdmin.previewSql").click();+ await flush();+ expect(request).toMatchObject({ action: "update", target: ref, attributes: [], arguments: [{ position: 2, value: { kind: "value", value: "only changed argument" } }] });+ expect(details.snapshot.arguments.value[0]!.value).toEqual({ kind: "value", value: "keep override" });+ });+ it("uses the existing edit picker for a new Program without migrating old-position or opaque overrides", async () => {+ const scheduler = { kind: "scheduler" as const, scope, owner: "Owner", name: "Program_job" };+ mocks.nativeJobOpenContext.mockResolvedValue({ scope, engine: "oracle", sessionUser: "Owner", actualDatabase: "DB", productVersion: "19" });+ mocks.nativeJobList.mockResolvedValue({+ jobs: { status: "available", value: [{ ref: scheduler, name: scheduler.name, owner: "Owner", enabled: true, jobType: "STORED_PROCEDURE", state: "SCHEDULED", nextRun: null, comments: null, aliases: [], logUser: null, privUser: null, schemaUser: null }] },+ source: { source: "SYS.DBA_SCHEDULER_JOBS", coverage: "database" },+ offset: 0,+ limit: 100,+ });+ details.snapshot.ref = scheduler;+ details.snapshot.definition = { status: "available", value: { ENABLED: true, PROGRAM_OWNER: "Owner", PROGRAM_NAME: "Old.Program", JOB_TYPE: null, JOB_ACTION: null, NUMBER_OF_ARGUMENTS: null, SCHEDULE_OWNER: null, SCHEDULE_NAME: null } };+ details.snapshot.arguments = {+ status: "available",+ value: [+ { position: 1, dataType: "VARCHAR2", value: { kind: "value", value: "old private override" }, editable: true },+ { position: 2, dataType: "OBJECT", value: { kind: "opaque", value: { object: "old" } }, editable: false },+ ],+ };+ const program = { owner: 'Other.Owner"', name: "New,Program.One" };+ mocks.nativeJobReferences.mockImplementation(async ({ kind, schema, name }) => ({+ objects: {+ status: "available",+ value:+ kind === "program-arguments"+ ? [+ { DBX_OWNER: schema, DBX_NAME: name, ARGUMENT_POSITION: 1, ARGUMENT_TYPE: "VARCHAR2", DEFAULT_VALUE: "target default", OUT_ARGUMENT: false },+ { DBX_OWNER: schema, DBX_NAME: name, ARGUMENT_POSITION: 2, ARGUMENT_TYPE: "NUMBER", DEFAULT_VALUE: null, OUT_ARGUMENT: false },+ ]+ : [{ DBX_OWNER: program.owner, DBX_NAME: program.name, PROGRAM_TYPE: "STORED_PROCEDURE", PROGRAM_ACTION: "target_proc", NUMBER_OF_ARGUMENTS: 2 }],+ },+ source: { source: "SYS.ALL_SCHEDULER_PROGRAMS", coverage: "accessible" },+ offset: 0,+ limit: 100,+ }));+ const root = await mount({ ...connection, db_type: "oracle" });+ button(root, "nativeJobs.editJob").click();+ await flush();+ expect(root.querySelector<HTMLInputElement>('[aria-label="nativeJobs.definitionFields.PROGRAM_NAME"]')!.disabled).toBe(false);+ [...root.querySelector('[aria-label="nativeJobs.definitionFields.PROGRAM_NAME"]')!.parentElement!.querySelectorAll<HTMLButtonElement>("button")].at(-1)!.click();+ await flush();+ root.querySelector<HTMLButtonElement>("[data-native-reference]")!.click();+ await flush();+ button(root, "nativeJobs.arguments").click();+ await flush();+ expect([...root.querySelectorAll<HTMLTextAreaElement>('[aria-label="nativeJobs.programDefault"]')].map((field) => field.value)).toContain("target default");+ expect([...root.querySelectorAll<HTMLTextAreaElement>('[aria-label="nativeJobs.argumentValue"]')].map((field) => field.value)).not.toContain("old private override");+ const state = root.querySelector<HTMLSelectElement>('[aria-label="nativeJobs.argumentState"]')!;+ expect(state.value).toBe("inherit");+ state.value = "value";+ state.dispatchEvent(new Event("change", { bubbles: true }));+ await flush();+ input(root, "nativeJobs.argumentValue", "new target value");+ button(root, "damengJobAdmin.previewSql").click();+ await flush();+ expect(request).toMatchObject({+ action: "update",+ target: scheduler,+ finalEnabled: true,+ attributes: [{ name: "PROGRAM_NAME", change: { kind: "set", value: program } }],+ arguments: [],+ argumentTarget: {+ program,+ arguments: [+ { position: 1, dataType: "VARCHAR2", value: { kind: "value", value: "new target value" } },+ { position: 2, dataType: "NUMBER", value: { kind: "inherit" } },+ ],+ },+ });+ expect(details.snapshot.arguments.value[0]!.value).toEqual({ kind: "value", value: "old private override" });+ });+ it("selects a typed Window group and captures a disabled final state without writing ENABLED as an attribute", async () => {+ const scheduler = { kind: "scheduler" as const, scope, owner: "Owner", name: "Calendar_job" };+ mocks.nativeJobOpenContext.mockResolvedValue({ scope, engine: "oracle", sessionUser: "Owner", actualDatabase: "DB", productVersion: "19" });+ mocks.nativeJobList.mockResolvedValue({+ jobs: { status: "available", value: [{ ref: scheduler, name: scheduler.name, owner: "Owner", enabled: true, jobType: "PLSQL_BLOCK", state: "SCHEDULED", nextRun: null, comments: null, aliases: [], logUser: null, privUser: null, schemaUser: null }] },+ source: { source: "SYS.DBA_SCHEDULER_JOBS", coverage: "database" },+ offset: 0,+ limit: 100,+ });+ details.snapshot.ref = scheduler;+ details.snapshot.definition = {+ status: "available",+ value: { ENABLED: true, PROGRAM_OWNER: null, PROGRAM_NAME: null, JOB_TYPE: "PLSQL_BLOCK", JOB_ACTION: "BEGIN NULL; END;", NUMBER_OF_ARGUMENTS: 0, SCHEDULE_OWNER: null, SCHEDULE_NAME: null, SCHEDULE_TYPE: "CALENDAR", START_DATE: "2030-01-01T00:00:00+08:00", REPEAT_INTERVAL: "FREQ=DAILY" },+ };+ mocks.nativeJobReferences.mockResolvedValue({ objects: { status: "available", value: [{ DBX_OWNER: "SYS", DBX_NAME: "Night,Group.One", GROUP_TYPE: "WINDOW" }] }, source: { source: "SYS.ALL_SCHEDULER_GROUPS", coverage: "accessible" }, offset: 0, limit: 100 });+ const root = await mount({ ...connection, db_type: "oracle" });+ button(root, "nativeJobs.editJob").click();+ await flush();+ const kind = root.querySelector<HTMLSelectElement>('select[aria-label="nativeJobs.chooseReference"]')!;+ kind.value = "window-group";+ kind.dispatchEvent(new Event("change", { bubbles: true }));+ const enabled = root.querySelector<HTMLInputElement>('[aria-label="nativeJobs.definitionFields.ENABLED"]')!;+ enabled.checked = false;+ enabled.dispatchEvent(new Event("change", { bubbles: true }));+ await flush();+ [...root.querySelector('[aria-label="nativeJobs.definitionFields.SCHEDULE_NAME"]')!.parentElement!.querySelectorAll<HTMLButtonElement>("button")].at(-1)!.click();+ await flush();+ expect(mocks.nativeJobReferences).toHaveBeenLastCalledWith(expect.objectContaining({ kind: "window-group" }));+ root.querySelector<HTMLButtonElement>("[data-native-reference]")!.click();+ await flush();+ expect(root.textContent).toContain("nativeJobs.inactiveInlineDraft");+ expect(root.querySelector<HTMLInputElement>('[aria-label="nativeJobs.definitionFields.START_DATE"]')!.disabled).toBe(true);+ button(root, "damengJobAdmin.previewSql").click();+ await flush();+ expect(request).toMatchObject({ action: "update", finalEnabled: false, attributes: [{ name: "SCHEDULE_NAME", change: { kind: "set", value: { owner: "SYS", name: "Night,Group.One", kind: "window-group" } } }], arguments: [] });+ expect(request).not.toHaveProperty("argumentTarget");+ });+ it("edits a queue event in the original dialog without copying inactive calendar fields or dispatching apply", async () => {+ const scheduler = { kind: "scheduler" as const, scope, owner: "Owner", name: "Event_job" };+ mocks.nativeJobOpenContext.mockResolvedValue({ scope, engine: "oracle", sessionUser: "Owner", actualDatabase: "DB", productVersion: "19" });+ mocks.nativeJobList.mockResolvedValue({+ jobs: { status: "available", value: [{ ref: scheduler, name: scheduler.name, owner: "Owner", enabled: true, jobType: "PLSQL_BLOCK", state: "SCHEDULED", nextRun: null, comments: null, aliases: [], logUser: null, privUser: null, schemaUser: null }] },+ source: { source: "SYS.DBA_SCHEDULER_JOBS", coverage: "database" },+ offset: 0,+ limit: 100,+ });+ details.snapshot.ref = scheduler;+ details.snapshot.definition = {+ status: "available",+ value: {+ ENABLED: true,+ PROGRAM_OWNER: null,+ PROGRAM_NAME: null,+ JOB_TYPE: "PLSQL_BLOCK",+ JOB_ACTION: "BEGIN NULL; END;",+ NUMBER_OF_ARGUMENTS: 0,+ SCHEDULE_OWNER: "Calendar.Owner",+ SCHEDULE_NAME: "Named",+ SCHEDULE_TYPE: "NAMED",+ START_DATE: null,+ END_DATE: null,+ REPEAT_INTERVAL: null,+ EVENT_CONDITION: null,+ EVENT_QUEUE_OWNER: null,+ EVENT_QUEUE_NAME: null,+ FILE_WATCHER_OWNER: null,+ FILE_WATCHER_NAME: null,+ },+ };+ const root = await mount({ ...connection, db_type: "oracle" });+ button(root, "nativeJobs.editJob").click();+ await flush();+ const mode = root.querySelector<HTMLSelectElement>('[aria-label="nativeJobs.scheduleMode"]')!;+ mode.value = "queue";+ mode.dispatchEvent(new Event("change", { bubbles: true }));+ await flush();+ input(root, "nativeJobs.eventQueueOwner", "Queue.Owner");+ input(root, "nativeJobs.eventQueueName", 'Q,One"');+ input(root, "nativeJobs.eventQueueAgent", "Agent.Exact");+ input(root, "nativeJobs.eventCondition", "tab.user_data.ready = 'Y'");+ button(root, "damengJobAdmin.previewSql").click();+ await flush();+ expect(request).toMatchObject({+ finalEnabled: true,+ attributes: [+ { name: "SCHEDULE_NAME", change: { kind: "clear" } },+ { name: "EVENT_SPEC", change: { kind: "set", value: { condition: "tab.user_data.ready = 'Y'", source: { kind: "queue", owner: "Queue.Owner", name: 'Q,One"', agent: "Agent.Exact" } } } },+ ],+ });+ expect(mocks.nativeJobApply).not.toHaveBeenCalled();+ });+ it("keeps host and named destination drafts separate and previews only the selected native slot", async () => {+ const scheduler = { kind: "scheduler" as const, scope, owner: "Owner", name: "Host_job" };+ mocks.nativeJobOpenContext.mockResolvedValue({ scope, engine: "oracle", sessionUser: "Owner", actualDatabase: "DB", productVersion: "19" });+ mocks.nativeJobList.mockResolvedValue({+ jobs: { status: "available", value: [{ ref: scheduler, name: scheduler.name, owner: "Owner", enabled: true, jobType: "STORED_PROCEDURE", state: "SCHEDULED", nextRun: null, comments: null, aliases: [], logUser: null, privUser: null, schemaUser: null }] },+ source: { source: "SYS.DBA_SCHEDULER_JOBS", coverage: "database" },+ offset: 0,+ limit: 100,+ });+ details.snapshot.ref = scheduler;+ details.snapshot.definition = { status: "available", value: { ENABLED: true, PROGRAM_OWNER: null, PROGRAM_NAME: null, JOB_TYPE: "STORED_PROCEDURE", JOB_ACTION: "proc", NUMBER_OF_ARGUMENTS: 0, DESTINATION_OWNER: null, DESTINATION: "host.with.dots:1500" } };+ mocks.nativeJobReferences.mockResolvedValue({ objects: { status: "available", value: [{ DBX_OWNER: "Dest.Owner", DBX_NAME: "Named,Dest" }] }, source: { source: "SYS.ALL_SCHEDULER_DB_DESTS", coverage: "accessible" }, offset: 0, limit: 100 });+ const root = await mount({ ...connection, db_type: "oracle" });+ button(root, "nativeJobs.editJob").click();+ await flush();+ button(root, "nativeJobs.advanced").click();+ await flush();+ expect(root.querySelector<HTMLInputElement>('[aria-label="nativeJobs.definitionFields.DESTINATION"]')!.value).toBe("host.with.dots:1500");+ expect(root.querySelector('[aria-label="nativeJobs.definitionFields.DESTINATION_NAME"]')).toBeNull();+ input(root, "nativeJobs.definitionFields.DESTINATION", "Retained.Host:1501");+ const mode = root.querySelector<HTMLSelectElement>('[aria-label="nativeJobs.destinationMode"]')!;+ mode.value = "named";+ mode.dispatchEvent(new Event("change", { bubbles: true }));+ await flush();+ const field = root.querySelector<HTMLInputElement>('[aria-label="nativeJobs.definitionFields.DESTINATION_NAME"]')!.parentElement!;+ [...field.querySelectorAll<HTMLButtonElement>("button")].find((button) => button.textContent?.includes("nativeJobs.chooseReference") && !button.textContent?.includes("destinationGroup"))!.click();+ await flush();+ root.querySelector<HTMLButtonElement>("[data-native-reference]")!.click();+ await flush();+ mode.value = "legacy";+ mode.dispatchEvent(new Event("change", { bubbles: true }));+ await flush();+ expect(root.querySelector<HTMLInputElement>('[aria-label="nativeJobs.definitionFields.DESTINATION"]')!.value).toBe("Retained.Host:1501");+ mode.value = "named";+ mode.dispatchEvent(new Event("change", { bubbles: true }));+ await flush();+ button(root, "damengJobAdmin.previewSql").click();+ await flush();+ expect(request).toMatchObject({ action: "update", attributes: [{ name: "DESTINATION_NAME", change: { kind: "set", value: { owner: "Dest.Owner", name: "Named,Dest" } } }] });+ expect(request?.action === "update" && request.attributes.some(({ name }) => name === "DESTINATION")).toBe(false);+ expect(mocks.nativeJobApply).not.toHaveBeenCalled();+ });+ it.each(["set", "clear"] as const)("previews a raw host %s through DESTINATION without applying it", async (change) => {+ const scheduler = { kind: "scheduler" as const, scope, owner: "Owner", name: "Host_job" };+ mocks.nativeJobOpenContext.mockResolvedValue({ scope, engine: "oracle", sessionUser: "Owner", productVersion: "19" });+ mocks.nativeJobList.mockResolvedValue({ jobs: { status: "available", value: [{ ref: scheduler, name: scheduler.name, owner: "Owner", enabled: true, aliases: [] }] }, source: { coverage: "database" }, offset: 0, limit: 100 });+ details.snapshot.ref = scheduler;+ details.snapshot.definition = { status: "available", value: { ENABLED: true, PROGRAM_OWNER: null, PROGRAM_NAME: null, JOB_TYPE: "STORED_PROCEDURE", JOB_ACTION: "proc", NUMBER_OF_ARGUMENTS: 0, DESTINATION_OWNER: null, DESTINATION: "host.with.dots:1500" } };+ const root = await mount({ ...connection, db_type: "oracle" });+ button(root, "nativeJobs.editJob").click();+ await flush();+ button(root, "nativeJobs.advanced").click();+ await flush();+ if (change === "set") input(root, "nativeJobs.definitionFields.DESTINATION", "Exact.Host:1600");+ else {+ const field = root.querySelector('[aria-label="nativeJobs.definitionFields.DESTINATION"]')!.parentElement!;+ [...field.querySelectorAll<HTMLButtonElement>("button")].find((button) => button.textContent === "NULL")!.click();+ await flush();+ expect(root.querySelector<HTMLSelectElement>('[aria-label="nativeJobs.destinationMode"]')!.value).toBe("local");+ }+ button(root, "damengJobAdmin.previewSql").click();+ await flush();+ expect(request).toMatchObject({ action: "update", finalEnabled: true, attributes: [{ name: "DESTINATION", change: change === "set" ? { kind: "set", value: "Exact.Host:1600" } : { kind: "clear" } }] });+ expect(mocks.nativeJobApply).not.toHaveBeenCalled();+ });+ it("restores original inline values only to the draft and still requires a new preview", async () => {+ const scheduler = { kind: "scheduler" as const, scope, owner: "Owner", name: "Restore_job" };+ mocks.nativeJobOpenContext.mockResolvedValue({ scope, engine: "oracle", sessionUser: "Owner", actualDatabase: "DB", productVersion: "19" });+ mocks.nativeJobList.mockResolvedValue({+ jobs: { status: "available", value: [{ ref: scheduler, name: scheduler.name, owner: "Owner", enabled: true, jobType: "STORED_PROCEDURE", state: "SCHEDULED", nextRun: null, comments: null, aliases: [], logUser: null, privUser: null, schemaUser: null }] },+ source: { source: "SYS.DBA_SCHEDULER_JOBS", coverage: "database" },+ offset: 0,+ limit: 100,+ });+ details.snapshot.ref = scheduler;+ details.snapshot.definition = { status: "available", value: { ENABLED: true, PROGRAM_OWNER: null, PROGRAM_NAME: null, JOB_TYPE: "STORED_PROCEDURE", JOB_ACTION: "original_proc", NUMBER_OF_ARGUMENTS: 1, SCHEDULE_OWNER: null, SCHEDULE_NAME: null } };+ details.snapshot.arguments = { status: "available", value: [{ position: 1, dataType: "VARCHAR2", value: { kind: "value", value: "original input" }, editable: true }] };+ const root = await mount({ ...connection, db_type: "oracle" });+ button(root, "nativeJobs.editJob").click();+ await flush();+ input(root, "nativeJobs.definitionFields.JOB_ACTION", "target_proc");+ input(root, "nativeJobs.definitionFields.NUMBER_OF_ARGUMENTS", "2");+ await flush();+ button(root, "nativeJobs.restoreDefinitionDraft").click();+ await flush();+ expect(root.querySelector<HTMLTextAreaElement>('[aria-label="nativeJobs.definitionFields.JOB_ACTION"]')!.value).toBe("original_proc");+ expect(root.querySelector<HTMLInputElement>('[aria-label="nativeJobs.definitionFields.NUMBER_OF_ARGUMENTS"]')!.value).toBe("1");+ expect(root.textContent).not.toContain("nativeJobs.explicitNull");+ expect(mocks.nativeJobPrepare).not.toHaveBeenCalled();+ expect(mocks.nativeJobApply).not.toHaveBeenCalled();+ button(root, "damengJobAdmin.previewSql").click();+ await flush();+ expect(request).toMatchObject({ finalEnabled: true, attributes: [], argumentTarget: { program: null, arguments: [{ position: 1, dataType: "VARCHAR2", value: { kind: "value", value: "original input" } }] } });+ });+ it("creates a file arrival trigger through the existing File watcher picker", async () => {+ mocks.nativeJobOpenContext.mockResolvedValue({ scope, engine: "oracle", sessionUser: "Owner", actualDatabase: "DB", productVersion: "19" });+ mocks.nativeJobList.mockResolvedValue({ jobs: { status: "empty" }, source: { source: "SYS.DBA_SCHEDULER_JOBS", coverage: "database" }, offset: 0, limit: 100 });+ mocks.nativeJobReferences.mockResolvedValue({ objects: { status: "available", value: [{ DBX_OWNER: 'File.Owner"', DBX_NAME: "Arrival,One" }] }, source: { source: "SYS.ALL_SCHEDULER_FILE_WATCHERS", coverage: "accessible" }, offset: 0, limit: 100 });+ const root = await mount({ ...connection, db_type: "oracle" });+ button(root, "damengJobAdmin.newJob").click();+ await flush();+ input(root, "damengJobAdmin.jobName", "File_job");+ const mode = root.querySelector<HTMLSelectElement>('[aria-label="nativeJobs.scheduleMode"]')!;+ mode.value = "file-watcher";+ mode.dispatchEvent(new Event("change", { bubbles: true }));+ await flush();+ [...root.querySelector('[aria-label="nativeJobs.fileWatcherName"]')!.parentElement!.querySelectorAll<HTMLButtonElement>("button")].at(-1)!.click();+ await flush();+ expect(mocks.nativeJobReferences).toHaveBeenLastCalledWith(expect.objectContaining({ kind: "file-watcher", scope }));+ root.querySelector<HTMLButtonElement>("[data-native-reference]")!.click();+ await flush();+ expect(root.querySelector<HTMLInputElement>('[aria-label="nativeJobs.fileWatcherOwner"]')!.value).toBe('File.Owner"');+ input(root, "nativeJobs.eventCondition", "tab.user_data.file_size > 0");+ button(root, "damengJobAdmin.previewSql").click();+ await flush();+ expect(request).toMatchObject({ action: "create", definition: { kind: "scheduler", eventCondition: "tab.user_data.file_size > 0", eventSource: { kind: "file-watcher", reference: { owner: 'File.Owner"', name: "Arrival,One" } } } });+ if (request?.action === "create") expect(request.definition).not.toHaveProperty("repeatInterval");+ expect(mocks.executeMulti).not.toHaveBeenCalled();+ });+ it("reuses the existing reference pickers and retains the edit when Core rejects a Chain destination group", async () => {+ const scheduler = { kind: "scheduler" as const, scope, owner: "Owner", name: "Chain_job" };+ mocks.nativeJobOpenContext.mockResolvedValue({ scope, engine: "oracle", sessionUser: "Owner", actualDatabase: "DB", productVersion: "19" });+ mocks.nativeJobList.mockResolvedValue({+ jobs: { status: "available", value: [{ ref: scheduler, name: scheduler.name, owner: "Owner", enabled: true, jobType: "CHAIN", state: "SCHEDULED", nextRun: null, comments: null, aliases: [], logUser: null, privUser: null, schemaUser: null }] },+ source: { source: "SYS.DBA_SCHEDULER_JOBS", coverage: "database" },+ offset: 0,+ limit: 100,+ });+ details.snapshot.ref = scheduler;+ details.snapshot.definition = {+ status: "available",+ value: {+ ENABLED: true,+ PROGRAM_OWNER: null,+ PROGRAM_NAME: null,+ JOB_TYPE: "CHAIN",+ JOB_ACTION: '"Owner"."Old_chain"',+ NUMBER_OF_ARGUMENTS: 0,+ CONNECT_CREDENTIAL_OWNER: "Credentials.Owner",+ CONNECT_CREDENTIAL_NAME: "Old.Login",+ CREDENTIAL_OWNER: null,+ CREDENTIAL_NAME: null,+ DESTINATION_OWNER: null,+ DESTINATION: null,+ },+ };+ mocks.nativeJobPrepare.mockImplementation(async (value: NativeJobRequest) => {+ request = value;+ if (value.action === "update" && value.attributes.some((attribute) => attribute.name === "DESTINATION_NAME" && attribute.change.kind === "set" && typeof attribute.change.value === "object" && !Array.isArray(attribute.change.value) && attribute.change.value?.kind === "destination-group"))+ throw new Error("native_job_reference_not_applicable");+ return { planId: "corrected-plan", operationId: "corrected-operation", scope, target: scheduler, steps: [{ id: "attributes", label: "native_job_step_attributes", sql: "reviewed remaining definition" }] };+ });+ mocks.nativeJobReferences.mockImplementation(async ({ kind }) => ({+ objects: { status: "available", value: [{ DBX_OWNER: 'Other.Owner"', DBX_NAME: kind === "chain" ? "Chain,New" : kind === "credential" ? "Login,New" : "Group,New", ...(kind === "destination-group" ? { GROUP_TYPE: "DB_DEST" } : {}) }] },+ source: { source: "SYS.ALL_SCHEDULER_GROUPS", coverage: "accessible" },+ offset: 0,+ limit: 100,+ }));+ const root = await mount({ ...connection, db_type: "oracle" });+ button(root, "nativeJobs.editJob").click();+ await flush();+ [...root.querySelector('[aria-label="nativeJobs.definitionFields.JOB_ACTION"]')!.parentElement!.querySelectorAll<HTMLButtonElement>("button")].at(-1)!.click();+ await flush();+ expect(mocks.nativeJobReferences).toHaveBeenLastCalledWith(expect.objectContaining({ kind: "chain" }));+ root.querySelector<HTMLButtonElement>("[data-native-reference]")!.click();+ await flush();+ button(root, "nativeJobs.advanced").click();+ await flush();+ expect(root.querySelector<HTMLInputElement>('[aria-label="nativeJobs.definitionFields.CONNECT_CREDENTIAL_NAME"]')!.value).toBe('"Credentials.Owner"."Old.Login"');+ [...root.querySelector('[aria-label="nativeJobs.definitionFields.CONNECT_CREDENTIAL_NAME"]')!.parentElement!.querySelectorAll<HTMLButtonElement>("button")].at(-1)!.click();+ await flush();+ root.querySelector<HTMLButtonElement>("[data-native-reference]")!.click();+ await flush();+ const destinationMode = root.querySelector<HTMLSelectElement>('[aria-label="nativeJobs.destinationMode"]')!;+ destinationMode.value = "named";+ destinationMode.dispatchEvent(new Event("change", { bubbles: true }));+ await flush();+ [...root.querySelector('[aria-label="nativeJobs.definitionFields.DESTINATION_NAME"]')!.parentElement!.querySelectorAll<HTMLButtonElement>("button")].at(-1)!.click();+ await flush();+ expect(mocks.nativeJobReferences).toHaveBeenLastCalledWith(expect.objectContaining({ kind: "destination-group" }));+ root.querySelector<HTMLButtonElement>("[data-native-reference]")!.click();+ await flush();+ button(root, "damengJobAdmin.previewSql").click();+ await flush();+ expect(request).toMatchObject({+ finalEnabled: true,+ attributes: [+ { name: "JOB_ACTION", change: { kind: "set", value: '"Other.Owner"""."Chain,New"' } },+ { name: "CONNECT_CREDENTIAL_NAME", change: { kind: "set", value: { owner: 'Other.Owner"', name: "Login,New" } } },+ { name: "DESTINATION_NAME", change: { kind: "set", value: { owner: 'Other.Owner"', name: "Group,New", kind: "destination-group" } } },+ ],+ });+ expect(root.textContent).toContain("native_job_reference_not_applicable");+ expect(mocks.nativeJobApply).not.toHaveBeenCalled();+ [...root.querySelector('[aria-label="nativeJobs.definitionFields.DESTINATION_NAME"]')!.parentElement!.querySelectorAll<HTMLButtonElement>("button")].find((element) => element.textContent === "NULL")!.click();+ await flush();+ button(root, "damengJobAdmin.previewSql").click();+ await flush();+ expect(request?.action === "update" && request.attributes.some((attribute) => attribute.name === "DESTINATION_NAME")).toBe(false);+ expect(mocks.nativeJobPrepare).toHaveBeenCalledTimes(2);+ expect(mocks.nativeJobApply).not.toHaveBeenCalled();+ });+ it("retains a complete inline parameter target and original activation intent after a partial count conversion", async () => {+ const scheduler = { kind: "scheduler" as const, scope, owner: "Owner", name: "Inline_job" };+ mocks.nativeJobOpenContext.mockResolvedValue({ scope, engine: "oracle", sessionUser: "Owner", actualDatabase: "DB", productVersion: "19" });+ mocks.nativeJobList.mockResolvedValue({+ jobs: { status: "available", value: [{ ref: scheduler, name: scheduler.name, owner: "Owner", enabled: true, jobType: "STORED_PROCEDURE", state: "SCHEDULED", nextRun: null, comments: null, aliases: [], logUser: null, privUser: null, schemaUser: null }] },+ source: { source: "SYS.DBA_SCHEDULER_JOBS", coverage: "database" },+ offset: 0,+ limit: 100,+ });+ details.snapshot.ref = scheduler;+ details.snapshot.definition = { status: "available", value: { ENABLED: true, PROGRAM_OWNER: null, PROGRAM_NAME: null, JOB_TYPE: "STORED_PROCEDURE", JOB_ACTION: "inline_proc", NUMBER_OF_ARGUMENTS: 1 } };+ details.snapshot.arguments = { status: "available", value: [{ position: 1, dataType: "VARCHAR2", value: { kind: "value", value: "original override" }, editable: true }] };+ mocks.nativeJobPrepare.mockImplementation(async (value: NativeJobRequest) => {+ request = value;+ return { planId: "immutable-plan", operationId: "operation", scope, target: scheduler, steps: [{ id: "attributes", label: "native_job_step_attributes", sql: "reviewed definition" }] };+ });+ const root = await mount({ ...connection, db_type: "oracle" });+ button(root, "nativeJobs.editJob").click();+ await flush();+ input(root, "nativeJobs.definitionFields.NUMBER_OF_ARGUMENTS", "2");+ button(root, "damengJobAdmin.previewSql").click();+ await flush();+ const complete = structuredClone(request);+ expect(complete).toMatchObject({+ finalEnabled: true,+ argumentTarget: {+ program: null,+ arguments: [+ { position: 1, value: { kind: "value", value: "original override" } },+ { position: 2, value: { kind: "unset" } },+ ],+ },+ });+ details.snapshot.revision = "after";+ details.snapshot.definition.value.ENABLED = false;+ details.snapshot.definition.value.NUMBER_OF_ARGUMENTS = 2;+ mocks.nativeJobApply.mockResolvedValue({+ operationId: "operation",+ target: scheduler,+ state: "finished",+ outcome: "partial",+ cancelRequested: false,+ steps: [+ { id: "attributes", state: "applied", reason: null, vendorCode: null },+ { id: "argument:2", state: "failed", reason: "native_failure", vendorCode: 1 },+ ],+ reason: "native_failure",+ });+ button(root, "damengJobAdmin.applySql").click();+ await flush();+ button(root, "nativeJobs.correctDraft").click();+ await flush();+ button(root, "damengJobAdmin.previewSql").click();+ await flush();+ expect(request).toMatchObject({ baseline: "after", finalEnabled: true, attributes: [], argumentTarget: complete && "argumentTarget" in complete ? complete.argumentTarget : undefined });+ });+ it("creates and edits Oracle traditional jobs in the shared page without exposing a session-kill stop", async () => {+ const legacy = { kind: "legacy" as const, scope, jobId: "900719925474099312345" };+ mocks.nativeJobOpenContext.mockResolvedValue({ scope, engine: "oracle", sessionUser: "Owner", actualDatabase: "DB", productVersion: "19" });+ mocks.nativeJobList.mockResolvedValue({+ jobs: { status: "available", value: [{ ref: legacy, name: legacy.jobId, owner: null, enabled: false, jobType: "legacy", state: "BROKEN", nextRun: null, comments: null, aliases: [], logUser: "Log", privUser: "Privilege", schemaUser: "Owner" }] },+ source: { source: "SYS.DBA_JOBS", coverage: "database" },+ offset: 0,+ limit: 100,+ });+ mocks.nativeJobRead.mockResolvedValue({ ...details, snapshot: { ...details.snapshot, ref: legacy, definition: { status: "available", value: { WHAT: "old();", NEXT_DATE: "2026-10-21 10:00:00", INTERVAL: "NULL", INSTANCE: 0, LOG_USER: "Log", PRIV_USER: "Privilege", SCHEMA_USER: "Owner" } } } });+ const root = await mount({ ...connection, db_type: "oracle", database: "SERVICE" }, { kind: "legacy", jobId: legacy.jobId });+ expect(mocks.nativeJobList).toHaveBeenLastCalledWith({ scope, kind: "legacy", filter: "", offset: 0, limit: 100 });+ expect(root.textContent).toContain("nativeJobs.legacyNoStop");+ expect(root.textContent).toContain("nativeJobs.runForeground");+ expect(root.textContent).not.toContain("damengJobAdmin.stopRunning");+ expect(mocks.executeQuery).not.toHaveBeenCalled();+ button(root, "nativeJobs.editJob").click();+ await flush();+ input(root, "nativeJobs.definitionFields.WHAT", "corrected();");+ button(root, "damengJobAdmin.previewSql").click();+ await flush();+ expect(request).toMatchObject({ action: "update", target: legacy, attributes: [{ name: "WHAT", change: { kind: "set", value: "corrected();" } }] });+ button(root, "common.cancel").click();+ await flush();+ button(root, "damengJobAdmin.newJob").click();+ await flush();+ expect(root.querySelector('[aria-label="damengJobAdmin.jobName"]')).toBeNull();+ input(root, "nativeJobs.definitionFields.WHAT", "new_work();");+ input(root, "nativeJobs.definitionFields.NEXT_DATE", "2026-10-21 12:00:00");+ button(root, "damengJobAdmin.previewSql").click();+ await flush();+ expect(request).toMatchObject({ action: "create", scope, definition: { kind: "legacy", what: "new_work();", nextDate: "2026-10-21 12:00:00", enabled: false, schema: "Owner", instance: 0 } });+ expect(request).not.toHaveProperty("target");+ });+ it("keeps OB base attributes read-only while editing its effective duration and Zone", async () => {+ const ref = { kind: "scheduler" as const, scope, owner: "Owner", name: "OB_job" };+ mocks.nativeJobOpenContext.mockResolvedValue({ scope, engine: "oceanbase-oracle", sessionUser: "Owner", actualDatabase: "DB", productVersion: "4.2.5.7" });+ mocks.nativeJobList.mockResolvedValue({ jobs: { status: "available", value: [{ ref, name: ref.name, owner: ref.owner, enabled: false, aliases: [] }] }, source: { source: "SYS.DBA_SCHEDULER_JOBS", coverage: "database" }, offset: 0, limit: 100 });+ details.snapshot.ref = ref;+ details.snapshot.definition = { status: "available", value: { JOB_TYPE: "PLSQL_BLOCK", JOB_ACTION: "BEGIN kept(); END;", COMMENTS: "keep", AUTO_DROP: false, MAX_FAILURES: 2, MAX_RUN_DURATION: "+000 00:02:00", INSTANCE_ID: "RANDOM" } };+ const root = await mount({ ...connection, db_type: "oceanbase-oracle" });+ button(root, "nativeJobs.editJob").click();+ await flush();+ expect(root.querySelector<HTMLTextAreaElement>('[aria-label="nativeJobs.definitionFields.JOB_ACTION"]')!.disabled).toBe(true);+ expect(root.querySelector<HTMLInputElement>('[aria-label="nativeJobs.definitionFields.COMMENTS"]')!.disabled).toBe(true);+ expect(root.textContent).toContain("nativeJobs.obSchedulerDefinitionReadOnly");+ button(root, "nativeJobs.advanced").click();+ await flush();+ const zone = root.querySelector<HTMLInputElement>('[aria-label="nativeJobs.definitionFields.ZONE"]')!;+ expect(zone.type).toBe("text");+ expect(zone.value).toBe("RANDOM");+ expect(zone.disabled).toBe(false);+ input(root, "nativeJobs.definitionFields.ZONE", "zone1");+ input(root, "nativeJobs.definitionFields.MAX_RUN_DURATION", "0 00:03:00");+ expect(root.querySelector('[aria-label="nativeJobs.definitionFields.JOB_PRIORITY"]')).toBeNull();+ button(root, "damengJobAdmin.previewSql").click();+ await flush();+ expect(request).toMatchObject({+ action: "update",+ attributes: [+ { name: "INSTANCE_ID", change: { kind: "set", value: "zone1" } },+ { name: "MAX_RUN_DURATION", change: { kind: "set", value: "0 00:03:00" } },+ ],+ });+ });+ it("edits and clears the OB Legacy Zone from raw INSTANCE without changing the native snapshot", async () => {+ const legacy = { kind: "legacy" as const, scope, jobId: "41" };+ mocks.nativeJobOpenContext.mockResolvedValue({ scope, engine: "oceanbase-oracle", sessionUser: "Owner", actualDatabase: "DB", productVersion: "4.2.5.7" });+ mocks.nativeJobList.mockResolvedValue({ jobs: { status: "available", value: [{ ref: legacy, name: "41", owner: null, enabled: false, aliases: [] }] }, source: { source: "SYS.USER_JOBS", coverage: "current_user" }, offset: 0, limit: 100 });+ details.snapshot.ref = legacy;+ details.snapshot.definition = { status: "available", value: { WHAT: "old();", NEXT_DATE: "2026-10-21 10:00:00", INTERVAL: "SYSDATE+1", INSTANCE: "zone1", LOG_USER: "Owner", PRIV_USER: "Owner", SCHEMA_USER: "Owner" } };+ const root = await mount({ ...connection, db_type: "oceanbase-oracle" }, legacy);+ button(root, "nativeJobs.editJob").click();+ await flush();+ const zone = root.querySelector<HTMLInputElement>('[aria-label="nativeJobs.definitionFields.ZONE"]')!;+ expect(zone.value).toBe("zone1");+ expect(zone.disabled).toBe(false);+ expect(zone.type).toBe("text");+ input(root, "nativeJobs.definitionFields.ZONE", "zone2");+ button(root, "damengJobAdmin.previewSql").click();+ await flush();+ expect(request).toMatchObject({ action: "update", target: legacy, attributes: [{ name: "ZONE", change: { kind: "set", value: "zone2" } }] });+ button(root, "common.cancel").click();+ await flush();+ button(root, "nativeJobs.editJob").click();+ await flush();+ button(root, "NULL").click();+ await flush();+ button(root, "damengJobAdmin.previewSql").click();+ await flush();+ expect(request).toMatchObject({ action: "update", attributes: [{ name: "ZONE", change: { kind: "clear" } }] });+ expect(details.snapshot.definition.value.INSTANCE).toBe("zone1");+ expect(details.snapshot.definition.value).not.toHaveProperty("ZONE");+ });+ it("previews the OB Legacy foreground run and its native restoration of future scheduling", async () => {+ const legacy = { kind: "legacy" as const, scope, jobId: "41" };+ mocks.nativeJobOpenContext.mockResolvedValue({ scope, engine: "oceanbase-oracle", sessionUser: "Owner", actualDatabase: "DB", productVersion: "4.2.5.7" });+ mocks.nativeJobList.mockResolvedValue({ jobs: { status: "available", value: [{ ref: legacy, name: "41", owner: null, enabled: false, aliases: [] }] }, source: { source: "SYS.USER_JOBS", coverage: "current_user" }, offset: 0, limit: 100 });+ details.snapshot.ref = legacy;+ mocks.nativeJobPrepare.mockImplementation(async (value: NativeJobRequest) => {+ request = value;+ return { planId: "plan", operationId: "operation", scope, target: legacy, steps: [{ id: "run", label: "native_job_step_run", sql: "BEGIN SYS.DBMS_JOB.RUN(41); END;" }] };+ });+ const root = await mount({ ...connection, db_type: "oceanbase-oracle" }, legacy);+ button(root, "nativeJobs.runForeground").click();+ await flush();+ expect(request).toMatchObject({ action: "run", target: legacy });+ expect(root.textContent).toContain("nativeJobs.legacyRunRestoresScheduling");+ expect(mocks.nativeJobApply).not.toHaveBeenCalled();+ });+ it("offers only OB native creation types while keeping initial definition inputs writable", async () => {+ mocks.nativeJobOpenContext.mockResolvedValue({ scope, engine: "oceanbase-oracle", sessionUser: "Owner", actualDatabase: "DB", productVersion: "4.2.5.7" });+ mocks.nativeJobList.mockResolvedValue({ jobs: { status: "empty" }, source: { source: "SYS.DBA_SCHEDULER_JOBS", coverage: "database" }, offset: 0, limit: 100 });+ const root = await mount({ ...connection, db_type: "oceanbase-oracle" });+ button(root, "damengJobAdmin.newJob").click();+ await flush();+ const type = root.querySelector<HTMLSelectElement>('[aria-label="nativeJobs.definitionFields.JOB_TYPE"]')!;+ expect([...type.options].map((option) => option.value)).toEqual(["PLSQL_BLOCK", "STORED_PROCEDURE"]);+ expect(root.querySelector<HTMLTextAreaElement>('[aria-label="nativeJobs.definitionFields.JOB_ACTION"]')!.disabled).toBe(false);+ expect(root.querySelector('[aria-label="nativeJobs.definitionFields.SCHEDULE_NAME"]')).toBeNull();+ button(root, "nativeJobs.advanced").click();+ await flush();+ expect(root.querySelector('[aria-label="nativeJobs.definitionFields.CREDENTIAL_NAME"]')).toBeNull();+ expect(root.querySelector('[aria-label="nativeJobs.definitionFields.DESTINATION_NAME"]')).toBeNull();+ expect(root.querySelector<HTMLInputElement>('[aria-label="nativeJobs.definitionFields.ZONE"]')!.disabled).toBe(false);+ });+ it("retains different-owner drafts when switching jobs and keeps denied arguments separate from readable definition fields", async () => {+ const first = { kind: "scheduler" as const, scope, owner: "One", name: "Same" };+ const second = { ...first, owner: "Two" };+ mocks.nativeJobOpenContext.mockResolvedValue({ scope, engine: "oceanbase-oracle", sessionUser: "One", actualDatabase: "DB", productVersion: "4.2.5.7" });+ mocks.nativeJobList.mockResolvedValue({+ jobs: { status: "available", value: [first, second].map((ref) => ({ ref, name: ref.name, owner: ref.owner, enabled: false, jobType: "PLSQL_BLOCK", state: null, nextRun: null, comments: null, aliases: [], logUser: null, privUser: null, schemaUser: null })) },+ source: { source: "SYS.ALL_SCHEDULER_JOBS", coverage: "accessible" },+ offset: 0,+ limit: 100,+ });+ mocks.nativeJobRead.mockImplementation(async (ref) => ({+ ...details,+ snapshot: { ...details.snapshot, ref, definition: { status: "available", value: { JOB_TYPE: "PLSQL_BLOCK", JOB_ACTION: "BEGIN old(); END;", MAX_RUN_DURATION: "+000 00:00:00" } }, arguments: { status: "denied", reason: "privilege_missing" } },+ }));+ const root = await mount({ ...connection, db_type: "oceanbase-oracle" });+ button(root, "nativeJobs.editJob").click();+ await flush();+ button(root, "nativeJobs.advanced").click();+ await flush();+ input(root, "nativeJobs.definitionFields.MAX_RUN_DURATION", "0 00:02:00");+ button(root, "common.cancel").click();+ await flush();+ [...root.querySelectorAll("button")].find((element) => element.textContent?.includes("Same") && element.textContent.includes("Two"))!.click();+ await flush();+ [...root.querySelectorAll("button")].find((element) => element.textContent?.includes("Same") && element.textContent.includes("One"))!.click();+ await flush();+ button(root, "nativeJobs.editJob").click();+ await flush();+ button(root, "nativeJobs.advanced").click();+ await flush();+ expect(root.querySelector<HTMLInputElement>('[aria-label="nativeJobs.definitionFields.MAX_RUN_DURATION"]')?.value).toBe("0 00:02:00");+ button(root, "nativeJobs.arguments").click();+ await flush();+ expect(root.textContent).toContain("nativeJobs.partitionUnavailable");+ button(root, "nativeJobs.definition").click();+ await flush();+ button(root, "damengJobAdmin.previewSql").click();+ await flush();+ expect(request).toMatchObject({ action: "update", target: first, attributes: [{ name: "MAX_RUN_DURATION", change: { kind: "set", value: "0 00:02:00" } }], arguments: [] });+ expect(root.textContent).not.toContain("nativeJobs.forceStop");+ });+ it("rebinds an explicit native selection outside the current list page to the new authenticated context", async () => {+ const selected = { kind: "scheduler" as const, owner: "Exact.Owner", name: "Outside.Page" };+ mocks.nativeJobOpenContext.mockResolvedValue({ scope, engine: "oracle", sessionUser: "Owner", actualDatabase: "DB", productVersion: "19" });+ mocks.nativeJobList.mockResolvedValue({ jobs: { status: "empty" }, source: { source: "SYS.DBA_SCHEDULER_JOBS", coverage: "database" }, offset: 0, limit: 100 });+ mocks.nativeJobRead.mockImplementation(async (ref) => ({ ...details, snapshot: { ...details.snapshot, ref, definition: { status: "available", value: { JOB_ACTION: "retained();", ENABLED: false } } } }));+ const root = await mount({ ...connection, db_type: "oracle" }, selected);+ expect(mocks.nativeJobRead).toHaveBeenLastCalledWith({ ...selected, scope });+ expect(root.textContent).toContain("Outside.Page");+ expect(mocks.track.mock.calls[0]![0]()).toMatchObject({ selectedJob: selected, kind: "scheduler" });+ });+ it("uses the shared native page for Oracle and preserves exact owners when two Scheduler jobs have the same name", async () => {+ const first = { kind: "scheduler" as const, scope, owner: "Owner.One", name: "Same,Job" };+ const second = { ...first, owner: "Owner.Two" };+ mocks.nativeJobOpenContext.mockResolvedValue({ scope, engine: "oracle", sessionUser: "Owner.One", actualDatabase: "DB", productVersion: "19" });+ mocks.nativeJobList.mockResolvedValue({+ jobs: { status: "available", value: [first, second].map((ref) => ({ ref, name: ref.name, owner: ref.owner, enabled: false, jobType: "PLSQL_BLOCK", state: "DISABLED", nextRun: null, comments: null, aliases: [], logUser: null, privUser: null, schemaUser: null })) },+ source: { source: "SYS.DBA_SCHEDULER_JOBS", coverage: "database" },+ offset: 0,+ limit: 100,+ });+ mocks.nativeJobRead.mockImplementation(async (ref) => ({ ...structuredClone(details), snapshot: { ...details.snapshot, ref, definition: { status: "available", value: { JOB_TYPE: "PLSQL_BLOCK", JOB_ACTION: "BEGIN old(); END;", COMMENTS: "keep", AUTO_DROP: false, NUMBER_OF_ARGUMENTS: 0 } } } }));+ const root = await mount({ ...connection, db_type: "oracle" });+ expect(mocks.executeQuery).not.toHaveBeenCalled();+ expect(mocks.nativeJobOpenContext).toHaveBeenCalledWith("c", "");+ const selected = [...root.querySelectorAll("button")].find((element) => element.textContent?.includes("Same,Job") && element.textContent.includes("Owner.Two"))!;+ expect(selected).toBeDefined();+ selected.click();+ await flush();+ expect(mocks.nativeJobRead).toHaveBeenLastCalledWith(second);+ button(root, "nativeJobs.editJob").click();+ await flush();+ input(root, "nativeJobs.definitionFields.JOB_ACTION", "BEGIN corrected(); END;");+ button(root, "damengJobAdmin.previewSql").click();+ await flush();+ expect(request).toMatchObject({ action: "update", target: second, attributes: [{ name: "JOB_ACTION", change: { kind: "set", value: "BEGIN corrected(); END;" } }] });+ expect(mocks.executeMulti).not.toHaveBeenCalled();+ });+ it("searches the backend beyond the loaded page and persists the actual page offset", async () => {+ vi.useFakeTimers();+ const root = await mount();+ expect(mocks.track.mock.calls[0]![0]()).toMatchObject({ listOffset: 0 });+ const search = root.querySelector<HTMLInputElement>('[placeholder="damengJobAdmin.searchJob"]')!;+ search.value = "Owner's description";+ search.dispatchEvent(new Event("input", { bubbles: true }));+ await flush();+ await vi.advanceTimersByTimeAsync(200);+ await flush();+ expect(mocks.nativeJobList).toHaveBeenLastCalledWith({ scope, kind: "dameng-native", filter: "Owner's description", offset: 0, limit: 100 });+ expect(button(root, "nativeJobs.nextPage").disabled).toBe(true);+ });+ it("keeps the existing new-job entry but prepares a disabled-first native creation instead of executing editor SQL", async () => {+ const root = await mount();+ button(root, "damengJobAdmin.newJob").click();+ await flush();+ input(root, "damengJobAdmin.jobName", "New_job");+ button(root, "damengJobAdmin.previewSql").click();+ await flush();+ expect(request).toMatchObject({ action: "create", scope, definition: { kind: "dameng-native", name: "New_job", enabled: true, configuration: { steps: [{ kind: "add", name: "STEP1" }], schedules: [{ kind: "add", name: "SCHEDULE1" }] } } });+ expect(request).not.toHaveProperty("target");+ button(root, "damengJobAdmin.applySql").click();+ await flush();+ expect(mocks.nativeJobApply).toHaveBeenCalledExactlyOnceWith("immutable-plan");+ expect(mocks.executeMulti).not.toHaveBeenCalled();+ });++ it("continues a partially created job outside the loaded page using its acknowledged child IDs instead of creating it again", async () => {+ const original = structuredClone(details);+ const created = { ...target, name: "New_job", jobId: "900719925474099312346" };+ const createdDetails = structuredClone(details);+ createdDetails.snapshot.ref = created;+ createdDetails.snapshot.revision = "created-baseline";+ if (createdDetails.snapshot.definition.status === "available") {+ createdDetails.snapshot.definition.value.NAME = "New_job";+ createdDetails.snapshot.definition.value.ID = created.jobId;+ }+ createdDetails.steps = { status: "available", value: [{ ID: "100", JOBID: created.jobId, NAME: "STEP1", TYPE: 0, COMMAND: "SELECT 1;", RETRY_INTERVAL: 0 }] };+ mocks.nativeJobRead.mockImplementation(async (ref) => structuredClone(ref.jobId === created.jobId ? createdDetails : original));+ mocks.nativeJobApply.mockResolvedValue({+ operationId: "operation",+ target: created,+ state: "finished",+ outcome: "partial",+ cancelRequested: false,+ steps: [+ { id: "create", state: "applied", reason: null, vendorCode: null },+ { id: "steps:add:0", state: "applied", reason: null, vendorCode: null },+ { id: "config_commit", state: "failed", reason: "native_failure", vendorCode: -1 },+ ],+ reason: "native_failure",+ createdChildren: [{ partition: "steps", name: "STEP1", id: "100" }],+ });+ const root = await mount();+ button(root, "damengJobAdmin.newJob").click();+ await flush();+ input(root, "damengJobAdmin.jobName", "New_job");+ button(root, "damengJobAdmin.previewSql").click();+ await flush();+ button(root, "damengJobAdmin.applySql").click();+ await flush();+ expect(root.textContent).toContain("nativeJobs.outcomes.partial");+ expect(root.textContent).toContain("New_job");+ button(root, "nativeJobs.correctDraft").click();+ await flush();+ button(root, "nativeJobs.steps").click();+ await flush();+ expect(root.querySelector<HTMLTextAreaElement>('[aria-label="nativeJobs.fields.COMMAND_INPUT"]')?.value).toBe("SELECT 1;");+ input(root, "nativeJobs.fields.RETRY_INTERVAL", "4");+ button(root, "damengJobAdmin.previewSql").click();+ await flush();+ expect(request).toMatchObject({+ action: "configure-dameng",+ target: created,+ baseline: "created-baseline",+ configuration: { steps: [{ kind: "update", name: "STEP1", attributes: [{ name: "RETRY_INTERVAL", change: { kind: "set", value: 4 } }] }], schedules: [{ kind: "add", name: "SCHEDULE1" }] },+ });+ expect(mocks.executeMulti).not.toHaveBeenCalled();+ });++ it("creates multiple native steps with a forward dependency and preserves the first input when switching steps", async () => {+ const root = await mount();+ button(root, "damengJobAdmin.newJob").click();+ await flush();+ button(root, "nativeJobs.steps").click();+ await flush();+ input(root, "nativeJobs.fields.COMMAND_INPUT", "BEGIN report(); END;");+ button(root, "nativeJobs.add").click();+ await flush();+ input(root, "nativeJobs.fields.NAME", "STATS");+ const type = root.querySelector<HTMLSelectElement>('[aria-label="nativeJobs.fields.TYPE"]')!;+ type.value = "3";+ type.dispatchEvent(new Event("change", { bubbles: true }));+ const selection = root.querySelector<HTMLSelectElement>('[aria-label="nativeJobs.steps"]')!;+ selection.value = "0";+ selection.dispatchEvent(new Event("change", { bubbles: true }));+ await flush();+ expect(root.querySelector<HTMLTextAreaElement>('[aria-label="nativeJobs.fields.COMMAND_INPUT"]')?.value).toBe("BEGIN report(); END;");+ const action = root.querySelector<HTMLSelectElement>('[aria-label="nativeJobs.fields.SUCC_ACTION"]')!;+ action.value = "3";+ action.dispatchEvent(new Event("change", { bubbles: true }));+ input(root, "nativeJobs.fields.SUCC_NEXT_STEP", "STATS");+ button(root, "damengJobAdmin.previewSql").click();+ await flush();+ expect(request).toMatchObject({+ action: "create",+ definition: {+ configuration: {+ steps: [+ {+ kind: "add",+ name: "STEP1",+ attributes: expect.arrayContaining([+ { name: "COMMAND_INPUT", change: { kind: "set", value: "BEGIN report(); END;" } },+ { name: "SUCC_NEXT_STEP", change: { kind: "set", value: "STATS" } },+ ]),+ },+ { kind: "add", name: "STATS", attributes: [{ name: "TYPE", change: { kind: "set", value: 3 } }] },+ ],+ },+ },+ });+ });++ it("does not disguise a denied list as an empty list", async () => {+ mocks.nativeJobList.mockResolvedValue({ jobs: { status: "denied", reason: "privilege_missing" }, source: { source: "SYSJOB.USER_JOBS_VIEW", coverage: "current_user" }, offset: 0, limit: 100 });+ const root = await mount();+ expect(root.textContent).toContain("nativeJobs.partitionUnavailable");+ expect(root.textContent).not.toContain("nativeJobs.emptyJobs");+ expect(root.textContent).not.toContain("damengJobAdmin.emptyJobs");+ expect(mocks.nativeJobRead).not.toHaveBeenCalled();+ });+ it("loads exact native details and sends a same-page edit through immutable prepare/apply instead of editor SQL", async () => {+ const root = await mount();+ expect(mocks.nativeJobRead).toHaveBeenCalledWith(target);+ expect(root.textContent).toContain("SELECT 1;");+ button(root, "nativeJobs.editJob").click();+ await flush();+ input(root, "nativeJobs.fields.DESCRIBE", "new description");+ button(root, "damengJobAdmin.previewSql").click();+ await flush();+ expect(request).toEqual({ action: "configure-dameng", target, baseline: "baseline", configuration: { attributes: [{ name: "DESCRIBE", change: { kind: "set", value: "new description" } }], steps: [], schedules: [] } });+ expect(root.textContent).toContain("native reviewed SQL");+ button(root, "damengJobAdmin.applySql").click();+ await flush();+ expect(mocks.nativeJobApply).toHaveBeenCalledExactlyOnceWith("immutable-plan");+ expect(mocks.executeMulti).not.toHaveBeenCalled();+ expect(root.textContent).toContain("nativeJobs.outcomes.verified");+ expect(mocks.nativeJobOpenContext).toHaveBeenCalledTimes(1);+ });++ it("retains SQL input after partial success and re-previews only a corrected remaining field", async () => {+ const root = await mount();+ button(root, "nativeJobs.editJob").click();+ await flush();+ button(root, "nativeJobs.steps").click();+ await flush();+ input(root, "nativeJobs.fields.COMMAND_INPUT", "BEGIN work('private'); END;");+ await flush();+ expect(root.querySelector<HTMLTextAreaElement>('[aria-label="nativeJobs.fields.COMMAND_INPUT"]')?.value).toBe("BEGIN work('private'); END;");+ button(root, "damengJobAdmin.previewSql").click();+ await flush();+ expect(request).toMatchObject({ configuration: { steps: [{ kind: "update", name: "sql", attributes: [{ name: "COMMAND_INPUT", change: { kind: "set", value: "BEGIN work('private'); END;" } }] }] } });+ if (details.steps.status === "available") details.steps.value[0]!.COMMAND = "BEGIN work('private'); END;";+ mocks.nativeJobApply.mockResolvedValue({+ operationId: "operation",+ target,+ state: "finished",+ outcome: "partial",+ cancelRequested: false,+ steps: [+ { id: "steps:edit:0", state: "applied", reason: null, vendorCode: null },+ { id: "config_commit", state: "failed", reason: "native_failure", vendorCode: -1 },+ ],+ reason: "native_failure",+ });+ button(root, "damengJobAdmin.applySql").click();+ await flush();+ expect(root.textContent).toContain("nativeJobs.outcomes.partial");+ button(root, "nativeJobs.correctDraft").click();+ await flush();+ button(root, "nativeJobs.steps").click();+ await flush();+ expect(root.querySelector<HTMLTextAreaElement>('[aria-label="nativeJobs.fields.COMMAND_INPUT"]')?.value).toBe("BEGIN work('private'); END;");+ input(root, "nativeJobs.fields.RETRY_INTERVAL", "10");+ button(root, "damengJobAdmin.previewSql").click();+ await flush();+ expect(request).toMatchObject({ configuration: { steps: [{ kind: "update", name: "sql", attributes: [{ name: "RETRY_INTERVAL", change: { kind: "set", value: 10 } }] }] } });+ });++ it("allows native stop when running metadata is unknown and does not label an accepted run successful", async () => {+ const root = await mount();+ expect(button(root, "damengJobAdmin.stopRunning").disabled).toBe(false);+ button(root, "damengJobAdmin.stopRunning").click();+ await flush();+ expect(request).toEqual({ action: "stop", target, baseline: "baseline" });+ mocks.nativeJobApply.mockResolvedValue({ operationId: "operation", target, state: "finished", outcome: "accepted", cancelRequested: false, steps: [{ id: "stop", state: "accepted", reason: null, vendorCode: null }], reason: null });+ button(root, "damengJobAdmin.applySql").click();+ await flush();+ expect(root.textContent).toContain("nativeJobs.outcomes.accepted");+ expect(mocks.toast).not.toHaveBeenCalledWith("damengJobAdmin.applySuccess", expect.anything());+ });++ it("shows unavailable history rather than the empty-history state", async () => {+ const root = await mount();+ button(root, "damengJobAdmin.histories").click();+ await flush();+ expect(root.textContent).toContain("nativeJobs.partitionUnavailable");+ expect(root.textContent).not.toContain("damengJobAdmin.emptyDetails");+ });+ it.each(["unavailable", "uncertain"] as const)("keeps a single %s observation summary and preserves native diagnostics in the original record", async (association) => {+ const root = await mount();+ button(root, "damengJobAdmin.stopRunning").click();+ await flush();+ mocks.nativeJobApply.mockResolvedValue({+ operationId: "operation",+ target,+ state: "finished",+ outcome: "unknown",+ cancelRequested: false,+ steps: [{ id: "stop", state: "unknown", reason: "native_step_receipt_unknown", vendorCode: -1 }],+ reason: "native_job_step_outcome_unknown",+ executionObservation: { observedAt: "native observation time", association, reason: "native_history_unreadable", running: { status: "unknown", reason: "running_unreadable" }, history: { status: "denied", reason: "history_denied" }, sources: {}, candidates: [] },+ });+ button(root, "damengJobAdmin.applySql").click();+ await flush();+ const record = root.querySelector("details")!;+ expect(record).not.toBeNull();+ expect(record.open).toBe(false);+ expect(record.textContent).toContain("native_job_step_outcome_unknown");+ expect(record.textContent).toContain("native_step_receipt_unknown");+ expect(record.textContent).toContain("nativeJobs.observationReadStatus");+ expect(record.textContent).toContain("nativeJobs.observationEmpty");+ const primary = root.querySelector('section[aria-live="polite"]')!.cloneNode(true) as HTMLElement;+ primary.querySelectorAll("details").forEach((element) => element.remove());+ expect(primary.textContent).toContain("nativeJobs.outcomes.unknown");+ expect(primary.textContent).toContain(association === "uncertain" ? "nativeJobs.associationUncertain" : "nativeJobs.observationUnavailable");+ expect(primary.textContent).not.toContain("nativeJobs.observationReadStatus");+ expect(primary.textContent).not.toContain("nativeJobs.observationEmpty");+ expect(primary.textContent).not.toContain("native_job_step_outcome_unknown");+ expect(button(root, "nativeJobs.observeExecution").disabled).toBe(false);+ expect(mocks.nativeJobApply).toHaveBeenCalledTimes(1);+ });+});diff --git a/apps/desktop/src/lib/__tests__/database/NativeJobArgumentValueEditor.component.spec.ts b/apps/desktop/src/lib/__tests__/database/NativeJobArgumentValueEditor.component.spec.tsnew file mode 100644index 0000000000..44aefe7761--- /dev/null+++ b/apps/desktop/src/lib/__tests__/database/NativeJobArgumentValueEditor.component.spec.ts@@ -0,0 +1,142 @@+// @vitest-environment happy-dom+import { createApp, defineComponent, h, nextTick, ref } from "vue";+import { createI18n } from "vue-i18n";+import { expect, it } from "vitest";+import zh from "@/i18n/locales/zh-CN";+import NativeJobArgumentValueEditor from "@/components/admin/NativeJobArgumentValueEditor.vue";+import type { NativeJobValue } from "@/lib/database/nativeJobs";++function mount(initial: NativeJobValue, readonly = false) {+ const value = ref(initial);+ const root = document.createElement("div");+ document.body.append(root);+ const app = createApp(defineComponent({ setup: () => () => h(NativeJobArgumentValueEditor, { modelValue: value.value, "onUpdate:modelValue": (next: NativeJobValue) => (value.value = next), anydata: true, readonly, label: "参数值" }) }));+ app.use(createI18n({ legacy: false, locale: "zh-CN", messages: { "zh-CN": zh } }));+ app.mount(root);+ return {+ root,+ value,+ close: () => {+ app.unmount();+ root.remove();+ },+ };+}++it("keeps JSON-looking ordinary text on the string setter path", async () => {+ const fixture = mount('{"$dbx":"oracle-anydata-v1","scalarType":"number","value":"1"}');+ try {+ expect(fixture.root.querySelector("select")!.value).toBe("text");+ const input = fixture.root.querySelector("textarea")!;+ input.value = " text with trailing spaces ";+ input.dispatchEvent(new Event("input", { bubbles: true }));+ await nextTick();+ expect(fixture.value.value).toBe(" text with trailing spaces ");+ } finally {+ fixture.close();+ }+});++it("retains the readable legacy scalar display for non-ANYDATA defaults", () => {+ const fixture = mount(42, true);+ try {+ expect(fixture.root.querySelector("textarea")!.value).toBe("42");+ expect(fixture.value.value).toBe(42);+ } finally {+ fixture.close();+ }+});++it("edits legacy NUMBER envelopes without coercing exact decimals through JavaScript numbers", async () => {+ const fixture = mount({ $dbx: "oracle-anydata-v1", typeName: "SYS.NUMBER", value: "12345678901234567890123456789012345678" });+ try {+ expect(fixture.root.querySelector("select")!.value).toBe("number");+ const input = fixture.root.querySelector("textarea")!;+ expect(input.value).toBe("12345678901234567890123456789012345678");+ input.value = "-0.000000000000000000000000000001";+ input.dispatchEvent(new Event("input", { bubbles: true }));+ await nextTick();+ expect(fixture.value.value).toEqual({ $dbx: "oracle-anydata-v1", scalarType: "number", value: input.value });+ } finally {+ fixture.close();+ }+});++it("keeps explicit typed NULL distinct from ordinary NULL and offers every closed scalar type", async () => {+ const fixture = mount({ $dbx: "oracle-anydata-v1", scalarType: "char", value: "x " });+ try {+ const select = fixture.root.querySelector("select")!;+ expect([...select.options].map((option) => option.value)).toEqual(["text", "varchar2", "char", "nvarchar2", "nchar", "number", "date", "timestamp", "timestamp-tz", "timestamp-ltz", "interval-ym", "interval-ds", "raw", "binary-float", "binary-double", "urowid"]);+ const checkbox = fixture.root.querySelector<HTMLInputElement>('input[type="checkbox"]')!;+ checkbox.checked = true;+ checkbox.dispatchEvent(new Event("change", { bubbles: true }));+ await nextTick();+ expect(fixture.value.value).toEqual({ $dbx: "oracle-anydata-v1", scalarType: "char", value: null });+ expect(fixture.root.querySelector("textarea")).toBeNull();+ } finally {+ fixture.close();+ }+});++it("keeps BC civil dates and fractional seconds as exact strings with local time-zone fields", async () => {+ const initial = { $dbx: "oracle-anydata-v1", scalarType: "timestamp-tz", value: { civilDate: "-0001-12-31", seconds: "86399.123456789", region: "America/New_York", offset: "-05:00", abbreviation: "EST" } };+ const fixture = mount(initial);+ try {+ const inputs = [...fixture.root.querySelectorAll<HTMLInputElement>('input[type="text"]')];+ expect(inputs.map((input) => input.value)).toEqual(["-0001-12-31", "23:59:59.123456789", "America/New_York", "-05:00", "EST"]);+ inputs[1]!.value = "00:00:00.000000001";+ inputs[1]!.dispatchEvent(new Event("input", { bubbles: true }));+ await nextTick();+ expect(fixture.value.value).toEqual({ ...initial, value: { ...initial.value, seconds: "0.000000001" } });+ } finally {+ fixture.close();+ }+});++it("replaces an older JDN date only when the user explicitly enters a civil date", async () => {+ const fixture = mount({ $dbx: "oracle-anydata-v1", scalarType: "timestamp", value: { day: "1234567", seconds: "1.123456789" } });+ try {+ const date = fixture.root.querySelector<HTMLInputElement>('input[type="text"]')!;+ date.value = "2026-10-21";+ date.dispatchEvent(new Event("input", { bubbles: true }));+ await nextTick();+ expect(fixture.value.value).toEqual({ $dbx: "oracle-anydata-v1", scalarType: "timestamp", value: { civilDate: "2026-10-21", seconds: "1.123456789" } });+ } finally {+ fixture.close();+ }+});++it("does not update a kept or otherwise read-only scalar", async () => {+ const initial = { $dbx: "oracle-anydata-v1", scalarType: "raw", value: "00FF" };+ const fixture = mount(initial, true);+ try {+ expect(fixture.root.querySelector("select")!.disabled).toBe(true);+ const input = fixture.root.querySelector("textarea")!;+ expect(input.readOnly).toBe(true);+ input.value = "01";+ input.dispatchEvent(new Event("input", { bubbles: true }));+ await nextTick();+ expect(fixture.value.value).toEqual(initial);+ } finally {+ fixture.close();+ }+});++it.each([+ ["nvarchar2", "引号'、反斜线\\、😀与尾空格 "],+ ["interval-ds", "-86399999999999999999999"],+ ["interval-ym", "-11999999999"],+ ["binary-double", "3FF0000000000001"],+ ["raw", "00FF0000"],+])("keeps %s payloads as full text", async (scalarType, text) => {+ const fixture = mount({ $dbx: "oracle-anydata-v1", scalarType, value: text });+ try {+ const input = fixture.root.querySelector("textarea")!;+ expect(input.value).toBe(text);+ input.dispatchEvent(new Event("input", { bubbles: true }));+ await nextTick();+ expect(fixture.value.value).toEqual({ $dbx: "oracle-anydata-v1", scalarType, value: text });+ } finally {+ fixture.close();+ }+});diff --git a/apps/desktop/src/lib/__tests__/database/NativeJobDefinitionEditor.locale.spec.ts b/apps/desktop/src/lib/__tests__/database/NativeJobDefinitionEditor.locale.spec.tsnew file mode 100644index 0000000000..5492a5bb0f--- /dev/null+++ b/apps/desktop/src/lib/__tests__/database/NativeJobDefinitionEditor.locale.spec.ts@@ -0,0 +1,200 @@+// @vitest-environment happy-dom+import { createApp, defineComponent, h, nextTick, ref } from "vue";+import { createI18n } from "vue-i18n";+import { expect, it, vi } from "vitest";+import zh from "@/i18n/locales/zh-CN";+import NativeJobDefinitionEditor from "@/components/admin/NativeJobDefinitionEditor.vue";+import type { NativeJobDefinitionDraft } from "@/lib/database/nativeJobAdmin";+import type { NativeJobDetails } from "@/lib/database/nativeJobs";++vi.mock("@/lib/backend/api", () => ({ nativeJobReferences: vi.fn() }));++it("allows DM named replacement without exposing inline attachment, detach or Oracle trigger categories", async () => {+ for (const named of [true, false]) {+ const details = {+ snapshot: {+ ref: { kind: "scheduler" },+ revision: "read",+ definition: {+ status: "available",+ value: {+ PROGRAM_OWNER: named ? "Owner" : null,+ PROGRAM_NAME: named ? "P1" : null,+ SCHEDULE_OWNER: named ? "Owner" : null,+ SCHEDULE_NAME: named ? "S1" : null,+ SCHEDULE_TYPE: "CALENDAR",+ JOB_TYPE: "STORED_PROCEDURE",+ JOB_ACTION: "proc",+ NUMBER_OF_ARGUMENTS: 0,+ },+ },+ arguments: { status: "available", value: [] },+ },+ } as NativeJobDetails;+ const root = document.createElement("div");+ document.body.append(root);+ const app = createApp(NativeJobDefinitionEditor, { engine: "dameng", kind: "scheduler", details, modelValue: {} });+ app.use(createI18n({ legacy: false, locale: "zh-CN", messages: { "zh-CN": zh } }));+ try {+ app.mount(root);+ await nextTick();+ for (const label of ["程序名称", "调度名称"]) expect(root.querySelector<HTMLInputElement>(`[aria-label="${label}"]`)!.disabled).toBe(!named);+ expect([...root.querySelectorAll("button")].some((button) => button.textContent?.trim() === "选择程序")).toBe(named);+ expect([...root.querySelectorAll("button")].some((button) => button.textContent?.trim() === "选择调度")).toBe(named);+ expect(root.querySelector('option[value="window"]')).toBeNull();+ expect(root.querySelector('option[value="file-watcher"]')).toBeNull();+ for (const input of root.querySelectorAll('[aria-label="程序名称"], [aria-label="调度名称"]')) {+ expect(input.closest("div")?.textContent).not.toContain("NULL");+ }+ } finally {+ app.unmount();+ root.remove();+ }+ }+});++it("renders advanced labels, reference choices and enum labels in Chinese while retaining native values", async () => {+ const scope = { connectionId: "c", database: "", contextId: "ctx" };+ const details = {+ snapshot: {+ ref: { scope, kind: "scheduler", owner: "Owner", name: "Job" },+ revision: "read",+ definition: {+ status: "available",+ value: {+ ENABLED: false,+ JOB_TYPE: "STORED_PROCEDURE",+ JOB_ACTION: "proc",+ NUMBER_OF_ARGUMENTS: 0,+ PROGRAM_OWNER: null,+ PROGRAM_NAME: null,+ SCHEDULE_OWNER: null,+ SCHEDULE_NAME: null,+ JOB_CLASS: "DEFAULT_JOB_CLASS",+ CREDENTIAL_OWNER: null,+ CREDENTIAL_NAME: null,+ CONNECT_CREDENTIAL_OWNER: null,+ CONNECT_CREDENTIAL_NAME: null,+ DESTINATION_OWNER: null,+ DESTINATION: "exact.host:1500",+ LOGGING_LEVEL: "RUNS",+ },+ },+ arguments: { status: "available", value: [] },+ },+ } as NativeJobDetails;+ const draft = ref<NativeJobDefinitionDraft>({});+ const root = document.createElement("div");+ document.body.append(root);+ const app = createApp(defineComponent({ setup: () => () => h(NativeJobDefinitionEditor, { engine: "oracle", kind: "scheduler", scope, details, modelValue: draft.value, "onUpdate:modelValue": (value: NativeJobDefinitionDraft) => (draft.value = value) }) }));+ app.use(createI18n({ legacy: false, locale: "zh-CN", messages: { "zh-CN": zh } }));+ const button = (label: string) => {+ const result = [...root.querySelectorAll<HTMLButtonElement>("button")].find((button) => button.textContent?.trim() === label);+ if (!result) throw new Error(`Missing button: ${label}`);+ return result;+ };+ try {+ app.mount(root);+ button("高级属性").click();+ await nextTick();+ for (const label of [+ "作业类",+ "优先级",+ "最多运行次数",+ "最多失败次数",+ "最长运行时长",+ "调度延迟上限",+ "允许重新启动",+ "窗口关闭时停止",+ "保存运行输出",+ "允许在受限模式运行",+ "实例亲和性",+ "跟随默认时区",+ "执行实例",+ "作业权重",+ "触发事件掩码",+ "连接凭据",+ "运行凭据",+ "远程主机 (host[:port])",+ "日志记录级别",+ ]) {+ expect(root.querySelector(`[aria-label="${label}"]`), label).not.toBeNull();+ }+ expect(root.querySelector<HTMLInputElement>('[aria-label="作业类"]')!.value).toBe("DEFAULT_JOB_CLASS");+ const logging = root.querySelector<HTMLSelectElement>('[aria-label="日志记录级别"]')!;+ expect([...logging.options].map((option) => [option.value, option.textContent])).toEqual([+ ["OFF", "不记录"],+ ["RUNS", "运行记录"],+ ["FAILED RUNS", "仅记录失败"],+ ["FULL", "完整记录"],+ ]);+ const mode = root.querySelector<HTMLSelectElement>('[aria-label="执行目标"]')!;+ mode.value = "named";+ mode.dispatchEvent(new Event("change", { bubbles: true }));+ await nextTick();+ expect(root.querySelector('[aria-label="命名目的地"]')).not.toBeNull();+ expect(button("选择凭据")).toBeDefined();+ expect(button("选择目的地")).toBeDefined();+ expect(button("选择目的地组")).toBeDefined();+ button("作业定义").click();+ await nextTick();+ const type = root.querySelector<HTMLSelectElement>('[aria-label="作业类型"]')!;+ expect([...type.options].find((option) => option.value === "STORED_PROCEDURE")?.textContent).toBe("存储过程");+ expect([...type.options].find((option) => option.value === "PLSQL_BLOCK")?.textContent).toBe("PL/SQL 块");+ expect(button("选择程序")).toBeDefined();+ expect(button("选择调度")).toBeDefined();+ } finally {+ app.unmount();+ root.remove();+ }+});++it("activates a typed argument without stringifying its envelope and keeps typed NULL as a value", async () => {+ const number = { $dbx: "oracle-anydata-v1", typeName: "SYS.NUMBER", value: "9007199254740993.123456789" };+ const typedNull = { $dbx: "oracle-anydata-v1", scalarType: "char", value: null };+ const details = {+ snapshot: {+ ref: { kind: "scheduler" },+ revision: "read",+ definition: { status: "available", value: { JOB_STYLE: "REGULAR" } },+ arguments: {+ status: "available",+ value: [+ { position: 1, dataType: "NUMBER", value: { kind: "value", value: number }, editable: true },+ { position: 2, dataType: "VARCHAR2", value: { kind: "value", value: typedNull }, editable: true },+ ],+ },+ },+ } as NativeJobDetails;+ const draft = ref<NativeJobDefinitionDraft>({});+ const root = document.createElement("div");+ document.body.append(root);+ const app = createApp(defineComponent({ setup: () => () => h(NativeJobDefinitionEditor, { engine: "oracle", kind: "scheduler", details, modelValue: draft.value, "onUpdate:modelValue": (value: NativeJobDefinitionDraft) => (draft.value = value) }) }));+ app.use(createI18n({ legacy: false, locale: "zh-CN", messages: { "zh-CN": zh } }));+ try {+ app.mount(root);+ [...root.querySelectorAll<HTMLButtonElement>("button")].find((button) => button.textContent?.trim() === "参数")!.click();+ await nextTick();+ expect(root.querySelector<HTMLTextAreaElement>('[aria-label="参数 1 的值"]')!.value).toBe(number.value);+ for (const position of [1, 2]) {+ const state = root.querySelector<HTMLSelectElement>(`[aria-label="参数 ${position} 的状态"]`)!;+ state.value = "value";+ state.dispatchEvent(new Event("change", { bubbles: true }));+ await nextTick();+ }+ expect(draft.value.arguments).toEqual([+ { position: 1, value: { kind: "value", value: number } },+ { position: 2, value: { kind: "value", value: typedNull } },+ ]);+ const numberInput = root.querySelector<HTMLTextAreaElement>('[aria-label="参数 1 的值"]')!;+ numberInput.value = "-1.000000000000000000000000000000000001";+ numberInput.dispatchEvent(new Event("input", { bubbles: true }));+ await nextTick();+ expect(draft.value.arguments![0]!.value).toEqual({ kind: "value", value: { $dbx: "oracle-anydata-v1", scalarType: "number", value: numberInput.value } });+ expect(root.textContent).not.toContain('"$dbx"');+ expect(root.querySelector<HTMLInputElement>('input[type="checkbox"]:checked')).not.toBeNull();+ } finally {+ app.unmount();+ root.remove();+ }+});diff --git a/apps/desktop/src/lib/__tests__/database/NativeJobReferencePicker.component.spec.ts b/apps/desktop/src/lib/__tests__/database/NativeJobReferencePicker.component.spec.tsnew file mode 100644index 0000000000..d8a89c9ac6--- /dev/null+++ b/apps/desktop/src/lib/__tests__/database/NativeJobReferencePicker.component.spec.ts@@ -0,0 +1,158 @@+// @vitest-environment happy-dom+import { createApp, defineComponent, h, nextTick, ref, type Component } from "vue";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import type { NativeJobReferenceCatalog, NativeJobReferenceKind, NativeJobScope } from "@/lib/database/nativeJobs";++const references = vi.hoisted(() => vi.fn());+function passthrough(tag: string): Component {+ return defineComponent({+ inheritAttrs: false,+ setup:+ (_, { attrs, slots }) =>+ () =>+ h(tag, attrs, slots.default?.()),+ });+}+vi.mock("vue-i18n", () => ({ useI18n: () => ({ t: (key: string, values?: Record<string, string>) => (key === "nativeJobs.chooseReference" ? `Choose ${values?.kind}` : key) }) }));+vi.mock("@/lib/backend/api", () => ({ nativeJobReferences: references }));+vi.mock("@/components/ui/button", () => ({ Button: passthrough("button") }));+vi.mock("@/components/ui/input", () => ({+ Input: defineComponent({+ inheritAttrs: false,+ setup:+ (_, { attrs }) =>+ () =>+ h("input", { ...attrs, value: attrs.modelValue, onInput: (event: Event) => (attrs["onUpdate:modelValue"] as (value: string) => void)((event.target as HTMLInputElement).value) }),+ }),+}));+vi.mock("@/components/ui/dialog", () => ({+ Dialog: defineComponent({+ inheritAttrs: false,+ setup:+ (_, { attrs, slots }) =>+ () =>+ attrs.open ? h("section", { role: "dialog" }, slots.default?.()) : null,+ }),+ DialogContent: passthrough("div"),+ DialogHeader: passthrough("header"),+ DialogTitle: passthrough("h2"),+}));+import NativeJobReferencePicker from "@/components/admin/NativeJobReferencePicker.vue";++const scope: NativeJobScope = { connectionId: "c", database: "", contextId: "context" };+const mounted: Array<{ app: ReturnType<typeof createApp>; root: HTMLElement }> = [];+const page = (objects: NativeJobReferenceCatalog["objects"], offset = 0): NativeJobReferenceCatalog => ({ objects, source: { source: "SYS.ALL_SCHEDULER_PROGRAMS", coverage: "accessible" }, offset, limit: 100 });+async function flush() {+ for (let index = 0; index < 12; index++) {+ await Promise.resolve();+ await nextTick();+ }+}+async function mount(kind: Exclude<NativeJobReferenceKind, "program-arguments" | "destination-group-members"> = "program") {+ const currentScope = ref(scope);+ const disabled = ref(false);+ const selected = vi.fn();+ const root = document.createElement("div");+ document.body.append(root);+ const app = createApp({ setup: () => () => h(NativeJobReferencePicker, { scope: currentScope.value, kind, disabled: disabled.value, onSelect: selected }) });+ app.mount(root);+ mounted.push({ app, root });+ await flush();+ return { root, selected, currentScope, disabled };+}+function button(root: HTMLElement, label: string) {+ const result = [...root.querySelectorAll<HTMLButtonElement>("button")].find((element) => element.textContent?.trim() === label);+ if (!result) throw new Error(`Missing ${label}`);+ return result;+}+function input(root: HTMLElement, label: string, value: string) {+ const element = root.querySelector<HTMLInputElement>(`[aria-label="${label}"]`)!;+ element.value = value;+ element.dispatchEvent(new Event("input", { bubbles: true }));+}+beforeEach(() => {+ references.mockReset();+});+afterEach(() => {+ for (const { app, root } of mounted.splice(0)) {+ app.unmount();+ root.remove();+ }+});++describe("native reference selection", () => {+ it.each(["window", "window-group", "file-watcher", "destination-group"] as const)("reuses the picker for the %s category without changing the selected identity", async (kind) => {+ const row = { DBX_OWNER: "SYS", DBX_NAME: 'Exact.Name,One"', ...(kind.endsWith("-group") ? { GROUP_TYPE: kind === "destination-group" ? "DB_DEST" : "WINDOW" } : {}) };+ references.mockResolvedValue(page({ status: "available", value: [row] }));+ const { root, selected } = await mount(kind);+ button(root, `Choose nativeJobs.referenceKinds.${kind}`).click();+ await flush();+ expect(references).toHaveBeenCalledWith({ scope, kind, schema: undefined, filter: "", offset: 0, limit: 100 });+ root.querySelector<HTMLButtonElement>("[data-native-reference]")!.click();+ expect(selected).toHaveBeenCalledWith({ owner: row.DBX_OWNER, name: row.DBX_NAME, metadata: row });+ });+ it("loads only when opened and emits separate exact owner and name components", async () => {+ const row = { DBX_OWNER: 'Owner.One"', DBX_NAME: "Program,one", COMMENTS: "read only metadata" };+ references.mockResolvedValue(page({ status: "available", value: [row] }));+ const { root, selected } = await mount();+ expect(references).not.toHaveBeenCalled();+ button(root, "Choose nativeJobs.referenceKinds.program").click();+ await flush();+ expect(references).toHaveBeenCalledWith({ scope, kind: "program", schema: undefined, filter: "", offset: 0, limit: 100 });+ expect(root.textContent).toContain("nativeJobs.catalogCoverage.accessible");+ root.querySelector<HTMLButtonElement>("[data-native-reference]")!.click();+ await flush();+ expect(selected).toHaveBeenCalledWith({ owner: row.DBX_OWNER, name: row.DBX_NAME, metadata: row });+ expect(root.querySelector('[role="dialog"]')).toBeNull();+ });+ it("keeps denied, unavailable and successful empty catalogs distinct", async () => {+ for (const status of ["denied", "unknown", "empty"] as const) {+ references.mockResolvedValue(page(status === "empty" ? { status } : { status, reason: "native catalog" }));+ const { root, selected } = await mount();+ button(root, "Choose nativeJobs.referenceKinds.program").click();+ await flush();+ expect(root.textContent).toContain(status === "empty" ? "nativeJobs.emptyReferences" : "nativeJobs.referenceCatalogUnavailable");+ expect(root.querySelector("[data-native-reference]")).toBeNull();+ expect(selected).not.toHaveBeenCalled();+ }+ });+ it("pages at the backend and submits owner and filter without normalizing exact identifiers", async () => {+ references.mockResolvedValue(page({ status: "truncated", value: [{ DBX_OWNER: "Owner", DBX_NAME: "Program" }], limit: 100 }));+ const { root } = await mount();+ button(root, "Choose nativeJobs.referenceKinds.program").click();+ await flush();+ button(root, "nativeJobs.nextPage").click();+ await flush();+ expect(references.mock.calls.at(-1)?.[0].offset).toBe(100);+ input(root, "nativeJobs.ownerFilter", "Mixed Case.Owner");+ input(root, "nativeJobs.referenceFilter", "10%_!");+ root.querySelector("form")!.dispatchEvent(new Event("submit", { bubbles: true, cancelable: true }));+ await flush();+ expect(references.mock.calls.at(-1)?.[0]).toMatchObject({ schema: "Mixed Case.Owner", filter: "10%_!", offset: 0 });+ });+ it("discards an old context response and cannot select while the caller is disabled", async () => {+ let resolve!: (value: NativeJobReferenceCatalog) => void;+ references.mockImplementationOnce(+ () =>+ new Promise<NativeJobReferenceCatalog>((done) => {+ resolve = done;+ }),+ );+ const { root, currentScope, selected, disabled } = await mount();+ button(root, "Choose nativeJobs.referenceKinds.program").click();+ await flush();+ currentScope.value = { ...scope, contextId: "new-context" };+ await flush();+ resolve(page({ status: "available", value: [{ DBX_OWNER: "Old", DBX_NAME: "Old" }] }));+ await flush();+ expect(root.querySelector('[role="dialog"]')).toBeNull();+ references.mockResolvedValue(page({ status: "available", value: [{ DBX_OWNER: "New", DBX_NAME: "New" }] }));+ button(root, "Choose nativeJobs.referenceKinds.program").click();+ await flush();+ expect(references.mock.calls.at(-1)?.[0].scope.contextId).toBe("new-context");+ disabled.value = true;+ await flush();+ root.querySelector<HTMLButtonElement>("[data-native-reference]")!.click();+ expect(selected).not.toHaveBeenCalled();+ });+});diff --git a/apps/desktop/src/lib/__tests__/database/databaseObjectCapabilities.spec.ts b/apps/desktop/src/lib/__tests__/database/databaseObjectCapabilities.spec.tsindex 12adeb110a..c6041e9b98 100644--- a/apps/desktop/src/lib/__tests__/database/databaseObjectCapabilities.spec.ts+++ b/apps/desktop/src/lib/__tests__/database/databaseObjectCapabilities.spec.ts@@ -30,7 +30,7 @@ describe("databaseObjectCapabilities", () => {});it("exposes supported programmable objects for Dameng", () => {- expect(sidebarObjectKindsForDatabase("dameng")).toEqual(expect.arrayContaining(["MATERIALIZED_VIEW", "SEQUENCE", "PACKAGE", "PACKAGE_BODY"]));+ expect(sidebarObjectKindsForDatabase("dameng")).toEqual(expect.arrayContaining(["MATERIALIZED_VIEW", "TRIGGER", "SEQUENCE", "PACKAGE", "PACKAGE_BODY"]));});it.each(["oracle", "oceanbase-oracle", "dameng"] as const)("exposes %s types and bodies through the existing read-only browsing paths", (dbType) => {@@ -50,8 +50,8 @@ describe("databaseObjectCapabilities", () => {it("exposes OceanBase Oracle sequences and synonyms through the grouped object path", () => {const oceanBaseObjects = sidebarObjectKindsForDatabase("oceanbase-oracle");- expect(oceanBaseObjects).toEqual(["TABLE", "VIEW", "MATERIALIZED_VIEW", "PROCEDURE", "FUNCTION", "SEQUENCE", "INDEX", "SYNONYM", "PACKAGE", "PACKAGE_BODY", "TYPE", "TYPE_BODY"]);- expect(databaseObjectCapabilities("oceanbase-oracle").sourceReadable).toEqual(["VIEW", "MATERIALIZED_VIEW", "PROCEDURE", "FUNCTION", "SEQUENCE", "SYNONYM", "PACKAGE", "PACKAGE_BODY", "TYPE", "TYPE_BODY"]);+ expect(oceanBaseObjects).toEqual(["TABLE", "VIEW", "MATERIALIZED_VIEW", "PROCEDURE", "FUNCTION", "TRIGGER", "SEQUENCE", "INDEX", "SYNONYM", "PACKAGE", "PACKAGE_BODY", "TYPE", "TYPE_BODY"]);+ expect(databaseObjectCapabilities("oceanbase-oracle").sourceReadable).toEqual(["VIEW", "MATERIALIZED_VIEW", "PROCEDURE", "FUNCTION", "TRIGGER", "SEQUENCE", "SYNONYM", "PACKAGE", "PACKAGE_BODY", "TYPE", "TYPE_BODY"]);expect(buildObjectGroupPlaceholderNodes({nodeId: "connection:database:APP",@@ -60,13 +60,13 @@ describe("databaseObjectCapabilities", () => {schema: "APP",objectTypes: oceanBaseObjects,}).map((node) => node.type),- ).toEqual(["group-tables", "group-views", "group-materialized-views", "group-procedures", "group-functions", "group-sequences", "group-database-indexes", "group-synonyms", "group-packages", "group-types"]);+ ).toEqual(["group-tables", "group-views", "group-materialized-views", "group-procedures", "group-functions", "group-triggers", "group-sequences", "group-database-indexes", "group-synonyms", "group-packages", "group-types"]);});it("exposes Oracle sequences through the existing grouped object path", () => {const oracleObjects = sidebarObjectKindsForDatabase("oracle");- expect(oracleObjects).toEqual(["TABLE", "VIEW", "MATERIALIZED_VIEW", "PROCEDURE", "FUNCTION", "SEQUENCE", "INDEX", "SYNONYM", "PACKAGE", "PACKAGE_BODY", "TYPE", "TYPE_BODY"]);+ expect(oracleObjects).toEqual(["TABLE", "VIEW", "MATERIALIZED_VIEW", "PROCEDURE", "FUNCTION", "TRIGGER", "SEQUENCE", "INDEX", "SYNONYM", "PACKAGE", "PACKAGE_BODY", "TYPE", "TYPE_BODY"]);expect(databaseObjectCapabilities("oracle").sourceReadable).toContain("SEQUENCE");expect(buildObjectGroupPlaceholderNodes({@@ -134,6 +134,13 @@ describe("databaseObjectCapabilities", () => {expect(sidebarObjectKindsForDatabase("vastbase")).not.toContain("TRIGGER");});+ it("discovers Oracle-family triggers alongside the main TYPE and INDEX capabilities", () => {+ for (const dbType of ["oracle", "oceanbase-oracle", "dameng"] as const) {+ expect(databaseObjectCapabilities(dbType).sourceReadable).toContain("TRIGGER");+ expect(sidebarObjectKindsForDatabase(dbType)).toEqual(expect.arrayContaining(["TRIGGER", "TYPE", "TYPE_BODY", "INDEX"]));+ }+ });+it("exposes sequences for Kingbase and Vastbase via the agent PostgreSQL catalogs", () => {for (const dbType of ["kingbase", "vastbase"] as const) {expect(sidebarObjectKindsForDatabase(dbType), dbType).toContain("SEQUENCE");diff --git a/apps/desktop/src/lib/__tests__/database/databaseObjectDependencies.spec.ts b/apps/desktop/src/lib/__tests__/database/databaseObjectDependencies.spec.tsindex 07ac4b87c9..389e08ff95 100644--- a/apps/desktop/src/lib/__tests__/database/databaseObjectDependencies.spec.ts+++ b/apps/desktop/src/lib/__tests__/database/databaseObjectDependencies.spec.ts@@ -1,5 +1,6 @@import { describe, expect, it } from "vitest";import { canViewDatabaseObjectDependencies, databaseDependencyProviderFor } from "@/lib/database/databaseObjectDependencies";+import type { TreeNode, TriggerInfo } from "@/types/database";const node = (overrides: Record<string, unknown> = {}) => ({type: "table" as const,@@ -10,6 +11,27 @@ const node = (overrides: Record<string, unknown> = {}) => ({});describe("database dependency providers", () => {+ it("limits DM dependency support to the exact trigger adapter and preserves its raw owner/name", () => {+ const trigger: TriggerInfo = { name: " Tr'ig ", event: "INSERT", timing: "BEFORE", oracle_metadata: { contractVersion: 1, identityMode: "exact", engine: "dm", engineVersion: "8.1.3", owner: " Owner ", name: " Tr'ig ", scope: "TABLE", reads: {} } };+ const item: TreeNode = { id: "t", type: "trigger", label: "display label", schema: " Owner ", objectName: trigger.name, meta: trigger };+ const provider = databaseDependencyProviderFor("dameng");+ expect(provider).not.toBeNull();+ expect(provider!.supports(item)).toBe(true);+ expect(provider!.buildQuery(item)).toContain("d.NAME = ' Tr''ig '");+ expect(provider!.buildQuery(item)).toContain("d.TYPE = 'TRIGGER'");+ expect(provider!.targetLabel?.(item)).toMatchObject({ name: " Owner . Tr'ig " });+ for (const changed of [+ { ...item, meta: undefined },+ { ...item, schema: "Other" },+ { ...item, type: "procedure" as const },+ ]) {+ expect(provider!.supports(changed)).toBe(false);+ expect(provider!.buildQuery(changed)).toBeNull();+ }+ trigger.oracle_metadata!.engineVersion = "6.0";+ expect(provider!.supports(item)).toBe(false);+ });+it("resolves only providers registered for the requested database", () => {expect(databaseDependencyProviderFor("xugu")?.databaseType).toBe("xugu");expect(databaseDependencyProviderFor("oracle")?.databaseType).toBe("oracle");diff --git a/apps/desktop/src/lib/__tests__/database/nativeJobAdmin.spec.ts b/apps/desktop/src/lib/__tests__/database/nativeJobAdmin.spec.tsnew file mode 100644index 0000000000..6d5b45d208--- /dev/null+++ b/apps/desktop/src/lib/__tests__/database/nativeJobAdmin.spec.ts@@ -0,0 +1,370 @@+import { describe, expect, it } from "vitest";+import {+ buildNativeJobDefinitionCreate,+ buildNativeJobDefinitionEdit,+ initializeNativeJobDefinitionEdit,+ nativeJobDefinitionForEdit,+ nativeJobAdminKinds,+ nativeJobAdminEngine,+ nativeJobAdminSupported,+ newNativeJobDefinitionDraft,+ nativeJobProgramArgumentLayout,+ rebaseNativeJobDefinitionCreation,+ restoreNativeJobDefinitionDraft,+ selectNativeJobArgumentContext,+ type NativeJobDefinitionDraft,+} from "@/lib/database/nativeJobAdmin";+import { buildNativeJobEdit, type NativeJobDetails, type NativeJobOperationStatus, type NativeJobRow } from "@/lib/database/nativeJobs";++const scope = { connectionId: "c", database: "", contextId: "context" };+describe("shared native Job admin adapter", () => {+ it("uses actual OceanBase compatibility mode only for Job capability on JDBC", () => {+ for (const driver_label of ["OceanBase", "Oracle", "Dameng"]) {+ const connection = { db_type: "jdbc" as const, connection_string: "jdbc:oceanbase://host/db", driver_label, database_info: { productName: "OceanBase", compatibilityMode: "ORACLE" } };+ expect(nativeJobAdminEngine(connection)).toBe("oceanbase-oracle");+ expect(nativeJobAdminSupported(connection)).toBe(true);+ for (const compatibilityMode of [undefined, "mysql", "unknown"]) {+ const unavailable = { ...connection, database_info: { productName: "OceanBase", compatibilityMode } };+ expect(nativeJobAdminEngine(unavailable)).toBeUndefined();+ expect(nativeJobAdminSupported(unavailable)).toBe(false);+ }+ }+ });+ it("supports Oracle thin, OCI, Oracle JDBC, OB Oracle and Dameng without changing Xugu", () => {+ for (const connection of [{ db_type: "oracle" as const }, { db_type: "oracle" as const, driver_profile: "oracle-oci" }, { db_type: "jdbc" as const, connection_string: "jdbc:oracle:thin:@host/service" }, { db_type: "oceanbase-oracle" as const }, { db_type: "dameng" as const }])+ expect(nativeJobAdminSupported(connection)).toBe(true);+ for (const db_type of ["xugu", "mysql", "oceanbase", "jdbc"] as const) expect(nativeJobAdminSupported({ db_type })).toBe(false);+ expect(nativeJobAdminKinds("oracle")).toEqual(["scheduler", "legacy"]);+ expect(nativeJobAdminKinds("dameng")).toEqual(["dameng-native", "scheduler", "legacy"]);+ });+ it("creates an inline Scheduler with explicit offset dates and retained advanced fields", () => {+ const draft = newNativeJobDefinitionDraft("scheduler");+ draft.attributes!.JOB_ACTION = { kind: "set", value: "BEGIN work('private'); END;" };+ draft.attributes!.START_DATE = { kind: "set", value: "2026-10-21T10:00:00+08:00" };+ draft.attributes!.MAX_FAILURES = { kind: "set", value: 7 };+ const request = buildNativeJobDefinitionCreate(scope, "oracle", "scheduler", "Exact.Owner", " Job,One ", draft);+ expect(request).toMatchObject({+ action: "create",+ scope,+ definition: { kind: "scheduler", owner: "Exact.Owner", name: " Job,One ", jobType: "PLSQL_BLOCK", jobAction: "BEGIN work('private'); END;", startDate: "2026-10-21T10:00:00+08:00", enabled: false, attributes: [{ name: "MAX_FAILURES", change: { kind: "set", value: 7 } }] },+ });+ expect(request).not.toHaveProperty("target");+ });+ it("uses exact program and schedule references rather than splitting qualified names or rewriting inactive inline input", () => {+ const draft = newNativeJobDefinitionDraft("scheduler");+ Object.assign(draft.attributes!, { PROGRAM_OWNER: { kind: "set", value: "Program.Owner" }, PROGRAM_NAME: { kind: "set", value: 'P,"One' }, SCHEDULE_OWNER: { kind: "set", value: "Calendar.Owner" }, SCHEDULE_NAME: { kind: "set", value: "Week.Name" } });+ const request = buildNativeJobDefinitionCreate(scope, "oracle", "scheduler", "Owner", "New_job", draft);+ expect(request.definition).toMatchObject({ program: { owner: "Program.Owner", name: 'P,"One' }, schedule: { owner: "Calendar.Owner", name: "Week.Name" }, numberOfArguments: 0 });+ expect(request.definition).not.toHaveProperty("jobType");+ expect(request.definition).not.toHaveProperty("startDate");+ expect(draft.attributes!.JOB_ACTION).toEqual({ kind: "set", value: "BEGIN NULL; END;" });+ });+ it("keeps Oracle instance and OceanBase zone distinct for targetless traditional creation", () => {+ const draft = newNativeJobDefinitionDraft("legacy");+ Object.assign(draft.attributes!, { WHAT: { kind: "set", value: "run_work();" }, NEXT_DATE: { kind: "set", value: "2026-10-21 10:00:00" }, ZONE: { kind: "set", value: "zone1" }, INSTANCE: { kind: "set", value: 2 } });+ const oracle = buildNativeJobDefinitionCreate(scope, "oracle", "legacy", "Exact Owner", "", draft);+ expect(oracle.definition).toMatchObject({ kind: "legacy", schema: "Exact Owner", instance: 2, enabled: false });+ expect(oracle.definition).not.toHaveProperty("zone");+ const ob = buildNativeJobDefinitionCreate(scope, "oceanbase-oracle", "legacy", "Owner", "", draft);+ expect(ob.definition).toMatchObject({ kind: "legacy", zone: "zone1", enabled: false });+ expect(ob.definition).not.toHaveProperty("instance");+ });+ it("retains argument drafts by exact Program identity without applying inactive inline or other Program overrides", () => {+ const draft = newNativeJobDefinitionDraft("scheduler");+ draft.arguments = [{ position: 1, value: { kind: "value", value: "inline original" } }];+ draft.argumentTypes = { 1: "VARCHAR2" };+ draft.attributes!.PROGRAM_NAME = { kind: "set", value: "Program.One" };+ expect(buildNativeJobDefinitionCreate(scope, "oracle", "scheduler", "Owner", "Job", draft).definition).toMatchObject({ arguments: [] });+ selectNativeJobArgumentContext(draft, "Owner", "Program.One");+ expect(draft.arguments).toEqual([]);+ draft.arguments!.push({ position: 2, value: { kind: "value", value: "program override" } });+ draft.argumentTypes![2] = "NUMBER";+ selectNativeJobArgumentContext(draft, "Another.Owner", "Program.One");+ expect(draft.arguments).toEqual([]);+ selectNativeJobArgumentContext(draft, "Owner", "Program.One");+ expect(draft.arguments).toEqual([{ position: 2, value: { kind: "value", value: "program override" } }]);+ selectNativeJobArgumentContext(draft, "Owner");+ expect(draft.arguments).toEqual([{ position: 1, value: { kind: "value", value: "inline original" } }]);+ expect(draft.argumentTypes).toEqual({ 1: "VARCHAR2" });+ });+ it("captures the original Scheduler enabled intent and argument context before a conversion can pause it", () => {+ const details = { snapshot: { ref: { kind: "scheduler", scope, owner: "Owner", name: "Job" }, definition: { status: "available", value: { ENABLED: "TRUE", PROGRAM_OWNER: "Other.Owner", PROGRAM_NAME: "Program.A" } } } } as NativeJobDetails;+ const draft: NativeJobDefinitionDraft = { arguments: [{ position: 1, value: { kind: "value", value: "original override" } }], argumentTypes: { 1: "VARCHAR2" } };+ initializeNativeJobDefinitionEdit(details, draft);+ expect(draft.finalEnabled).toBe(true);+ expect(draft.argumentContext).toBe(JSON.stringify(["Other.Owner", "Program.A"]));+ selectNativeJobArgumentContext(draft, "Other.Owner", "Program.B");+ expect(draft.arguments).toEqual([]);+ if (details.snapshot.definition.status === "available") details.snapshot.definition.value.ENABLED = false;+ initializeNativeJobDefinitionEdit(details, draft);+ expect(draft.finalEnabled).toBe(true);+ expect(draft.argumentContext).toBe(JSON.stringify(["Other.Owner", "Program.B"]));+ selectNativeJobArgumentContext(draft, "Other.Owner", "Program.A");+ expect(draft.arguments).toEqual([{ position: 1, value: { kind: "value", value: "original override" } }]);+ expect(draft.argumentTypes).toEqual({ 1: "VARCHAR2" });+ draft.finalEnabled = false;+ initializeNativeJobDefinitionEdit(details, draft);+ expect(draft.finalEnabled).toBe(false);+ });+ it("sends a complete new Program context without copying old-position overrides or inactive inline fields", () => {+ const details = {+ snapshot: {+ ref: { kind: "scheduler", scope, owner: "Owner", name: "Job" },+ revision: "before",+ definition: { status: "available", value: { ENABLED: true, PROGRAM_OWNER: "Owner", PROGRAM_NAME: "A", JOB_TYPE: null, JOB_ACTION: null, NUMBER_OF_ARGUMENTS: null } },+ arguments: { status: "available", value: [{ position: 1, dataType: "VARCHAR2", value: { kind: "value", value: "old secret" }, editable: true }] },+ },+ } as NativeJobDetails;+ const draft: NativeJobDefinitionDraft = {};+ initializeNativeJobDefinitionEdit(details, draft);+ selectNativeJobArgumentContext(draft, "Other.Owner", "New,Program");+ draft.attributes = { PROGRAM_OWNER: { kind: "set", value: "Other.Owner" }, PROGRAM_NAME: { kind: "set", value: "New,Program" }, JOB_TYPE: { kind: "set", value: "STORED_PROCEDURE" }, JOB_ACTION: { kind: "set", value: "inactive_proc" }, NUMBER_OF_ARGUMENTS: { kind: "set", value: 7 } };+ draft.argumentLayouts = { [draft.argumentContext!]: { status: "available", value: [{ position: 1, dataType: "NUMBER", value: { kind: "inherit" }, editable: true }] } };+ const request = buildNativeJobDefinitionEdit(details, "oracle", draft);+ expect(request.attributes).toEqual([{ name: "PROGRAM_NAME", change: { kind: "set", value: { owner: "Other.Owner", name: "New,Program" } } }]);+ expect(request.arguments).toEqual([]);+ expect(request.argumentTarget).toEqual({ program: { owner: "Other.Owner", name: "New,Program" }, arguments: [{ position: 1, dataType: "NUMBER", value: { kind: "inherit" } }] });+ expect(request.finalEnabled).toBe(true);+ details.snapshot.revision = "partial";+ details.snapshot.definition = { status: "available", value: { ENABLED: false, PROGRAM_OWNER: "Other.Owner", PROGRAM_NAME: "New,Program", JOB_TYPE: null, JOB_ACTION: null, NUMBER_OF_ARGUMENTS: null } };+ const remaining = buildNativeJobDefinitionEdit(details, "oracle", draft);+ expect(remaining.attributes).toEqual([]);+ expect(remaining.argumentTarget).toEqual(request.argumentTarget);+ expect(remaining.finalEnabled).toBe(true);+ expect(draft.attributes.JOB_ACTION).toEqual({ kind: "set", value: "inactive_proc" });+ });+ it("leaves ordinary edits on their old delta contract and drops identical exact references", () => {+ const details = { snapshot: { ref: { kind: "scheduler", scope, owner: "Owner", name: "Job" }, revision: "read", definition: { status: "available", value: { ENABLED: true, PROGRAM_OWNER: "Owner", PROGRAM_NAME: "A", COMMENTS: "old" } }, arguments: { status: "empty" } } } as NativeJobDetails;+ const draft: NativeJobDefinitionDraft = { attributes: { PROGRAM_OWNER: { kind: "set", value: "Owner" }, PROGRAM_NAME: { kind: "set", value: "A" }, COMMENTS: { kind: "set", value: "new" } } };+ initializeNativeJobDefinitionEdit(details, draft);+ const request = buildNativeJobDefinitionEdit(details, "oracle", draft);+ expect(request.attributes).toEqual([{ name: "COMMENTS", change: { kind: "set", value: "new" } }]);+ expect(request).not.toHaveProperty("finalEnabled");+ expect(request).not.toHaveProperty("argumentTarget");+ if (details.snapshot.definition.status === "available") delete details.snapshot.definition.value.PROGRAM_OWNER;+ expect(buildNativeJobDefinitionEdit(details, "oracle", { attributes: { COMMENTS: { kind: "set", value: "new" } } }).attributes).toEqual([{ name: "COMMENTS", change: { kind: "set", value: "new" } }]);+ });+ it("uses complete Program descriptions, keeps unknown defaults unknown and prevents metadata overrides", () => {+ const program = { status: "available" as const, value: { NUMBER_OF_ARGUMENTS: 2 } };+ const args = {+ status: "available" as const,+ value: [+ { ARGUMENT_POSITION: 1, ARGUMENT_TYPE: "NUMBER", DEFAULT_VALUE: null },+ { ARGUMENT_POSITION: 2, ARGUMENT_TYPE: "SYS.AQ$_JMS_TEXT_MESSAGE", METADATA_ATTRIBUTE: "EVENT_MESSAGE", OUT_ARGUMENT: false },+ ],+ };+ const layout = nativeJobProgramArgumentLayout(program, args);+ expect(layout).toMatchObject({+ status: "available",+ value: [+ { position: 1, value: { kind: "inherit" }, editable: true, defaultValue: { status: "unknown" } },+ { position: 2, editable: false, metadataAttribute: "EVENT_MESSAGE" },+ ],+ });+ expect(nativeJobProgramArgumentLayout(program, { status: "empty" }).status).toBe("unknown");+ expect(nativeJobProgramArgumentLayout(program, { status: "truncated", value: args.value, limit: 2 })).toEqual({ status: "unknown", reason: "native_job_arguments_truncated" });+ expect(nativeJobProgramArgumentLayout({ status: "available", value: { NUMBER_OF_ARGUMENTS: 0 } }, { status: "empty" })).toEqual({ status: "available", value: [] });+ });+ it("uses backend-decoded defaults before misleading string projections and never parses ANYDATA locators", () => {+ const typed = { kind: "value", value: { $dbx: "oracle-anydata-v1", scalarType: "number", value: "9.007199254740993E15" } };+ const rows: NativeJobRow[] = [+ { ARGUMENT_POSITION: 1, DEFAULT_VALUE: "wrong fallback", DEFAULT_ANYDATA_VALUE: "locator", DBX_ARGUMENT_DEFAULT: { status: "available", value: typed } },+ { ARGUMENT_POSITION: 2, DEFAULT_VALUE: "also wrong", DBX_ANYDATA_PRESENT: 1, DEFAULT_ANYDATA_VALUE: "opaque locator" },+ { ARGUMENT_POSITION: 3, DEFAULT_VALUE: "plain text", DBX_ANYDATA_PRESENT: 0 },+ ];+ const layout = nativeJobProgramArgumentLayout({ status: "available", value: { NUMBER_OF_ARGUMENTS: 3 } }, { status: "available", value: rows });+ expect(layout).toMatchObject({+ status: "available",+ value: [+ { position: 1, defaultValue: { status: "available", value: typed } },+ { position: 2, defaultValue: { status: "available", value: { kind: "opaque", value: "opaque locator" } } },+ { position: 3, defaultValue: { status: "available", value: { kind: "value", value: "plain text" } } },+ ],+ });+ });+ it("keeps final intent for a remaining Schedule activation without requiring unrelated Program metadata", () => {+ const details = {+ snapshot: { ref: { kind: "scheduler", scope, owner: "Owner", name: "Job" }, revision: "before", definition: { status: "available", value: { ENABLED: true, PROGRAM_NAME: "Unreadable owner", SCHEDULE_OWNER: null, SCHEDULE_NAME: null } }, arguments: { status: "denied", reason: "not readable" } },+ } as NativeJobDetails;+ const draft: NativeJobDefinitionDraft = {};+ initializeNativeJobDefinitionEdit(details, draft);+ draft.transitionRetained = true;+ draft.attributes = { SCHEDULE_OWNER: { kind: "set", value: "SYS" }, SCHEDULE_NAME: { kind: "set", value: "Window.Group" } };+ draft.referenceKinds = { SCHEDULE_NAME: "window-group" };+ expect(buildNativeJobDefinitionEdit(details, "oracle", draft)).toMatchObject({ finalEnabled: true, attributes: [{ name: "SCHEDULE_NAME", change: { kind: "set", value: { owner: "SYS", name: "Window.Group", kind: "window-group" } } }] });+ details.snapshot.definition = { status: "available", value: { ENABLED: false, PROGRAM_NAME: "Unreadable owner", SCHEDULE_OWNER: "SYS", SCHEDULE_NAME: "Window.Group", SCHEDULE_TYPE: "WINDOW_GROUP" } };+ const remaining = buildNativeJobDefinitionEdit(details, "oracle", draft);+ expect(remaining).toMatchObject({ finalEnabled: true, attributes: [], arguments: [] });+ expect(remaining).not.toHaveProperty("argumentTarget");+ });+ it("does not invent an enabled intent from missing metadata or for a traditional Job", () => {+ const draft: NativeJobDefinitionDraft = {};+ const details = { snapshot: { ref: { kind: "legacy", scope, jobId: "41" }, definition: { status: "available", value: { BROKEN: "N" } } } } as NativeJobDetails;+ initializeNativeJobDefinitionEdit(details, draft);+ expect(draft).toEqual({});+ details.snapshot.ref = { kind: "scheduler", scope, owner: "Owner", name: "Job" };+ details.snapshot.definition = { status: "unknown", reason: "unreadable" };+ initializeNativeJobDefinitionEdit(details, draft);+ expect(draft).toEqual({});+ });+ it("projects exact credential and destination components without reinterpreting an old host destination", () => {+ const native = { status: "available" as const, value: { CREDENTIAL_OWNER: "Credentials.Owner", CREDENTIAL_NAME: 'Login,One"', CONNECT_CREDENTIAL_OWNER: null, CONNECT_CREDENTIAL_NAME: null, DESTINATION_OWNER: "Remote.Owner", DESTINATION: "Remote.DB" } };+ const projected = nativeJobDefinitionForEdit("oracle", "scheduler", native);+ expect(projected).toMatchObject({ status: "available", value: { CREDENTIAL_NAME: { owner: "Credentials.Owner", name: 'Login,One"' }, CONNECT_CREDENTIAL_NAME: null, DESTINATION_NAME: { owner: "Remote.Owner", name: "Remote.DB" }, DESTINATION: "Remote.DB" } });+ expect(native.value.CREDENTIAL_NAME).toBe('Login,One"');+ const host = nativeJobDefinitionForEdit("oracle", "scheduler", { status: "available", value: { DESTINATION_OWNER: null, DESTINATION: "host.example:15000" } });+ expect(host).toMatchObject({ status: "available", value: { DESTINATION: "host.example:15000" } });+ if (host.status === "available") expect(host.value).not.toHaveProperty("DESTINATION_NAME");+ });+ it("restores the original target into a new preview while retaining the inactive target's argument draft", () => {+ const details = {+ snapshot: {+ ref: { kind: "scheduler", scope, owner: "Owner", name: "Job" },+ revision: "before",+ definition: {+ status: "available",+ value: {+ ENABLED: true,+ PROGRAM_OWNER: "Owner",+ PROGRAM_NAME: "A",+ JOB_TYPE: null,+ JOB_ACTION: null,+ NUMBER_OF_ARGUMENTS: null,+ SCHEDULE_OWNER: null,+ SCHEDULE_NAME: null,+ SCHEDULE_TYPE: "CALENDAR",+ START_DATE: "2030-01-01T00:00:00+08:00",+ END_DATE: null,+ REPEAT_INTERVAL: "FREQ=DAILY",+ COMMENTS: "original",+ },+ },+ arguments: { status: "available", value: [{ position: 1, dataType: "VARCHAR2", value: { kind: "value", value: "original override" }, editable: true }] },+ },+ } as NativeJobDetails;+ const draft: NativeJobDefinitionDraft = {};+ initializeNativeJobDefinitionEdit(details, draft);+ selectNativeJobArgumentContext(draft, "Other.Owner", "B");+ draft.arguments = [{ position: 1, value: { kind: "value", value: "target B input" } }];+ draft.attributes = { PROGRAM_OWNER: { kind: "set", value: "Other.Owner" }, PROGRAM_NAME: { kind: "set", value: "B" }, COMMENTS: { kind: "set", value: "target comment" } };+ details.snapshot.revision = "after-partial";+ details.snapshot.definition = { status: "available", value: { ...details.snapshot.definition.value, ENABLED: false, PROGRAM_OWNER: "Other.Owner", PROGRAM_NAME: "B" } };+ restoreNativeJobDefinitionDraft(draft);+ const request = buildNativeJobDefinitionEdit(details, "oracle", draft);+ expect(request).toMatchObject({+ baseline: "after-partial",+ finalEnabled: true,+ attributes: [{ name: "PROGRAM_NAME", change: { kind: "set", value: { owner: "Owner", name: "A" } } }],+ argumentTarget: { program: { owner: "Owner", name: "A" }, arguments: [{ position: 1, dataType: "VARCHAR2", value: { kind: "value", value: "original override" } }] },+ });+ expect(draft.originalSnapshot?.definition).toMatchObject({ status: "available", value: { ENABLED: true, PROGRAM_NAME: "A" } });+ selectNativeJobArgumentContext(draft, "Other.Owner", "B");+ expect(draft.arguments).toEqual([{ position: 1, value: { kind: "value", value: "target B input" } }]);+ });+ it("creates queue and file arrival triggers without sending the inactive named or calendar schedule", () => {+ for (const scheduleMode of ["queue", "file-watcher"] as const) {+ const draft = newNativeJobDefinitionDraft("scheduler");+ draft.attributes!.SCHEDULE_NAME = { kind: "set", value: "inactive schedule" };+ draft.attributes!.REPEAT_INTERVAL = { kind: "set", value: "FREQ=DAILY" };+ draft.scheduleMode = scheduleMode;+ draft.eventDraft = { condition: "tab.user_data.ready = 'Y'", queueOwner: "Queue.Owner", queueName: "Q,1", agent: "Agent.One", watcherOwner: "Watch.Owner", watcherName: 'Arrival,"One' };+ const definition = buildNativeJobDefinitionCreate(scope, "oracle", "scheduler", "Owner", "New", draft).definition;+ expect(definition).toMatchObject({ eventCondition: "tab.user_data.ready = 'Y'", eventSource: scheduleMode === "queue" ? { kind: "queue", owner: "Queue.Owner", name: "Q,1", agent: "Agent.One" } : { kind: "file-watcher", reference: { owner: "Watch.Owner", name: 'Arrival,"One' } } });+ expect(definition).not.toHaveProperty("schedule");+ expect(definition).not.toHaveProperty("repeatInterval");+ }+ });+ it("edits an event trigger with exact source components and preserves unrelated opaque parameter metadata", () => {+ const details = {+ snapshot: {+ ref: { kind: "scheduler", scope, owner: "Owner", name: "Job" },+ revision: "read",+ definition: {+ status: "available",+ value: {+ ENABLED: true,+ PROGRAM_OWNER: "Unknown.ProgramOwner",+ PROGRAM_NAME: "Program",+ SCHEDULE_OWNER: "Calendar.Owner",+ SCHEDULE_NAME: "Calendar",+ SCHEDULE_TYPE: "NAMED",+ EVENT_QUEUE_OWNER: null,+ EVENT_QUEUE_NAME: null,+ FILE_WATCHER_OWNER: null,+ FILE_WATCHER_NAME: null,+ EVENT_CONDITION: null,+ },+ },+ arguments: { status: "denied", reason: "no argument access" },+ },+ } as NativeJobDetails;+ const draft: NativeJobDefinitionDraft = {};+ initializeNativeJobDefinitionEdit(details, draft);+ draft.scheduleMode = "queue";+ draft.eventDraft = { condition: "tab.user_data.flag = 'Y'", queueOwner: "Queue.Owner", queueName: 'Q,"One', agent: "Exact.Agent", watcherOwner: "", watcherName: "" };+ const request = buildNativeJobDefinitionEdit(details, "oracle", draft);+ expect(request).toMatchObject({+ finalEnabled: true,+ attributes: [+ { name: "SCHEDULE_NAME", change: { kind: "clear" } },+ { name: "EVENT_SPEC", change: { kind: "set", value: { condition: "tab.user_data.flag = 'Y'", source: { kind: "queue", owner: "Queue.Owner", name: 'Q,"One', agent: "Exact.Agent" } } } },+ ],+ });+ expect(request).not.toHaveProperty("argumentTarget");+ expect(request.arguments).toEqual([]);+ });+ it("shares the OB Legacy Zone projection for no-op comparison without changing native INSTANCE", () => {+ const original = { status: "available" as const, value: { INSTANCE: "zone1", WHAT: "kept();" } };+ const definition = nativeJobDefinitionForEdit("oceanbase-oracle", "legacy", original);+ const snapshot = { ref: { kind: "legacy" as const, scope, jobId: "41" }, revision: "read", definition, arguments: { status: "empty" as const } };+ expect(buildNativeJobEdit(snapshot, { attributes: { ZONE: { kind: "set", value: "zone1" } } }).attributes).toEqual([]);+ expect(buildNativeJobEdit(snapshot, { attributes: { ZONE: { kind: "clear" } } }).attributes).toEqual([{ name: "ZONE", change: { kind: "clear" } }]);+ expect(original.value).toEqual({ INSTANCE: "zone1", WHAT: "kept();" });+ expect(nativeJobDefinitionForEdit("oracle", "legacy", original)).toBe(original);+ snapshot.definition = nativeJobDefinitionForEdit("oceanbase-oracle", "legacy", { status: "available", value: { INSTANCE: null } });+ expect(buildNativeJobEdit(snapshot, { attributes: { ZONE: { kind: "clear" } } }).attributes).toEqual([]);+ });+ it("restores an original host through the raw destination slot rather than a named-reference clear", () => {+ const original = {+ snapshot: {+ ref: { kind: "scheduler", scope, owner: "Owner", name: "Host_job" },+ revision: "original",+ definition: { status: "available", value: { ENABLED: true, PROGRAM_OWNER: null, PROGRAM_NAME: null, JOB_TYPE: "STORED_PROCEDURE", JOB_ACTION: "proc", NUMBER_OF_ARGUMENTS: 0, SCHEDULE_OWNER: null, SCHEDULE_NAME: null, DESTINATION_OWNER: null, DESTINATION: "Host.With.Dots:1500" } },+ arguments: { status: "available", value: [] },+ },+ } as NativeJobDetails;+ const draft: NativeJobDefinitionDraft = {};+ initializeNativeJobDefinitionEdit(original, draft);+ draft.attributes = { DESTINATION_NAME: { kind: "set", value: { owner: "Remote.Owner", name: "Named" } } };+ const current = structuredClone(original);+ if (current.snapshot.definition.status !== "available") throw new Error("fixture definition");+ Object.assign(current.snapshot.definition.value, { DESTINATION_OWNER: "Remote.Owner", DESTINATION: "Named" });+ restoreNativeJobDefinitionDraft(draft, current);+ const request = buildNativeJobDefinitionEdit(current, "oracle", draft);+ expect(request.attributes).toContainEqual({ name: "DESTINATION", change: { kind: "set", value: "Host.With.Dots:1500" } });+ expect(request.attributes.some(({ name }) => name === "DESTINATION_NAME")).toBe(false);+ expect(request.finalEnabled).toBe(true);+ expect(original.snapshot.definition).toMatchObject({ value: { DESTINATION_OWNER: null, DESTINATION: "Host.With.Dots:1500" } });+ });+ it("rebases only acknowledged Scheduler creation and never resubmits creation-only flags as attributes", () => {+ const target = { scope, kind: "scheduler" as const, owner: "Owner", name: "Job" };+ const details = { snapshot: { ref: target, revision: "new", definition: { status: "available", value: { JOB_TYPE: "PLSQL_BLOCK", JOB_ACTION: "BEGIN NULL; END;", NUMBER_OF_ARGUMENTS: 0, AUTO_DROP: true } }, arguments: { status: "empty" } } } as NativeJobDetails;+ const draft = newNativeJobDefinitionDraft("scheduler");+ Object.assign(draft.attributes!, { ENABLED: { kind: "set", value: true }, JOB_PRIORITY: { kind: "set", value: 7 } });+ const status = { target, steps: [{ id: "create", state: "applied" }], outcome: "partial" } as NativeJobOperationStatus;+ const rebased = rebaseNativeJobDefinitionCreation(details, draft, status);+ expect(buildNativeJobEdit(details.snapshot, rebased).attributes).toEqual([+ { name: "START_DATE", change: draft.attributes!.START_DATE },+ { name: "JOB_PRIORITY", change: { kind: "set", value: 7 } },+ ]);+ expect(rebased.attributes).not.toHaveProperty("ENABLED");+ status.steps[0]!.state = "unknown";+ expect(rebaseNativeJobDefinitionCreation(details, draft, status)).toEqual({});+ expect(draft.attributes!.ENABLED).toEqual({ kind: "set", value: true });+ status.steps[0]!.state = "applied";+ Object.assign(draft.attributes!, { PROGRAM_NAME: { kind: "set", value: "Program" }, SCHEDULE_NAME: { kind: "set", value: "Schedule" } });+ const referenced = rebaseNativeJobDefinitionCreation(details, draft, status);+ for (const name of ["JOB_TYPE", "JOB_ACTION", "NUMBER_OF_ARGUMENTS", "START_DATE", "END_DATE", "REPEAT_INTERVAL"]) expect(referenced.attributes).not.toHaveProperty(name);+ expect(referenced.attributes!.JOB_PRIORITY).toEqual({ kind: "set", value: 7 });+ });+});diff --git a/apps/desktop/src/lib/__tests__/database/nativeJobs.spec.ts b/apps/desktop/src/lib/__tests__/database/nativeJobs.spec.tsnew file mode 100644index 0000000000..7f709777de--- /dev/null+++ b/apps/desktop/src/lib/__tests__/database/nativeJobs.spec.ts@@ -0,0 +1,328 @@+import { describe, expect, it } from "vitest";+import { reactive } from "vue";+import {+ buildNativeJobDamengCreate,+ buildNativeJobDamengEdit,+ rebaseNativeJobDamengCreation,+ rebaseNativeJobDamengDraft,+ buildNativeJobEdit,+ nativeJobRefKey,+ oracleSchedulerObjectName,+ type NativeJobDamengEditDraft,+ type NativeJobDetails,+ type NativeJobOperationStatus,+ type NativeJobRef,+ type NativeJobSnapshot,+} from "@/lib/database/nativeJobs";++const scope = { connectionId: "connection-a", database: "tenant/schema", contextId: "context-1" };+const scheduler = (owner: string, name: string): NativeJobRef => ({ scope: { ...scope }, kind: "scheduler", owner, name });++describe("native Job identity", () => {+ it("keeps the exact scope and identifier components separate", () => {+ const selected = scheduler("owner.with.dot", "Job,One");+ const otherOwner = scheduler("owner", "with.dot.Job,One");+ expect(nativeJobRefKey(selected)).not.toBe(nativeJobRefKey(otherOwner));+ expect(nativeJobRefKey(selected)).not.toBe(nativeJobRefKey(scheduler("OWNER.WITH.DOT", "Job,One")));+ expect(nativeJobRefKey(selected)).not.toBe(nativeJobRefKey({ ...selected, scope: { ...scope, contextId: "context-2" } }));+ expect(nativeJobRefKey(selected)).toBe(nativeJobRefKey(structuredClone(selected)));+ });++ it("quotes a single native Scheduler object rather than a comma-separated list", () => {+ expect(oracleSchedulerObjectName(scheduler('owner"one', ' Job,Two." '))).toBe('"owner""one"." Job,Two."" "');+ });++ it("keeps numeric Job IDs above JavaScript's safe integer range distinct", () => {+ expect(nativeJobRefKey({ scope, kind: "legacy", jobId: "9007199254740993" })).not.toBe(nativeJobRefKey({ scope, kind: "legacy", jobId: "9007199254740994" }));+ });++ it.each([9007199254740992, "0", "1e3"])("rejects a lossy or noncanonical Job ID: %s", (jobId) => {+ expect(() => nativeJobRefKey({ scope, kind: "legacy", jobId } as NativeJobRef)).toThrow("native_job_id_invalid");+ });+});++function damengDetails(): NativeJobDetails {+ return {+ snapshot: { ref: { kind: "dameng-native", scope: { ...scope }, jobId: "41", name: "Job_1" }, revision: "revision", definition: { status: "available", value: { DESCRIBE: "keep job", ENABLE: false } }, arguments: { status: "empty" } },+ nativeIdentity: { status: "available", value: { DBX_JOB_ID: "41", DBX_CREATED_AT: "creation" } },+ consistency: { status: "available", value: null },+ parameterMetadata: { status: "unsupported", reason: "not_applicable" },+ steps: {+ status: "available",+ value: [+ { ID: "11", NAME: "backup", TYPE: 6, COMMAND: "native generated backup command", DESCRIBE: "keep backup" },+ { ID: "12", NAME: "sql", TYPE: 0, COMMAND: "SELECT 1;", RETRY_INTERVAL: 0 },+ ],+ },+ schedules: { status: "available", value: [{ ID: "21", NAME: "daily", ENABLE: true, DURING_END_DATE: null, DESCRIBE: "keep schedule" }] },+ running: { status: "unknown", reason: "not_readable" },+ history: { status: "empty" },+ sources: {},+ };+}++describe("Dameng configuration draft", () => {+ it("rebases a renamed parent and child only by frozen identities while retaining unfinished fields", () => {+ const before = damengDetails();+ const after = damengDetails();+ after.snapshot.ref = { kind: "dameng-native", scope, jobId: "41", name: "Renamed Job" };+ after.snapshot.definition = { status: "available", value: { NAME: "Renamed Job", ENABLE: false } };+ if (after.steps.status === "available") after.steps.value[1]!.NAME = "renamed_sql";+ after.schedules = { status: "empty" };+ after.sources.schedules = { source: "SYSJOB.SYSJOBSCHEDULES", coverage: "database" };+ const draft: NativeJobDamengEditDraft = {+ attributes: { NAME: { kind: "set", value: "Renamed Job" }, ENABLE: { kind: "set", value: true } },+ steps: [{ kind: "update", name: "sql", attributes: { NAME: { kind: "set", value: "renamed_sql" }, COMMAND_INPUT: { kind: "set", value: "SELECT 1;" }, RETRY_INTERVAL: { kind: "set", value: 7 } } }],+ schedules: [{ kind: "drop", name: "daily" }],+ };+ const status: NativeJobOperationStatus = { operationId: "rename", target: after.snapshot.ref, state: "finished", outcome: "partial", cancelRequested: false, steps: [], reason: "enable_failed" };+ const corrected = rebaseNativeJobDamengDraft(before, after, draft, status, "Owner");+ expect(corrected.attributes).toEqual({ ENABLE: { kind: "set", value: true } });+ expect(corrected.steps).toEqual([{ kind: "update", name: "renamed_sql", attributes: { RETRY_INTERVAL: { kind: "set", value: 7 } } }]);+ expect(corrected.schedules).toEqual([]);+ const unknown = rebaseNativeJobDamengDraft(before, after, draft, { ...status, outcome: "unknown" }, "Owner");+ expect(unknown.attributes?.NAME).toEqual(draft.attributes?.NAME);+ expect(unknown.schedules).toEqual([{ kind: "drop", name: "daily", attributes: {} }]);+ expect(draft.steps?.[0]?.name).toBe("sql");+ after.nativeIdentity = { status: "available", value: { DBX_JOB_ID: "41", DBX_CREATED_AT: "replacement" } };+ expect(() => rebaseNativeJobDamengDraft(before, after, draft, status, "Owner")).toThrow("native_job_identity_mismatch");+ });++ it("does not use rounded numeric child identities to adopt a retained create", () => {+ const details = damengDetails();+ details.steps = { status: "available", value: [{ ID: 9007199254740992, NAME: "new_step" }] };+ const draft: NativeJobDamengEditDraft = { steps: [{ kind: "add", name: "new_step", attributes: {} }] };+ const status: NativeJobOperationStatus = { operationId: "create", target: details.snapshot.ref, state: "finished", outcome: "partial", cancelRequested: false, steps: [], reason: null, createdChildren: [{ partition: "steps", name: "new_step", id: "9007199254740992" }] };+ expect(rebaseNativeJobDamengCreation(details, draft, status).steps?.[0]?.kind).toBe("add");+ details.steps.value[0]!.DBX_CHILD_ID = "9007199254740992";+ expect(rebaseNativeJobDamengCreation(details, draft, status).steps?.[0]?.kind).toBe("update");+ });+ it("builds native creation with one activation choice and all steps without inventing a target", () => {+ const draft = reactive<NativeJobDamengEditDraft>({ attributes: { ENABLE: { kind: "set", value: false }, DESCRIBE: { kind: "clear" } }, steps: [{ kind: "add", name: "STEP1", attributes: { COMMAND_INPUT: { kind: "set", value: "BEGIN work('private'); END;" } } }], schedules: [] });+ const request = buildNativeJobDamengCreate(scope, "New_job", draft);+ expect(request).toEqual({+ action: "create",+ scope,+ definition: {+ kind: "dameng-native",+ name: "New_job",+ enabled: false,+ configuration: { attributes: [{ name: "DESCRIBE", change: { kind: "clear" } }], steps: [{ kind: "add", name: "STEP1", attributes: [{ name: "COMMAND_INPUT", change: { kind: "set", value: "BEGIN work('private'); END;" } }] }], schedules: [] },+ },+ });+ draft.steps![0]!.attributes!.COMMAND_INPUT = { kind: "set", value: "changed after preview" };+ expect(JSON.stringify(request)).toContain("BEGIN work('private'); END;");+ expect(request).not.toHaveProperty("target");+ expect(request.scope).not.toBe(scope);+ expect(buildNativeJobDamengCreate(scope, "Default_job", {}).definition).toMatchObject({ enabled: true });+ });++ it("rejects existing-child actions and invalid activation values before a create preview", () => {+ expect(() => buildNativeJobDamengCreate(scope, "New_job", { steps: [{ kind: "drop", name: "old" }] })).toThrow("native_job_creation_children_must_be_new");+ expect(() => buildNativeJobDamengCreate(scope, "New_job", { attributes: { ENABLE: { kind: "clear" } } })).toThrow("native_job_attribute_type_invalid");+ expect(() => buildNativeJobDamengCreate(scope, "New_job", { attributes: { ENABLE: { kind: "set", value: "true" } } })).toThrow("native_job_attribute_type_invalid");+ });++ it("rebases only acknowledged created child identities and keeps the remaining input", () => {+ const details = damengDetails();+ const draft: NativeJobDamengEditDraft = {+ steps: [{ kind: "add", name: "sql", attributes: { COMMAND_INPUT: { kind: "set", value: "SELECT 1;" }, RETRY_INTERVAL: { kind: "set", value: 7 } } }],+ schedules: [{ kind: "add", name: "new_daily", attributes: { DURING_START_DATE: { kind: "set", value: "CURDATE" } } }],+ };+ const status: NativeJobOperationStatus = { operationId: "operation", target: details.snapshot.ref, state: "finished", outcome: "partial", cancelRequested: false, steps: [], reason: "native_failure", createdChildren: [{ partition: "steps", name: "sql", id: "12" }] };+ const corrected = rebaseNativeJobDamengCreation(details, draft, status);+ expect(corrected.steps?.[0]?.kind).toBe("update");+ expect(corrected.schedules?.[0]?.kind).toBe("add");+ expect(buildNativeJobDamengEdit(details, corrected).configuration.steps).toEqual([{ kind: "update", name: "sql", attributes: [{ name: "RETRY_INTERVAL", change: { kind: "set", value: 7 } }] }]);+ expect(draft.steps?.[0]?.kind).toBe("add");+ status.createdChildren![0]!.id = "replacement";+ expect(rebaseNativeJobDamengCreation(details, draft, status).steps?.[0]?.kind).toBe("add");+ status.createdChildren = [];+ expect(rebaseNativeJobDamengCreation(details, draft, status).steps?.[0]?.kind).toBe("add");+ });++ it("does not turn native integer flags into unnecessary checkbox edits", () => {+ const details = damengDetails();+ if (details.snapshot.definition.status === "available") details.snapshot.definition.value.ENABLE = 1;+ if (details.steps.status === "available") details.steps.value[1]!.APPEND_FLAG = 0;+ const request = buildNativeJobDamengEdit(details, { attributes: { ENABLE: { kind: "set", value: true } }, steps: [{ kind: "update", name: "sql", attributes: { APPEND_FLAG: { kind: "set", value: false } } }] });+ expect(request.configuration).toEqual({ attributes: [], steps: [], schedules: [] });+ });+ it("changes only selected child fields and does not turn a generated command into native input", () => {+ const details = damengDetails();+ const before = structuredClone(details);+ const request = buildNativeJobDamengEdit(details, {+ attributes: { DESCRIBE: { kind: "set", value: "keep job" } },+ steps: [{ kind: "update", name: "backup", attributes: { DESCRIBE: { kind: "set", value: "new description" } } }],+ });+ expect(request.configuration).toEqual({ attributes: [], steps: [{ kind: "update", name: "backup", attributes: [{ name: "DESCRIBE", change: { kind: "set", value: "new description" } }] }], schedules: [] });+ expect(details).toEqual(before);+ });++ it("omits already applied SQL edits and keeps explicit backup input even if it resembles catalog text", () => {+ const details = damengDetails();+ const request = buildNativeJobDamengEdit(details, {+ steps: [+ { kind: "update", name: "sql", attributes: { COMMAND_INPUT: { kind: "set", value: "SELECT 1;" }, RETRY_INTERVAL: { kind: "set", value: 0 } } },+ { kind: "update", name: "backup", attributes: { COMMAND_INPUT: { kind: "set", value: "native generated backup command" } } },+ ],+ });+ expect(request.configuration.steps).toEqual([{ kind: "update", name: "backup", attributes: [{ name: "COMMAND_INPUT", change: { kind: "set", value: "native generated backup command" } }] }]);+ const switched = buildNativeJobDamengEdit(details, { steps: [{ kind: "update", name: "sql", attributes: { TYPE: { kind: "set", value: 6 }, COMMAND_INPUT: { kind: "set", value: "SELECT 1;" } } }] });+ expect(switched.configuration.steps?.[0]).toMatchObject({+ attributes: [+ { name: "TYPE", change: { value: 6 } },+ { name: "COMMAND_INPUT", change: { value: "SELECT 1;" } },+ ],+ });+ });++ it("preserves add/drop intent and clear semantics without sending unchanged schedules", () => {+ const details = damengDetails();+ const request = buildNativeJobDamengEdit(details, {+ steps: [+ { kind: "add", name: "next_step", attributes: { COMMAND_INPUT: { kind: "set", value: "SELECT 2;" } } },+ { kind: "drop", name: "sql" },+ ],+ schedules: [{ kind: "update", name: "daily", attributes: { DURING_END_DATE: { kind: "clear" } } }],+ });+ expect(request.configuration.steps).toEqual([+ { kind: "add", name: "next_step", attributes: [{ name: "COMMAND_INPUT", change: { kind: "set", value: "SELECT 2;" } }] },+ { kind: "drop", name: "sql" },+ ]);+ expect(request.configuration.schedules).toEqual([]);+ });++ it.each(["denied", "unknown", "truncated"] as const)("keeps a %s step partition from being rewritten while allowing a schedule-only edit", (status) => {+ const details = damengDetails();+ details.steps = status === "truncated" ? { status, value: [], limit: 1 } : { status, reason: "not_available" };+ expect(() => buildNativeJobDamengEdit(details, { steps: [{ kind: "drop", name: "sql" }] })).toThrow("native_job_metadata_incomplete");+ expect(buildNativeJobDamengEdit(details, { schedules: [{ kind: "drop", name: "daily" }] }).configuration.schedules).toEqual([{ kind: "drop", name: "daily" }]);+ });++ it("detaches nested drafts and refuses missing children instead of guessing after a refresh", () => {+ const details = reactive(damengDetails());+ const input = reactive({ kind: "set" as const, value: "original body" });+ const request = buildNativeJobDamengEdit(details, { steps: [{ kind: "add", name: "new_step", attributes: { COMMAND_INPUT: input } }] });+ input.value = "later body";+ details.snapshot.ref.scope.contextId = "new context";+ expect(request.target.scope.contextId).toBe("context-1");+ expect(request.configuration.steps?.[0]).toMatchObject({ attributes: [{ change: { value: "original body" } }] });+ expect(() => buildNativeJobDamengEdit(details, { steps: [{ kind: "drop", name: "missing" }] })).toThrow("native_job_child_missing");+ });+});++describe("native Job edit draft", () => {+ it("changes only the chosen field without requiring unreadable arguments or rewriting opaque values", () => {+ const snapshot: NativeJobSnapshot = {+ ref: scheduler("OWNER", "Job"),+ revision: "server-revision-1",+ definition: { status: "available", value: { comments: "old", end_date: null, advanced: { raw: ["unchanged", 7] } } },+ arguments: { status: "denied", reason: "ORA-01031" },+ };+ const before = structuredClone(snapshot);+ expect(+ buildNativeJobEdit(snapshot, {+ attributes: { comments: { kind: "set", value: "new" }, end_date: { kind: "keep" } },+ }),+ ).toEqual({+ action: "update",+ target: snapshot.ref,+ baseline: "server-revision-1",+ attributes: [{ name: "comments", change: { kind: "set", value: "new" } }],+ arguments: [],+ });+ expect(snapshot).toEqual(before);+ });++ it("preserves unset, inherited, NULL and opaque arguments while sending only requested overrides", () => {+ const snapshot: NativeJobSnapshot = {+ ref: scheduler("OWNER", "Job"),+ revision: "server-revision-2",+ definition: { status: "available", value: {} },+ arguments: {+ status: "available",+ value: [+ { position: 1, dataType: "VARCHAR2", value: { kind: "inherit" }, editable: true },+ { position: 2, dataType: "VARCHAR2", value: { kind: "value", value: "text" }, editable: true },+ { position: 3, dataType: "ANYDATA", value: { kind: "opaque", value: { native: "unchanged" } }, editable: false },+ { position: 4, dataType: "NUMBER", value: { kind: "null" }, editable: true },+ { position: 5, dataType: "DATE", value: { kind: "unset" }, editable: true },+ ],+ },+ };+ const before = structuredClone(snapshot);+ const edit = buildNativeJobEdit(snapshot, {+ arguments: [+ { position: 2, value: { kind: "inherit" } },+ { position: 1, value: { kind: "null" } },+ { position: 3, value: { kind: "opaque", value: { native: "unchanged" } } },+ { position: 4, value: { kind: "null" } },+ { position: 5, value: { kind: "unset" } },+ ],+ });+ expect(edit.arguments).toEqual([+ { position: 1, value: { kind: "null" } },+ { position: 2, value: { kind: "inherit" } },+ ]);+ expect(snapshot).toEqual(before);+ });++ it.each(["denied", "unknown", "truncated"] as const)("blocks argument edits on %s metadata and retains the draft", (status) => {+ const snapshot: NativeJobSnapshot = {+ ref: scheduler("OWNER", "Job"),+ revision: "baseline",+ definition: { status: "available", value: { comments: "old" } },+ arguments: status === "truncated" ? { status, value: [], limit: 1 } : { status, reason: "not available" },+ };+ const draft = { arguments: [{ position: 1, value: { kind: "null" as const } }] };+ const before = structuredClone(draft);+ expect(() => buildNativeJobEdit(snapshot, draft)).toThrow("native_job_arguments_unavailable");+ expect(draft).toEqual(before);+ expect(buildNativeJobEdit(snapshot, { attributes: { comments: { kind: "set", value: "new" } } }).attributes).toHaveLength(1);+ });++ it("keeps opaque arguments read-only without making the rest of the Job read-only", () => {+ const snapshot: NativeJobSnapshot = {+ ref: scheduler("OWNER", "Job"),+ revision: "baseline",+ definition: { status: "available", value: { comments: "old" } },+ arguments: { status: "available", value: [{ position: 1, dataType: "ANYDATA", value: { kind: "opaque", value: "raw" }, editable: false }] },+ };+ expect(() => buildNativeJobEdit(snapshot, { arguments: [{ position: 1, value: { kind: "null" } }] })).toThrow("native_job_argument_not_editable");+ expect(buildNativeJobEdit(snapshot, { attributes: { comments: { kind: "set", value: "new" } } }).arguments).toEqual([]);+ });++ it("keeps clear, keep and unchanged compound values out of unrelated updates", () => {+ const snapshot: NativeJobSnapshot = {+ ref: scheduler("OWNER", "Job"),+ revision: "baseline",+ definition: { status: "available", value: { end_date: "2030-01-01T00:00:00+08:00", comments: null, advanced: { a: 1, b: [true, null] } } },+ arguments: { status: "empty" },+ };+ expect(+ buildNativeJobEdit(snapshot, {+ attributes: {+ end_date: { kind: "clear" },+ comments: { kind: "clear" },+ advanced: { kind: "set", value: { b: [true, null], a: 1 } },+ },+ }).attributes,+ ).toEqual([{ name: "end_date", change: { kind: "clear" } }]);+ });++ it("detaches the request from reactive targets and draft values before selection or input changes", () => {+ const snapshot = reactive<NativeJobSnapshot>({+ ref: scheduler("OWNER", "Original"),+ revision: "baseline",+ definition: { status: "available", value: {} },+ arguments: { status: "empty" },+ });+ const value = reactive({ values: ["confirmed"] });+ const edit = buildNativeJobEdit(snapshot, { attributes: { advanced: { kind: "set", value } } });+ snapshot.ref.scope.contextId = "different-context";+ value.values[0] = "later input";+ expect(edit.target.scope.contextId).toBe("context-1");+ expect(edit.attributes).toEqual([{ name: "advanced", change: { kind: "set", value: { values: ["confirmed"] } } }]);+ });+});diff --git a/apps/desktop/src/lib/__tests__/database/objectDependencyDetails.spec.ts b/apps/desktop/src/lib/__tests__/database/objectDependencyDetails.spec.tsindex d8523859cf..ba4adb4c71 100644--- a/apps/desktop/src/lib/__tests__/database/objectDependencyDetails.spec.ts+++ b/apps/desktop/src/lib/__tests__/database/objectDependencyDetails.spec.ts@@ -1,13 +1,32 @@import { describe, expect, it } from "vitest";-import { isObjectDependencySection, objectDependencyNavigation, objectDependencyRows, objectDependencySql, objectDependencyTarget, objectForeignKeyRows, objectOwnershipRows, relationObjectNavigation, type ObjectDependencyRow } from "@/lib/database/objectDependencyDetails";+import { isObjectDependencySection, objectDependencyNavigation, objectDependencyRows, objectDependencySql, objectDependencyTarget, objectRelationKinds, objectForeignKeyRows, objectOwnershipRows, relationObjectNavigation, type ObjectDependencyRow } from "@/lib/database/objectDependencyDetails";import { oracleObjectDependenciesSql } from "@/lib/database/oracleObjectDependencies";import { normalizeOracleNavigationTarget, sqlObjectNavigationContextTarget, sqlObjectNavigationSourceKind } from "@/lib/sql/sqlNavigation";-import type { QueryResult, QueryTab } from "@/types/database";+import type { QueryResult, QueryTab, TriggerInfo } from "@/types/database";const details = { connectionId: "original", database: "ORCL", schema: "Mixed.Schema", name: "Mixed.P", objectType: "PROCEDURE" as const, section: "dependencies" as const };const row: ObjectDependencyRow = { direction: "DEPENDS_ON", name: "Mixed.Table", schema: "Other.Schema", type: "TABLE", dependencyType: "HARD", link: "", sourceType: "PROCEDURE" };describe("object dependency details", () => {+ it("uses the existing dependency query only for a matching exact DM8 trigger, never DM routines or a compatibility label", () => {+ const trigger: TriggerInfo = { name: " Tr'ig ", timing: "BEFORE", event: "INSERT", oracle_metadata: { contractVersion: 1, identityMode: "exact", engine: "dm", engineVersion: "8.1.3", owner: " Owner ", name: " Tr'ig ", objectId: "trigger-id", scope: "TABLE", reads: {} } };+ const triggerDetails = { ...details, schema: " Owner ", name: trigger.name, objectType: "TRIGGER" as const, catalog: " Catalog " };+ const target = objectDependencyTarget(triggerDetails, "dameng", trigger);+ expect(target).toEqual({ connectionId: details.connectionId, database: details.database, schema: " Owner ", name: " Tr'ig ", objectType: "TRIGGER", catalog: " Catalog ", databaseType: "dameng" });+ expect(objectRelationKinds(target!)).toEqual(["dependencies"]);+ expect(() => objectDependencySql(target!, "ownership")).toThrow("not supported");+ expect(() => objectDependencySql(target!, "foreignKeys")).toThrow("not supported");+ expect(objectDependencySql(target!)).toContain("d.NAME = ' Tr''ig '");+ expect(objectDependencySql(target!)).toContain("d.TYPE = 'TRIGGER'");+ expect(objectDependencySql(target!)).toContain("d.REFERENCED_TYPE = 'TRIGGER'");+ expect(objectDependencyTarget(details, "dameng", trigger)).toBeUndefined();+ expect(objectDependencyTarget(triggerDetails, "dameng")).toBeUndefined();+ expect(objectDependencyTarget(triggerDetails, "oracle", trigger)).toBeUndefined();+ expect(objectDependencyTarget({ ...triggerDetails, schema: "different" }, "dameng", trigger)).toBeUndefined();+ trigger.oracle_metadata!.engineVersion = "6.0";+ expect(objectDependencyTarget(triggerDetails, "dameng", trigger)).toBeUndefined();+ });+it("keeps captured identity and reuses the provider SQL without changing quoting or package scope", () => {const target = objectDependencyTarget(details, "oceanbase-oracle")!;expect(target).toEqual({ connectionId: "original", database: "ORCL", schema: "Mixed.Schema", name: "Mixed.P", objectType: "PROCEDURE" });diff --git a/apps/desktop/src/lib/__tests__/database/oracleObjectDependencies.spec.ts b/apps/desktop/src/lib/__tests__/database/oracleObjectDependencies.spec.tsindex 4bc0a5f54e..e8d8b3fb61 100644--- a/apps/desktop/src/lib/__tests__/database/oracleObjectDependencies.spec.ts+++ b/apps/desktop/src/lib/__tests__/database/oracleObjectDependencies.spec.ts@@ -49,6 +49,9 @@ describe("Oracle object dependencies", () => {expect(oracleDependencyProvider.supports(node({ type: "procedure", parentType: "package", parentName: "PKG" }))).toBe(false);expect(oracleDependencyProvider.supports(node({ type: "procedure", parentType: "package", parentName: "PKG", parentSchema: undefined }))).toBe(false);expect(oracleDependencyProvider.supports(node({ type: "column" }))).toBe(false);- expect(oracleDependencyProvider.supports(node({ type: "trigger" }))).toBe(true);+ expect(oracleDependencyProvider.supports(node({ type: "trigger" }))).toBe(false);+ const trigger = node({ type: "trigger", meta: { name: "RUN_JOB", event: "INSERT", timing: "BEFORE", oracle_metadata: { contractVersion: 1, identityMode: "exact", engine: "oracle", owner: "APP", name: "RUN_JOB", scope: "TABLE", reads: {} } } });+ expect(oracleDependencyProvider.supports(trigger)).toBe(true);+ expect(oracleDependencyProvider.buildQuery(trigger)).toContain("d.TYPE = 'TRIGGER'");});});diff --git a/apps/desktop/src/lib/__tests__/database/oracleTriggerPlan.spec.ts b/apps/desktop/src/lib/__tests__/database/oracleTriggerPlan.spec.tsnew file mode 100644index 0000000000..948ccd9ba7--- /dev/null+++ b/apps/desktop/src/lib/__tests__/database/oracleTriggerPlan.spec.ts@@ -0,0 +1,695 @@+import { createPinia, setActivePinia } from "pinia";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import type { ConnectionConfig, ObjectSource } from "@/types/database";+import type { BackendError } from "@/lib/backend/errorUtils";++const mocks = vi.hoisted(() => ({ source: vi.fn(), query: vi.fn(), objects: vi.fn(), unlockState: vi.fn(), prepareSql: vi.fn(), dropSql: vi.fn(), invoke: vi.fn() }));+vi.mock("@tauri-apps/api/core", () => ({ invoke: mocks.invoke }));+vi.mock("@/lib/backend/api", () => ({+ getObjectSource: mocks.source,+ executeQuery: mocks.query,+ listObjects: mocks.objects,+ prepareOracleTriggerSql: mocks.prepareSql,+ buildDropObjectSql: mocks.dropSql,+ connectionWriteUnlockState: mocks.unlockState,+ deleteSchemaCachePrefix: vi.fn().mockResolvedValue(undefined),+ listInstalledAgents: vi.fn().mockResolvedValue([]),+}));++const target = { connectionId: "trigger-plan", database: "service", catalog: "container", owner: " Trigger Owner ", name: ' Tr"ig ', executionSchema: " Execution Owner " };++function source(enabled: boolean): ObjectSource {+ return {+ name: target.name,+ schema: target.owner,+ object_type: "TRIGGER",+ source: "BEGIN :NEW.V := 7; END;",+ editable: false,+ trigger: {+ name: target.name,+ event: "UPDATE",+ timing: "INSTEAD OF",+ enabled,+ valid: false,+ oracle_metadata: {+ contractVersion: 1,+ identityMode: "exact",+ engine: "oceanbase-oracle",+ engineVersion: "4.2.5.7_107",+ owner: target.owner,+ name: target.name,+ objectId: "9007199254740993",+ lastDdlTime: "2026-10-21 08:00:00",+ scope: "VIEW",+ parent: { owner: " Parent Owner ", name: " View ", objectType: "VIEW" },+ definition: { origin: "catalog-body", format: "body", complete: false },+ errors: [{ sequence: 1, line: 3, position: 7, text: "Missing procedure" }],+ reads: { identity: { state: "available" }, scope: { state: "available" }, parent: { state: "available" }, enabled: { state: "available" }, validity: { state: "available" }, definition: { state: "denied" }, errors: { state: "available" } },+ },+ },+ };+}++beforeEach(async () => {+ vi.resetModules();+ vi.clearAllMocks();+ mocks.source.mockReset();+ mocks.query.mockReset();+ mocks.prepareSql.mockReset();+ mocks.dropSql.mockReset().mockResolvedValue('DROP TRIGGER " Trigger Owner "." Tr""ig ";');+ mocks.unlockState.mockReset().mockResolvedValue(0);+ const data = new Map<string, string>();+ vi.stubGlobal("localStorage", { getItem: (key: string) => data.get(key) ?? null, setItem: (key: string, value: string) => data.set(key, value), removeItem: (key: string) => data.delete(key) });+ setActivePinia(createPinia());+ const { useConnectionStore } = await import("@/stores/connectionStore");+ const store = useConnectionStore();+ store.connections = [{ id: target.connectionId, name: "Trigger test", db_type: "oceanbase-oracle", username: " Execution Owner ", database: "service" } as ConnectionConfig];+ store.connectedIds.add(target.connectionId);+ mocks.query.mockResolvedValue({ columns: [], rows: [], affected_rows: 0, execution_time_ms: 1 });+});++describe("Oracle-family trigger action plans", () => {+ afterEach(() => vi.unstubAllGlobals());++ it.each([false, true])("preserves each trigger execution schema and the legacy statement's captured/default schema (explicit unset=%s)", async (explicitUnset) => {+ const second = { ...target, owner: "Other.Owner", name: "OtherTrigger", executionSchema: "Other.Execution" };+ const gone = new Set<string>();+ const key = (owner: string, name: string) => JSON.stringify([owner, name]);+ const quote = (name: string) => `"${name.replaceAll('"', '""')}"`;+ mocks.source.mockImplementation(async (_id, _db, owner, name) => {+ const raw = source(false);+ raw.name = raw.trigger!.name = name;+ raw.schema = raw.trigger!.oracle_metadata!.owner = owner;+ raw.trigger!.oracle_metadata!.name = name;+ raw.trigger!.oracle_metadata!.objectId = gone.has(key(owner, name)) ? null : `${owner}-physical-id`;+ raw.trigger!.oracle_metadata!.reads.identity = { state: gone.has(key(owner, name)) ? "empty" : "available" };+ return raw;+ });+ mocks.dropSql.mockImplementation(async (input) => `DROP TRIGGER ${quote(input.schema)}.${quote(input.name)};`);+ mocks.query.mockImplementation(async (_id, _db, sql) => {+ if (sql.startsWith("SELECT USER")) return { columns: ["SESSION_USER"], rows: [["Login.Owner"]] };+ if (sql.includes("DBA_OBJECTS")) return { columns: ["OWNER", "OBJECT_NAME"], rows: [] };+ if (sql.startsWith("SELECT")) return { columns: ["OWNER", "OBJECT_NAME", "OBJECT_TYPE", "OBJECT_ID"], rows: [[" Parent Owner ", " View ", "VIEW", "parent-id"]] };+ for (const item of [target, second]) if (sql === `DROP TRIGGER ${quote(item.owner)}.${quote(item.name)};`) gone.add(key(item.owner, item.name));+ return { columns: [], rows: [] };+ });+ const { prepareOracleTriggerPlan, prepareOracleTriggerDropBatchPlan, executeOracleTriggerDropBatchPlan } = await import("@/lib/database/oracleTriggerPlan");+ const firstPlan = await prepareOracleTriggerPlan({ target, action: "delete" });+ const secondPlan = await prepareOracleTriggerPlan({ target: second, action: "delete" });+ const legacy = { id: "legacy", sql: 'DROP TRIGGER "Legacy.Owner"."Legacy";', ...(explicitUnset ? { executionSchema: undefined } : {}) };+ const plan = prepareOracleTriggerDropBatchPlan({ target, engine: "oceanbase-oracle", entries: [{ id: "first", sql: firstPlan.steps[0].sql, triggerPlan: firstPlan }, legacy, { id: "second", sql: secondPlan.steps[0].sql, triggerPlan: secondPlan }] });+ const result = await executeOracleTriggerDropBatchPlan(plan, { confirmed: true, isCurrent: () => true, timeoutSecs: 0 });+ expect(result.steps.map((step) => step.state)).toEqual(["committed", "committed", "committed"]);+ expect(result.steps[1].elapsedMs).toBeTypeOf("number");+ const writes = mocks.query.mock.calls.filter((call) => !call[2].startsWith("SELECT"));+ expect(writes.map((call) => call[3])).toEqual([target.executionSchema, explicitUnset ? undefined : target.executionSchema, second.executionSchema]);+ expect(writes.every((call) => call[4] === undefined && call[5].catalog === target.catalog)).toBe(true);+ expect(writes.map((call) => call[5].timeoutSecs)).toEqual([0, 0, 0]);+ await expect(executeOracleTriggerDropBatchPlan(plan, { confirmed: true, isCurrent: () => true })).rejects.toThrow(/remaining deletions/i);+ expect(mocks.query.mock.calls.filter((call) => !call[2].startsWith("SELECT"))).toHaveLength(3);+ });++ it.each(["tauri", "http"] as const)("sends catalog through real %s query options, not the execution identifier", async (kind) => {+ const { useConnectionStore } = await import("@/stores/connectionStore");+ useConnectionStore().getConfig(target.connectionId)!.query_timeout_secs = 0;+ const envelopes: Record<string, unknown>[] = [];+ let enabled = false;+ mocks.source.mockImplementation(async () => source(enabled));+ const execute = (payload: Record<string, unknown>) => {+ envelopes.push(payload);+ enabled = true;+ return { columns: [], rows: [] };+ };+ mocks.invoke.mockImplementation(async (_command, payload) => execute(payload));+ vi.stubGlobal(+ "fetch",+ vi.fn(async (_url, init) => ({ ok: true, json: async () => execute(JSON.parse(init.body)) })),+ );+ const transport = kind === "tauri" ? await import("@/lib/backend/tauri") : await import("@/lib/backend/http");+ mocks.query.mockImplementation(transport.executeQuery);+ const { prepareOracleTriggerPlan, executeOracleTriggerPlan } = await import("@/lib/database/oracleTriggerPlan");+ const result = await executeOracleTriggerPlan(await prepareOracleTriggerPlan({ target, action: "enable" }), { confirmed: true });+ expect(result.steps[0]).toMatchObject({ state: "committed", verification: "applied" });+ expect(envelopes).toHaveLength(1);+ expect(envelopes[0]).toMatchObject({ connectionId: target.connectionId, database: target.database, schema: target.executionSchema, catalog: target.catalog, timeoutSecs: 0 });+ expect(envelopes[0].executionId).toBeUndefined();+ });++ it("rejects a same-name replacement of the identity already shown by the calling form", async () => {+ const changed = source(false);+ changed.trigger!.oracle_metadata!.objectId = "replacement-id";+ mocks.source.mockResolvedValue(changed);+ const { prepareOracleTriggerPlan } = await import("@/lib/database/oracleTriggerPlan");+ await expect(prepareOracleTriggerPlan({ target, action: "enable", expectedObjectId: "9007199254740993" })).rejects.toThrow(/replaced|identity/i);+ expect(mocks.query).not.toHaveBeenCalled();+ });++ it("creates the new table before obtaining its real parent ID, then sends the exact confirmed trigger", async () => {+ const triggerName = "new_trigger",+ parentOwner = " Parent Owner ",+ tableName = "NewTable";+ const tableSql = 'CREATE TABLE " Parent Owner "."NewTable" ("ID" NUMBER)';+ const triggerSql = 'CREATE TRIGGER " Trigger Owner "."new_trigger" BEFORE INSERT ON " Parent Owner "."NewTable" DISABLE BEGIN NULL; END;';+ let tableExists = false,+ triggerExists = false;+ mocks.source.mockImplementation(async () => {+ const raw = source(false);+ raw.name = triggerName;+ raw.source = triggerExists ? triggerSql : "";+ raw.trigger!.name = triggerName;+ raw.trigger!.statement = "BEGIN NULL; END;";+ raw.trigger!.valid = true;+ Object.assign(raw.trigger!.oracle_metadata!, {+ name: triggerName,+ objectId: triggerExists ? "created-trigger-id" : null,+ scope: triggerExists ? "TABLE" : "UNKNOWN",+ parent: triggerExists ? { owner: parentOwner, name: tableName, objectType: "TABLE" } : null,+ definition: { origin: "ALL_SOURCE", format: "ddl", complete: triggerExists },+ });+ raw.trigger!.oracle_metadata!.reads.identity = { state: triggerExists ? "available" : "empty" };+ raw.trigger!.oracle_metadata!.reads.definition = { state: triggerExists ? "available" : "empty" };+ return raw;+ });+ mocks.prepareSql.mockImplementation(async (input) => ({ definition: input.source, comparisonSource: input.source, header: { scope: "RELATION", owner: parentOwner, name: tableName, viewOnly: false, pluggable: false }, requiresStateRestore: false }));+ mocks.query.mockImplementation(async (_id, _db, sql) => {+ if (sql.startsWith("SELECT")) {+ if (!tableExists) throw new Error("The parent does not exist before CREATE TABLE");+ return { columns: ["OWNER", "OBJECT_NAME", "OBJECT_TYPE", "OBJECT_ID"], rows: [[parentOwner, tableName, "TABLE", "new-parent-id"]] };+ }+ if (sql === tableSql) tableExists = true;+ if (sql === triggerSql) triggerExists = true;+ return { columns: [], rows: [], affected_rows: 0 };+ });+ const { prepareOracleTriggerStructurePlan } = await import("@/lib/database/oracleTriggerStructurePlan");+ const { executeOracleTriggerStructurePlan } = await import("@/lib/database/oracleTriggerPlan");+ const plan = await prepareOracleTriggerStructurePlan({+ target: { ...target, owner: parentOwner, tableName, parentType: "TABLE", databaseType: "oceanbase-oracle", newTable: true },+ statements: [tableSql, triggerSql],+ operations: [{ draftId: "new", action: "create", owner: target.owner, name: triggerName, statementIndex: 1, statementCount: 1, enabled: false }],+ triggers: [{ id: "new", name: triggerName, timing: "BEFORE", event: "INSERT", statement: "BEGIN NULL; END;", enabled: false, markedForDrop: false, oracleExact: { owner: target.owner, parentType: "TABLE" } }],+ });+ expect(mocks.query).not.toHaveBeenCalled();+ const result = await executeOracleTriggerStructurePlan(plan, { confirmed: true, isCurrent: () => true });+ expect(result.steps.map((step) => step.state)).toEqual(["committed", "committed"]);+ for (const call of mocks.query.mock.calls) {+ expect(call[4]).toBeUndefined();+ expect(call[5]).toMatchObject({ catalog: target.catalog });+ }+ expect(mocks.query.mock.calls.filter((call) => !call[2].startsWith("SELECT")).map((call) => call[2])).toEqual([tableSql, triggerSql]);+ await expect(executeOracleTriggerStructurePlan(plan, { confirmed: true, isCurrent: () => true })).rejects.toThrow(/already attempted/i);+ });++ it.each([true, false])("only permits a lossless structured rename and stops after a rejected CREATE (structured=%s)", async (structured) => {+ const old = source(false);+ old.source = 'CREATE OR REPLACE TRIGGER " Trigger Owner "." Tr""ig " INSTEAD OF UPDATE ON " Parent Owner "." View " BEGIN NULL; END;';+ if (!structured) old.source = old.source.replace(" BEGIN", " FOLLOWS OTHER_TRIGGER BEGIN");+ old.trigger!.statement = "BEGIN NULL; END;";+ old.trigger!.valid = true;+ old.trigger!.oracle_metadata!.definition = { origin: "ALL_SOURCE", format: "ddl", complete: true };+ old.trigger!.oracle_metadata!.reads.definition = { state: "available" };+ let oldExists = true;+ const newName = "NewTrigger",+ createSql = 'CREATE TRIGGER " Trigger Owner "."NewTrigger" INSTEAD OF UPDATE ON " Parent Owner "." View " DISABLE BEGIN NULL; END;',+ dropSql = 'DROP TRIGGER " Trigger Owner "." Tr""ig ";';+ mocks.source.mockImplementation(async (_id, _db, _owner, name) => {+ if (name === target.name && oldExists) return JSON.parse(JSON.stringify(old));+ const absent = source(false);+ absent.name = name;+ absent.source = "";+ absent.trigger!.name = name;+ Object.assign(absent.trigger!.oracle_metadata!, { name, objectId: null });+ absent.trigger!.oracle_metadata!.reads.identity = { state: "empty" };+ return absent;+ });+ mocks.prepareSql.mockImplementation(async (input) => ({ definition: input.source, comparisonSource: input.source, structuredEditable: structured, header: { scope: "RELATION", owner: " Parent Owner ", name: " View ", viewOnly: true, pluggable: false }, requiresStateRestore: false }));+ mocks.dropSql.mockResolvedValue(dropSql);+ mocks.query.mockImplementation(async (_id, _db, sql) => {+ if (sql.startsWith("SELECT USER")) return { columns: ["SESSION_USER"], rows: [[target.owner]] };+ if (sql.startsWith("SELECT")) return { columns: ["OWNER", "OBJECT_NAME", "OBJECT_TYPE", "OBJECT_ID"], rows: [[" Parent Owner ", " View ", "VIEW", "parent-id"]] };+ if (sql === dropSql) {+ oldExists = false;+ return { columns: [], rows: [] };+ }+ return {+ columns: [],+ rows: [],+ execution_error: true,+ error: {+ version: 1,+ code: "DBX-JDBC-4001",+ messageKey: "backendErrors.jdbc.sqlFailed",+ messageParams: {},+ source: "jdbc-agent",+ operationOutcome: "unknown",+ detail: "ORA-01031: insufficient privileges",+ origin: { subsystem: "database", adapter: "jdbc-agent" },+ diagnostics: { category: "sql", stage: "execute", vendorCode: 1031 },+ },+ };+ });+ const { prepareOracleTriggerStructurePlan } = await import("@/lib/database/oracleTriggerStructurePlan");+ const { executeOracleTriggerStructurePlan } = await import("@/lib/database/oracleTriggerPlan");+ const preparing = prepareOracleTriggerStructurePlan({+ target: { ...target, owner: " Parent Owner ", tableName: " View ", parentType: "VIEW", databaseType: "oceanbase-oracle", newTable: false },+ statements: [dropSql, createSql, "COMMENT ON TABLE later IS 'not sent'"],+ operations: [+ { draftId: "rename", action: "delete", owner: target.owner, name: target.name, statementIndex: 0, statementCount: 1 },+ { draftId: "rename", action: "create", owner: target.owner, name: newName, statementIndex: 1, statementCount: 1, enabled: false },+ ],+ triggers: [{ id: "rename", name: newName, timing: old.trigger!.timing, event: old.trigger!.event, statement: old.trigger!.statement!, enabled: false, original: old.trigger!, markedForDrop: false, loadedOracleSource: old.source, oracleExact: { owner: target.owner, parentType: "VIEW" } }],+ });+ if (!structured) {+ await expect(preparing).rejects.toThrow("Edit the complete trigger source");+ expect(mocks.query.mock.calls.filter((call) => !call[2].startsWith("SELECT"))).toHaveLength(0);+ return;+ }+ const plan = await preparing;+ const result = await executeOracleTriggerStructurePlan(plan, { confirmed: true, isCurrent: () => true });+ expect(result.steps.map((step) => step.state)).toEqual(["committed", "rejected", "notExecuted"]);+ expect(plan.groups[0].plan?.before.raw.source).toBe(old.source);+ expect(mocks.query.mock.calls.filter((call) => !call[2].startsWith("SELECT")).map((call) => call[2])).toEqual([dropSql, createSql]);+ await expect(executeOracleTriggerStructurePlan(plan, { confirmed: true, isCurrent: () => true })).rejects.toThrow(/already attempted/i);+ });+ it("enables the exact trigger through its own owner without requiring a replaceable source", async () => {+ mocks.source.mockResolvedValueOnce(source(false)).mockResolvedValueOnce(source(false)).mockResolvedValueOnce(source(true));+ const { prepareOracleTriggerPlan, executeOracleTriggerPlan } = await import("@/lib/database/oracleTriggerPlan");+ const plan = await prepareOracleTriggerPlan({ target, action: "enable" });+ expect(plan.steps.map((step) => step.sql)).toEqual(['ALTER TRIGGER " Trigger Owner "." Tr""ig " ENABLE;']);+ const result = await executeOracleTriggerPlan(plan, { confirmed: true });+ expect(mocks.query).toHaveBeenCalledWith(target.connectionId, "service", 'ALTER TRIGGER " Trigger Owner "." Tr""ig " ENABLE;', " Execution Owner ", undefined, { catalog: "container", timeoutSecs: 60 });+ expect(result.steps[0]).toMatchObject({ state: "committed", verification: "applied" });+ expect(result.snapshot?.raw.trigger).toMatchObject({ enabled: true, valid: false });+ expect(result.snapshot?.metadata.parent).toEqual({ owner: " Parent Owner ", name: " View ", objectType: "VIEW" });+ expect(result.snapshot?.raw.source).toBe("BEGIN :NEW.V := 7; END;");+ expect(result.snapshot?.metadata.errors).toEqual([{ sequence: 1, line: 3, position: 7, text: "Missing procedure" }]);+ });++ it("retains an unknown dispatched write and recovers by read-only verification without replaying it", async () => {+ mocks.source.mockResolvedValueOnce(source(false)).mockResolvedValueOnce(source(false)).mockRejectedValueOnce(new Error("readback disconnected")).mockResolvedValueOnce(source(true)).mockResolvedValueOnce(source(true)).mockResolvedValueOnce(source(true));+ mocks.query.mockRejectedValue(new Error("response lost after dispatch"));+ const { prepareOracleTriggerPlan, executeOracleTriggerPlan, readOracleTriggerSnapshot } = await import("@/lib/database/oracleTriggerPlan");+ const plan = await prepareOracleTriggerPlan({ target, action: "enable" });+ const result = await executeOracleTriggerPlan(plan, { confirmed: true });+ expect(result.steps[0]).toMatchObject({ state: "unknown", verification: "unverified", error: "response lost after dispatch", readbackError: "readback disconnected" });+ expect(Object.isFrozen(plan.before.identity)).toBe(true);+ await expect(executeOracleTriggerPlan(plan, { confirmed: true })).rejects.toThrow();+ expect(mocks.query).toHaveBeenCalledTimes(1);+ const verified = await readOracleTriggerSnapshot(target);+ expect(verified.raw.trigger?.enabled).toBe(true);+ const remaining = await prepareOracleTriggerPlan({ target, action: "enable" });+ expect(remaining.steps).toEqual([]);+ const recovered = await executeOracleTriggerPlan(remaining, { confirmed: true });+ expect(recovered.snapshot?.raw.trigger?.enabled).toBe(true);+ expect(mocks.query).toHaveBeenCalledTimes(1);+ await expect(executeOracleTriggerPlan(plan, { confirmed: true })).rejects.toThrow();+ });++ it("keeps a verified native write committed when the auxiliary list refresh fails", async () => {+ mocks.source.mockResolvedValueOnce(source(false)).mockResolvedValueOnce(source(false)).mockResolvedValueOnce(source(true));+ mocks.objects.mockRejectedValueOnce(new Error("list refresh failed"));+ const api = await import("@/lib/backend/api");+ const { prepareOracleTriggerPlan, executeOracleTriggerPlan } = await import("@/lib/database/oracleTriggerPlan");+ const plan = await prepareOracleTriggerPlan({ target, action: "enable" });+ const result = await executeOracleTriggerPlan(plan, {+ confirmed: true,+ refresh: async (fixed) => {+ await api.listObjects(fixed.connectionId, fixed.database, fixed.owner, ["TRIGGER"]);+ },+ });+ expect(result.steps[0]).toMatchObject({ state: "committed", verification: "applied" });+ expect(result.refreshError).toBe("list refresh failed");+ expect(mocks.objects).toHaveBeenCalledWith(target.connectionId, "service", " Trigger Owner ", ["TRIGGER"]);+ expect(mocks.query).toHaveBeenCalledTimes(1);+ });++ it.each([+ {+ name: "native permission refusal",+ state: "rejected",+ receipt: "rejected",+ error: {+ version: 1,+ code: "DBX-JDBC-4001",+ messageKey: "backendErrors.jdbc.sqlFailed",+ messageParams: { stage: "execute" },+ source: "jdbc-agent",+ operationOutcome: "unknown",+ origin: { subsystem: "database", adapter: "jdbc-agent" },+ detail: "ORA-01031: insufficient privileges",+ diagnostics: { category: "sql", stage: "execute", sqlState: "42000", vendorCode: 1031 },+ } as BackendError,+ },+ {+ name: "known pre-execution failure",+ state: "notExecuted",+ receipt: "notStarted",+ error: {+ version: 1,+ code: "DBX-JDBC-1001",+ messageKey: "backendErrors.jdbc.connectionFailed",+ messageParams: { stage: "connect" },+ source: "jdbc-agent",+ operationOutcome: "not_started",+ origin: { subsystem: "database", adapter: "jdbc-agent" },+ detail: "Connection could not start",+ diagnostics: { category: "connection", stage: "connect" },+ } as BackendError,+ },+ ])("separates $name from an unknown write", async ({ error, state, receipt }) => {+ mocks.source.mockResolvedValueOnce(source(false)).mockResolvedValueOnce(source(false)).mockResolvedValueOnce(source(false));+ mocks.query.mockResolvedValueOnce({ columns: [], rows: [], affected_rows: 0, execution_time_ms: 1, execution_error: true, error });+ const { prepareOracleTriggerPlan, executeOracleTriggerPlan } = await import("@/lib/database/oracleTriggerPlan");+ const plan = await prepareOracleTriggerPlan({ target, action: "enable" });+ const result = await executeOracleTriggerPlan(plan, { confirmed: true });+ expect(result.steps[0]).toMatchObject({ state, verification: "unchanged", receipt, error: error.detail });+ expect(result.snapshot?.raw.trigger?.enabled).toBe(false);+ expect(mocks.query).toHaveBeenCalledTimes(1);+ await expect(executeOracleTriggerPlan(plan, { confirmed: true })).rejects.toThrow();+ });++ it.each([true, false])("does not request write access for an unchanged action, but preserves the guard when currently enabled=%s", async (enabled) => {+ const { useConnectionStore } = await import("@/stores/connectionStore");+ useConnectionStore().getConfig(target.connectionId)!.read_only = true;+ mocks.source.mockResolvedValue(source(enabled));+ const { useReadOnlyUnlockStore } = await import("@/stores/readOnlyUnlockStore");+ const unlock = useReadOnlyUnlockStore();+ const { prepareOracleTriggerPlan, executeOracleTriggerPlan } = await import("@/lib/database/oracleTriggerPlan");+ const plan = await prepareOracleTriggerPlan({ target, action: "enable" });+ let finished = false;+ const pending = executeOracleTriggerPlan(plan, { confirmed: true }).then((result) => {+ finished = true;+ return result;+ });+ await vi.waitFor(() => expect(finished || Boolean(unlock.pending)).toBe(true));+ const requested = unlock.pending;+ if (requested) unlock.cancel();+ const result = await pending;+ expect(Boolean(requested)).toBe(!enabled);+ if (enabled) {+ expect(result.cancelled).not.toBe(true);+ expect(result.snapshot?.raw.trigger?.enabled).toBe(true);+ expect(mocks.unlockState).not.toHaveBeenCalled();+ } else expect(result.cancelled).toBe(true);+ expect(mocks.query).not.toHaveBeenCalled();+ });++ it("compiles a verified OB trigger without a parent/full source and reports HTTP-success-but-INVALID", async () => {+ const raw = source(true);+ raw.trigger!.oracle_metadata!.scope = "UNKNOWN";+ raw.trigger!.oracle_metadata!.parent = null;+ raw.trigger!.oracle_metadata!.reads.scope = { state: "unavailable" };+ raw.trigger!.oracle_metadata!.reads.parent = { state: "unavailable" };+ mocks.source.mockResolvedValue(raw);+ const { prepareOracleTriggerPlan, executeOracleTriggerPlan } = await import("@/lib/database/oracleTriggerPlan");+ const plan = await prepareOracleTriggerPlan({ target, action: "compile" });+ expect(plan.steps.map((step) => step.sql)).toEqual(['ALTER TRIGGER " Trigger Owner "." Tr""ig " COMPILE']);+ const result = await executeOracleTriggerPlan(plan, { confirmed: true });+ expect(result.steps[0]).toMatchObject({ state: "committed", verification: "invalid", receipt: "accepted" });+ expect(result.snapshot?.raw.trigger).toMatchObject({ enabled: true, valid: false });+ expect(result.snapshot?.metadata.errors).toEqual([{ sequence: 1, line: 3, position: 7, text: "Missing procedure" }]);+ expect(mocks.query.mock.calls.map((call) => call[2])).toEqual(['ALTER TRIGGER " Trigger Owner "." Tr""ig " COMPILE']);+ });++ it("rejects a same-ID same-second source change inside a q-quoted literal before sending DDL", async () => {+ const before = source(false),+ changed = source(false),+ after = source(true);+ before.source = "BEGIN :NEW.V := q'[first\r\nsecond]'; END;";+ changed.source = "BEGIN :NEW.V := q'[first\nsecond]'; END;";+ after.source = changed.source;+ mocks.source.mockResolvedValueOnce(before).mockResolvedValueOnce(changed).mockResolvedValueOnce(after);+ const { prepareOracleTriggerPlan, executeOracleTriggerPlan } = await import("@/lib/database/oracleTriggerPlan");+ const plan = await prepareOracleTriggerPlan({ target, action: "enable" });+ await expect(executeOracleTriggerPlan(plan, { confirmed: true })).rejects.toThrow("changed");+ expect(mocks.query).not.toHaveBeenCalled();+ });++ it("keeps the requested action and execution target fixed while metadata is loading", async () => {+ let release!: (value: ObjectSource) => void;+ mocks.source.mockReturnValueOnce(+ new Promise<ObjectSource>((resolve) => {+ release = resolve;+ }),+ );+ const { prepareOracleTriggerPlan } = await import("@/lib/database/oracleTriggerPlan");+ const input = { target: { ...target }, action: "enable" as "enable" | "disable" };+ const pending = prepareOracleTriggerPlan(input);+ input.action = "disable";+ input.target.owner = "Changed Owner";+ input.target.executionSchema = "Changed Execution";+ release(source(false));+ const plan = await pending;+ expect(plan.action).toBe("enable");+ expect(plan.target).toEqual(target);+ expect(plan.steps.map((step) => step.sql)).toEqual(['ALTER TRIGGER " Trigger Owner "." Tr""ig " ENABLE;']);+ expect(mocks.query).not.toHaveBeenCalled();+ });++ it("reads DM's disabled INVALID state after a native compilation error and never sends ENABLE", async () => {+ const { useConnectionStore } = await import("@/stores/connectionStore");+ useConnectionStore().getConfig(target.connectionId)!.db_type = "jdbc";+ const before = source(true),+ after = source(false);+ before.trigger!.valid = true;+ before.trigger!.oracle_metadata!.errors = [];+ for (const raw of [before, after]) {+ raw.trigger!.oracle_metadata!.engine = "dm";+ raw.trigger!.oracle_metadata!.engineVersion = "8.1.5";+ }+ after.trigger!.oracle_metadata!.lastDdlTime = "2026-10-21 08:00:01";+ mocks.source.mockResolvedValueOnce(before).mockResolvedValueOnce(before).mockResolvedValueOnce(after);+ const error: BackendError = {+ version: 1,+ code: "DBX-JDBC-4001",+ messageKey: "backendErrors.jdbc.sqlFailed",+ messageParams: { stage: "execute" },+ source: "jdbc-agent",+ operationOutcome: "unknown",+ origin: { subsystem: "database", adapter: "jdbc-agent" },+ detail: "Trigger compilation failed",+ diagnostics: { category: "sql", stage: "execute", sqlState: "42000", vendorCode: -2007 },+ };+ mocks.query.mockResolvedValueOnce({ columns: [], rows: [], affected_rows: 0, execution_time_ms: 1, execution_error: true, error });+ const { prepareOracleTriggerPlan, executeOracleTriggerPlan } = await import("@/lib/database/oracleTriggerPlan");+ const plan = await prepareOracleTriggerPlan({ target, action: "compile" });+ const result = await executeOracleTriggerPlan(plan, { confirmed: true });+ expect(result.steps[0]).toMatchObject({ verification: "invalid", error: "Trigger compilation failed" });+ expect(result.snapshot?.raw.trigger).toMatchObject({ enabled: false, valid: false });+ expect(result.snapshot?.metadata.errors?.[0]).toMatchObject({ line: 3, position: 7, text: "Missing procedure" });+ expect(mocks.query.mock.calls.map((call) => call[2])).toEqual(['ALTER TRIGGER " Trigger Owner "." Tr""ig " COMPILE']);+ });++ it("creates only a plain CREATE on the verified independent parent and reports the actual INVALID object", async () => {+ const absent = source(false),+ created = source(false);+ absent.source = "";+ absent.trigger!.oracle_metadata!.objectId = null;+ absent.trigger!.oracle_metadata!.reads.identity = { state: "empty" };+ const definition = 'CREATE TRIGGER " Trigger Owner "." Tr""ig " INSTEAD OF UPDATE ON " Parent Owner "." View " DISABLE BEGIN NULL; END;';+ created.source = definition;+ created.trigger!.oracle_metadata!.definition = { origin: "DBMS_METADATA", format: "ddl", complete: true };+ created.trigger!.oracle_metadata!.reads.definition = { state: "available" };+ mocks.prepareSql.mockResolvedValue({ definition, comparisonSource: definition, header: { scope: "RELATION", owner: " Parent Owner ", name: " View ", viewOnly: true, pluggable: false }, inlineEnabled: false, requiresStateRestore: false });+ mocks.source.mockResolvedValueOnce(absent).mockResolvedValueOnce(absent).mockResolvedValueOnce(created);+ mocks.query.mockImplementation(async (_id, _db, sql) => (sql.startsWith("SELECT") ? { columns: ["OWNER", "OBJECT_NAME", "OBJECT_TYPE", "OBJECT_ID"], rows: [[" Parent Owner ", " View ", "VIEW", "9007199254740995"]] } : { columns: [], rows: [] }));+ const { prepareOracleTriggerPlan, executeOracleTriggerPlan } = await import("@/lib/database/oracleTriggerPlan");+ const plan = await prepareOracleTriggerPlan({ target, action: "create", source: definition, enabled: false, selection: { scope: "VIEW", owner: " Parent Owner ", name: " View " } });+ expect(plan.expectedAfter?.binding).toEqual({ scope: "VIEW", owner: " Parent Owner ", name: " View ", pluggable: false });+ expect(plan.steps.map((step) => step.sql)).toEqual([definition]);+ const result = await executeOracleTriggerPlan(plan, { confirmed: true });+ expect(result.steps[0]).toMatchObject({ state: "committed", verification: "invalid" });+ expect(mocks.query.mock.calls.filter((call) => !call[2].startsWith("SELECT")).map((call) => call[2])).toEqual([definition]);+ });++ it("blocks replacement against a different loaded source baseline and a parent rebuilt after confirmation", async () => {+ const before = source(false);+ before.source = 'CREATE TRIGGER " Trigger Owner "." Tr""ig " INSTEAD OF UPDATE ON " Parent Owner "." View " DISABLE BEGIN NULL; END;';+ before.trigger!.oracle_metadata!.definition = { origin: "DBMS_METADATA", format: "ddl", complete: true };+ before.trigger!.oracle_metadata!.reads.definition = { state: "available" };+ mocks.prepareSql.mockResolvedValue({ definition: before.source, comparisonSource: before.source, header: { scope: "RELATION", owner: " Parent Owner ", name: " View ", viewOnly: true, pluggable: false }, requiresStateRestore: false });+ mocks.source.mockResolvedValue(before);+ let parentReads = 0;+ mocks.query.mockImplementation(async () => ({ columns: ["OWNER", "OBJECT_NAME", "OBJECT_TYPE", "OBJECT_ID"], rows: [[" Parent Owner ", " View ", "VIEW", ++parentReads === 1 ? "parent-before" : "parent-rebuilt"]] }));+ const { readOracleTriggerSnapshot, prepareOracleTriggerPlan, executeOracleTriggerPlan } = await import("@/lib/database/oracleTriggerPlan");+ const baseline = await readOracleTriggerSnapshot(target);+ const plan = await prepareOracleTriggerPlan({ target, action: "replace", baseline, source: before.source });+ await expect(executeOracleTriggerPlan(plan, { confirmed: true })).rejects.toThrow(/owning object|parent|scope/i);+ expect(mocks.query.mock.calls.every((call) => call[2].startsWith("SELECT"))).toBe(true);+ const changed = JSON.parse(JSON.stringify(before));+ changed.source += " -- other writer";+ mocks.source.mockResolvedValue(changed);+ await expect(prepareOracleTriggerPlan({ target, action: "replace", baseline, source: before.source })).rejects.toThrow(/changed|baseline/i);+ });++ it("does not treat a cross-owner empty ALL_* read as a verified deletion when the global dictionary is denied", async () => {+ const absent = source(false);+ absent.source = "";+ absent.trigger!.oracle_metadata!.objectId = null;+ absent.trigger!.oracle_metadata!.reads.identity = { state: "empty" };+ mocks.source.mockResolvedValueOnce(source(false)).mockResolvedValueOnce(source(false)).mockResolvedValueOnce(absent);+ mocks.query.mockImplementation(async (_id, _db, sql) => {+ if (sql.includes("DBA_OBJECTS")) throw new Error("global dictionary denied");+ if (sql.includes("SELECT USER")) return { columns: ["SESSION_USER"], rows: [[" Execution Owner "]] };+ if (sql.startsWith("SELECT")) return { columns: ["OWNER", "OBJECT_NAME", "OBJECT_TYPE", "OBJECT_ID"], rows: [[" Parent Owner ", " View ", "VIEW", "parent-before"]] };+ return { columns: [], rows: [] };+ });+ const { prepareOracleTriggerPlan, executeOracleTriggerPlan } = await import("@/lib/database/oracleTriggerPlan");+ const plan = await prepareOracleTriggerPlan({ target, action: "delete" });+ const result = await executeOracleTriggerPlan(plan, { confirmed: true });+ expect(result.steps[0]).toMatchObject({ state: "unknown", verification: "unverified", receipt: "accepted" });+ expect(result.steps[0].readbackError).toContain("global dictionary denied");+ expect(mocks.query.mock.calls.filter((call) => !call[2].startsWith("SELECT")).map((call) => call[2])).toEqual(['DROP TRIGGER " Trigger Owner "." Tr""ig ";']);+ await expect(executeOracleTriggerPlan(plan, { confirmed: true })).rejects.toThrow();+ });++ it("keeps DM's committed definition and stops its separately previewed disabled-state restoration after a lost receipt", async () => {+ const absent = source(false),+ created = source(true);+ const definition = 'CREATE TRIGGER " Trigger Owner "." Tr""ig " INSTEAD OF UPDATE ON " Parent Owner "." View " BEGIN NULL; END;';+ for (const raw of [absent, created]) {+ raw.trigger!.oracle_metadata!.engine = "dm";+ raw.trigger!.oracle_metadata!.engineVersion = "8.1.5";+ }+ absent.source = "";+ absent.trigger!.oracle_metadata!.objectId = null;+ absent.trigger!.oracle_metadata!.reads.identity = { state: "empty" };+ created.source = definition;+ created.trigger!.valid = true;+ created.trigger!.oracle_metadata!.definition = { origin: "DBMS_METADATA", format: "ddl", complete: true };+ created.trigger!.oracle_metadata!.reads.definition = { state: "available" };+ mocks.source.mockResolvedValueOnce(absent).mockResolvedValueOnce(absent).mockResolvedValueOnce(created);+ mocks.prepareSql.mockResolvedValue({ definition, comparisonSource: definition, header: { scope: "RELATION", owner: " Parent Owner ", name: " View ", viewOnly: true, pluggable: false }, requiresStateRestore: true });+ mocks.query.mockImplementation(async (_id, _db, sql) => {+ if (sql.startsWith("SELECT")) return { columns: ["OWNER", "OBJECT_NAME", "OBJECT_TYPE", "OBJECT_ID"], rows: [[" Parent Owner ", " View ", "VIEW", "parent-before"]] };+ throw new Error("write response lost");+ });+ const { prepareOracleTriggerPlan, executeOracleTriggerPlan } = await import("@/lib/database/oracleTriggerPlan");+ const plan = await prepareOracleTriggerPlan({ target, action: "create", source: definition, enabled: false, selection: { scope: "VIEW", owner: " Parent Owner ", name: " View " } });+ expect(plan.steps.map((step) => step.action)).toEqual(["create", "disable"]);+ const result = await executeOracleTriggerPlan(plan, { confirmed: true });+ expect(result.steps.map(({ state, verification }) => ({ state, verification }))).toEqual([+ { state: "unknown", verification: "applied" },+ { state: "notExecuted", verification: "unverified" },+ ]);+ expect(result.snapshot?.raw.trigger?.enabled).toBe(true);+ expect(mocks.query.mock.calls.filter((call) => !call[2].startsWith("SELECT")).map((call) => call[2])).toEqual([definition]);+ await expect(executeOracleTriggerPlan(plan, { confirmed: true })).rejects.toThrow();+ });++ it("verifies a deletion of the actual session user's trigger without requiring DBA_OBJECTS and leaves the parent intact", async () => {+ const absent = source(false);+ absent.source = "";+ absent.trigger!.oracle_metadata!.objectId = null;+ absent.trigger!.oracle_metadata!.reads.identity = { state: "empty" };+ mocks.source.mockResolvedValueOnce(source(false)).mockResolvedValueOnce(source(false)).mockResolvedValueOnce(absent);+ mocks.query.mockImplementation(async (_id, _db, sql) => {+ if (sql.includes("SELECT USER")) return { columns: ["SESSION_USER"], rows: [[target.owner]] };+ if (sql.startsWith("SELECT")) return { columns: ["OWNER", "OBJECT_NAME", "OBJECT_TYPE", "OBJECT_ID"], rows: [[" Parent Owner ", " View ", "VIEW", "parent-before"]] };+ return { columns: [], rows: [] };+ });+ const { prepareOracleTriggerPlan, executeOracleTriggerPlan } = await import("@/lib/database/oracleTriggerPlan");+ const result = await executeOracleTriggerPlan(await prepareOracleTriggerPlan({ target, action: "delete" }), { confirmed: true });+ expect(result.steps[0]).toMatchObject({ state: "committed", verification: "deleted" });+ expect(mocks.query.mock.calls.some((call) => call[2].includes("DBA_OBJECTS"))).toBe(false);+ expect(mocks.query.mock.calls.filter((call) => !call[2].startsWith("SELECT")).map((call) => call[2])).toEqual(['DROP TRIGGER " Trigger Owner "." Tr""ig ";']);+ });++ it("keeps a post-dispatch result on its fixed target when only the UI moves away", async () => {+ let current = true;+ mocks.source.mockResolvedValueOnce(source(false)).mockResolvedValueOnce(source(false)).mockResolvedValueOnce(source(true));+ mocks.query.mockImplementationOnce(async () => {+ current = false;+ return { columns: [], rows: [] };+ });+ const { prepareOracleTriggerPlan, executeOracleTriggerPlan } = await import("@/lib/database/oracleTriggerPlan");+ const result = await executeOracleTriggerPlan(await prepareOracleTriggerPlan({ target, action: "enable" }), { confirmed: true, isCurrent: () => current });+ expect(result.steps[0]).toMatchObject({ state: "committed", verification: "applied" });+ expect(result.snapshot?.target).toEqual(target);+ expect(mocks.query).toHaveBeenCalledTimes(1);+ });++ it("retires only the real parent's trigger facets after a write, keeping columns and another catalog warm", async () => {+ const { loadObjectMetadataFacet } = await import("@/lib/metadata/objectMetadataCache");+ const parent = { connectionId: target.connectionId, database: target.database, catalog: target.catalog, schema: " Parent Owner ", tableName: " View ", objectType: "VIEW" as const };+ await loadObjectMetadataFacet(parent, "columns", async () => ["column-keep"]);+ await loadObjectMetadataFacet(parent, "triggers", async () => ["legacy-old"]);+ await loadObjectMetadataFacet({ ...parent, oracleTriggerContract: 1 }, "triggers", async () => ["exact-old"]);+ await loadObjectMetadataFacet({ ...parent, exactIdentity: true, oracleTriggerContract: 1 }, "triggers", async () => ["identity-old"]);+ await loadObjectMetadataFacet({ ...parent, catalog: "another-catalog" }, "triggers", async () => ["catalog-keep"]);+ mocks.source.mockResolvedValueOnce(source(false)).mockResolvedValueOnce(source(false)).mockResolvedValueOnce(source(true));+ const { prepareOracleTriggerPlan, executeOracleTriggerPlan } = await import("@/lib/database/oracleTriggerPlan");+ await executeOracleTriggerPlan(await prepareOracleTriggerPlan({ target, action: "enable" }), { confirmed: true });+ expect((await loadObjectMetadataFacet(parent, "triggers", async () => ["legacy-new"])).value).toEqual(["legacy-new"]);+ expect((await loadObjectMetadataFacet({ ...parent, oracleTriggerContract: 1 }, "triggers", async () => ["exact-new"])).value).toEqual(["exact-new"]);+ expect((await loadObjectMetadataFacet({ ...parent, exactIdentity: true, oracleTriggerContract: 1 }, "triggers", async () => ["identity-new"])).value).toEqual(["identity-new"]);+ expect((await loadObjectMetadataFacet(parent, "columns", async () => ["incorrect-column-reload"])).value).toEqual(["column-keep"]);+ expect((await loadObjectMetadataFacet({ ...parent, catalog: "another-catalog" }, "triggers", async () => ["incorrect-catalog-reload"])).value).toEqual(["catalog-keep"]);+ });++ it("does not report an enable as verified when a known complete body changed during execution", async () => {+ const before = source(false),+ after = source(true);+ for (const raw of [before, after]) {+ raw.trigger!.oracle_metadata!.definition = { origin: "DBMS_METADATA", format: "ddl", complete: true };+ raw.trigger!.oracle_metadata!.reads.definition = { state: "available" };+ }+ before.source = 'CREATE TRIGGER " Trigger Owner "." Tr""ig " INSTEAD OF UPDATE ON " Parent Owner "." View " BEGIN NULL; END;';+ after.source = before.source.replace("NULL;", "other_procedure;");+ mocks.source.mockResolvedValueOnce(before).mockResolvedValueOnce(before).mockResolvedValueOnce(after);+ mocks.prepareSql.mockImplementation(async (input) => ({ definition: input.source, comparisonSource: input.source, header: { scope: "RELATION", owner: " Parent Owner ", name: " View ", viewOnly: true, pluggable: false }, requiresStateRestore: false }));+ const { prepareOracleTriggerPlan, executeOracleTriggerPlan } = await import("@/lib/database/oracleTriggerPlan");+ const result = await executeOracleTriggerPlan(await prepareOracleTriggerPlan({ target, action: "enable" }), { confirmed: true });+ expect(result.steps[0]).toMatchObject({ state: "unknown", verification: "mismatch", receipt: "accepted" });+ expect(result.snapshot?.raw.trigger?.enabled).toBe(true);+ expect(mocks.query).toHaveBeenCalledTimes(1);+ });++ it.each(["enable", "replace"] as const)("rechecks action-specific read authority after confirmation for %s", async (action) => {+ const before = source(false);+ before.source = 'CREATE TRIGGER " Trigger Owner "." Tr""ig " INSTEAD OF UPDATE ON " Parent Owner "." View " DISABLE BEGIN NULL; END;';+ before.trigger!.oracle_metadata!.definition = { origin: "DBMS_METADATA", format: "ddl", complete: true };+ before.trigger!.oracle_metadata!.reads.definition = { state: "available" };+ const latest: ObjectSource = JSON.parse(JSON.stringify(before));+ if (action === "replace") {+ latest.trigger!.oracle_metadata!.definition!.complete = false;+ latest.trigger!.oracle_metadata!.reads.definition = { state: "denied" };+ } else latest.trigger!.oracle_metadata!.reads.scope = { state: "unavailable" };+ mocks.prepareSql.mockImplementation(async (input) => ({ definition: input.source, comparisonSource: input.source, header: { scope: "RELATION", owner: " Parent Owner ", name: " View ", viewOnly: true, pluggable: false }, requiresStateRestore: false }));+ mocks.query.mockImplementation(async () => ({ columns: ["OWNER", "OBJECT_NAME", "OBJECT_TYPE", "OBJECT_ID"], rows: [[" Parent Owner ", " View ", "VIEW", "parent-id"]] }));+ mocks.source.mockResolvedValueOnce(before);+ const { prepareOracleTriggerPlan, readOracleTriggerSnapshot, executeOracleTriggerPlan } = await import("@/lib/database/oracleTriggerPlan");+ const baseline = action === "replace" ? await readOracleTriggerSnapshot(target) : undefined;+ if (baseline) mocks.source.mockResolvedValueOnce(before);+ const plan = await prepareOracleTriggerPlan({ target, action, ...(baseline ? { baseline, source: before.source } : {}) });+ mocks.source.mockResolvedValue(latest);+ await expect(executeOracleTriggerPlan(plan, { confirmed: true })).rejects.toThrow(/complete|scope|unavailable/i);+ expect(mocks.query.mock.calls.every((call) => call[2].startsWith("SELECT"))).toBe(true);+ });++ it("verifies a plain CREATE against OceanBase's CREATE OR REPLACE export wrapper without changing its body", async () => {+ const absent = source(false),+ created = source(true);+ absent.source = "";+ absent.trigger!.oracle_metadata!.objectId = null;+ absent.trigger!.oracle_metadata!.reads.identity = { state: "empty" };+ const tail = ' " Trigger Owner "." Tr""ig " INSTEAD OF UPDATE ON " Parent Owner "." View " ENABLE\nBEGIN NULL; END;';+ const definition = `CREATE TRIGGER${tail}`,+ exported = `CREATE OR REPLACE TRIGGER${tail}`;+ created.source = `${exported}\nALTER TRIGGER " Trigger Owner "." Tr""ig " ENABLE`;+ created.trigger!.valid = true;+ created.trigger!.oracle_metadata!.definition = { origin: "DBMS_METADATA", format: "ddl", complete: true };+ created.trigger!.oracle_metadata!.reads.definition = { state: "available" };+ mocks.prepareSql.mockImplementation(async (input) => ({+ definition: input.source === created.source ? exported : input.source === exported && input.purpose === "create" ? `CREATE TRIGGER${tail}` : definition,+ comparisonSource: exported,+ header: { scope: "RELATION", owner: " Parent Owner ", name: " View ", viewOnly: true, pluggable: false },+ requiresStateRestore: false,+ }));+ mocks.source.mockResolvedValueOnce(absent).mockResolvedValueOnce(absent).mockResolvedValueOnce(created);+ mocks.query.mockImplementation(async (_id, _db, sql) => (sql.startsWith("SELECT") ? { columns: ["OWNER", "OBJECT_NAME", "OBJECT_TYPE", "OBJECT_ID"], rows: [[" Parent Owner ", " View ", "VIEW", "parent-id"]] } : { columns: [], rows: [] }));+ const { prepareOracleTriggerPlan, executeOracleTriggerPlan } = await import("@/lib/database/oracleTriggerPlan");+ const result = await executeOracleTriggerPlan(await prepareOracleTriggerPlan({ target, action: "create", source: definition, selection: { scope: "VIEW", owner: " Parent Owner ", name: " View " } }), { confirmed: true });+ expect(result.steps[0]).toMatchObject({ state: "committed", verification: "applied" });+ expect(mocks.query.mock.calls.filter((call) => !call[2].startsWith("SELECT")).map((call) => call[2])).toEqual([definition]);+ });+});diff --git a/apps/desktop/src/lib/__tests__/database/triggerToggleSql.spec.ts b/apps/desktop/src/lib/__tests__/database/triggerToggleSql.spec.tsindex 5ca939835a..f299a70ef0 100644--- a/apps/desktop/src/lib/__tests__/database/triggerToggleSql.spec.ts+++ b/apps/desktop/src/lib/__tests__/database/triggerToggleSql.spec.ts@@ -2,6 +2,31 @@ import { describe, expect, it } from "vitest";import { buildTriggerToggleSql, supportsTriggerToggle } from "@/lib/database/triggerToggleSql";describe("triggerToggleSql", () => {+ describe("exact Oracle-family actions", () => {+ it.each(["oracle", "oceanbase-oracle", "dameng"] as const)("%s preserves raw trigger owner/name independently of a parent", (databaseType) => {+ expect(buildTriggerToggleSql({ databaseType, schema: " Owner ", triggerName: ' Tr"ig ', tableName: "must-not-appear", enabled: false, identityMode: "exact", scope: "VIEW" })).toBe('ALTER TRIGGER " Owner "." Tr""ig " DISABLE;');+ });++ it.each(["SCHEMA", "DATABASE", "TIMER"] as const)("DM %s toggles only the selected native event trigger", (scope) => {+ expect(buildTriggerToggleSql({ databaseType: "dameng", schema: " O'wner ", triggerName: " Tr'ig ", enabled: false, identityMode: "exact", scope })).toBe("SP_ENABLE_EVT_TRIGGER(' O''wner ', ' Tr''ig ', 0);");+ expect(buildTriggerToggleSql({ databaseType: "dameng", schema: " O'wner ", triggerName: " Tr'ig ", enabled: true, identityMode: "exact", scope })).toBe("SP_ENABLE_EVT_TRIGGER(' O''wner ', ' Tr''ig ', 1);");+ });++ it("does not fall back to a legacy or unknown-scope write when exact prerequisites are missing", () => {+ const options = { databaseType: "oracle", schema: "APP", triggerName: "T", enabled: true, identityMode: "exact", scope: "TABLE" } as const;+ expect(buildTriggerToggleSql({ ...options, schema: undefined })).toBeNull();+ expect(buildTriggerToggleSql({ ...options, triggerName: "T\0" })).toBeNull();+ expect(buildTriggerToggleSql({ ...options, scope: "UNKNOWN" })).toBeNull();+ expect(buildTriggerToggleSql({ ...options, databaseType: "oceanbase-oracle", scope: "SCHEMA" })).toBeNull();+ expect(buildTriggerToggleSql({ ...options, databaseType: "postgres", tableName: "ORDERS" })).toBeNull();+ });++ it("keeps default callers' original trim, optional owner and native DM behavior", () => {+ expect(buildTriggerToggleSql({ databaseType: "dameng", schema: " APP ", triggerName: " T ", enabled: false })).toBe('ALTER TRIGGER "APP"."T" DISABLE;');+ expect(buildTriggerToggleSql({ databaseType: "oracle", triggerName: " T ", enabled: true })).toBe('ALTER TRIGGER "T" ENABLE;');+ });+ });+describe("supportsTriggerToggle", () => {it("returns true for supported database types", () => {expect(supportsTriggerToggle("sqlserver")).toBe(true);diff --git a/apps/desktop/src/lib/__tests__/sidebar/sidebarActiveTabTarget.spec.ts b/apps/desktop/src/lib/__tests__/sidebar/sidebarActiveTabTarget.spec.tsindex 8b5616ecd2..bd30156b5c 100644--- a/apps/desktop/src/lib/__tests__/sidebar/sidebarActiveTabTarget.spec.ts+++ b/apps/desktop/src/lib/__tests__/sidebar/sidebarActiveTabTarget.spec.ts@@ -106,6 +106,7 @@ describe("management page sidebar targets", () => {["dameng-users", "dameng-users"],["dameng-roles", "dameng-roles"],["dameng-jobs", "dameng-job-admin"],+ ["database-jobs", "database-job-admin"],] as const)("locates %s at its dedicated %s node", (mode, nodeType) => {const target = activeTabSidebarTarget({ mode, connectionId: "conn" } as QueryTab);expect(target).toEqual({ type: "management", connectionId: "conn", nodeType });diff --git a/apps/desktop/src/lib/__tests__/sidebar/sidebarTreeLabel.nativeJobs.spec.ts b/apps/desktop/src/lib/__tests__/sidebar/sidebarTreeLabel.nativeJobs.spec.tsnew file mode 100644index 0000000000..75f42c3580--- /dev/null+++ b/apps/desktop/src/lib/__tests__/sidebar/sidebarTreeLabel.nativeJobs.spec.ts@@ -0,0 +1,10 @@+import { describe, expect, it } from "vitest";+import { sidebarTreeDisplayLabel } from "@/lib/sidebar/sidebarTreeLabel";+import type { TreeNode } from "@/types/database";++describe("sidebar tree labels", () => {+ it("translates the native job entry for rendering and width measurement", () => {+ const node: TreeNode = { id: "jobs", type: "database-job-admin", label: "tree.nativeJobs" };+ expect(sidebarTreeDisplayLabel(node, (key) => `translated:${key}`)).toBe("translated:tree.nativeJobs");+ });+});diff --git a/apps/desktop/src/lib/__tests__/table/oracleTriggerErrorPosition.spec.ts b/apps/desktop/src/lib/__tests__/table/oracleTriggerErrorPosition.spec.tsnew file mode 100644index 0000000000..560684f7d6--- /dev/null+++ b/apps/desktop/src/lib/__tests__/table/oracleTriggerErrorPosition.spec.ts@@ -0,0 +1,54 @@+import { describe, expect, it } from "vitest";+import type { ObjectSource } from "@/types/database";+import { oracleTriggerErrorEditorOffset } from "@/lib/table/objectSourceLoad";++function source(text = 'TRIGGER "Owner"."Trigger"\nBEFORE INSERT ON "Parent"."T"\nBEGIN\n missing_proc;\nEND;\n'): ObjectSource {+ return {+ name: "Trigger",+ schema: "Owner",+ object_type: "TRIGGER",+ source: text,+ trigger: {+ name: "Trigger",+ event: "INSERT",+ timing: "BEFORE",+ oracle_metadata: { contractVersion: 1, identityMode: "exact", engine: "oracle", owner: "Owner", name: "Trigger", scope: "TABLE", definition: { origin: "ALL_SOURCE", format: "declaration", complete: true }, reads: { definition: { state: "available" } } },+ },+ };+}+describe("stored trigger diagnostics to the existing editor", () => {+ it.each(["CREATE OR REPLACE ", "-- my unsaved comment\nCREATE OR REPLACE "])("accounts for the actual wrapper and preceding draft text (%s)", (prefix) => {+ const raw = source();+ const editor = prefix + raw.source.trim();+ expect(oracleTriggerErrorEditorOffset(raw, editor, { line: 4, position: 3 })).toBe(editor.indexOf("missing_proc"));+ });+ it("uses dictionary lines and Unicode characters while returning a CodeMirror UTF-16 offset", () => {+ const raw = source(source().source.replace(" missing_proc", " 😀 missing_proc").replaceAll("\n", "\r\n"));+ const editor = "CREATE OR REPLACE " + raw.source.replaceAll("\r\n", "\n").trim();+ expect(oracleTriggerErrorEditorOffset(raw, editor, { line: 4, position: 5 })).toBe(editor.indexOf("missing_proc"));+ });+ it.each(["changed", "duplicate", "commented", "literal", "export", "partial", "wrong-identity"])("does not guess an error location for %s source", (condition) => {+ const raw = source();+ let editor = "CREATE OR REPLACE " + raw.source.trim();+ if (condition === "changed") editor = editor.replace("missing_proc", "corrected_proc");+ if (condition === "duplicate") editor += "\n/* " + raw.source.trim() + " */";+ if (condition === "commented") editor = "/* " + raw.source.trim() + " */";+ if (condition === "literal") editor = "SELECT q'[" + raw.source.trim() + "]' FROM DUAL";+ if (condition === "export") {+ raw.trigger!.oracle_metadata!.definition!.origin = "DBMS_METADATA";+ raw.trigger!.oracle_metadata!.definition!.format = "ddl";+ }+ if (condition === "partial") raw.trigger!.oracle_metadata!.definition!.complete = false;+ if (condition === "wrong-identity") raw.schema = "Other";+ expect(oracleTriggerErrorEditorOffset(raw, editor, { line: 4, position: 3 })).toBeUndefined();+ });+ it.each([+ { line: 0, position: 1 },+ { line: 99, position: 1 },+ { line: 4, position: 999 },+ { line: null, position: 3 },+ ])("does not clamp unavailable coordinates into a different token (%j)", (error) => {+ const raw = source();+ expect(oracleTriggerErrorEditorOffset(raw, "CREATE OR REPLACE " + raw.source, error)).toBeUndefined();+ });+});diff --git a/apps/desktop/src/lib/__tests__/table/oracleTriggerProjection.spec.ts b/apps/desktop/src/lib/__tests__/table/oracleTriggerProjection.spec.tsnew file mode 100644index 0000000000..832aae79ca--- /dev/null+++ b/apps/desktop/src/lib/__tests__/table/oracleTriggerProjection.spec.ts@@ -0,0 +1,124 @@+import { describe, expect, it } from "vitest";+import type { ObjectInfo, TriggerInfo, TableStructureEditorDraft } from "@/types/database";+import { createTriggerDrafts } from "@/lib/table/tableStructureEditorState";+import { reconcileOracleTriggerStructureDraft } from "@/lib/database/oracleTriggerStructurePlan";+import { buildGroupedObjectTreeNodes, buildSimpleObjectTreeNodes, tablePageRowAnchorKey } from "@/lib/table/tableTree";+import { buildObjectBrowserRows, objectBrowserRowMatchesPinnedTreeNode, objectBrowserRowPinnedTreeNodeIdentity } from "@/lib/table/objectBrowserRows";+import { exactOracleTriggerNodeMetadata, oracleTriggerIdentityKey, oracleTriggerObjectReadOptions } from "@/lib/database/oracleTriggerIdentity";++function object(name = ' Tr:ig" ', owner = " Owner: ", id = "9007199254740993", scope: "VIEW" | "SCHEMA" = "VIEW"): ObjectInfo {+ const trigger: TriggerInfo = {+ name,+ event: "UPDATE",+ timing: "INSTEAD OF",+ enabled: true,+ valid: false,+ oracle_metadata: {+ contractVersion: 1,+ identityMode: "exact",+ engine: "oracle",+ owner,+ name,+ objectId: id,+ scope,+ ...(scope === "VIEW" ? { parent: { owner: " Parent Owner ", name: ' Parent" ', objectType: "VIEW" } } : { scopeOwner: " Scope Owner " }),+ reads: { identity: { state: "available" } },+ },+ };+ return { name, schema: owner, object_type: "TRIGGER", parent_schema: "must-not-be-used", parent_name: "wrong-parent", trigger };+}++describe("Oracle-family exact trigger projections", () => {+ it("gives same-name triggers distinct owner-bound structure IDs while retaining legacy IDs", () => {+ const [a, b] = createTriggerDrafts([object("T", "A").trigger!, object("T", "B").trigger!]);+ expect(a.id).not.toBe(b.id);+ expect(createTriggerDrafts([{ name: "T", event: "INSERT", timing: "BEFORE" }])[0].id).toBe("existing:T");+ });++ it.each([+ ["T", "B"],+ [" T ", "A"],+ ["t", "A"],+ ])("reconciles raw identity %s / %s separately without changing another trigger's draft", (secondName, secondOwner) => {+ const originals = [object("T", "A", "a-id").trigger!, object(secondName, secondOwner, "b-id").trigger!];+ const triggers = createTriggerDrafts(originals).map((trigger, index) => ({ ...trigger, id: `owner-${index}`, enabled: index === 0 ? false : trigger.enabled }));+ const draft = { columns: [], indexes: [], foreignKeys: [], triggers, tableComment: "", originalTableComment: "" } as TableStructureEditorDraft;+ const next = reconcileOracleTriggerStructureDraft(draft, { columns: [], indexes: [], foreignKeys: [], triggers: structuredClone(originals), constraints: [], comment: "" }, { columns: new Set(), indexes: new Set(), foreignKeys: new Set(), triggers: new Set([triggers[0].id]) }, "oracle");+ expect(next.triggers).toHaveLength(2);+ expect(next.triggers.find((trigger) => trigger.id === "owner-0")).toMatchObject({ enabled: false, original: { oracle_metadata: { owner: "A", objectId: "a-id" } } });+ expect(next.triggers.find((trigger) => trigger.id === "owner-1")).toMatchObject({ original: { oracle_metadata: { owner: secondOwner, name: secondName, objectId: "b-id" } } });+ });+ it("does not extract a target from a label or contradicting node identity", () => {+ const nodes = buildSimpleObjectTreeNodes({ nodeId: "n", connectionId: "c", database: "d", objects: [object()] });+ expect(exactOracleTriggerNodeMetadata(nodes[0])).toEqual(object().trigger!.oracle_metadata);+ expect(exactOracleTriggerNodeMetadata({ ...nodes[0], objectName: undefined })).toBeUndefined();+ expect(exactOracleTriggerNodeMetadata({ ...nodes[0], schema: "Owner:" })).toBeUndefined();+ expect(exactOracleTriggerNodeMetadata({ ...nodes[0], meta: undefined })).toBeUndefined();+ });++ it("uses encoded tuples rather than ambiguous display delimiters", () => {+ expect(oracleTriggerIdentityKey({ owner: "A:B", name: "C" })).not.toBe(oracleTriggerIdentityKey({ owner: "A", name: "B:C" }));+ expect(oracleTriggerIdentityKey({ owner: "A", name: " C " })).not.toBe(oracleTriggerIdentityKey({ owner: "A", name: "C" }));+ expect(oracleTriggerIdentityKey({ owner: "A", name: "C" }, "D")).not.toBe(oracleTriggerIdentityKey({ owner: "A", name: "C" }));+ });++ it("adds read prerequisites to new trigger usage without changing old unknown-JDBC mixed reads", () => {+ const unknown = { db_type: "jdbc" as const, driver_label: "Oracle-compatible Yashan", database_info: { productName: "YashanDB" } };+ expect(oracleTriggerObjectReadOptions(unknown)).toBeUndefined();+ expect(oracleTriggerObjectReadOptions(unknown, ["TABLE", "TRIGGER"])).toBeUndefined();+ expect(oracleTriggerObjectReadOptions(unknown, ["TRIGGER"])).toEqual({ identityMode: "exact" });+ expect(oracleTriggerObjectReadOptions({ ...unknown, database_info: { productName: "Oracle" } })).toEqual({ identityMode: "exact" });+ expect(oracleTriggerObjectReadOptions({ db_type: "oracle" }, [])).toBeUndefined();+ expect(oracleTriggerObjectReadOptions({ db_type: "oracle" }, ["PROCEDURE"])).toBeUndefined();+ expect(oracleTriggerObjectReadOptions({ db_type: "mysql" }, ["TRIGGER"])).toBeUndefined();+ });++ for (const layout of ["simple", "grouped"] as const) {+ it(`${layout} preserves raw trigger and independent parent identity without merging approximate names`, () => {+ const objects = [object(), object('Tr:ig"'), object(' Tr:ig" ', " owner: ")];+ const context = { nodeId: "c:d:s", connectionId: "c", database: "d", schema: "execution", catalog: " Catalog ", objects };+ const nodes = layout === "simple" ? buildSimpleObjectTreeNodes(context) : buildGroupedObjectTreeNodes(context).find((group) => group.type === "group-triggers")!.children!;+ expect(nodes).toHaveLength(3);+ expect(new Set(nodes.map((node) => node.id)).size).toBe(3);+ const raw = nodes.find((node) => node.schema === " Owner: " && node.objectName === ' Tr:ig" ')!;+ expect(raw).toMatchObject({ schema: " Owner: ", objectName: ' Tr:ig" ', catalog: " Catalog ", parentSchema: " Parent Owner ", parentName: ' Parent" ', parentType: "view", tableName: ' Parent" ', valid: false, meta: objects[0].trigger });+ expect(raw.partitionParentName).toBeUndefined();+ });++ it(`${layout} shows non-table scope without a fabricated owning table`, () => {+ const context = { nodeId: "c:d:s", connectionId: "c", database: "d", schema: "execution", objects: [object(" Schema Trigger ", " Owner ", "3", "SCHEMA")] };+ const nodes = layout === "simple" ? buildSimpleObjectTreeNodes(context) : buildGroupedObjectTreeNodes(context)[0].children!;+ expect(nodes[0].objectName).toBe(" Schema Trigger ");+ expect(nodes[0].parentName).toBeUndefined();+ expect(nodes[0].tableName).toBeUndefined();+ });+ }++ it("object-browser rows retain the same metadata instead of projecting trigger parents as partitions", () => {+ const objects = [object(), object('Tr:ig"'), object(" Schema Trigger ", " Owner ", "3", "SCHEMA")];+ const rows = buildObjectBrowserRows({ objects, database: "d", fallbackSchema: "execution" });+ expect(rows.map((row) => row.name)).toEqual(objects.map((entry) => entry.name));+ expect(rows[0]).toMatchObject({ schema: " Owner: ", valid: false, trigger: objects[0].trigger });+ expect(rows.every((row) => row.partitionParentName === undefined && row.partitionParentSchema === undefined)).toBe(true);+ });++ it("page anchors distinguish quoted names, owners and same-name object recreation", () => {+ const first = object();+ const second = object('Tr:ig"', " owner: ");+ const recreated = object(first.name, first.schema!, "99");+ const anchor = (entry: ObjectInfo) => tablePageRowAnchorKey(entry.name, entry.schema, entry.parent_name, entry.trigger);+ expect(anchor(first)).not.toBe(anchor(second));+ expect(anchor(first)).not.toBe(anchor(recreated));+ expect(tablePageRowAnchorKey("TABLE", "APP")).toBe(tablePageRowAnchorKey("table", "app"));+ });++ it("pins use the exact owner even when it equals the database display alias", () => {+ const context = { connectionId: "c", database: "d", catalog: " Catalog ", schema: "execution" };+ const [row] = buildObjectBrowserRows({ objects: [object(" Trigger ", "d")], database: "d", fallbackSchema: "execution" });+ const identity = objectBrowserRowPinnedTreeNodeIdentity(row, context);+ expect(objectBrowserRowMatchesPinnedTreeNode(row, identity, context)).toBe(true);+ expect(objectBrowserRowMatchesPinnedTreeNode(row, { ...identity, schema: "" }, context)).toBe(false);+ expect(objectBrowserRowMatchesPinnedTreeNode(row, { ...identity, name: "Trigger" }, context)).toBe(false);+ expect(objectBrowserRowMatchesPinnedTreeNode(row, { ...identity, catalog: "Catalog" }, context)).toBe(false);+ });+});diff --git a/apps/desktop/src/lib/backend/__tests__/nativeJobTransport.spec.ts b/apps/desktop/src/lib/backend/__tests__/nativeJobTransport.spec.tsnew file mode 100644index 0000000000..873a474936--- /dev/null+++ b/apps/desktop/src/lib/backend/__tests__/nativeJobTransport.spec.ts@@ -0,0 +1,205 @@+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import * as http from "../http";+import * as tauri from "../tauri";+import * as api from "../api";+import type { NativeJobRequest, NativeJobValue } from "../../database/nativeJobs";++const { invoke } = vi.hoisted(() => ({ invoke: vi.fn() }));+vi.mock("@tauri-apps/api/core", () => ({ invoke, Channel: class {} }));++const scope = { connectionId: "connection a", database: "Owner.With.Dot", contextId: "bound-context" };+const target = { kind: "scheduler" as const, scope, owner: "Exact Owner", name: " Job,\"One's " };+const list = { scope, kind: "scheduler" as const, schema: "Exact Owner", filter: "%not-a-wildcard_", offset: 500, limit: 100 };+const mutation = { action: "update" as const, target, baseline: "bound-revision", attributes: [{ name: "COMMENTS", change: { kind: "set" as const, value: "literal 'comment'" } }], arguments: [] };+const cases = [+ { name: "nativeJobOpenContext", command: "native_job_open_context", route: "context", args: [scope.connectionId, scope.database], invoke: { connectionId: scope.connectionId, database: scope.database }, body: { connectionId: scope.connectionId, database: scope.database } },+ { name: "nativeJobList", command: "native_job_list", route: "list", args: [list], invoke: { request: list }, body: list },+ { name: "nativeJobReferences", command: "native_job_references", route: "references", args: [{ ...list, kind: "program", name: 'Program,"Exact' }], invoke: { request: { ...list, kind: "program", name: 'Program,"Exact' } }, body: { ...list, kind: "program", name: 'Program,"Exact' } },+ { name: "nativeJobRead", command: "native_job_read", route: "read", args: [target], invoke: { target }, body: target },+ { name: "nativeJobPrepare", command: "native_job_prepare", route: "prepare", args: [mutation], invoke: { mutation }, body: mutation },+ { name: "nativeJobApply", command: "native_job_apply", route: "apply", args: ["immutable-plan"], invoke: { planId: "immutable-plan" }, body: { planId: "immutable-plan" } },+ { name: "nativeJobStatus", command: "native_job_status", route: "status", args: ["operation-id"], invoke: { operationId: "operation-id" }, body: { operationId: "operation-id" } },+ { name: "nativeJobCancel", command: "native_job_cancel", route: "cancel", args: ["operation-id"], invoke: { operationId: "operation-id" }, body: { operationId: "operation-id" } },+] as const;++describe("native Job dual transport", () => {+ const fetch = vi.fn();+ const response = { operationId: "operation-id", target, state: "finished", outcome: "unknown", cancelRequested: true, steps: [], reason: "native_job_execution_outcome_unknown" };+ beforeEach(() => {+ vi.resetAllMocks();+ vi.stubGlobal("fetch", fetch);+ fetch.mockImplementation(async () => new Response(JSON.stringify(response), { status: 200, headers: { "Content-Type": "application/json" } }));+ invoke.mockResolvedValue(response);+ });+ afterEach(() => vi.unstubAllGlobals());++ it.each(cases)("$name preserves the exact target and shared response through both real adapters", async (operation) => {+ expect(await Reflect.apply(tauri[operation.name], undefined, operation.args)).toEqual(response);+ expect(invoke).toHaveBeenCalledExactlyOnceWith(operation.command, operation.invoke);+ expect(await Reflect.apply(http[operation.name], undefined, operation.args)).toEqual(response);+ expect(fetch).toHaveBeenCalledTimes(1);+ const [url, init] = fetch.mock.calls[0];+ expect(new URL(String(url), "http://localhost").pathname).toBe(`/api/schema/native-jobs/${operation.route}`);+ expect(init.method).toBe("POST");+ expect(JSON.parse(init.body)).toEqual(operation.body);+ expect(await Reflect.apply(api[operation.name], undefined, operation.args)).toEqual(response);+ expect(fetch).toHaveBeenCalledTimes(2);+ });++ it("does not retry an apply whose transport response was lost", async () => {+ fetch.mockRejectedValue(new TypeError("network response lost"));+ await expect(http.nativeJobApply("immutable-plan")).rejects.toThrow("network response lost");+ expect(fetch).toHaveBeenCalledTimes(1);+ });++ it("transports typed scalar, civil-date and typed-NULL payloads without stringification or numeric coercion", async () => {+ const values: NativeJobValue[] = [+ '{"$dbx":"oracle-anydata-v1","scalarType":"number","value":"1"}',+ ...["varchar2", "char", "nvarchar2", "nchar"].map((scalarType) => ({ $dbx: "oracle-anydata-v1", scalarType, value: "引号'\\😀 " })),+ { $dbx: "oracle-anydata-v1", scalarType: "number", value: "9007199254740993.123456789" },+ { $dbx: "oracle-anydata-v1", scalarType: "char", value: null },+ { $dbx: "oracle-anydata-v1", scalarType: "timestamp-tz", value: { civilDate: "-0001-12-31", seconds: "86399.123456789", region: "America/New_York", offset: "-04:00", abbreviation: "EDT" } },+ { $dbx: "oracle-anydata-v1", scalarType: "interval-ds", value: "-86399999999999999999999" },+ { $dbx: "oracle-anydata-v1", scalarType: "binary-double", value: "3FF0000000000001" },+ { $dbx: "oracle-anydata-v1", scalarType: "raw", value: "00FF0000" },+ ];+ const request: NativeJobRequest = { ...mutation, arguments: values.map((value, index) => ({ position: index + 1, value: { kind: "value", value } })) };+ await tauri.nativeJobPrepare(request);+ expect(invoke).toHaveBeenCalledExactlyOnceWith("native_job_prepare", { mutation: request });+ await http.nativeJobPrepare(request);+ expect(JSON.parse(fetch.mock.calls[0][1].body)).toEqual(request);+ });++ it.each(["window", "window-group", "file-watcher", "destination-group"] as const)("preserves the %s reference category through both transports", async (kind) => {+ const request = { scope, kind, schema: 'Exact.Owner"', name: "Named,Reference.One", filter: "", offset: 0, limit: 1 };+ const catalog = { objects: { status: "available", value: [{ DBX_OWNER: request.schema, DBX_NAME: request.name }] }, source: { source: "native-reference", coverage: "accessible" }, offset: 0, limit: 1 };+ invoke.mockResolvedValue(catalog);+ fetch.mockResolvedValue(new Response(JSON.stringify(catalog), { headers: { "Content-Type": "application/json" } }));+ expect(await tauri.nativeJobReferences(request)).toEqual(catalog);+ expect(invoke).toHaveBeenCalledExactlyOnceWith("native_job_references", { request });+ expect(await http.nativeJobReferences(request)).toEqual(catalog);+ expect(JSON.parse(fetch.mock.calls[0][1].body)).toEqual(request);+ });++ it.each([false, true])("keeps final enabled intent %s with exact reference components in both previews", async (finalEnabled) => {+ const request: NativeJobRequest = {+ ...mutation,+ finalEnabled,+ attributes: [{ name: "PROGRAM_NAME", change: { kind: "set", value: { owner: 'Other.Owner"', name: "Program,A.B", kind: "program" } } }],+ argumentTarget: { program: { owner: 'Other.Owner"', name: "Program,A.B" }, arguments: [{ position: 1, dataType: "NUMBER", value: { kind: "null" } }] },+ };+ const plan = { planId: "plan", operationId: "operation", scope, target, steps: [] };+ invoke.mockResolvedValue(plan);+ fetch.mockResolvedValue(new Response(JSON.stringify(plan), { headers: { "Content-Type": "application/json" } }));+ expect(await tauri.nativeJobPrepare(request)).toEqual(plan);+ expect(invoke).toHaveBeenCalledExactlyOnceWith("native_job_prepare", { mutation: request });+ expect(await http.nativeJobPrepare(request)).toEqual(plan);+ expect(JSON.parse(fetch.mock.calls[0][1].body)).toEqual(request);+ expect(mutation).not.toHaveProperty("finalEnabled");+ });++ it("previews a new legacy Job without inventing a numeric ID or changing its scope", async () => {+ const request = { action: "create" as const, scope, definition: { kind: "legacy" as const, what: "private_call('x');", nextDate: "2026-10-21 10:20:30", interval: "NULL", enabled: false, schema: "Exact Owner" } };+ const plan = { planId: "plan", operationId: "operation", scope, target: null, steps: [] };+ invoke.mockResolvedValue(plan);+ fetch.mockResolvedValue(new Response(JSON.stringify(plan), { headers: { "Content-Type": "application/json" } }));+ expect(await tauri.nativeJobPrepare(request)).toEqual(plan);+ expect(invoke).toHaveBeenCalledExactlyOnceWith("native_job_prepare", { mutation: request });+ expect(await http.nativeJobPrepare(request)).toEqual(plan);+ expect(JSON.parse(fetch.mock.calls[0][1].body)).toEqual(request);+ expect(JSON.parse(fetch.mock.calls[0][1].body)).not.toHaveProperty("target");+ });++ it("opts into native observation using only the operation ID and preserves exact instance keys", async () => {+ const result = {+ ...response,+ outcome: "accepted",+ executionObservation: {+ observedAt: "2026-10-21T12:00:00Z",+ association: "uncertain",+ reason: "native_job_observation_request_uncertain",+ running: { status: "empty" },+ history: { status: "available", value: [{ LOG_ID: "900719925474099312345", STATUS: "FAILED" }] },+ sources: {},+ candidates: [{ nativeKey: "900719925474099312345", phase: "history", evidence: "new-history", row: { LOG_ID: "900719925474099312345", STATUS: "FAILED" } }],+ },+ };+ invoke.mockResolvedValue(result);+ fetch.mockResolvedValue(new Response(JSON.stringify(result), { headers: { "Content-Type": "application/json" } }));+ expect(await tauri.nativeJobStatus("operation", true)).toEqual(result);+ expect(invoke).toHaveBeenCalledExactlyOnceWith("native_job_status", { operationId: "operation", observe: true });+ expect(await http.nativeJobStatus("operation", true)).toEqual(result);+ expect(JSON.parse(fetch.mock.calls[0][1].body)).toEqual({ operationId: "operation", observe: true });+ });++ it("preserves Scheduler references and observed native generations without numeric coercion", async () => {+ const request = {+ action: "create" as const,+ scope,+ definition: {+ kind: "scheduler" as const,+ owner: target.owner,+ name: target.name,+ program: { owner: "Other.Owner", name: 'Program,"Name' },+ schedule: { owner: "CalendarOwner", name: "Calendar.Name" },+ numberOfArguments: 0,+ enabled: false,+ autoDrop: false,+ arguments: [{ position: 1, dataType: "VARCHAR2", value: { kind: "inherit" as const } }],+ },+ };+ const plan = { planId: "scheduler-plan", operationId: "scheduler-operation", scope, target, steps: [] };+ const result = { ...response, observedIdentity: { DBX_JOB_ID: "900719925474099312345", DBX_CREATED_AT: "exact generation" } };+ invoke.mockImplementation(async (command: string) => (command === "native_job_prepare" ? plan : result));+ fetch.mockImplementation(async (url: string) => new Response(JSON.stringify(url.endsWith("/prepare") ? plan : result), { headers: { "Content-Type": "application/json" } }));+ expect(await tauri.nativeJobPrepare(request)).toEqual(plan);+ expect(await http.nativeJobPrepare(request)).toEqual(plan);+ expect(JSON.parse(fetch.mock.calls[0][1].body)).toEqual(request);+ expect(await tauri.nativeJobStatus("operation-id")).toEqual(result);+ expect(await http.nativeJobStatus("operation-id")).toEqual(result);+ });++ it("preserves Dameng child edits and explicit native command input through both transports", async () => {+ const request: NativeJobRequest = {+ action: "configure-dameng",+ target: { kind: "dameng-native", scope, jobId: "900719925474099312345", name: "Job_1" },+ baseline: "native-baseline",+ configuration: {+ attributes: [{ name: "ENABLE", change: { kind: "set", value: false } }],+ steps: [+ {+ kind: "update",+ name: "backup",+ attributes: [+ { name: "COMMAND_INPUT", change: { kind: "set", value: "01000000E:\\backups" } },+ { name: "SUCC_NEXT_STEP", change: { kind: "clear" } },+ ],+ },+ ],+ schedules: [+ { kind: "add", name: "new_schedule" },+ { kind: "drop", name: "old_schedule" },+ ],+ },+ };+ expect(await tauri.nativeJobPrepare(request)).toEqual(response);+ expect(invoke).toHaveBeenCalledExactlyOnceWith("native_job_prepare", { mutation: request });+ expect(await http.nativeJobPrepare(request)).toEqual(response);+ expect(JSON.parse(fetch.mock.calls[0][1].body)).toEqual(request);+ expect(await api.nativeJobPrepare(request)).toEqual(response);+ expect(JSON.parse(fetch.mock.calls[1][1].body)).toEqual(request);+ });++ it("keeps native Dameng creation targetless and returns acknowledged child IDs as exact strings", async () => {+ const request: NativeJobRequest = { action: "create", scope, definition: { kind: "dameng-native", name: "New_job", enabled: false, configuration: { steps: [{ kind: "add", name: "sql", attributes: [{ name: "COMMAND_INPUT", change: { kind: "set", value: "SELECT 1;" } }] }] } } };+ const plan = { planId: "native-create", operationId: "operation", scope, target: null, steps: [] };+ const result = { ...response, createdChildren: [{ partition: "steps", name: "sql", id: "900719925474099312345" }] };+ invoke.mockImplementation(async (command: string) => (command === "native_job_prepare" ? plan : result));+ fetch.mockImplementation(async (url: string) => new Response(JSON.stringify(url.endsWith("/prepare") ? plan : result), { headers: { "Content-Type": "application/json" } }));+ expect(await tauri.nativeJobPrepare(request)).toEqual(plan);+ expect(await http.nativeJobPrepare(request)).toEqual(plan);+ expect(JSON.parse(fetch.mock.calls[0][1].body)).toEqual(request);+ expect(await tauri.nativeJobStatus("operation")).toEqual(result);+ expect(await http.nativeJobStatus("operation")).toEqual(result);+ });+});diff --git a/apps/desktop/src/lib/backend/__tests__/triggerMetadataTransport.spec.ts b/apps/desktop/src/lib/backend/__tests__/triggerMetadataTransport.spec.tsnew file mode 100644index 0000000000..24c0747f15--- /dev/null+++ b/apps/desktop/src/lib/backend/__tests__/triggerMetadataTransport.spec.ts@@ -0,0 +1,80 @@+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++const mocks = vi.hoisted(() => ({ invoke: vi.fn() }));+vi.mock("@tauri-apps/api/core", () => ({ invoke: mocks.invoke }));+vi.mock("@tauri-apps/api/event", () => ({ listen: vi.fn() }));++const cases = [+ { method: "listObjects", command: "list_objects", route: "/api/schema/objects", args: ["connection", "database", " Owner ", ["TRIGGER"], "mix", 1, 2, "catalog", undefined, undefined, { identityMode: "exact" }] },+ { method: "listTriggers", command: "list_triggers", route: "/api/schema/triggers", args: ["connection", "database", " Parent Owner ", " Parent ", "catalog", { identityMode: "exact" }] },+ { method: "getObjectSource", command: "get_object_source", route: "/api/schema/object-source", args: ["connection", "database", " Owner ", " Trigger ", "TRIGGER", undefined, undefined, { identityMode: "exact", catalog: "catalog" }] },+] as const;++describe("opt-in trigger identity dual transport", () => {+ beforeEach(() => vi.clearAllMocks());+ afterEach(() => vi.unstubAllGlobals());++ it.each(cases)("Tauri $method transports exact options and raw identities", async ({ method, command, args }) => {+ const response = { marker: "unchanged metadata" };+ mocks.invoke.mockResolvedValue(response);+ const transport = await import("@/lib/backend/tauri");+ const call = transport[method] as (...args: unknown[]) => Promise<unknown>;+ await expect(call(...args)).resolves.toBe(response);+ expect(mocks.invoke).toHaveBeenCalledWith(command, expect.objectContaining({ identityMode: "exact", catalog: "catalog", schema: args[2] }));+ if (method === "listTriggers") expect(mocks.invoke.mock.calls[0][1].table).toBe(" Parent ");+ if (method === "getObjectSource") expect(mocks.invoke.mock.calls[0][1].name).toBe(" Trigger ");+ });++ it.each(cases)("Web $method transports the same options and raw identities", async ({ method, route, args }) => {+ const response = { marker: "unchanged metadata" };+ const fetch = vi.fn().mockResolvedValue({ ok: true, json: vi.fn().mockResolvedValue(response) });+ vi.stubGlobal("fetch", fetch);+ const transport = await import("@/lib/backend/http");+ const call = transport[method] as (...args: unknown[]) => Promise<unknown>;+ await expect(call(...args)).resolves.toBe(response);+ const url = new URL(String(fetch.mock.calls[0][0]), "http://localhost");+ expect(url.pathname).toBe(route);+ expect(url.searchParams.get("identity_mode")).toBe("exact");+ expect(url.searchParams.get("catalog")).toBe("catalog");+ expect(url.searchParams.get("schema")).toBe(args[2]);+ if (method === "listTriggers") expect(url.searchParams.get("table")).toBe(" Parent ");+ if (method === "getObjectSource") expect(url.searchParams.get("table")).toBe(" Trigger ");+ if (method === "listObjects") {+ expect(url.searchParams.get("object_types")).toBe("TRIGGER");+ expect(url.searchParams.get("limit")).toBe("1");+ expect(url.searchParams.get("offset")).toBe("2");+ }+ });++ it("does not add exact preconditions or source catalog to default Tauri callers", async () => {+ mocks.invoke.mockResolvedValue({});+ const transport = await import("@/lib/backend/tauri");+ await transport.getObjectSource("connection", "database", "owner", "trigger", "TRIGGER");+ expect(mocks.invoke.mock.calls[0][1]).not.toHaveProperty("identityMode");+ expect(mocks.invoke.mock.calls[0][1]).not.toHaveProperty("catalog");+ });++ it("keeps the default Web read contract", async () => {+ const fetch = vi.fn().mockResolvedValue({ ok: true, json: vi.fn().mockResolvedValue([]) });+ vi.stubGlobal("fetch", fetch);+ const transport = await import("@/lib/backend/http");+ await transport.listTriggers("connection", "database", "owner", "table");+ const url = new URL(String(fetch.mock.calls[0][0]), "http://localhost");+ expect(url.searchParams.has("identity_mode")).toBe(false);+ });++ it.each(["tauri", "http"] as const)("%s forwards pure trigger SQL preparation without changing target text", async (kind) => {+ const input = { databaseType: "oracle", owner: " Owner ", name: ' Tr"ig ', source: "-- 原始正文\nCREATE TRIGGER ...", purpose: "replace", enabled: false, binding: { scope: "VIEW", owner: " Parent Owner ", name: " View ", pluggable: false } };+ const response = { definition: "prepared definition", header: { scope: "RELATION", owner: " Parent Owner ", name: " View ", viewOnly: true, pluggable: false }, inlineEnabled: false, exportEnabled: null, requiresStateRestore: false };+ mocks.invoke.mockResolvedValue(response);+ const fetch = vi.fn().mockResolvedValue({ ok: true, json: vi.fn().mockResolvedValue(response) });+ vi.stubGlobal("fetch", fetch);+ const transport = (kind === "tauri" ? await import("@/lib/backend/tauri") : await import("@/lib/backend/http")) as unknown as { prepareOracleTriggerSql: (input: unknown) => Promise<unknown> };+ await expect(transport.prepareOracleTriggerSql(input)).resolves.toBe(response);+ if (kind === "tauri") expect(mocks.invoke).toHaveBeenCalledWith("prepare_oracle_trigger_sql", { input });+ else {+ expect(String(fetch.mock.calls[0][0])).toContain("/api/query/prepare-oracle-trigger-sql");+ expect(JSON.parse(fetch.mock.calls[0][1].body)).toEqual({ input });+ }+ });+});diff --git a/apps/desktop/src/lib/backend/api.ts b/apps/desktop/src/lib/backend/api.tsindex e01631962d..82ba8eedfb 100644--- a/apps/desktop/src/lib/backend/api.ts+++ b/apps/desktop/src/lib/backend/api.ts@@ -227,6 +227,14 @@ export const completionAssistantSearch = forward("completionAssistantSearch");export const getObjectSource = forward("getObjectSource");export const getEventInfo = forward("getEventInfo");export const getCustomTypeDetails = forward("getCustomTypeDetails");+export const nativeJobOpenContext = forward("nativeJobOpenContext");+export const nativeJobList = forward("nativeJobList");+export const nativeJobReferences = forward("nativeJobReferences");+export const nativeJobRead = forward("nativeJobRead");+export const nativeJobPrepare = forward("nativeJobPrepare");+export const nativeJobApply = forward("nativeJobApply");+export const nativeJobStatus = forward("nativeJobStatus");+export const nativeJobCancel = forward("nativeJobCancel");export const getOracleTypeManagementSnapshot = forward("getOracleTypeManagementSnapshot");export const buildOracleTypeManagementSql = forward("buildOracleTypeManagementSql");export const verifyOracleTypeData = forward("verifyOracleTypeData");@@ -342,6 +350,7 @@ export const buildDuplicateTableStructureSql = forward("buildDuplicateTableStrucexport const buildCopyTableDataSql = forward("buildCopyTableDataSql");export const buildExecutableObjectSourceStatements = forward("buildExecutableObjectSourceStatements");export const validateOracleExecutableObjectSource = forward("validateOracleExecutableObjectSource");+export const prepareOracleTriggerSql = forward("prepareOracleTriggerSql");export const fingerprintOracleRoutineObjectSource = forward("fingerprintOracleRoutineObjectSource");export const buildExecutableObjectSourceSql = forward("buildExecutableObjectSourceSql");export const buildEditableObjectSource = forward("buildEditableObjectSource");diff --git a/apps/desktop/src/lib/backend/http.ts b/apps/desktop/src/lib/backend/http.tsindex 511300e4b9..609afcd6a4 100644--- a/apps/desktop/src/lib/backend/http.ts+++ b/apps/desktop/src/lib/backend/http.ts@@ -6,6 +6,7 @@ import type { MongoRestoreUpload, MongoSourceReadOptions } from "./mongodbDumpTyimport type { DamengDumpKind, DamengDumpRequest, DamengDumpProgress } from "./damengDumpTypes";import type { UserSkillRootSettings, UserSkillsListResult, UserSkillsReadResult } from "@/types/userSkills";import type { DatabaseBackupCommand, DatabaseBackupBackgroundStatus } from "@/lib/backup/backgroundDatabaseBackup";+import type { NativeJobContext, NativeJobDetails, NativeJobList, NativeJobListRequest, NativeJobRequest, NativeJobOperationStatus, NativeJobPreparedPlan, NativeJobRef, NativeJobReferenceCatalog, NativeJobReferenceListRequest } from "@/lib/database/nativeJobs";import type { PluginUiStorageItemRef, SqlFileFailureLogExportPayload, SqlFileFailureLogInfo, SqlFileFailureLogKey, SqlFileFailureLogTextPayload, SyncCatalogItem, SyncSelection, SyncSnapshotCatalog } from "@/lib/backend/tauri";import { FAILURE_LOG_TEXT_TOO_LARGE } from "@/lib/export/failureLogExport";import { saveTextFile } from "@/lib/export/saveTextFile";@@ -260,6 +261,7 @@ import type { BuildTableSelectSqlOptions } from "@/lib/table/tableSelectSql";import type { DatabaseSearchSql, DatabaseSearchSqlOptions, SearchResultWhereOptions } from "@/lib/database/databaseSearch";import type { DatabaseStructureSearchSql, DatabaseStructureSearchSqlOptions } from "@/lib/database/databaseStructureSearch";import type { BuildEditableObjectSourceSqlInput, BuildRoutineRenameObjectSourceInput, FingerprintOracleRoutineObjectSourceInput, RewriteOracleRoutineReferencesInput, ValidateOracleExecutableObjectSourceInput } from "@/lib/table/objectSourceEditor";+import type { OracleTriggerSqlInput, PreparedOracleTriggerSql } from "@/lib/database/oracleTriggerSql";import type { OracleTableReferenceRewriteInput, OracleViewRenameSource, OracleViewRenameSourceInput, OracleViewRenameSourceReview } from "@/types/database";import type { BuildViewDdlInput } from "@/lib/table/viewDdl";import type { BuildRenameObjectSqlOptions } from "@/lib/table/objectRenameSql";@@ -1262,8 +1264,9 @@ export async function listObjects(catalog?: string,tableNameFilter?: TableNameFilter,executionId?: string,- exactIdentity?: boolean,+ options?: boolean | import("@/types/database").MetadataReadOptions,): Promise<ObjectInfo[]> {+ const readOptions = typeof options === "object" ? options : undefined;return get(`/api/schema/objects?${qs({connection_id: connectionId,@@ -1273,10 +1276,11 @@ export async function listObjects(filter,limit,offset,- catalog,+ catalog: readOptions?.catalog ?? catalog,table_name_filter: tableNameFilter ? JSON.stringify(tableNameFilter) : undefined,execution_id: executionId,- exact_identity: exactIdentity || undefined,+ identity_mode: readOptions?.identityMode,+ exact_identity: options === true || undefined,})}`,);}@@ -1293,8 +1297,8 @@ export async function completionAssistantSearch(request: CompletionAssistantRequreturn post("/api/schema/completion-assistant", request);}-export async function getObjectSource(connectionId: string, database: string, schema: string, name: string, objectType: ObjectSourceKind, signature?: string, relationName?: string): Promise<ObjectSource> {- return get(`/api/schema/object-source?${qs({ connection_id: connectionId, database, schema, table: name, object_type: objectType, signature, relation_name: relationName })}`);+export async function getObjectSource(connectionId: string, database: string, schema: string, name: string, objectType: ObjectSourceKind, signature?: string, relationName?: string, options?: import("@/types/database").MetadataReadOptions): Promise<ObjectSource> {+ return get(`/api/schema/object-source?${qs({ connection_id: connectionId, database, schema, table: name, object_type: objectType, signature, relation_name: relationName, identity_mode: options?.identityMode, catalog: options?.catalog })}`);}export async function getEventInfo(connectionId: string, database: string, schema: string, name: string): Promise<MysqlEventInfo> {@@ -1305,6 +1309,31 @@ export async function getCustomTypeDetails(connectionId: string, database: strinreturn get(`/api/schema/custom-type-details?${qs({ connection_id: connectionId, database, schema, table: name })}`);}+export function nativeJobOpenContext(connectionId: string, database: string): Promise<NativeJobContext> {+ return post("/api/schema/native-jobs/context", { connectionId, database });+}+export function nativeJobList(request: NativeJobListRequest): Promise<NativeJobList> {+ return post("/api/schema/native-jobs/list", request);+}+export function nativeJobReferences(request: NativeJobReferenceListRequest): Promise<NativeJobReferenceCatalog> {+ return post("/api/schema/native-jobs/references", request);+}+export function nativeJobRead(target: NativeJobRef): Promise<NativeJobDetails> {+ return post("/api/schema/native-jobs/read", target);+}+export function nativeJobPrepare(mutation: NativeJobRequest): Promise<NativeJobPreparedPlan> {+ return post("/api/schema/native-jobs/prepare", mutation);+}+export function nativeJobApply(planId: string): Promise<NativeJobOperationStatus> {+ return post("/api/schema/native-jobs/apply", { planId });+}+export function nativeJobStatus(operationId: string, observe?: boolean): Promise<NativeJobOperationStatus> {+ return post("/api/schema/native-jobs/status", { operationId, ...(observe ? { observe: true } : {}) });+}+export function nativeJobCancel(operationId: string): Promise<NativeJobOperationStatus> {+ return post("/api/schema/native-jobs/cancel", { operationId });+}+export async function getOracleTypeManagementSnapshot(connectionId: string, database: string, owner: string, name: string, knownObjects: OracleTypeManagementObjectKey[] = []): Promise<OracleTypeManagementSnapshot> {if (knownObjects.length) return post("/api/schema/oracle-type-management-snapshot", { target: { connectionId, database, owner, name }, knownObjects });return get(`/api/schema/oracle-type-management-snapshot?${qs({ connection_id: connectionId, database, schema: owner, table: name })}`);@@ -1365,8 +1394,9 @@ export async function listForeignKeysForDatabase(connectionId: string, database:return get(`/api/schema/foreign-keys-for-database?${qs({ connection_id: connectionId, database, schema, catalog, execution_id: executionId })}`);}-export async function listTriggers(connectionId: string, database: string, schema: string, table: string, catalog?: string, exactIdentity?: boolean): Promise<TriggerInfo[]> {- return get(`/api/schema/triggers?${qs({ connection_id: connectionId, database, schema, table, catalog, exact_identity: exactIdentity || undefined })}`);+export async function listTriggers(connectionId: string, database: string, schema: string, table: string, catalog?: string, options?: boolean | import("@/types/database").MetadataReadOptions): Promise<TriggerInfo[]> {+ const readOptions = typeof options === "object" ? options : undefined;+ return get(`/api/schema/triggers?${qs({ connection_id: connectionId, database, schema, table, catalog: readOptions?.catalog ?? catalog, identity_mode: readOptions?.identityMode, exact_identity: options === true || undefined })}`);}export async function listConstraints(connectionId: string, database: string, schema: string, table: string, catalog?: string, exactIdentity?: boolean): Promise<ConstraintInfo[]> {@@ -2072,6 +2102,10 @@ export async function validateOracleExecutableObjectSource(input: ValidateOraclereturn post("/api/query/validate-oracle-executable-object-source", { input });}+export async function prepareOracleTriggerSql(input: OracleTriggerSqlInput): Promise<PreparedOracleTriggerSql> {+ return post("/api/query/prepare-oracle-trigger-sql", { input });+}+export async function fingerprintOracleRoutineObjectSource(input: FingerprintOracleRoutineObjectSourceInput): Promise<string> {return post("/api/query/fingerprint-oracle-routine-object-source", { input });}diff --git a/apps/desktop/src/lib/backend/tauri.ts b/apps/desktop/src/lib/backend/tauri.tsindex 4ff2afa160..abb384d366 100644--- a/apps/desktop/src/lib/backend/tauri.ts+++ b/apps/desktop/src/lib/backend/tauri.ts@@ -7,6 +7,7 @@ import type { MongoRestoreUpload, MongoSourceReadOptions } from "./mongodbDumpTyimport type { DamengDumpKind, DamengDumpRequest, DamengDumpProgress } from "./damengDumpTypes";import type { UserSkillRootSettings, UserSkillsListResult, UserSkillsReadResult } from "@/types/userSkills";import type { DatabaseBackupCommand, DatabaseBackupBackgroundStatus } from "@/lib/backup/backgroundDatabaseBackup";+import type { NativeJobContext, NativeJobDetails, NativeJobList, NativeJobListRequest, NativeJobRequest, NativeJobOperationStatus, NativeJobPreparedPlan, NativeJobRef, NativeJobReferenceCatalog, NativeJobReferenceListRequest } from "@/lib/database/nativeJobs";import { functionDiffsToWire, functionInfoFromWire, schemaDiffPreparationFromWire, schemaDiffPreparationToWire, type FunctionInfoWire, type SchemaDiffPreparationWire } from "./functionInfoTransport";import type { OracleRoutineSnapshot, OracleRoutineOperation, OracleRoutineOperationObservation, OracleRoutineSaveInput, OracleRoutinePlanInput, OracleRoutinePlan, OracleRoutineReadOptions, OracleRoutineIdentity } from "@/types/schemaDiff";@@ -183,6 +184,7 @@ import type { BuildTableSelectSqlOptions } from "@/lib/table/tableSelectSql";import type { DatabaseSearchSql, DatabaseSearchSqlOptions, SearchResultWhereOptions } from "@/lib/database/databaseSearch";import type { DatabaseStructureSearchSql, DatabaseStructureSearchSqlOptions } from "@/lib/database/databaseStructureSearch";import type { BuildEditableObjectSourceSqlInput, BuildRoutineRenameObjectSourceInput, FingerprintOracleRoutineObjectSourceInput, RewriteOracleRoutineReferencesInput, ValidateOracleExecutableObjectSourceInput } from "@/lib/table/objectSourceEditor";+import type { OracleTriggerSqlInput, PreparedOracleTriggerSql } from "@/lib/database/oracleTriggerSql";import type { OracleTableReferenceRewriteInput, OracleViewRenameSource, OracleViewRenameSourceInput, OracleViewRenameSourceReview } from "@/types/database";import type { BuildViewDdlInput } from "@/lib/table/viewDdl";import type { BuildRenameObjectSqlOptions } from "@/lib/table/objectRenameSql";@@ -1877,8 +1879,9 @@ export async function listObjects(catalog?: string,tableNameFilter?: import("@/types/database").TableNameFilter,executionId?: string,- exactIdentity?: boolean,+ options?: boolean | import("@/types/database").MetadataReadOptions,): Promise<ObjectInfo[]> {+ const readOptions = typeof options === "object" ? options : undefined;return invoke("list_objects", {connectionId,database,@@ -1887,10 +1890,11 @@ export async function listObjects(filter,limit,offset,- catalog,+ catalog: readOptions?.catalog ?? catalog,tableNameFilter,executionId,- ...(exactIdentity ? { exactIdentity: true } : {}),+ ...(readOptions?.identityMode ? { identityMode: readOptions.identityMode } : {}),+ ...(options === true ? { exactIdentity: true } : {}),});}@@ -1906,7 +1910,7 @@ export async function completionAssistantSearch(request: CompletionAssistantRequreturn invoke("completion_assistant_search", { request });}-export async function getObjectSource(connectionId: string, database: string, schema: string, name: string, objectType: ObjectSourceKind, signature?: string, relationName?: string): Promise<ObjectSource> {+export async function getObjectSource(connectionId: string, database: string, schema: string, name: string, objectType: ObjectSourceKind, signature?: string, relationName?: string, options?: import("@/types/database").MetadataReadOptions): Promise<ObjectSource> {return invoke("get_object_source", {connectionId,database,@@ -1915,6 +1919,8 @@ export async function getObjectSource(connectionId: string, database: string, scobjectType,signature,relationName,+ ...(options?.identityMode ? { identityMode: options.identityMode } : {}),+ ...(options?.catalog !== undefined ? { catalog: options.catalog } : {}),});}@@ -1933,6 +1939,32 @@ export async function listSchemaInfos(connectionId: string, database: string): Pexport async function getCustomTypeDetails(connectionId: string, database: string, schema: string, name: string): Promise<CustomTypeDetails> {return invoke("get_custom_type_details", { connectionId, database, schema, name });}++export function nativeJobOpenContext(connectionId: string, database: string): Promise<NativeJobContext> {+ return invokeBackend("native_job_open_context", { connectionId, database });+}+export function nativeJobList(request: NativeJobListRequest): Promise<NativeJobList> {+ return invokeBackend("native_job_list", { request });+}+export function nativeJobReferences(request: NativeJobReferenceListRequest): Promise<NativeJobReferenceCatalog> {+ return invokeBackend("native_job_references", { request });+}+export function nativeJobRead(target: NativeJobRef): Promise<NativeJobDetails> {+ return invokeBackend("native_job_read", { target });+}+export function nativeJobPrepare(mutation: NativeJobRequest): Promise<NativeJobPreparedPlan> {+ return invokeBackend("native_job_prepare", { mutation });+}+export function nativeJobApply(planId: string): Promise<NativeJobOperationStatus> {+ return invokeBackend("native_job_apply", { planId });+}+export function nativeJobStatus(operationId: string, observe?: boolean): Promise<NativeJobOperationStatus> {+ return invokeBackend("native_job_status", { operationId, ...(observe ? { observe: true } : {}) });+}+export function nativeJobCancel(operationId: string): Promise<NativeJobOperationStatus> {+ return invokeBackend("native_job_cancel", { operationId });+}+export async function getOracleTypeManagementSnapshot(connectionId: string, database: string, owner: string, name: string, knownObjects: OracleTypeManagementObjectKey[] = []): Promise<OracleTypeManagementSnapshot> {return invoke("get_oracle_type_management_snapshot", { connectionId, database, owner, name, knownObjects });}@@ -2508,6 +2540,10 @@ export async function validateOracleExecutableObjectSource(input: ValidateOraclereturn invoke("validate_oracle_executable_object_source", { input });}+export async function prepareOracleTriggerSql(input: OracleTriggerSqlInput): Promise<PreparedOracleTriggerSql> {+ return invoke("prepare_oracle_trigger_sql", { input });+}+export async function fingerprintOracleRoutineObjectSource(input: FingerprintOracleRoutineObjectSourceInput): Promise<string> {return invoke("fingerprint_oracle_routine_object_source", { input });}@@ -2749,14 +2785,16 @@ export async function listForeignKeysForDatabase(connectionId: string, database:return invoke("list_foreign_keys_for_database", { connectionId, database, schema, catalog, executionId });}-export async function listTriggers(connectionId: string, database: string, schema: string, table: string, catalog?: string, exactIdentity?: boolean): Promise<TriggerInfo[]> {+export async function listTriggers(connectionId: string, database: string, schema: string, table: string, catalog?: string, options?: boolean | import("@/types/database").MetadataReadOptions): Promise<TriggerInfo[]> {+ const readOptions = typeof options === "object" ? options : undefined;return invoke("list_triggers", {connectionId,database,schema,table,- catalog,- ...(exactIdentity ? { exactIdentity: true } : {}),+ catalog: readOptions?.catalog ?? catalog,+ ...(readOptions?.identityMode ? { identityMode: readOptions.identityMode } : {}),+ ...(options === true ? { exactIdentity: true } : {}),});}diff --git a/apps/desktop/src/lib/database/__tests__/oracleInvalidObjects.spec.ts b/apps/desktop/src/lib/database/__tests__/oracleInvalidObjects.spec.tsindex fa37d5dd8a..c2397b2e4e 100644--- a/apps/desktop/src/lib/database/__tests__/oracleInvalidObjects.spec.ts+++ b/apps/desktop/src/lib/database/__tests__/oracleInvalidObjects.spec.ts@@ -141,6 +141,17 @@ describe("Oracle invalid-object SQL and mapping", () => {expect(() => buildOracleCompileSql("oceanbase-oracle", "APP", { name: "V", type: "VIEW" })).toThrow();});+ it("adds only the verified OB trigger profile without changing default or unrelated compile capabilities", () => {+ const trigger = { name: ' Tr"ig ', type: "TRIGGER" };+ const triggerProfile = { contractVersion: 1, identityMode: "exact", engine: "oceanbase-oracle", engineVersion: "4.2.5.7_107" } as const;+ expect(buildOracleCompileSql("oceanbase-oracle", " Owner ", trigger, { triggerProfile })).toBe('ALTER TRIGGER " Owner "." Tr""ig " COMPILE');+ expect(() => buildOracleCompileSql("oceanbase-oracle", " Owner ", trigger)).toThrow();+ expect(() => buildOracleCompileSql("oceanbase-oracle", " Owner ", trigger, { triggerProfile: { ...triggerProfile, engineVersion: "4.3.0" } })).toThrow();+ expect(() => buildOracleCompileSql("oceanbase-oracle", " Owner ", trigger, { triggerProfile: { ...triggerProfile, engineVersion: undefined } })).toThrow();+ expect(() => buildOracleCompileSql("oceanbase-oracle", " Owner ", { name: "V", type: "VIEW" }, { triggerProfile })).toThrow();+ expect(() => buildOracleCompileSql("oceanbase-oracle", " Owner ", { name: "T", type: "TYPE" }, { triggerProfile })).toThrow();+ });+it("maps numeric error locations and keeps the database sequence", () => {expect(mapOracleObjectErrors([diff --git a/apps/desktop/src/lib/database/databaseObjectCapabilities.ts b/apps/desktop/src/lib/database/databaseObjectCapabilities.tsindex 4b7f7729b2..0d19e5fefc 100644--- a/apps/desktop/src/lib/database/databaseObjectCapabilities.ts+++ b/apps/desktop/src/lib/database/databaseObjectCapabilities.ts@@ -34,9 +34,9 @@ const KINGBASE_OBJECTS: SidebarObjectKind[] = ["TABLE", "VIEW", "MATERIALIZED_VIconst VASTBASE_OBJECTS: SidebarObjectKind[] = ["TABLE", "VIEW", "MATERIALIZED_VIEW", "PROCEDURE", "FUNCTION", "SEQUENCE", "TYPE"];const POSTGRES_LIKE_OBJECTS: SidebarObjectKind[] = ["TABLE", "VIEW", "MATERIALIZED_VIEW", "PROCEDURE", "FUNCTION"];-const ORACLE_OBJECTS: SidebarObjectKind[] = ["TABLE", "VIEW", "MATERIALIZED_VIEW", "PROCEDURE", "FUNCTION", "SEQUENCE", "INDEX", "SYNONYM", "PACKAGE", "PACKAGE_BODY", "TYPE", "TYPE_BODY"];-const OCEANBASE_ORACLE_OBJECTS: SidebarObjectKind[] = ["TABLE", "VIEW", "MATERIALIZED_VIEW", "PROCEDURE", "FUNCTION", "SEQUENCE", "INDEX", "SYNONYM", "PACKAGE", "PACKAGE_BODY", "TYPE", "TYPE_BODY"];-const DAMENG_OBJECTS: SidebarObjectKind[] = ["TABLE", "VIEW", "MATERIALIZED_VIEW", "PROCEDURE", "FUNCTION", "SEQUENCE", "INDEX", "PACKAGE", "PACKAGE_BODY", "TYPE", "TYPE_BODY"];+const ORACLE_OBJECTS: SidebarObjectKind[] = ["TABLE", "VIEW", "MATERIALIZED_VIEW", "PROCEDURE", "FUNCTION", "TRIGGER", "SEQUENCE", "INDEX", "SYNONYM", "PACKAGE", "PACKAGE_BODY", "TYPE", "TYPE_BODY"];+const OCEANBASE_ORACLE_OBJECTS: SidebarObjectKind[] = ["TABLE", "VIEW", "MATERIALIZED_VIEW", "PROCEDURE", "FUNCTION", "TRIGGER", "SEQUENCE", "INDEX", "SYNONYM", "PACKAGE", "PACKAGE_BODY", "TYPE", "TYPE_BODY"];+const DAMENG_OBJECTS: SidebarObjectKind[] = ["TABLE", "VIEW", "MATERIALIZED_VIEW", "PROCEDURE", "FUNCTION", "TRIGGER", "SEQUENCE", "INDEX", "PACKAGE", "PACKAGE_BODY", "TYPE", "TYPE_BODY"];export function supportsSchemaIndexManagement(dbType?: DatabaseType): boolean {return dbType === "oracle" || dbType === "oceanbase-oracle" || dbType === "dameng";diff --git a/apps/desktop/src/lib/database/databaseObjectDependencies.ts b/apps/desktop/src/lib/database/databaseObjectDependencies.tsindex f031d6e04d..6b8ca7b476 100644--- a/apps/desktop/src/lib/database/databaseObjectDependencies.ts+++ b/apps/desktop/src/lib/database/databaseObjectDependencies.ts@@ -1,6 +1,6 @@import type { DatabaseType, TreeNode } from "@/types/database";import { xuguDependencyProvider } from "@/lib/database/xuguObjectDependencies";-import { oracleDependencyProvider } from "@/lib/database/oracleObjectDependencies";+import { oracleDependencyProvider, dmTriggerDependencyProvider } from "@/lib/database/oracleObjectDependencies";import { supportsTypeObjectSource } from "@/lib/database/databaseObjectCapabilities";/**@@ -8,7 +8,7 @@ import { supportsTypeObjectSource } from "@/lib/database/databaseObjectCapabilit* Keeping this contract small lets providers remain independent of Vue state* and makes it possible to test them without constructing a full tree node.*/-export type DependencyTreeNode = Pick<TreeNode, "type" | "schema" | "objectName" | "label" | "parentType" | "parentName" | "parentSchema">;+export type DependencyTreeNode = Pick<TreeNode, "type" | "schema" | "objectName" | "label" | "parentType" | "parentName" | "parentSchema" | "meta">;/*** Database-specific dependency inspection contract.@@ -27,6 +27,7 @@ const PROVIDERS: Partial<Record<DatabaseType, DatabaseDependencyProvider>> = {xugu: xuguDependencyProvider,oracle: oracleDependencyProvider,"oceanbase-oracle": oracleDependencyProvider,+ dameng: dmTriggerDependencyProvider,};export function databaseDependencyProviderFor(databaseType?: DatabaseType): DatabaseDependencyProvider | null {diff --git a/apps/desktop/src/lib/database/nativeJobAdmin.ts b/apps/desktop/src/lib/database/nativeJobAdmin.tsnew file mode 100644index 0000000000..d40bf4903c--- /dev/null+++ b/apps/desktop/src/lib/database/nativeJobAdmin.ts@@ -0,0 +1,477 @@+import { effectiveDatabaseTypeForConnection, type JdbcDialectConnection } from "@/lib/database/jdbcDialect";+import {+ buildNativeJobEdit,+ nativeJobRefKey,+ type NativeJobArgument,+ type NativeJobArgumentValue,+ type NativeJobCreateArgument,+ type NativeJobDetails,+ type NativeJobEdit,+ type NativeJobEditDraft,+ type NativeJobEngine,+ type NativeJobEventSource,+ type NativeJobKind,+ type NativeJobMetadata,+ type NativeJobObjectReference,+ type NativeJobOperationStatus,+ type NativeJobReferenceKind,+ type NativeJobRequest,+ type NativeJobRow,+ type NativeJobScope,+ type NativeJobSnapshot,+ type NativeJobValue,+} from "@/lib/database/nativeJobs";++export interface NativeJobDefinitionDraft extends NativeJobEditDraft {+ finalEnabled?: boolean;+ originalSnapshot?: NativeJobSnapshot;+ reconcileArguments?: boolean;+ transitionRetained?: boolean;+ argumentLayouts?: Record<string, NativeJobMetadata<NativeJobArgument[]>>;+ referenceKinds?: Record<string, NativeJobReferenceKind>;+ scheduleMode?: NativeJobScheduleMode;+ destinationMode?: NativeJobDestinationMode;+ eventDraft?: NativeJobEventDraft;+ argumentTypes?: Record<number, string>;+ argumentContext?: string;+ argumentDrafts?: Record<string, { arguments: NonNullable<NativeJobEditDraft["arguments"]>; argumentTypes: Record<number, string> }>;+}++export type NativeJobScheduleMode = "inline" | "named" | "queue" | "file-watcher";+export type NativeJobDestinationMode = "local" | "legacy" | "named";+export function nativeJobDestinationMode(draft: NativeJobDefinitionDraft, definition: NativeJobRow): NativeJobDestinationMode {+ if (draft.destinationMode) return draft.destinationMode;+ if (typeof definition.DESTINATION_OWNER === "string" && definition.DESTINATION_OWNER) return "named";+ return typeof definition.DESTINATION === "string" && definition.DESTINATION ? "legacy" : "local";+}+export interface NativeJobEventDraft {+ condition: string;+ queueOwner: string;+ queueName: string;+ agent: string;+ watcherOwner: string;+ watcherName: string;+}++export function nativeJobEventDraft(definition: NativeJobRow): NativeJobEventDraft {+ const text = (name: string) => (typeof definition[name] === "string" ? definition[name] : "");+ return { condition: text("EVENT_CONDITION"), queueOwner: text("EVENT_QUEUE_OWNER"), queueName: text("EVENT_QUEUE_NAME"), agent: text("EVENT_QUEUE_AGENT"), watcherOwner: text("FILE_WATCHER_OWNER"), watcherName: text("FILE_WATCHER_NAME") };+}++export function nativeJobScheduleMode(draft: NativeJobDefinitionDraft, definition: NativeJobRow = {}): NativeJobScheduleMode {+ if (draft.scheduleMode) return draft.scheduleMode;+ const change = draft.attributes?.SCHEDULE_NAME;+ const name = change?.kind === "set" ? change.value : change?.kind === "clear" ? null : definition.SCHEDULE_NAME;+ if (name) return "named";+ if (definition.FILE_WATCHER_NAME) return "file-watcher";+ if (definition.EVENT_QUEUE_NAME) return "queue";+ return "inline";+}++function eventTrigger(draft: NativeJobDefinitionDraft): { condition: string | null; source: NativeJobEventSource & NativeJobValue } {+ const input = draft.eventDraft;+ if (!input) throw new TypeError("native_job_event_queue_required");+ const valid = (value: string) => value !== "" && !value.includes("\0");+ if (draft.scheduleMode === "file-watcher") {+ if (!valid(input.watcherOwner) || !valid(input.watcherName)) throw new TypeError("native_job_event_queue_required");+ return { condition: input.condition || null, source: { kind: "file-watcher", reference: { owner: input.watcherOwner, name: input.watcherName } } };+ }+ if (!valid(input.queueOwner) || !valid(input.queueName) || (input.agent && !valid(input.agent))) throw new TypeError("native_job_event_queue_required");+ return { condition: input.condition || null, source: { kind: "queue", owner: input.queueOwner, name: input.queueName, ...(input.agent ? { agent: input.agent } : {}) } };+}++/** Change the next draft, not the database; the normal fresh read/preview/confirm path still applies. */+export function restoreNativeJobDefinitionDraft(draft: NativeJobDefinitionDraft, details?: NativeJobDetails): void {+ const initial = draft.originalSnapshot;+ if (initial?.ref.kind !== "scheduler" || initial.definition.status !== "available") throw new TypeError("native_job_definition_unavailable");+ const projected = nativeJobDefinitionForEdit("oracle", "scheduler", initial.definition);+ if (projected.status !== "available") return;+ const original = projected.value;+ const names = new Set([...Object.keys(draft.attributes ?? {}), "PROGRAM_OWNER", "PROGRAM_NAME", "JOB_TYPE", "JOB_ACTION", "NUMBER_OF_ARGUMENTS", "SCHEDULE_OWNER", "SCHEDULE_NAME", "START_DATE", "END_DATE", "REPEAT_INTERVAL", "EVENT_SPEC", "DESTINATION", "DESTINATION_NAME"]);+ const attributes: NonNullable<NativeJobEditDraft["attributes"]> = {};+ for (const name of names) {+ const value = original[name];+ if (name !== "ENABLED" && value !== undefined) attributes[name] = value === null ? { kind: "clear" } : { kind: "set", value: structuredCloneValue(value) };+ }+ selectNativeJobArgumentContext(draft, typeof original.PROGRAM_OWNER === "string" ? original.PROGRAM_OWNER : "", typeof original.PROGRAM_NAME === "string" ? original.PROGRAM_NAME : undefined);+ draft.attributes = details ? Object.fromEntries(buildNativeJobEdit({ ...details.snapshot, definition: nativeJobDefinitionForEdit("oracle", "scheduler", details.snapshot.definition) }, { attributes }).attributes.map((attribute) => [attribute.name, attribute.change])) : attributes;+ draft.arguments = [];+ draft.argumentTypes = {};+ draft.eventDraft = nativeJobEventDraft(initial.definition.value);+ draft.scheduleMode = nativeJobScheduleMode({}, initial.definition.value);+ draft.destinationMode = nativeJobDestinationMode({}, initial.definition.value);+ draft.referenceKinds = { SCHEDULE_NAME: initial.definition.value.SCHEDULE_TYPE === "WINDOW" ? "window" : initial.definition.value.SCHEDULE_TYPE === "WINDOW_GROUP" ? "window-group" : "schedule" };+ draft.reconcileArguments ||= initial.arguments.status === "available";+ draft.transitionRetained = true;+ const enabled = initial.definition.value.ENABLED;+ if ([true, 1, "1", "TRUE", "true"].includes(enabled as string | number | boolean)) draft.finalEnabled = true;+ else if ([false, 0, "0", "FALSE", "false"].includes(enabled as string | number | boolean)) draft.finalEnabled = false;+}++/** Keep the pre-conversion intent even when a later read observes the paused job. */+export function initializeNativeJobDefinitionEdit(details: NativeJobDetails, draft: NativeJobDefinitionDraft): void {+ if (details.snapshot.ref.kind !== "scheduler" || details.snapshot.definition.status !== "available") return;+ const original = details.snapshot.definition.value;+ draft.originalSnapshot ??= structuredCloneValue(details.snapshot);+ if (draft.finalEnabled === undefined) {+ const enabled = original.ENABLED;+ if ([true, 1, "1", "TRUE", "true"].includes(enabled as string | number | boolean)) draft.finalEnabled = true;+ else if ([false, 0, "0", "FALSE", "false"].includes(enabled as string | number | boolean)) draft.finalEnabled = false;+ }+ if (!draft.argumentContext) {+ selectNativeJobArgumentContext(draft, typeof original.PROGRAM_OWNER === "string" ? original.PROGRAM_OWNER : "", typeof original.PROGRAM_NAME === "string" ? original.PROGRAM_NAME : undefined);+ draft.argumentLayouts ??= {};+ draft.argumentLayouts[draft.argumentContext!] = structuredCloneValue(details.snapshot.arguments);+ }+}++function argumentContext(owner: string, program?: string): string {+ return program ? JSON.stringify([owner, program]) : "inline";+}++/** Keep inactive inline/Program overrides in the draft, never apply them to another program. */+export function selectNativeJobArgumentContext(draft: NativeJobDefinitionDraft, owner: string, program?: string): void {+ const key = argumentContext(owner, program);+ if (draft.argumentContext && draft.argumentContext !== key) {+ if (draft.originalSnapshot) draft.reconcileArguments = true;+ draft.argumentDrafts ??= {};+ draft.argumentDrafts[draft.argumentContext] = { arguments: structuredCloneValue(draft.arguments ?? []), argumentTypes: { ...draft.argumentTypes } };+ const saved = draft.argumentDrafts[key];+ draft.arguments = structuredCloneValue(saved?.arguments ?? []);+ draft.argumentTypes = { ...saved?.argumentTypes };+ }+ draft.argumentContext = key;+}++/** Exact component references and the retained target inventory use the existing edit request. */+export function buildNativeJobDefinitionEdit(details: NativeJobDetails, engine: NativeJobEngine, draft: NativeJobDefinitionDraft): NativeJobEdit {+ const snapshot = { ...details.snapshot, definition: nativeJobDefinitionForEdit(engine, details.snapshot.ref.kind, details.snapshot.definition, details.legacyDefinition) };+ if (snapshot.ref.kind !== "scheduler") return buildNativeJobEdit(snapshot, draft);+ if (snapshot.definition.status !== "available") return buildNativeJobEdit(snapshot, draft);+ const original = snapshot.definition.value;+ const explicitFinalChange = draft.finalEnabled !== undefined && draft.originalSnapshot?.definition.status === "available" && [true, "TRUE", "true", 1, "1"].includes(draft.originalSnapshot.definition.value.ENABLED as string | number | boolean) !== draft.finalEnabled;+ if (+ !draft.reconcileArguments &&+ !draft.transitionRetained &&+ !draft.scheduleMode &&+ !draft.destinationMode &&+ !explicitFinalChange &&+ !Object.entries(draft.attributes ?? {}).some(+ ([name, change]) => change.kind !== "keep" && ["PROGRAM_OWNER", "PROGRAM_NAME", "SCHEDULE_OWNER", "SCHEDULE_NAME", "JOB_TYPE", "NUMBER_OF_ARGUMENTS", "CREDENTIAL_NAME", "CONNECT_CREDENTIAL_NAME", "DESTINATION", "DESTINATION_NAME", "EVENT_SPEC"].includes(name),+ )+ )+ return buildNativeJobEdit(snapshot, draft);+ const attributes = structuredCloneValue(draft.attributes ?? {});+ if (engine === "oracle" && draft.destinationMode) {+ if (draft.destinationMode === "local") {+ delete attributes.DESTINATION;+ delete attributes.DESTINATION_NAME;+ if (original.DESTINATION_NAME !== undefined && original.DESTINATION_NAME !== null) attributes.DESTINATION_NAME = { kind: "clear" };+ else if (original.DESTINATION !== undefined && original.DESTINATION !== null) attributes.DESTINATION = { kind: "clear" };+ } else {+ const active = draft.destinationMode === "legacy" ? "DESTINATION" : "DESTINATION_NAME";+ delete attributes[active === "DESTINATION" ? "DESTINATION_NAME" : "DESTINATION"];+ const previous = active === "DESTINATION" && original.DESTINATION_OWNER !== null ? null : original[active];+ const selected = attributes[active]?.kind === "set" ? attributes[active].value : attributes[active]?.kind === "clear" ? null : previous;+ if (selected === null || selected === undefined || selected === "") throw new TypeError("native_job_reference_input_invalid");+ }+ }+ if (draft.scheduleMode) {+ if (draft.scheduleMode !== "named") {+ attributes.SCHEDULE_NAME = { kind: "clear" };+ delete attributes.SCHEDULE_OWNER;+ }+ if (draft.scheduleMode === "queue" || draft.scheduleMode === "file-watcher") {+ attributes.EVENT_SPEC = { kind: "set", value: eventTrigger(draft) };+ delete attributes.REPEAT_INTERVAL;+ } else if (draft.scheduleMode === "inline") {+ if (original.EVENT_SPEC !== undefined && original.EVENT_SPEC !== null) attributes.EVENT_SPEC = { kind: "clear" };+ else delete attributes.EVENT_SPEC;+ }+ }+ const value = (name: string) => (attributes[name]?.kind === "set" ? attributes[name].value : attributes[name]?.kind === "clear" ? null : original[name]);+ const componentReference = (prefix: "PROGRAM" | "SCHEDULE"): NativeJobObjectReference | null => {+ const name = value(`${prefix}_NAME`);+ if (name === undefined || name === null || name === "") return null;+ if (typeof name === "object" && !Array.isArray(name) && typeof name.owner === "string" && typeof name.name === "string") return { owner: name.owner, name: name.name };+ const owner = value(`${prefix}_OWNER`);+ if (typeof owner !== "string" || !owner || typeof name !== "string" || !name || owner.includes("\0") || name.includes("\0")) throw new TypeError("native_job_reference_input_invalid");+ return { owner, name };+ };+ const touches = (names: string[]) => names.some((name) => attributes[name] && attributes[name].kind !== "keep");+ const programSelected = value("PROGRAM_NAME") !== undefined && value("PROGRAM_NAME") !== null && value("PROGRAM_NAME") !== "";+ const program = draft.reconcileArguments || touches(["PROGRAM_OWNER", "PROGRAM_NAME", "JOB_TYPE", "NUMBER_OF_ARGUMENTS"]) ? componentReference("PROGRAM") : null;+ for (const prefix of ["PROGRAM", "SCHEDULE"] as const) {+ const name = `${prefix}_NAME`,+ owner = `${prefix}_OWNER`;+ const supplied = touches([name, owner]);+ const reference = supplied ? componentReference(prefix) : null;+ delete attributes[owner];+ if (supplied) {+ const originalKind = prefix === "PROGRAM" ? "program" : original.SCHEDULE_TYPE === "WINDOW" ? "window" : original.SCHEDULE_TYPE === "WINDOW_GROUP" ? "window-group" : "schedule";+ const wantedKind = draft.referenceKinds?.[name] ?? originalKind;+ const same = reference ? original[name] === reference.name && original[owner] === reference.owner && wantedKind === originalKind : original[name] === null || original[name] === undefined;+ if (same) delete attributes[name];+ else attributes[name] = reference ? { kind: "set", value: { ...reference, ...(wantedKind !== (prefix === "PROGRAM" ? "program" : "schedule") ? { kind: wantedKind } : {}) } } : { kind: "clear" };+ }+ }+ if (programSelected) for (const name of ["JOB_TYPE", "JOB_ACTION", "NUMBER_OF_ARGUMENTS"]) delete attributes[name];+ if (value("SCHEDULE_NAME") !== undefined && value("SCHEDULE_NAME") !== null && value("SCHEDULE_NAME") !== "") for (const name of ["START_DATE", "END_DATE", "REPEAT_INTERVAL", "EVENT_SPEC"]) delete attributes[name];+ const request = buildNativeJobEdit(snapshot, { attributes });+ const contextChanged = request.attributes.some(({ name }) => ["PROGRAM_NAME", "JOB_TYPE", "NUMBER_OF_ARGUMENTS"].includes(name));+ const reconcile = contextChanged || draft.reconcileArguments === true;+ const transition =+ reconcile ||+ draft.transitionRetained ||+ request.attributes.some(({ name }) => ["PROGRAM_NAME", "SCHEDULE_NAME", "CREDENTIAL_NAME", "CONNECT_CREDENTIAL_NAME", "DESTINATION", "DESTINATION_NAME", "EVENT_SPEC"].includes(name)) ||+ (draft.finalEnabled !== undefined && draft.originalSnapshot?.definition.status === "available" && [true, "TRUE", "true", 1, "1"].includes(draft.originalSnapshot.definition.value.ENABLED as string | number | boolean) !== draft.finalEnabled);+ if (!transition) return buildNativeJobEdit(snapshot, { attributes, arguments: draft.arguments });+ if (draft.finalEnabled !== undefined) request.finalEnabled = draft.finalEnabled;+ if (!reconcile) {+ request.arguments = buildNativeJobEdit(snapshot, { arguments: draft.arguments }).arguments;+ return request;+ }+ const context = argumentContext(program?.owner ?? snapshot.ref.owner, program?.name);+ let layout = draft.argumentLayouts?.[context];+ if (!program) {+ const nativeCount = value("NUMBER_OF_ARGUMENTS");+ const count = typeof nativeCount === "string" && /^\d+$/.test(nativeCount) ? Number(nativeCount) : nativeCount;+ if (typeof count !== "number" || !Number.isSafeInteger(count) || count < 0 || count > 255) throw new TypeError("native_job_argument_count_invalid");+ const saved = layout?.status === "available" ? layout.value : [];+ layout = { status: "available", value: Array.from({ length: count }, (_, index) => saved.find((argument) => argument.position === index + 1) ?? { position: index + 1, dataType: draft.argumentTypes?.[index + 1] ?? "UNKNOWN", value: { kind: "unset" }, editable: true }) };+ }+ if (layout?.status !== "available") throw new TypeError("native_job_argument_target_unavailable");+ const active = draft.argumentContext === context ? draft : draft.argumentDrafts?.[context];+ request.argumentTarget = {+ program,+ arguments: nativeJobArgumentBaseline(draft, context, layout.value).map((argument) => {+ const change = active?.arguments?.find((change) => change.position === argument.position);+ const value = change?.value ?? argument.value;+ if (value.kind === "opaque") throw new TypeError("native_job_argument_not_editable");+ return { position: argument.position, dataType: active?.argumentTypes?.[argument.position] ?? argument.dataType, value: structuredCloneValue(value) };+ }),+ };+ return request;+}++/** Original overrides belong only to their original context, not the same position in a new one. */+export function nativeJobArgumentBaseline(draft: NativeJobDefinitionDraft, context: string, layout: NativeJobArgument[]): NativeJobArgument[] {+ const initial = draft.originalSnapshot;+ const definition = initial?.definition.status === "available" ? initial.definition.value : undefined;+ const originalContext = argumentContext(typeof definition?.PROGRAM_OWNER === "string" ? definition.PROGRAM_OWNER : "", typeof definition?.PROGRAM_NAME === "string" ? definition.PROGRAM_NAME : undefined);+ const originals = context === originalContext && initial?.arguments.status === "available" ? initial.arguments.value : [];+ return layout.map((argument) => {+ const original = originals.find((original) => original.position === argument.position);+ return { ...argument, value: structuredCloneValue(original?.value ?? argument.value), editable: argument.editable && original?.value.kind !== "opaque" };+ });+}++export function nativeJobProgramArgumentLayout(program: NativeJobMetadata<NativeJobRow> | undefined, argumentsMetadata: NativeJobMetadata<NativeJobRow[]> | undefined): NativeJobMetadata<NativeJobArgument[]> {+ if (program?.status !== "available") return { status: "unknown", reason: "native_job_program_argument_count_unavailable" };+ const count = Number(program.value.NUMBER_OF_ARGUMENTS);+ if (!Number.isSafeInteger(count) || count < 0 || count > 10_000 || program.value.NUMBER_OF_ARGUMENTS === null) return { status: "unknown", reason: "native_job_argument_count_unavailable" };+ if (argumentsMetadata?.status !== "available" && argumentsMetadata?.status !== "empty")+ return argumentsMetadata?.status === "truncated" ? { status: "unknown", reason: "native_job_arguments_truncated" } : (argumentsMetadata ?? { status: "unknown", reason: "native_job_argument_target_unavailable" });+ const rows = argumentsMetadata.status === "available" ? argumentsMetadata.value : [];+ if (rows.length !== count || new Set(rows.map((row) => Number(row.ARGUMENT_POSITION))).size !== count || rows.some((row) => !Number.isInteger(Number(row.ARGUMENT_POSITION)) || Number(row.ARGUMENT_POSITION) < 1 || Number(row.ARGUMENT_POSITION) > count))+ return { status: "unknown", reason: "native_job_argument_target_unavailable" };+ return {+ status: "available",+ value: rows+ .map<NativeJobArgument>((row) => {+ const metadataAttribute = typeof row.METADATA_ATTRIBUTE === "string" && row.METADATA_ATTRIBUTE ? row.METADATA_ATTRIBUTE : undefined;+ const decodedDefault = row.DBX_ARGUMENT_DEFAULT as unknown as NativeJobMetadata<NativeJobArgumentValue> | undefined;+ const hasAnydata = Object.prototype.hasOwnProperty.call(row, "DBX_ANYDATA_PRESENT") ? ![false, 0, "0", "FALSE", "false"].includes(row.DBX_ANYDATA_PRESENT as string | number | boolean) : row.DEFAULT_ANYDATA_VALUE !== undefined && row.DEFAULT_ANYDATA_VALUE !== null;+ return {+ position: Number(row.ARGUMENT_POSITION),+ name: typeof row.ARGUMENT_NAME === "string" ? row.ARGUMENT_NAME : undefined,+ dataType: typeof row.ARGUMENT_TYPE === "string" ? row.ARGUMENT_TYPE : "UNKNOWN",+ value: { kind: "inherit" },+ metadataAttribute,+ editable: !metadataAttribute && [undefined, null, false, 0, "0", "FALSE", "false"].includes(row.OUT_ARGUMENT as string | number | boolean | null | undefined),+ defaultValue: metadataAttribute+ ? undefined+ : decodedDefault+ ? decodedDefault+ : hasAnydata+ ? { status: "available", value: { kind: "opaque", value: row.DEFAULT_ANYDATA_VALUE ?? row } }+ : row.DEFAULT_VALUE !== undefined && row.DEFAULT_VALUE !== null+ ? { status: "available", value: { kind: "value", value: row.DEFAULT_VALUE } }+ : { status: "unknown", reason: "native_job_program_default_ambiguous" },+ };+ })+ .sort((a, b) => a.position - b.position),+ };+}++export function nativeJobAdminEngine(connection?: JdbcDialectConnection): NativeJobEngine | undefined {+ if (connection?.db_type === "jdbc" && connection.database_info?.productName?.toLowerCase() === "oceanbase") {+ return connection.database_info.compatibilityMode?.toLowerCase() === "oracle" ? "oceanbase-oracle" : undefined;+ }+ const type = effectiveDatabaseTypeForConnection(connection);+ return type === "oracle" || type === "oceanbase-oracle" || type === "dameng" ? type : undefined;+}++export function nativeJobAdminSupported(connection?: JdbcDialectConnection): boolean {+ return nativeJobAdminEngine(connection) !== undefined;+}++export function nativeJobAdminKinds(engine: NativeJobEngine): NativeJobKind[] {+ return engine === "dameng" ? ["dameng-native", "scheduler", "legacy"] : ["scheduler", "legacy"];+}++/** Editor aliases retain native columns and exact reference components; they never mutate the read. */+export function nativeJobDefinitionForEdit(engine: NativeJobEngine, kind: NativeJobKind, definition: NativeJobDetails["snapshot"]["definition"], legacyDefinition?: NativeJobDetails["legacyDefinition"]): NativeJobDetails["snapshot"]["definition"] {+ if (engine === "dameng" && kind === "legacy" && definition.status === "available" && legacyDefinition?.status === "available") {+ return { status: "available", value: { ...definition.value, ...legacyDefinition.value } };+ }+ if (engine === "oceanbase-oracle" && kind === "legacy" && definition.status === "available" && Object.prototype.hasOwnProperty.call(definition.value, "INSTANCE")) {+ return { status: "available", value: { ...definition.value, ZONE: definition.value.INSTANCE! } };+ }+ if (engine === "oracle" && kind === "scheduler" && definition.status === "available") {+ const value = { ...definition.value };+ for (const [field, owner, name] of [+ ["CREDENTIAL_NAME", "CREDENTIAL_OWNER", "CREDENTIAL_NAME"],+ ["CONNECT_CREDENTIAL_NAME", "CONNECT_CREDENTIAL_OWNER", "CONNECT_CREDENTIAL_NAME"],+ ["DESTINATION_NAME", "DESTINATION_OWNER", "DESTINATION"],+ ]) {+ if (value[name!] === null) value[field!] = null;+ else if (typeof value[owner!] === "string" && value[owner!] && typeof value[name!] === "string" && value[name!]) value[field!] = { owner: value[owner!]!, name: value[name!]! };+ }+ if (value.FILE_WATCHER_OWNER && value.FILE_WATCHER_NAME) value.EVENT_SPEC = { condition: value.EVENT_CONDITION ?? null, source: { kind: "file-watcher", reference: { owner: value.FILE_WATCHER_OWNER, name: value.FILE_WATCHER_NAME } } };+ else if (value.EVENT_QUEUE_OWNER && value.EVENT_QUEUE_NAME) value.EVENT_SPEC = { condition: value.EVENT_CONDITION ?? null, source: { kind: "queue", owner: value.EVENT_QUEUE_OWNER, name: value.EVENT_QUEUE_NAME, ...(value.EVENT_QUEUE_AGENT ? { agent: value.EVENT_QUEUE_AGENT } : {}) } };+ else if (["EVENT_CONDITION", "EVENT_QUEUE_NAME", "FILE_WATCHER_NAME"].some((name) => Object.prototype.hasOwnProperty.call(value, name))) value.EVENT_SPEC = null;+ return { status: "available", value };+ }+ return definition;+}++export type NativeJobAdminSelection = { kind: "scheduler"; owner: string; name: string } | { kind: "legacy"; jobId: string } | { kind: "dameng-native"; jobId: string; name: string };++export function nativeJobAdminSelection(ref: NativeJobAdminSelection): NativeJobAdminSelection {+ switch (ref.kind) {+ case "scheduler":+ return { kind: ref.kind, owner: ref.owner, name: ref.name };+ case "legacy":+ return { kind: ref.kind, jobId: ref.jobId };+ case "dameng-native":+ return { kind: ref.kind, jobId: ref.jobId, name: ref.name };+ }+}++export function nativeJobAdminSelectionKey(ref: NativeJobAdminSelection): string {+ return JSON.stringify(nativeJobAdminSelection(ref));+}++function localDateTime(): string {+ const now = new Date();+ const pad = (value: number) => String(value).padStart(2, "0");+ return `${now.getFullYear()}-${pad(now.getMonth() + 1)}-${pad(now.getDate())} ${pad(now.getHours())}:${pad(now.getMinutes())}:${pad(now.getSeconds())}`;+}++export function newNativeJobDefinitionDraft(kind: "scheduler" | "legacy"): NativeJobDefinitionDraft {+ const values: Record<string, NativeJobValue> =+ kind === "legacy" ? { WHAT: "BEGIN NULL; END;", NEXT_DATE: localDateTime(), INTERVAL: "NULL", INSTANCE: 0, ENABLED: false } : { JOB_TYPE: "PLSQL_BLOCK", JOB_ACTION: "BEGIN NULL; END;", NUMBER_OF_ARGUMENTS: 0, START_DATE: new Date().toISOString(), AUTO_DROP: true, ENABLED: false };+ return { attributes: Object.fromEntries(Object.entries(values).map(([name, value]) => [name, { kind: "set" as const, value }])), arguments: [], argumentContext: "inline" };+}++export function buildNativeJobDefinitionCreate(scope: NativeJobScope, engine: NativeJobEngine, kind: "scheduler" | "legacy", owner: string, name: string, draft: NativeJobDefinitionDraft): Extract<NativeJobRequest, { action: "create" }> {+ const value = (key: string, fallback?: NativeJobValue) => {+ const change = draft.attributes?.[key];+ return change?.kind === "set" ? change.value : change?.kind === "clear" ? null : fallback;+ };+ const text = (key: string, fallback = ""): string => {+ const result = value(key, fallback);+ if (typeof result !== "string") throw new TypeError("native_job_attribute_type_invalid");+ return result;+ };+ const optional = (key: string): string | undefined => {+ const result = value(key);+ if (result === undefined || result === null || result === "") return undefined;+ if (typeof result !== "string") throw new TypeError("native_job_attribute_type_invalid");+ return result;+ };+ const flag = (key: string, fallback: boolean): boolean => {+ const result = value(key, fallback);+ if (typeof result !== "boolean") throw new TypeError("native_job_attribute_type_invalid");+ return result;+ };+ const number = (key: string): number => {+ const result = value(key, 0);+ if (typeof result !== "number" || !Number.isSafeInteger(result) || result < 0) throw new TypeError("native_job_attribute_type_invalid");+ return result;+ };+ if (kind === "legacy") {+ return {+ action: "create",+ scope: { ...scope },+ definition: { kind, what: text("WHAT"), nextDate: text("NEXT_DATE"), interval: text("INTERVAL", "NULL"), enabled: flag("ENABLED", false), schema: owner, ...(engine === "oceanbase-oracle" ? { zone: optional("ZONE") } : { instance: number("INSTANCE") }) },+ };+ }+ const program = optional("PROGRAM_NAME");+ const mode = draft.scheduleMode;+ const schedule = mode && mode !== "named" ? undefined : optional("SCHEDULE_NAME");+ const event = mode === "queue" || mode === "file-watcher" ? eventTrigger(draft) : undefined;+ const base = new Set(["JOB_TYPE", "JOB_ACTION", "NUMBER_OF_ARGUMENTS", "PROGRAM_OWNER", "PROGRAM_NAME", "SCHEDULE_OWNER", "SCHEDULE_NAME", "START_DATE", "END_DATE", "REPEAT_INTERVAL", "AUTO_DROP", "ENABLED", "COMMENTS", "JOB_CLASS", "CREDENTIAL_NAME", "DESTINATION_NAME", "JOB_STYLE"]);+ const attributes = Object.entries(draft.attributes ?? {})+ .filter(([key, change]) => !base.has(key) && change.kind !== "keep")+ .map(([name, change]) => ({ name, change: change.kind === "set" ? { kind: "set" as const, value: structuredCloneValue(change.value) } : { kind: "clear" as const } }));+ const context = argumentContext(program ? text("PROGRAM_OWNER", owner) : owner, program);+ const active = draft.argumentContext && draft.argumentContext !== context ? draft.argumentDrafts?.[context] : draft;+ const args = (active?.arguments ?? []).map((argument) => ({ position: argument.position, dataType: active?.argumentTypes?.[argument.position] ?? "VARCHAR2", value: structuredCloneValue(argument.value) }) as NativeJobCreateArgument);+ return {+ action: "create",+ scope: { ...scope },+ definition: {+ kind,+ owner,+ name,+ ...(program ? { program: { owner: text("PROGRAM_OWNER", owner), name: program }, numberOfArguments: 0, jobStyle: optional("JOB_STYLE") } : { jobType: text("JOB_TYPE", "PLSQL_BLOCK"), jobAction: text("JOB_ACTION"), numberOfArguments: number("NUMBER_OF_ARGUMENTS") }),+ ...(schedule+ ? { schedule: { owner: text("SCHEDULE_OWNER", owner), name: schedule } }+ : event+ ? { startDate: optional("START_DATE"), endDate: optional("END_DATE"), eventCondition: event.condition ?? undefined, eventSource: event.source }+ : { startDate: optional("START_DATE"), endDate: optional("END_DATE"), repeatInterval: optional("REPEAT_INTERVAL") }),+ enabled: flag("ENABLED", false),+ autoDrop: flag("AUTO_DROP", true),+ comments: optional("COMMENTS"),+ jobClass: optional("JOB_CLASS"),+ credentialName: optional("CREDENTIAL_NAME"),+ destinationName: optional("DESTINATION_NAME"),+ attributes,+ arguments: args,+ },+ };+}++/** A retained creation becomes an edit only after this operation acknowledged CREATE. */+export function rebaseNativeJobDefinitionCreation(details: NativeJobDetails, draft: NativeJobDefinitionDraft, status: NativeJobOperationStatus): NativeJobDefinitionDraft {+ if (!status.target || nativeJobRefKey(status.target) !== nativeJobRefKey(details.snapshot.ref)) throw new TypeError("native_job_identity_mismatch");+ if (status.target.kind !== "scheduler" || status.steps.find((step) => step.id === "create")?.state !== "applied") return {};+ // Activation is a separate native control; passing ENABLED to SET_ATTRIBUTE is invalid.+ const creationOnly = new Set(["ENABLED", "PROGRAM_OWNER", "PROGRAM_NAME", "SCHEDULE_OWNER", "SCHEDULE_NAME", "CREDENTIAL_NAME", "DESTINATION_NAME", "JOB_STYLE"]);+ const program = draft.attributes?.PROGRAM_NAME;+ const schedule = draft.attributes?.SCHEDULE_NAME;+ if (program?.kind === "set" && typeof program.value === "string" && program.value !== "") {+ for (const name of ["JOB_TYPE", "JOB_ACTION", "NUMBER_OF_ARGUMENTS"]) creationOnly.add(name);+ }+ if (schedule?.kind === "set" && typeof schedule.value === "string" && schedule.value !== "") {+ for (const name of ["START_DATE", "END_DATE", "REPEAT_INTERVAL"]) creationOnly.add(name);+ }+ return {+ attributes: Object.fromEntries(+ Object.entries(draft.attributes ?? {})+ .filter(([name]) => !creationOnly.has(name))+ .map(([name, change]) => [name, structuredCloneValue(change)]),+ ),+ arguments: structuredCloneValue(draft.arguments ?? []),+ argumentTypes: { ...draft.argumentTypes },+ };+}++// Vue drafts are proxies, so native structuredClone is not a safe input boundary.+function structuredCloneValue<T>(value: T): T {+ if (value === null || typeof value !== "object") return value;+ if (Array.isArray(value)) return value.map(structuredCloneValue) as T;+ return Object.fromEntries(Object.entries(value).map(([key, entry]) => [key, structuredCloneValue(entry)])) as T;+}diff --git a/apps/desktop/src/lib/database/nativeJobs.ts b/apps/desktop/src/lib/database/nativeJobs.tsnew file mode 100644index 0000000000..9f9838f467--- /dev/null+++ b/apps/desktop/src/lib/database/nativeJobs.ts@@ -0,0 +1,495 @@+export interface NativeJobScope {+ connectionId: string;+ database: string;+ /** Opaque backend identity of the connected database/tenant/container. */+ contextId: string;+}++export type NativeJobRef = { scope: NativeJobScope; kind: "scheduler"; owner: string; name: string } | { scope: NativeJobScope; kind: "legacy"; jobId: string } | { scope: NativeJobScope; kind: "dameng-native"; jobId: string; name: string };++export type NativeJobValue = string | number | boolean | null | NativeJobValue[] | { [key: string]: NativeJobValue };++export type NativeJobMetadata<T> = { status: "available"; value: T } | { status: "truncated"; value: T; limit: number } | { status: "empty" } | { status: "denied" | "unsupported" | "error" | "unknown"; reason: string };++export type NativeJobFieldChange = { kind: "keep" } | { kind: "set"; value: NativeJobValue } | { kind: "clear" };++export type NativeJobArgumentValue = { kind: "unset" } | { kind: "inherit" } | { kind: "null" } | { kind: "value"; value: NativeJobValue } | { kind: "opaque"; value: NativeJobValue };++export interface NativeJobArgument {+ position: number;+ name?: string;+ dataType: string;+ value: NativeJobArgumentValue;+ defaultValue?: NativeJobMetadata<NativeJobArgumentValue>;+ metadataAttribute?: string;+ editable: boolean;+ reason?: string;+}++export interface NativeJobSnapshot {+ ref: NativeJobRef;+ /** Opaque definition baseline issued by the backend, not a UI label. */+ revision: string;+ definition: NativeJobMetadata<Record<string, NativeJobValue>>;+ arguments: NativeJobMetadata<NativeJobArgument[]>;+}++export type NativeJobEngine = "oracle" | "oceanbase-oracle" | "dameng";+export type NativeJobKind = NativeJobRef["kind"];+export type NativeJobRow = Record<string, NativeJobValue>;++export interface NativeJobContext {+ scope: NativeJobScope;+ engine: NativeJobEngine;+ sessionUser: string;+ actualDatabase: string | null;+ productVersion: string | null;+}++export interface NativeJobCatalogSource {+ source: string | null;+ coverage: "database" | "accessible" | "current_user" | null;+}++export interface NativeJobSummary {+ ref: NativeJobRef;+ name: string;+ owner: string | null;+ enabled: boolean | null;+ jobType: string | null;+ state: string | null;+ nextRun: NativeJobValue;+ comments: string | null;+ aliases: NativeJobRef[];+ logUser: string | null;+ privUser: string | null;+ schemaUser: string | null;+}++export interface NativeJobListRequest {+ scope: NativeJobScope;+ kind: NativeJobKind;+ schema?: string | null;+ filter?: string;+ offset?: number;+ limit?: number;+}++export interface NativeJobList {+ jobs: NativeJobMetadata<NativeJobSummary[]>;+ source: NativeJobCatalogSource;+ offset: number;+ limit: number;+}++export type NativeJobReferenceKind = "program" | "program-arguments" | "schedule" | "chain" | "credential" | "destination" | "window" | "window-group" | "file-watcher" | "destination-group" | "destination-group-members";+export interface NativeJobReferenceListRequest {+ scope: NativeJobScope;+ kind: NativeJobReferenceKind;+ schema?: string;+ name?: string;+ filter?: string;+ offset?: number;+ limit?: number;+}+export interface NativeJobReferenceCatalog {+ objects: NativeJobMetadata<NativeJobRow[]>;+ source: NativeJobCatalogSource;+ offset: number;+ limit: number;+}++export interface NativeJobDetails {+ snapshot: NativeJobSnapshot;+ nativeIdentity: NativeJobMetadata<NativeJobRow>;+ consistency: NativeJobMetadata<null>;+ parameterMetadata: NativeJobMetadata<NativeJobRow[]>;+ program?: NativeJobMetadata<NativeJobRow>;+ programArguments?: NativeJobMetadata<NativeJobRow[]>;+ legacyDefinition?: NativeJobMetadata<NativeJobRow>;+ steps: NativeJobMetadata<NativeJobRow[]>;+ schedules: NativeJobMetadata<NativeJobRow[]>;+ running: NativeJobMetadata<NativeJobRow[]>;+ history: NativeJobMetadata<NativeJobRow[]>;+ sources: Record<string, NativeJobCatalogSource>;+}++export interface NativeJobEditDraft {+ attributes?: Record<string, NativeJobFieldChange>;+ arguments?: { position: number; value: NativeJobArgumentValue }[];+}++export interface NativeJobEdit {+ action: "update";+ finalEnabled?: boolean;+ argumentTarget?: { program: NativeJobObjectReference | null; arguments: NativeJobCreateArgument[] };+ target: NativeJobRef;+ baseline: string;+ attributes: { name: string; change: Exclude<NativeJobFieldChange, { kind: "keep" }> }[];+ arguments: { position: number; value: Exclude<NativeJobArgumentValue, { kind: "opaque" }> }[];+}++export type NativeJobDamengChildChange = { kind: "add" | "update"; name: string; attributes?: NativeJobEdit["attributes"] } | { kind: "drop"; name: string };++export interface NativeJobDamengConfiguration {+ attributes?: NativeJobEdit["attributes"];+ steps?: NativeJobDamengChildChange[];+ schedules?: NativeJobDamengChildChange[];+}++export interface NativeJobDamengChildDraft {+ kind: "add" | "update" | "drop";+ name: string;+ attributes?: NativeJobEditDraft["attributes"];+}++export interface NativeJobDamengEditDraft {+ attributes?: NativeJobEditDraft["attributes"];+ steps?: NativeJobDamengChildDraft[];+ schedules?: NativeJobDamengChildDraft[];+}++export type NativeJobMutation =+ | NativeJobEdit+ | { target: NativeJobRef; baseline: string; action: "configure-dameng"; configuration: NativeJobDamengConfiguration }+ | { target: NativeJobRef; baseline: string; action: "enable" | "disable" | "run" | "clear-history" }+ | { target: NativeJobRef; baseline: string; action: "stop" | "drop"; force?: boolean };++export interface NativeJobLegacyCreate {+ kind: "legacy";+ what: string;+ nextDate: string;+ interval: string;+ enabled: boolean;+ instance?: number;+ schema?: string;+ zone?: string;+}++export interface NativeJobObjectReference {+ owner: string;+ name: string;+}++export type NativeJobEventSource = { kind: "queue"; owner: string; name: string; agent?: string } | { kind: "file-watcher"; reference: NativeJobObjectReference };++export interface NativeJobCreateArgument {+ position: number;+ dataType: string;+ value: NativeJobArgumentValue;+}++export interface NativeJobSchedulerCreate {+ kind: "scheduler";+ owner: string;+ name: string;+ program?: NativeJobObjectReference;+ jobType?: string;+ jobAction?: string;+ numberOfArguments: number;+ schedule?: NativeJobObjectReference;+ startDate?: string;+ repeatInterval?: string;+ endDate?: string;+ eventCondition?: string;+ eventSource?: NativeJobEventSource;+ enabled: boolean;+ autoDrop: boolean;+ jobClass?: string;+ jobStyle?: string;+ comments?: string;+ credentialName?: string;+ destinationName?: string;+ attributes?: NativeJobEdit["attributes"];+ arguments?: NativeJobCreateArgument[];+}++export interface NativeJobDamengCreate {+ kind: "dameng-native";+ name: string;+ enabled: boolean;+ configuration: NativeJobDamengConfiguration;+}++export type NativeJobRequest = NativeJobMutation | { action: "create"; scope: NativeJobScope; definition: NativeJobLegacyCreate | NativeJobSchedulerCreate | NativeJobDamengCreate };++export interface NativeJobPreparedPlan {+ planId: string;+ operationId: string;+ scope: NativeJobScope;+ target: NativeJobRef | null;+ steps: { id: string; label: string; sql: string }[];+}++export interface NativeJobOperationStatus {+ operationId: string;+ target: NativeJobRef | null;+ observedIdentity?: NativeJobRow;+ createdChildren?: { partition: "steps" | "schedules"; name: string; id: string }[];+ executionObservation?: NativeJobExecutionObservation;+ state: "prepared" | "queued" | "running" | "finished";+ outcome: "not_started" | "not_applied" | "partial" | "unknown" | "verified" | "accepted";+ cancelRequested: boolean;+ steps: {+ id: string;+ state: "pending" | "dispatching" | "applied" | "accepted" | "failed" | "unknown" | "skipped";+ reason: string | null;+ vendorCode: number | null;+ }[];+ reason: string | null;+}++export interface NativeJobExecutionObservation {+ observedAt: string;+ association: "uncertain" | "unavailable";+ reason: string;+ running: NativeJobMetadata<NativeJobRow[]>;+ history: NativeJobMetadata<NativeJobRow[]>;+ sources: Record<string, NativeJobCatalogSource>;+ candidates: { nativeKey: string; phase: "running" | "history" | "not-observed"; evidence: "running-log-id" | "new-history"; row: NativeJobRow }[];+}++function identityPart(value: string, allowEmpty = false): string {+ if (typeof value !== "string" || (!allowEmpty && value.length === 0) || value.includes("\0")) {+ throw new TypeError("native_job_identity_invalid");+ }+ return value;+}++function numericJobId(value: string): string {+ if (typeof value !== "string" || !/^[1-9]\d*$/.test(value)) {+ throw new TypeError("native_job_id_invalid");+ }+ return value;+}++/** Exact components, not a display label or a SQL-qualified name. */+export function nativeJobRefKey(ref: NativeJobRef): string {+ const scope = [identityPart(ref.scope.connectionId), identityPart(ref.scope.database, true), identityPart(ref.scope.contextId)];+ switch (ref.kind) {+ case "scheduler":+ return JSON.stringify([...scope, ref.kind, identityPart(ref.owner), identityPart(ref.name)]);+ case "legacy":+ return JSON.stringify([...scope, ref.kind, numericJobId(ref.jobId)]);+ case "dameng-native":+ return JSON.stringify([...scope, ref.kind, numericJobId(ref.jobId), identityPart(ref.name)]);+ }+}++/** Oracle's object-name argument; SQL string binding/escaping is a separate step. */+export function oracleSchedulerObjectName(ref: NativeJobRef): string {+ if (ref.kind !== "scheduler") throw new TypeError("native_job_not_scheduler");+ const quote = (value: string) => `"${identityPart(value).replace(/"/g, '""')}"`;+ return `${quote(ref.owner)}.${quote(ref.name)}`;+}++function sameValue(left: NativeJobValue | undefined, right: NativeJobValue): boolean {+ if (left === right) return true;+ if (left === null || right === null || typeof left !== "object" || typeof right !== "object") return false;+ if (Array.isArray(left) || Array.isArray(right)) {+ return Array.isArray(left) && Array.isArray(right) && left.length === right.length && left.every((value, index) => sameValue(value, right[index]!));+ }+ const keys = Object.keys(left);+ return keys.length === Object.keys(right).length && keys.every((key) => Object.prototype.hasOwnProperty.call(right, key) && sameValue(left[key], right[key]!));+}++function copyValue(value: NativeJobValue): NativeJobValue {+ if (value === null || typeof value !== "object") return value;+ if (Array.isArray(value)) return value.map(copyValue);+ return Object.fromEntries(Object.entries(value).map(([key, entry]) => [key, copyValue(entry)]));+}++function attributeChanges(definition: NativeJobSnapshot["definition"], draft: NativeJobEditDraft["attributes"]): NativeJobEdit["attributes"] {+ const requested = Object.entries(draft ?? {}).filter(([, change]) => change.kind !== "keep");+ if (requested.length && definition.status !== "available") {+ throw new Error("native_job_definition_unavailable");+ }+ const attributes: NativeJobEdit["attributes"] = [];+ if (definition.status === "available") {+ for (const [name, change] of requested) {+ const previous = definition.value[name];+ if (change.kind === "set" && !sameValue(previous, change.value)) {+ attributes.push({ name, change: { kind: "set", value: copyValue(change.value) } });+ } else if (change.kind === "clear" && previous !== null) {+ attributes.push({ name, change: { kind: "clear" } });+ }+ }+ }+ return attributes;+}++/** Build the minimal edit request; the backend prepares and validates its execution plan. */+export function buildNativeJobEdit(snapshot: NativeJobSnapshot, draft: NativeJobEditDraft): NativeJobEdit {+ nativeJobRefKey(snapshot.ref);+ if (!snapshot.revision) throw new TypeError("native_job_baseline_missing");+ const attributes = attributeChanges(snapshot.definition, draft.attributes);+ const argumentEdits: NativeJobEdit["arguments"] = [];+ if (draft.arguments?.length) {+ if (snapshot.arguments.status !== "available" && snapshot.arguments.status !== "empty") {+ throw new Error("native_job_arguments_unavailable");+ }+ const original = new Map(snapshot.arguments.status === "available" ? snapshot.arguments.value.map((argument) => [argument.position, argument]) : []);+ const seen = new Set<number>();+ for (const change of draft.arguments) {+ if (!Number.isSafeInteger(change.position) || change.position < 1 || seen.has(change.position)) {+ throw new TypeError("native_job_argument_position_invalid");+ }+ seen.add(change.position);+ const argument = original.get(change.position);+ if (!argument) throw new Error("native_job_argument_missing");+ if (sameValue(argument.value, change.value)) continue;+ if (!argument.editable || change.value.kind === "opaque") throw new Error("native_job_argument_not_editable");+ const value = change.value.kind === "value" ? { kind: "value" as const, value: copyValue(change.value.value) } : { ...change.value };+ argumentEdits.push({ position: change.position, value });+ }+ argumentEdits.sort((left, right) => left.position - right.position);+ }+ return {+ action: "update",+ target: { ...snapshot.ref, scope: { ...snapshot.ref.scope } },+ baseline: snapshot.revision,+ attributes,+ arguments: argumentEdits,+ };+}++function damengAttributeChanges(row: NativeJobRow, draft: NativeJobEditDraft["attributes"]): NativeJobEdit["attributes"] {+ const comparison = { ...row };+ for (const name of ["ENABLE", "ENABLE_EMAIL", "ENABLE_NETSEND", "APPEND_FLAG"]) {+ const change = draft?.[name];+ if (change?.kind === "set" && typeof change.value === "boolean" && [0, 1, "0", "1", true, false].includes(row[name] as string | number | boolean)) comparison[name] = row[name] === 1 || row[name] === "1" || row[name] === true;+ }+ return attributeChanges({ status: "available", value: comparison }, draft);+}++function damengChildChanges(metadata: NativeJobMetadata<NativeJobRow[]>, part: "steps" | "schedules", drafts: NativeJobDamengChildDraft[] = []): NativeJobDamengChildChange[] {+ if (!drafts.length) return [];+ if (metadata.status !== "available" && metadata.status !== "empty") throw new Error("native_job_metadata_incomplete");+ const rows = metadata.status === "available" ? metadata.value : [];+ const byName = new Map<string, NativeJobRow>();+ for (const row of rows) {+ if (typeof row.NAME !== "string" || byName.has(row.NAME)) throw new Error("native_job_child_identity_ambiguous");+ byName.set(row.NAME, row);+ }+ const changes: NativeJobDamengChildChange[] = [];+ for (const draft of drafts) {+ const previous = byName.get(draft.name);+ if (draft.kind !== "add" && !previous) throw new Error("native_job_child_missing");+ if (draft.kind === "drop") {+ changes.push({ kind: "drop", name: draft.name });+ continue;+ }+ const fields = { ...(draft.kind === "add" ? {} : previous) };+ const wantedType = draft.attributes?.TYPE;+ const sqlType = (value: NativeJobValue | undefined) => value === 0 || value === "0";+ if (part === "steps" && previous?.COMMAND !== undefined && sqlType(previous.TYPE) && (wantedType?.kind === "set" ? sqlType(wantedType.value) : wantedType?.kind !== "clear")) {+ fields.COMMAND_INPUT = previous.COMMAND;+ }+ const attributes = damengAttributeChanges(fields, draft.attributes);+ if (draft.kind === "add" || attributes.length) changes.push({ kind: draft.kind, name: draft.name, attributes });+ }+ return changes;+}++/** Rebase a retained draft onto a fresh complete read; generated backup/DTS commands stay opaque. */+export function buildNativeJobDamengEdit(details: NativeJobDetails, draft: NativeJobDamengEditDraft): Extract<NativeJobMutation, { action: "configure-dameng" }> {+ const base = buildNativeJobEdit(details.snapshot, { attributes: draft.attributes });+ if (base.target.kind !== "dameng-native") throw new TypeError("native_job_kind_invalid");+ return {+ action: "configure-dameng",+ target: base.target,+ baseline: base.baseline,+ configuration: {+ attributes: details.snapshot.definition.status === "available" ? damengAttributeChanges(details.snapshot.definition.value, draft.attributes) : base.attributes,+ steps: damengChildChanges(details.steps, "steps", draft.steps),+ schedules: damengChildChanges(details.schedules, "schedules", draft.schedules),+ },+ };+}++export function buildNativeJobDamengCreate(scope: NativeJobScope, name: string, draft: NativeJobDamengEditDraft): Extract<NativeJobRequest, { action: "create" }> {+ identityPart(scope.connectionId);+ identityPart(scope.contextId);+ identityPart(scope.database, true);+ identityPart(name);+ const enable = draft.attributes?.ENABLE;+ if (enable?.kind === "clear" || (enable?.kind === "set" && typeof enable.value !== "boolean")) throw new TypeError("native_job_attribute_type_invalid");+ for (const part of ["steps", "schedules"] as const) {+ if (draft[part]?.some((child) => child.kind !== "add")) throw new TypeError("native_job_creation_children_must_be_new");+ }+ return {+ action: "create",+ scope: { ...scope },+ definition: {+ kind: "dameng-native",+ name,+ enabled: enable?.kind === "set" ? (enable.value as boolean) : true,+ configuration: {+ attributes: damengAttributeChanges({}, draft.attributes).filter((attribute) => attribute.name !== "ENABLE"),+ steps: damengChildChanges({ status: "empty" }, "steps", draft.steps),+ schedules: damengChildChanges({ status: "empty" }, "schedules", draft.schedules),+ },+ },+ };+}++function damengChildId(row: NativeJobRow): string | undefined {+ const value = row.DBX_CHILD_ID ?? row.ID;+ if (typeof value === "string" && /^[1-9]\d*$/.test(value)) return value;+ if (typeof value === "number" && Number.isSafeInteger(value) && value > 0) return String(value);+}++/** Only this operation's acknowledged child IDs may turn retained creates into edits. */+export function rebaseNativeJobDamengCreation(details: NativeJobDetails, draft: NativeJobDamengEditDraft, status: NativeJobOperationStatus): NativeJobDamengEditDraft {+ if (!status.target || nativeJobRefKey(status.target) !== nativeJobRefKey(details.snapshot.ref)) throw new TypeError("native_job_identity_mismatch");+ const result: NativeJobDamengEditDraft = { attributes: Object.fromEntries(Object.entries(draft.attributes ?? {}).map(([name, change]) => [name, change.kind === "set" ? { ...change, value: copyValue(change.value) } : { ...change }])) };+ for (const part of ["steps", "schedules"] as const) {+ const metadata = details[part];+ const rows = metadata.status === "available" ? metadata.value : [];+ result[part] = (draft[part] ?? []).map((child) => {+ const receipt = status.createdChildren?.find((created) => created.partition === part && created.name === child.name);+ const matched = receipt && rows.some((row) => row.NAME === child.name && damengChildId(row) === receipt.id);+ return { ...child, kind: child.kind === "add" && matched ? "update" : child.kind, attributes: Object.fromEntries(Object.entries(child.attributes ?? {}).map(([name, change]) => [name, change.kind === "set" ? { ...change, value: copyValue(change.value) } : { ...change }])) };+ });+ }+ return result;+}++export function rebaseNativeJobDamengDraft(before: NativeJobDetails, after: NativeJobDetails, draft: NativeJobDamengEditDraft, status: NativeJobOperationStatus, sessionUser: string): NativeJobDamengEditDraft {+ const original = before.snapshot.ref;+ const effective = after.snapshot.ref;+ if (original.kind !== "dameng-native" || effective.kind !== "dameng-native" || original.jobId !== effective.jobId || ["connectionId", "database", "contextId"].some((key) => original.scope[key as keyof NativeJobScope] !== effective.scope[key as keyof NativeJobScope]))+ throw new TypeError("native_job_identity_mismatch");+ if (+ before.nativeIdentity.status !== "available" ||+ after.nativeIdentity.status !== "available" ||+ ["DBX_JOB_ID", "DBX_CREATED_AT"].some((key) => before.nativeIdentity.status !== "available" || after.nativeIdentity.status !== "available" || before.nativeIdentity.value[key] !== after.nativeIdentity.value[key])+ )+ throw new TypeError("native_job_identity_mismatch");+ const result = rebaseNativeJobDamengCreation(after, draft, status);+ const known = status.outcome !== "unknown";+ if (known && after.snapshot.definition.status === "available") result.attributes = Object.fromEntries(damengAttributeChanges(after.snapshot.definition.value, result.attributes).map(({ name, change }) => [name, change]));+ for (const part of ["steps", "schedules"] as const) {+ const previous = before[part];+ const current = after[part];+ if ((current.status !== "available" && current.status !== "empty") || previous.status !== "available") continue;+ const coverage = after.sources[part]?.coverage;+ const complete = coverage === "database" || coverage === "accessible" || (coverage === "current_user" && after.snapshot.definition.status === "available" && after.snapshot.definition.value.USERNAME === sessionUser);+ const rows = current.status === "available" ? current.value : [];+ result[part] = (result[part] ?? []).flatMap<NativeJobDamengChildDraft>((child) => {+ if (child.kind === "add") return [child];+ const original = previous.value.find((row) => row.NAME === child.name);+ const originalId = original && damengChildId(original);+ const matches = originalId ? rows.filter((row) => damengChildId(row) === originalId) : [];+ if (matches.length !== 1) return known && complete && child.kind === "drop" && originalId && !matches.length ? [] : [child];+ const row = matches[0]!;+ if (typeof row.NAME !== "string") return [child];+ const renamed = { ...child, name: row.NAME };+ if (!known || child.kind === "drop") return [renamed];+ const baseline = { ...row, ...(part === "steps" && (row.TYPE === 0 || row.TYPE === "0") ? { COMMAND_INPUT: row.COMMAND! } : {}) };+ renamed.attributes = Object.fromEntries(damengAttributeChanges(baseline, child.attributes).map(({ name, change }) => [name, change]));+ return Object.keys(renamed.attributes).length ? [renamed] : [];+ });+ }+ return result;+}diff --git a/apps/desktop/src/lib/database/objectDependencyDetails.ts b/apps/desktop/src/lib/database/objectDependencyDetails.tsindex 4327e3716e..a7a266f998 100644--- a/apps/desktop/src/lib/database/objectDependencyDetails.ts+++ b/apps/desktop/src/lib/database/objectDependencyDetails.ts@@ -1,5 +1,7 @@-import type { DatabaseType, QueryResult, QueryTab } from "@/types/database";+import type { DatabaseType, QueryResult, QueryTab, TriggerInfo } from "@/types/database";import type { SqlObjectNavigationTarget, SqlObjectNavigationType } from "@/lib/sql/sqlNavigation";+import { BackendErrorException } from "@/lib/backend/errorUtils";+import { exactOracleTriggerMetadata } from "@/lib/database/oracleTriggerIdentity";import { oracleObjectRelationsSql, oracleObjectRelationKinds, type ObjectRelationKind, type OracleDependencyObjectType } from "@/lib/database/oracleObjectDependencies";export type ObjectDetails = NonNullable<QueryTab["objectDetails"]>;@@ -15,6 +17,7 @@ export interface ObjectDependencyTarget {catalog?: string;name: string;objectType: OracleDependencyObjectType;+ databaseType?: DatabaseType;}export interface ObjectDependencyRow {@@ -27,19 +30,25 @@ export interface ObjectDependencyRow {sourceType: string;}-export function objectDependencyTarget(details: (Omit<ObjectDependencyTarget, "objectType"> & { objectType: string; section?: ObjectDetailsSection }) | undefined, databaseType?: DatabaseType): ObjectDependencyTarget | undefined {- if (!details || (databaseType !== "oracle" && databaseType !== "oceanbase-oracle")) return;+export function objectDependencyTarget(details: (Omit<ObjectDependencyTarget, "objectType"> & { objectType: string; section?: ObjectDetailsSection }) | undefined, databaseType?: DatabaseType, trigger?: Pick<TriggerInfo, "name" | "oracle_metadata"> | null): ObjectDependencyTarget | undefined {+ if (!details) return;const type = details.objectType === "PACKAGE_BODY" ? "PACKAGE" : details.objectType;+ if (type === "TRIGGER") {+ const metadata = exactOracleTriggerMetadata(trigger);+ if (!metadata || metadata.owner !== details.schema || metadata.name !== details.name || metadata.engine !== (databaseType === "dameng" ? "dm" : databaseType)) return;+ if (metadata.engine === "dm" && !/(?:^|\D)8\./.test(metadata.engineVersion ?? "")) return;+ } else if (databaseType !== "oracle" && databaseType !== "oceanbase-oracle") return;if (!["TABLE", "VIEW", "MATERIALIZED_VIEW", "PROCEDURE", "FUNCTION", "PACKAGE", "TYPE", "TYPE_BODY", "SEQUENCE", "SYNONYM", "TRIGGER", "INDEX"].includes(type)) return;const { section: _section, ...identity } = details;- return { ...identity, objectType: type as OracleDependencyObjectType };+ return { ...identity, objectType: type as OracleDependencyObjectType, ...(databaseType === "dameng" ? { databaseType } : {}) };}export function objectDependencySql(target: ObjectDependencyTarget, kind: ObjectRelationKind = "dependencies"): string {+ if (!objectRelationKinds(target).includes(kind)) throw new Error("This relation kind is not supported for this object.");return oracleObjectRelationsSql({ schema: target.schema, objectName: target.name, objectType: target.objectType }, kind);}-export const objectRelationKinds = (target: ObjectDependencyTarget) => oracleObjectRelationKinds(target.objectType);+export const objectRelationKinds = (target: ObjectDependencyTarget): ObjectRelationKind[] => (target.databaseType === "dameng" ? ["dependencies"] : oracleObjectRelationKinds(target.objectType));export interface RelationObjectIdentity {schema: string;@@ -120,6 +129,7 @@ export function objectOwnershipNavigation(row: ObjectOwnershipRow): SqlObjectNav}export function objectDependencyRows(result: QueryResult): ObjectDependencyRow[] {+ if (result.execution_error) throw new BackendErrorException(result.error || "The dependency query failed.");const indexes = new Map(result.columns.map((name, index) => [name.toUpperCase(), index]));const required = ["DIRECTION", "OBJECT_OWNER", "OBJECT_NAME", "OBJECT_TYPE", "REFERENCED_OWNER", "REFERENCED_NAME", "REFERENCED_TYPE", "DEPENDENCY_TYPE", "REFERENCED_LINK_NAME"];if (required.some((name) => !indexes.has(name))) throw new Error("The dependency query returned an unexpected column layout.");diff --git a/apps/desktop/src/lib/database/oracleForeignKeys.ts b/apps/desktop/src/lib/database/oracleForeignKeys.tsindex 1e657de805..40cf8ccb49 100644--- a/apps/desktop/src/lib/database/oracleForeignKeys.ts+++ b/apps/desktop/src/lib/database/oracleForeignKeys.ts@@ -1,5 +1,5 @@import * as api from "@/lib/backend/api";-import type { BuildTableStructureChangeSqlOptions, OracleForeignKeyChange, OracleForeignKeyDefinition, OracleForeignKeyState, TablePartitionDefinition } from "@/lib/table/tableStructureEditorSql";+import type { BuildTableStructureChangeSqlOptions, OracleForeignKeyChange, OracleForeignKeyDefinition, OracleForeignKeyState, OracleTriggerStructureOperation, TablePartitionDefinition } from "@/lib/table/tableStructureEditorSql";import { foldCreatedTableName } from "@/lib/table/tableStructureEditorState";export interface OracleForeignKeyTarget {@@ -501,6 +501,7 @@ export interface OracleForeignKeyCreatePlan {references: OracleForeignKeyReferenceSnapshot[];session: { user: string; currentSchema: string };snapshot: string;+ triggerOperations?: OracleTriggerStructureOperation[];}export interface OracleForeignKeyCreateExecutionResult {@@ -556,17 +557,22 @@ export async function prepareOracleForeignKeyCreatePlan(target: OracleForeignKeyvalidateOracleForeignKeyReference(snapshot, source, definition, false, target.databaseType);references.push(snapshot);}- return { target, options, partitioning, changes, statements: [...generated.statements], references, session, snapshot: JSON.stringify({ session, references }) };+ return { target, options, partitioning, changes, statements: [...generated.statements], references, session, snapshot: JSON.stringify({ session, references }), ...(generated.triggerOperations?.length ? { triggerOperations: generated.triggerOperations } : {}) };+}++export async function preflightOracleForeignKeyCreatePlan(plan: OracleForeignKeyCreatePlan, canStart: () => boolean, connectionCurrent: () => boolean): Promise<boolean> {+ if (!canStart() || !connectionCurrent()) return false;+ const fresh = await prepareOracleForeignKeyCreatePlan(plan.target, plan.options, plan.changes, plan.partitioning, connectionCurrent);+ if (!connectionCurrent() || !canStart()) return false;+ if (fresh.snapshot !== plan.snapshot || JSON.stringify(fresh.statements) !== JSON.stringify(plan.statements)) invalid();+ return true;}/** Rechecks parent/session state, then executes CREATE and ordered FKs once each. */export async function executeOracleForeignKeyCreatePlan(plan: OracleForeignKeyCreatePlan, timeoutSecs: number, guards: (() => boolean) | { canStart?: () => boolean; connectionCurrent?: () => boolean }): Promise<OracleForeignKeyCreateExecutionResult | undefined> {const canStart = typeof guards === "function" ? guards : (guards.canStart ?? (() => true));const connectionCurrent = typeof guards === "function" ? guards : (guards.connectionCurrent ?? (() => true));- if (!canStart() || !connectionCurrent()) return undefined;- const fresh = await prepareOracleForeignKeyCreatePlan(plan.target, plan.options, plan.changes, plan.partitioning, connectionCurrent);- if (!connectionCurrent() || !canStart()) return undefined;- if (fresh.snapshot !== plan.snapshot || JSON.stringify(fresh.statements) !== JSON.stringify(plan.statements)) invalid();+ if (!(await preflightOracleForeignKeyCreatePlan(plan, canStart, connectionCurrent))) return undefined;const steps: OracleForeignKeyCreateExecutionResult["steps"] = plan.statements.map((sql) => ({ sql, state: "notExecuted" }));for (const step of steps) {if (!canStart() || !connectionCurrent()) break;@@ -592,6 +598,10 @@ export async function executeOracleForeignKeyCreatePlan(plan: OracleForeignKeyCrbreak;}}+ return readOracleForeignKeyCreateResult(plan, steps, connectionCurrent);+}++export async function readOracleForeignKeyCreateResult(plan: OracleForeignKeyCreatePlan, steps: OracleForeignKeyCreateExecutionResult["steps"], connectionCurrent: () => boolean): Promise<OracleForeignKeyCreateExecutionResult> {const outcome: OracleForeignKeyCreateExecutionResult = { steps };const createUnknown = steps[0]?.state === "unknown";if (!steps.some((step) => step.state === "committed") && !createUnknown) return outcome;diff --git a/apps/desktop/src/lib/database/oracleInvalidObjects.ts b/apps/desktop/src/lib/database/oracleInvalidObjects.tsindex 815a866766..efba2ef680 100644--- a/apps/desktop/src/lib/database/oracleInvalidObjects.ts+++ b/apps/desktop/src/lib/database/oracleInvalidObjects.ts@@ -1,4 +1,4 @@-import type { DatabaseType, ObjectSourceKind, QueryResult } from "@/types/database";+import type { DatabaseType, ObjectSourceKind, OracleTriggerMetadata, QueryResult } from "@/types/database";export type OracleInvalidObject = {owner: string;@@ -23,6 +23,10 @@ const ORACLE_COMPILE_TYPES = new Set(["VIEW", "MATERIALIZED VIEW", "PROCEDURE",const OCEANBASE_COMPILE_TYPES = new Set(["PROCEDURE", "FUNCTION", "PACKAGE", "PACKAGE BODY"]);+export interface OracleCompileOptions {+ triggerProfile?: Pick<OracleTriggerMetadata, "contractVersion" | "identityMode" | "engine" | "engineVersion">;+}+export function oracleInvalidObjectSourceKind(objectType: string): ObjectSourceKind | null {const kind = objectType.trim().toUpperCase().replaceAll(" ", "_");switch (kind) {@@ -118,16 +122,20 @@ export function buildOracleObjectStatusSql(owner: string, object: OracleInvalidOreturn `SELECT TO_CHAR(OBJECT_ID) AS OBJECT_ID, TO_CHAR(LAST_DDL_TIME, 'YYYY-MM-DD HH24:MI:SS') AS LAST_DDL_TIME, STATUS FROM ALL_OBJECTS WHERE OWNER = ${quoteOracleLiteral(owner)} AND OBJECT_NAME = ${quoteOracleLiteral(object.name)} AND OBJECT_TYPE = ${quoteOracleLiteral(object.type)}`;}-export function oracleCompileUnsupportedReason(dbType: DatabaseType, objectType: string): "unsupported-type" | "unsupported-on-engine" | null {+export function oracleCompileUnsupportedReason(dbType: DatabaseType, objectType: string, options?: OracleCompileOptions): "unsupported-type" | "unsupported-on-engine" | null {const type = objectType.toUpperCase();if (!ORACLE_COMPILE_TYPES.has(type)) return "unsupported-type";- if (dbType === "oceanbase-oracle" && !OCEANBASE_COMPILE_TYPES.has(type)) return "unsupported-on-engine";+ if (dbType === "oceanbase-oracle" && !OCEANBASE_COMPILE_TYPES.has(type)) {+ const profile = options?.triggerProfile;+ if (type === "TRIGGER" && profile?.contractVersion === 1 && profile.identityMode === "exact" && profile.engine === "oceanbase-oracle" && /(?:^|[^0-9])4\.2\.5\.7(?:[^0-9]|$)/.test(profile.engineVersion ?? "")) return null;+ return "unsupported-on-engine";+ }return null;}-export function buildOracleCompileSql(dbType: DatabaseType, owner: string, object: Pick<OracleInvalidObject, "name" | "type">): string {+export function buildOracleCompileSql(dbType: DatabaseType, owner: string, object: Pick<OracleInvalidObject, "name" | "type">, options?: OracleCompileOptions): string {const type = object.type.toUpperCase();- if (oracleCompileUnsupportedReason(dbType, type)) throw new Error("Unsupported Oracle object compile type");+ if (oracleCompileUnsupportedReason(dbType, type, options)) throw new Error("Unsupported Oracle object compile type");const qualified = `${quoteOracleIdentifier(owner)}.${quoteOracleIdentifier(object.name)}`;if (type === "SYNONYM") return `ALTER ${owner === "PUBLIC" ? "PUBLIC " : ""}SYNONYM ${owner === "PUBLIC" ? quoteOracleIdentifier(object.name) : qualified} COMPILE`;if (type === "MATERIALIZED VIEW") return `ALTER MATERIALIZED VIEW ${qualified} COMPILE`;diff --git a/apps/desktop/src/lib/database/oracleObjectDependencies.ts b/apps/desktop/src/lib/database/oracleObjectDependencies.tsindex c220d826a1..cdefa40ad0 100644--- a/apps/desktop/src/lib/database/oracleObjectDependencies.ts+++ b/apps/desktop/src/lib/database/oracleObjectDependencies.ts@@ -1,5 +1,6 @@import type { TreeNodeType } from "@/types/database";import type { DatabaseDependencyProvider, DependencyTreeNode } from "@/lib/database/databaseObjectDependencies";+import { exactOracleTriggerNodeMetadata } from "@/lib/database/oracleTriggerIdentity";export type OracleDependencyObjectType = "TABLE" | "VIEW" | "MATERIALIZED_VIEW" | "PROCEDURE" | "FUNCTION" | "PACKAGE" | "TYPE" | "TYPE_BODY" | "SEQUENCE" | "SYNONYM" | "TRIGGER" | "INDEX";export type ObjectRelationKind = "dependencies" | "foreignKeys" | "ownership";@@ -52,6 +53,10 @@ ORDER BY 1, 5, 6, 7`;}export function oracleTarget(node: DependencyTreeNode): { schema: string; name: string; type: OracleDependencyObjectType; packaged: boolean } | null {+ if (node.type === "trigger") {+ const metadata = exactOracleTriggerNodeMetadata(node);+ return metadata ? { schema: metadata.owner, name: metadata.name, type: "TRIGGER", packaged: false } : null;+ }const member = node.parentType === "package" && (node.type === "procedure" || node.type === "function");const type = member || node.type === "package" ? "PACKAGE" : oracleTypeForTreeNode(node.type);const schema = member ? node.parentSchema : node.schema;@@ -135,6 +140,20 @@ export const oracleDependencyProvider: DatabaseDependencyProvider = {},};+export const dmTriggerDependencyProvider: DatabaseDependencyProvider = {+ databaseType: "dameng",+ supports(node) {+ const metadata = exactOracleTriggerNodeMetadata(node);+ return metadata?.engine === "dm" && /(?:^|\D)8\./.test(metadata.engineVersion ?? "");+ },+ buildQuery(node) {+ return dmTriggerDependencyProvider.supports(node) ? oracleDependencyProvider.buildQuery(node) : null;+ },+ targetLabel(node) {+ return dmTriggerDependencyProvider.supports(node) ? oracleDependencyProvider.targetLabel!(node) : null;+ },+};+function quoteSqlString(value: string): string {return `'${value.replaceAll("'", "''")}'`;}diff --git a/apps/desktop/src/lib/database/oracleTriggerActions.ts b/apps/desktop/src/lib/database/oracleTriggerActions.tsnew file mode 100644index 0000000000..87bc9c4464--- /dev/null+++ b/apps/desktop/src/lib/database/oracleTriggerActions.ts@@ -0,0 +1,48 @@+import { watch } from "vue";+import { uuid } from "@/lib/common/utils";+import i18n from "@/i18n";+import { useConnectionStore } from "@/stores/connectionStore";+import { useSqlExecutionDangerStore } from "@/stores/sqlExecutionDangerStore";+import { useProductionSafetyStore } from "@/stores/productionSafetyStore";+import { executeOracleTriggerPlan, type OracleTriggerExecutionResult, type OracleTriggerPlan, type OracleTriggerSnapshot, type OracleTriggerTarget } from "./oracleTriggerPlan";++/** Reuse the application's SQL preview/confirmation queue; no second execution dialog or executor. */+export async function confirmOracleTriggerPlan(plan: OracleTriggerPlan, options: { isCurrent: () => boolean; refresh?: (target: Readonly<OracleTriggerTarget>, snapshot?: OracleTriggerSnapshot) => Promise<void> }): Promise<OracleTriggerExecutionResult> {+ const danger = useSqlExecutionDangerStore();+ const production = useProductionSafetyStore();+ const scopeId = `oracle-trigger:${uuid()}`;+ const stop = watch(+ options.isCurrent,+ (current) => {+ if (!current) {+ danger.cancelScope(scopeId);+ production.cancelScope(scopeId);+ }+ },+ { flush: "sync" },+ );+ try {+ const connection = useConnectionStore().getConfig(plan.target.connectionId);+ const binding = plan.expectedAfter?.binding;+ const parent = binding ?? (plan.before.metadata.parent ? { scope: plan.before.metadata.parent.objectType, ...plan.before.metadata.parent } : { scope: plan.before.metadata.scope, owner: plan.before.metadata.scopeOwner });+ const targets = [`TRIGGER ${plan.target.owner}.${plan.target.name}`, `ON ${parent.scope}${parent.owner ? ` ${parent.owner}${"name" in parent && parent.name ? `.${parent.name}` : ""}` : ""}`, `${i18n.global.t("oracleTrigger.executionSchema")}: ${plan.target.executionSchema}`];+ if (plan.steps.length > 1) targets.push(i18n.global.t("oracleTrigger.nonAtomic"));+ const confirmed =+ options.isCurrent() &&+ (plan.steps.length === 0 ||+ (await danger.requestConfirmation({+ sql: plan.steps.map((step) => step.sql).join("\n\n"),+ kind: "sql",+ connectionName: connection?.name,+ database: plan.target.database,+ targetLabel: targets.join("\n"),+ databaseType: plan.before.metadata.engine === "dm" ? "dameng" : plan.before.metadata.engine,+ scopeId,+ })));+ return await executeOracleTriggerPlan(plan, { confirmed, confirmationScope: scopeId, ...options });+ } finally {+ stop();+ danger.cancelScope(scopeId);+ production.cancelScope(scopeId);+ }+}diff --git a/apps/desktop/src/lib/database/oracleTriggerIdentity.ts b/apps/desktop/src/lib/database/oracleTriggerIdentity.tsnew file mode 100644index 0000000000..ee605b2e6d--- /dev/null+++ b/apps/desktop/src/lib/database/oracleTriggerIdentity.ts@@ -0,0 +1,47 @@+import type { DatabaseType, MetadataReadOptions, ObjectInfo, OracleTriggerMetadata, TriggerInfo, TreeNode } from "@/types/database";+import { effectiveDatabaseTypeForConnection, type JdbcDialectConnection } from "@/lib/database/jdbcDialect";++/** A read request is not an engine capability proof; the response must verify it. */+export function oracleTriggerReadOptions(databaseType?: DatabaseType, catalog?: string): MetadataReadOptions | undefined {+ if (databaseType !== "oracle" && databaseType !== "oceanbase-oracle" && databaseType !== "dameng") return;+ return { identityMode: "exact", ...(catalog === undefined ? {} : { catalog }) };+}++export function oracleTriggerObjectReadOptions(connection: JdbcDialectConnection | undefined, objectTypes?: readonly string[], catalog?: string): MetadataReadOptions | undefined {+ if (objectTypes && !objectTypes.includes("TRIGGER")) return;+ // A broad compatibility label may suggest a new trigger-only read. It must+ // not impose new provider requirements on existing mixed/parent reads.+ if (connection?.db_type === "jdbc" && !(objectTypes?.length === 1 && objectTypes[0] === "TRIGGER")) {+ const product = connection.database_info?.productName?.toLowerCase();+ if (!product || !["oracle", "oracle database", "oceanbase", "dm dbms", "dm8", "dameng"].includes(product)) return;+ }+ return oracleTriggerReadOptions(effectiveDatabaseTypeForConnection(connection), catalog);+}++/** This establishes the provider's identity semantics, not permission to write. */+export function exactOracleTriggerMetadata(trigger?: Pick<TriggerInfo, "name" | "oracle_metadata"> | null): OracleTriggerMetadata | undefined {+ const metadata = trigger?.oracle_metadata;+ if (!metadata || metadata.contractVersion !== 1 || metadata.identityMode !== "exact") return;+ if (!["oracle", "oceanbase-oracle", "dm"].includes(metadata.engine)) return;+ if (typeof metadata.owner !== "string" || metadata.owner.length === 0 || typeof metadata.name !== "string" || metadata.name.length === 0 || metadata.name !== trigger?.name) return;+ return metadata;+}++export function exactOracleTriggerObjectMetadata(object: ObjectInfo): OracleTriggerMetadata | undefined {+ if (object.object_type.toUpperCase() !== "TRIGGER") return;+ const metadata = exactOracleTriggerMetadata(object.trigger);+ if (!metadata || metadata.name !== object.name || (object.schema != null && metadata.owner !== object.schema)) return;+ return metadata;+}++/** Encoded raw tuples avoid delimiter collisions and preserve quoted case. */+export function oracleTriggerIdentityKey(metadata: Pick<OracleTriggerMetadata, "owner" | "name">, catalog?: string): string {+ return JSON.stringify(["oracle-trigger/v1", catalog ?? null, metadata.owner, metadata.name]);+}++export function exactOracleTriggerNodeMetadata(node: Pick<TreeNode, "type" | "meta" | "schema" | "objectName">): OracleTriggerMetadata | undefined {+ if (node.type !== "trigger" || !node.meta || !("oracle_metadata" in node.meta) || !("event" in node.meta) || !("timing" in node.meta)) return;+ const metadata = exactOracleTriggerMetadata(node.meta);+ if (!metadata || metadata.owner !== node.schema || metadata.name !== node.objectName) return;+ return metadata;+}diff --git a/apps/desktop/src/lib/database/oracleTriggerPlan.ts b/apps/desktop/src/lib/database/oracleTriggerPlan.tsnew file mode 100644index 0000000000..9cee4785fd--- /dev/null+++ b/apps/desktop/src/lib/database/oracleTriggerPlan.ts@@ -0,0 +1,754 @@+import * as api from "@/lib/backend/api";+import { BackendErrorException, formatError, normalizeBackendError } from "@/lib/backend/errorUtils";+import { connectionConfigFingerprint } from "@/lib/connection/connectionDatabaseInfo";+import { exactOracleTriggerMetadata } from "@/lib/database/oracleTriggerIdentity";+import { buildOracleCompileSql, oracleCompileUnsupportedReason } from "@/lib/database/oracleInvalidObjects";+import { buildTriggerToggleSql } from "@/lib/database/triggerToggleSql";+import { oracleTriggerDefinitionScopes, oracleTriggerSourceBinding, type OracleTriggerSqlBinding, type PreparedOracleTriggerSql, type OracleTriggerDatabaseType } from "@/lib/database/oracleTriggerSql";+import { executeWithProductionSqlGuard } from "@/lib/database/productionExecutionGuard";+import { assertSourceIdentity, captureSourceIdentity, freezeSourceIdentities, renewSourceIdentity, type SourceIdentitySnapshot } from "@/lib/table/objectSourceIdentity";+import { inspectExactOracleTriggerSource } from "@/lib/table/objectSourceLoad";+import { invalidateObjectMetadataFacet } from "@/lib/metadata/objectMetadataCache";+import { invalidateObjectDdl } from "@/lib/metadata/objectDdlCache";+import { useConnectionStore } from "@/stores/connectionStore";+import { useSettingsStore } from "@/stores/settingsStore";+import { queryTimeoutSecsForConnection } from "@/lib/sql/queryTimeout";+import type { ObjectSource, OracleTriggerMetadata, QueryResult } from "@/types/database";+import type { OracleTriggerStructurePlan } from "./oracleTriggerStructurePlan";+import type { OracleTriggerStructureOperation } from "@/lib/table/tableStructureEditorSql";++export interface OracleTriggerTarget {+ connectionId: string;+ database: string;+ catalog?: string;+ owner: string;+ name: string;+ /** Separate from the trigger owner and the owning table/view's owner. */+ executionSchema: string;+}++export interface OracleTriggerSnapshot {+ target: Readonly<OracleTriggerTarget>;+ raw: Readonly<ObjectSource>;+ metadata: Readonly<OracleTriggerMetadata>;+ identity: Readonly<SourceIdentitySnapshot>;+ exists: boolean;+}++export type OracleTriggerAction = "enable" | "disable" | "compile" | "create" | "replace" | "delete";+export interface OracleTriggerStep {+ action: OracleTriggerAction;+ sql: string;+}+export interface OracleTriggerPlan {+ target: Readonly<OracleTriggerTarget>;+ action: OracleTriggerAction;+ before: OracleTriggerSnapshot;+ expectedEnabled?: boolean;+ expectedAfter?: Readonly<{+ binding: Readonly<OracleTriggerSqlBinding>;+ proof: readonly string[];+ definition: string;+ comparisonSource: string;+ }>;+ parentBefore?: readonly string[];+ steps: readonly Readonly<OracleTriggerStep>[];+}++export interface OracleTriggerStepResult extends OracleTriggerStep {+ state: "notExecuted" | "rejected" | "committed" | "unknown";+ verification: "applied" | "deleted" | "unverified" | "mismatch" | "unchanged" | "valid" | "invalid";+ error?: string;+ readbackError?: string;+ receipt?: "accepted" | "unknown" | "rejected" | "notStarted";+ snapshot?: OracleTriggerSnapshot;+}+export interface OracleTriggerExecutionResult {+ steps: OracleTriggerStepResult[];+ snapshot?: OracleTriggerSnapshot;+ cancelled?: boolean;+ refreshError?: string;+}++interface ConnectionIdentity {+ revision: number;+ fingerprint: string;+}+const planConnections = new WeakMap<OracleTriggerPlan, ConnectionIdentity>();+const snapshotConnections = new WeakMap<OracleTriggerSnapshot, ConnectionIdentity>();++function connectionIdentity(target: Pick<OracleTriggerTarget, "connectionId">): ConnectionIdentity {+ const store = useConnectionStore();+ const config = store.getConfig(target.connectionId);+ if (!config || !store.connectedIds.has(target.connectionId)) throw new Error("Reconnect the trigger's connection before preparing a write");+ return { revision: store.connectionStateRevision(target.connectionId), fingerprint: connectionConfigFingerprint(config) };+}++function assertConnection(target: Pick<OracleTriggerTarget, "connectionId">, expected: ConnectionIdentity): void {+ const current = connectionIdentity(target);+ if (current.revision !== expected.revision || current.fingerprint !== expected.fingerprint) throw new Error("The connection changed; reload the trigger and prepare a new preview");+}++function sourceIdentity(target: OracleTriggerTarget): SourceIdentitySnapshot {+ return Object.freeze(captureSourceIdentity({ connectionId: target.connectionId, database: target.database, schema: target.owner, name: target.name, objectType: "TRIGGER" }));+}++function freezeSource(raw: ObjectSource, metadata: OracleTriggerMetadata): void {+ if (metadata.parent) Object.freeze(metadata.parent);+ if (metadata.definition) Object.freeze(metadata.definition);+ metadata.errors?.forEach(Object.freeze);+ if (metadata.errors) Object.freeze(metadata.errors);+ Object.values(metadata.reads).forEach((read) => read && Object.freeze(read));+ Object.freeze(metadata.reads);+ Object.freeze(metadata);+ if (raw.trigger) Object.freeze(raw.trigger);+ Object.freeze(raw);+}++async function fetchSnapshot(target: Readonly<OracleTriggerTarget>, connection: ConnectionIdentity): Promise<OracleTriggerSnapshot> {+ assertConnection(target, connection);+ const identity = sourceIdentity(target);+ const response = await api.getObjectSource(target.connectionId, target.database, target.owner, target.name, "TRIGGER", undefined, undefined, { identityMode: "exact", ...(target.catalog === undefined ? {} : { catalog: target.catalog }) });+ assertConnection(target, connection);+ return snapshotFromResponse(target, response, identity, connection);+}++function snapshotFromResponse(target: Readonly<OracleTriggerTarget>, response: ObjectSource, identity: Readonly<SourceIdentitySnapshot>, connection: ConnectionIdentity): OracleTriggerSnapshot {+ // ObjectSource is the JSON transport DTO. Copy its optional values without+ // structuredClone's inability to read a Vue proxy supplied by a consumer.+ const raw: ObjectSource = JSON.parse(JSON.stringify(response));+ const metadata = exactOracleTriggerMetadata(raw.trigger);+ if (!metadata || raw.object_type !== "TRIGGER" || raw.name !== target.name || raw.schema !== target.owner || metadata.owner !== target.owner || metadata.name !== target.name) throw new Error("Exact trigger identity was not verified; reload or update the metadata provider");+ const state = metadata.reads.identity?.state;+ if (state !== "empty" && (state !== "available" || typeof metadata.objectId !== "string" || metadata.objectId.length === 0)) throw new Error("The trigger object identity is unavailable; keep the draft and reload");+ freezeSource(raw, metadata);+ const snapshot = Object.freeze({ target, raw, metadata, identity, exists: state !== "empty" });+ snapshotConnections.set(snapshot, connection);+ return snapshot;+}++/** Read-only viewing retains old/partial provider text without authorizing an exact write. */+export async function readOracleTriggerSource(target: OracleTriggerTarget): Promise<{ raw: Readonly<ObjectSource>; snapshot?: OracleTriggerSnapshot; identityError?: string }> {+ if (!target.owner.length || !target.name.length || !target.executionSchema.length) throw new Error("Select the exact trigger owner/name and execution schema");+ const fixed = Object.freeze({ ...target });+ const connection = connectionIdentity(fixed);+ const identity = sourceIdentity(fixed);+ const raw = await api.getObjectSource(fixed.connectionId, fixed.database, fixed.owner, fixed.name, "TRIGGER", undefined, undefined, { identityMode: "exact", ...(fixed.catalog === undefined ? {} : { catalog: fixed.catalog }) });+ assertConnection(fixed, connection);+ try {+ const snapshot = snapshotFromResponse(fixed, raw, identity, connection);+ const renewed = Object.freeze({ ...snapshot, identity: Object.freeze(renewSourceIdentity(snapshot.identity)) });+ snapshotConnections.set(renewed, connection);+ return { raw: renewed.raw, snapshot: renewed };+ } catch (error) {+ return { raw, identityError: formatError(error) };+ }+}++export async function readOracleTriggerSnapshot(target: OracleTriggerTarget): Promise<OracleTriggerSnapshot> {+ const loaded = await readOracleTriggerSource(target);+ if (!loaded.snapshot) throw new Error(loaded.identityError);+ return loaded.snapshot;+}++export interface OracleTriggerPlanInput {+ target: OracleTriggerTarget;+ action: OracleTriggerAction;+ source?: string;+ /** The authoritative version loaded before the user's edits, not a fresh replacement for it. */+ baseline?: OracleTriggerSnapshot;+ selection?: OracleTriggerSqlBinding;+ enabled?: boolean;+ /** Optional identity already shown by the calling list/form, never inferred from a label. */+ expectedObjectId?: string;+}++export async function prepareOracleTriggerPlan(input: OracleTriggerPlanInput): Promise<OracleTriggerPlan> {+ const action = input.action;+ const draft = input.source,+ baseline = input.baseline,+ requestedEnabled = input.enabled;+ const selection = input.selection && { ...input.selection };+ const expectedObjectId = input.expectedObjectId;+ if (!["enable", "disable", "compile", "create", "replace", "delete"].includes(action)) throw new Error("Unsupported trigger action");+ if (action === "replace") {+ if (!baseline || !sameTarget(baseline.target, input.target)) throw new Error("Reload the complete trigger baseline before replacing it");+ const loadedConnection = snapshotConnections.get(baseline);+ if (!loadedConnection) throw new Error("Reload the authoritative trigger baseline before replacing it");+ assertConnection(input.target, loadedConnection);+ assertSourceIdentity(baseline.identity);+ }+ const connection = connectionIdentity(input.target);+ const before = await readOracleTriggerSnapshot(input.target);+ assertConnection(before.target, connection);+ if (expectedObjectId !== undefined && before.metadata.objectId !== expectedObjectId) throw new Error("The displayed trigger was replaced; keep the draft and reread its identity");+ if (action === "create" ? before.exists : !before.exists) throw new Error(action === "create" ? "A visible trigger already exists; reload it before preparing a replacement" : "No visible trigger matches this target; refresh before preparing the action");+ if (baseline && action === "replace" && !sameSnapshot(baseline, before)) throw new Error("The trigger changed since the loaded baseline; keep the draft and reload");+ const metadata = before.metadata;+ const relation = metadata.scope === "TABLE" || metadata.scope === "VIEW";+ assertActionReadability(before, action);+ if (metadata.engine === "dm" && !/(?:^|\D)8\./.test(metadata.engineVersion ?? "")) throw new Error("The connected DM8 version could not be verified for this action");+ const databaseType: OracleTriggerDatabaseType = metadata.engine === "dm" ? "dameng" : metadata.engine;+ let expectedEnabled: boolean | undefined;+ let expectedAfter: OracleTriggerPlan["expectedAfter"];+ let parentBefore: readonly string[] | undefined;+ let steps: OracleTriggerStep[];+ if (action === "compile" && oracleCompileUnsupportedReason(databaseType, "TRIGGER", { triggerProfile: metadata })) throw new Error("Trigger compilation has not been verified for the connected engine/version");+ if (action === "create" || action === "replace") {+ if (typeof draft !== "string" || !draft.trim()) throw new Error("Enter one complete trigger definition");+ if (action === "replace") {+ const loaded = await inspectExactOracleTriggerSource(before.raw, metadata.owner, metadata.name);+ if (!loaded.triggerSource.complete) throw new Error(loaded.triggerSource.error || "Reload the complete trigger baseline before replacing it");+ if (metadata.reads.enabled?.state !== "available" || typeof before.raw.trigger?.enabled !== "boolean") throw new Error("Read the actual enabled state before replacing the trigger");+ }+ const fallback = selection ?? (action === "replace" ? oracleTriggerSourceBinding(metadata) : undefined);+ const inspected = await api.prepareOracleTriggerSql({ databaseType, owner: metadata.owner, name: metadata.name, source: draft, purpose: "inspect", binding: selection });+ const binding = candidateBinding(inspected, fallback);+ if (!oracleTriggerDefinitionScopes(metadata).includes(binding.scope)) throw new Error("Full trigger creation/replacement is unavailable for this scope on the connected engine/version; OceanBase Oracle 4.2.5.7 supports TABLE/VIEW in this workflow");+ if (metadata.engine === "dm" && action === "replace" && !matchesBinding(metadata, binding)) throw new Error("DM cannot replace this trigger with a different owning object or scope; keep the draft");+ const proof = await verifyBinding(before.target, metadata.engine, binding);+ const desiredEnabled = requestedEnabled ?? (action === "replace" ? before.raw.trigger!.enabled : (inspected.inlineEnabled ?? true));+ if (typeof desiredEnabled !== "boolean") throw new Error("Read or select the trigger's enabled state before preparing the definition");+ expectedEnabled = desiredEnabled;+ const prepared = await api.prepareOracleTriggerSql({ databaseType, owner: metadata.owner, name: metadata.name, source: draft, purpose: action, binding, enabled: expectedEnabled });+ if (typeof prepared.comparisonSource !== "string") throw new Error("Update the trigger SQL provider before preparing this write");+ expectedAfter = Object.freeze({ binding: Object.freeze(binding), proof: Object.freeze(proof), definition: prepared.definition, comparisonSource: prepared.comparisonSource });+ steps = [{ action, sql: prepared.definition }];+ if (prepared.requiresStateRestore) {+ const sql = buildTriggerToggleSql({ databaseType, schema: metadata.owner, triggerName: metadata.name, enabled: false, identityMode: "exact", scope: binding.scope });+ if (!sql) throw new Error("Native disabled-state restoration is unavailable for this trigger scope");+ steps.push({ action: "disable", sql });+ }+ } else if (action === "delete") {+ const binding = oracleTriggerSourceBinding(metadata);+ if (binding && relation) {+ // The optional parent read is evidence for the result, not a new DROP privilege prerequisite.+ try {+ parentBefore = Object.freeze(await verifyBinding(before.target, metadata.engine, binding));+ } catch {+ /* report unverifiable parent on readback */+ }+ }+ const sql = await api.buildDropObjectSql({ databaseType, objectType: "TRIGGER", schema: metadata.owner, name: metadata.name });+ steps = [{ action, sql }];+ } else {+ expectedEnabled = action === "compile" ? undefined : action === "enable";+ const sql =+ action === "compile"+ ? buildOracleCompileSql(databaseType, metadata.owner, { name: metadata.name, type: "TRIGGER" }, { triggerProfile: metadata })+ : buildTriggerToggleSql({ databaseType, schema: metadata.owner, triggerName: metadata.name, enabled: expectedEnabled!, identityMode: "exact", scope: metadata.scope });+ if (!sql) throw new Error("This native trigger action is unavailable for the verified engine and scope");+ steps = action !== "compile" && metadata.reads.enabled?.state === "available" && before.raw.trigger?.enabled === expectedEnabled ? [] : [{ action, sql }];+ }+ const plan: OracleTriggerPlan = Object.freeze({ target: before.target, action, before, expectedEnabled, expectedAfter, parentBefore, steps: Object.freeze(steps.map((step) => Object.freeze(step))) });+ assertSourceIdentity(before.identity);+ assertConnection(before.target, connection);+ planConnections.set(plan, connection);+ return plan;+}++export async function executeOracleTriggerPlan(+ plan: OracleTriggerPlan,+ options: { confirmed: boolean; confirmationScope?: string; isCurrent?: () => boolean; timeoutSecs?: number; refresh?: (target: Readonly<OracleTriggerTarget>, snapshot?: OracleTriggerSnapshot) => Promise<void> },+): Promise<OracleTriggerExecutionResult> {+ return executePreparedTriggerPlan(plan, options, true);+}++async function executePreparedTriggerPlan(+ plan: OracleTriggerPlan,+ options: { confirmed: boolean; confirmationScope?: string; isCurrent?: () => boolean; timeoutSecs?: number; refresh?: (target: Readonly<OracleTriggerTarget>, snapshot?: OracleTriggerSnapshot) => Promise<void> },+ guard: boolean,+): Promise<OracleTriggerExecutionResult> {+ const cancelled = (): OracleTriggerExecutionResult => ({ steps: plan.steps.map((step) => ({ ...step, state: "notExecuted", verification: "unverified" })), cancelled: true });+ if (!options.confirmed || options.isCurrent?.() === false) return cancelled();+ const connection = planConnections.get(plan);+ if (!connection) throw new Error("Prepare a new trigger preview before executing it");+ assertSourceIdentity(plan.before.identity);+ assertConnection(plan.target, connection);+ const run = async (): Promise<OracleTriggerExecutionResult> => {+ if (options.isCurrent?.() === false) return cancelled();+ assertSourceIdentity(plan.before.identity);+ assertConnection(plan.target, connection);+ const frozen = freezeSourceIdentities([plan.before.identity]);+ let dispatched = false;+ try {+ let latest = await fetchSnapshot(plan.target, connection);+ if (!sameSnapshot(plan.before, latest)) throw new Error("The trigger changed after the preview; keep the draft and reload");+ assertActionReadability(latest, plan.action);+ if (plan.expectedAfter && !sameProof(plan.expectedAfter.proof, await verifyBinding(plan.target, latest.metadata.engine, plan.expectedAfter.binding))) throw new Error("The owning object or scope changed after the preview; keep the draft and reload");+ if (options.isCurrent?.() === false) return cancelled();+ const result: OracleTriggerExecutionResult = { steps: [], snapshot: latest };+ for (const [index, step] of plan.steps.entries()) {+ if (index && (result.steps[index - 1].state !== "committed" || result.steps[index - 1].verification === "invalid" || options.isCurrent?.() === false)) {+ result.steps.push({ ...step, state: "notExecuted", verification: "unverified" });+ continue;+ }+ try {+ assertConnection(plan.target, connection);+ } catch (error) {+ if (!index) throw error;+ result.steps.push({ ...step, state: "notExecuted", verification: "unverified", error: formatError(error) });+ continue;+ }+ frozen.markDispatched();+ dispatched = true;+ let accepted = false;+ let writeError: unknown;+ try {+ const timeoutSecs = options.timeoutSecs ?? queryTimeoutSecsForConnection(useConnectionStore().getConfig(plan.target.connectionId), useSettingsStore().editorSettings.globalQueryTimeoutSecs);+ const receipt = await api.executeQuery(plan.target.connectionId, plan.target.database, step.sql, plan.target.executionSchema, undefined, { catalog: plan.target.catalog, timeoutSecs });+ if (receipt.execution_error) throw new BackendErrorException(receipt.error || "Trigger statement failed");+ accepted = true;+ } catch (error) {+ writeError = error;+ }+ // A failed/lost receipt does not establish rejection. Always read the+ // fixed target; an attempted statement is never dispatched a second time.+ let after: OracleTriggerSnapshot | undefined;+ let readbackError: string | undefined;+ let verification: OracleTriggerStepResult["verification"] = "unverified";+ try {+ after = await fetchSnapshot(plan.target, connection);+ verification = await verifyStep(plan, step, latest, after, index);+ } catch (error) {+ readbackError = formatError(error);+ }+ const refusal = writeError === undefined ? "unknown" : knownReceiptFailure(writeError, latest.metadata.engine);+ if (refusal !== "unknown" && after && sameSnapshot(latest, after)) verification = "unchanged";+ const verified = verification === "applied" || verification === "deleted" || verification === "valid" || verification === "invalid";+ const state: OracleTriggerStepResult["state"] = refusal === "notStarted" ? "notExecuted" : refusal === "rejected" ? "rejected" : accepted && verified ? "committed" : "unknown";+ result.steps.push({ ...step, state, verification, snapshot: after, receipt: accepted ? "accepted" : refusal, ...(writeError === undefined ? {} : { error: formatError(writeError) }), ...(readbackError === undefined ? {} : { readbackError }) });+ result.snapshot = after;+ if (after) latest = after;+ }+ return result;+ } finally {+ if (dispatched) frozen.finish();+ else frozen.cancel();+ }+ };+ const guarded =+ !guard || plan.steps.length === 0+ ? await run()+ : await executeWithProductionSqlGuard<OracleTriggerExecutionResult>({+ connection: useConnectionStore().getConfig(plan.target.connectionId),+ database: plan.target.database,+ sql: plan.steps.map((step) => step.sql).join("\n"),+ scopeId: options.confirmationScope,+ execute: run,+ });+ if (!guarded) return cancelled();+ if (guarded.snapshot) {+ const snapshot = guarded.snapshot;+ try {+ const renewed = Object.freeze({ ...snapshot, identity: Object.freeze(renewSourceIdentity(snapshot.identity)) });+ snapshotConnections.set(renewed, connection);+ guarded.snapshot = renewed;+ for (const step of guarded.steps) if (step.snapshot === snapshot) step.snapshot = renewed;+ } catch (error) {+ guarded.refreshError = formatError(error);+ }+ }+ if (guarded.steps.some((step) => step.receipt !== undefined)) {+ try {+ const parents = [plan.before.metadata.parent, guarded.snapshot?.metadata.parent].filter((parent): parent is NonNullable<OracleTriggerMetadata["parent"]> => !!parent);+ const request = { connectionId: plan.target.connectionId, database: plan.target.database, catalog: plan.target.catalog, schema: plan.target.owner, tableName: plan.target.name, objectType: "TRIGGER" as const };+ const invalidations: Promise<unknown>[] = [invalidateObjectDdl(request, { metadata: false, strict: true }), useConnectionStore().invalidateOracleTriggerLists(plan.target, parents)];+ for (const parent of parents) {+ for (const objectType of parent.objectType === "VIEW" ? (["VIEW", undefined] as const) : ([undefined] as const)) invalidations.push(invalidateObjectMetadataFacet({ ...request, schema: parent.owner, tableName: parent.name, objectType }, "triggers", { strict: true }));+ }+ const results = await Promise.allSettled(invalidations);+ for (const result of results) if (result.status === "rejected") throw result.reason;+ } catch (error) {+ guarded.refreshError = [guarded.refreshError, formatError(error)].filter(Boolean).join("\n");+ }+ }+ if (+ ["enable", "disable", "compile"].includes(plan.action) &&+ !guarded.cancelled &&+ guarded.snapshot?.exists &&+ guarded.snapshot.metadata.objectId === plan.before.metadata.objectId &&+ guarded.snapshot.raw.trigger &&+ guarded.steps.every((step) => step.state === "committed" && ["applied", "valid", "invalid", "unchanged"].includes(step.verification))+ ) {+ try {+ assertConnection(plan.target, connection);+ assertSourceIdentity(guarded.snapshot.identity);+ useConnectionStore().syncOracleTriggerNodeState(plan.target, guarded.snapshot.raw.trigger);+ } catch (error) {+ guarded.refreshError = [guarded.refreshError, formatError(error)].filter(Boolean).join("\n");+ }+ }+ if (!guarded.cancelled && options.refresh) {+ try {+ assertConnection(plan.target, connection);+ await options.refresh(plan.target, guarded.snapshot);+ } catch (error) {+ guarded.refreshError = [guarded.refreshError, formatError(error)].filter(Boolean).join("\n");+ }+ }+ return guarded;+}++export interface OracleTriggerStructureStepResult {+ statementIndex: number;+ sql: string;+ state: OracleTriggerStepResult["state"];+ elapsedMs?: number;+ error?: string;+ trigger?: OracleTriggerStepResult;+}+export function assertTriggerStructureSql(statements: readonly string[], operation: Readonly<OracleTriggerStructureOperation>, plan: OracleTriggerPlan): void {+ if (plan.steps.length !== operation.statementCount || plan.steps.some((step, index) => step.sql !== statements[operation.statementIndex + index])) throw new Error("The actual trigger SQL differs from the confirmed table preview; regenerate it");+}+export interface OracleTriggerStructureExecutionResult {+ steps: OracleTriggerStructureStepResult[];+ triggerResults: { draftId: string; action: OracleTriggerAction; result: OracleTriggerExecutionResult }[];+ cancelled?: boolean;+}+const attemptedStructurePlans = new WeakSet<OracleTriggerStructurePlan>();++/** The original allowed structure order, through the existing single-statement seam. */+export async function executeOracleTriggerStructurePlan(plan: OracleTriggerStructurePlan, options: { confirmed: boolean; confirmationScope?: string; isCurrent: () => boolean; timeoutSecs?: number; preflight?: () => Promise<void> }): Promise<OracleTriggerStructureExecutionResult> {+ if (attemptedStructurePlans.has(plan)) throw new Error("This structure sequence was already attempted; reread and preview only the remaining changes");+ return executeTriggerSequence(+ {+ target: plan.target,+ connection: { revision: plan.revision, fingerprint: plan.configFingerprint },+ engine: plan.target.databaseType === "dameng" ? "dm" : plan.target.databaseType,+ statements: plan.statements,+ groups: plan.groups.map((group) => ({+ id: group.operation.draftId,+ action: group.operation.action,+ statementIndex: group.operation.statementIndex,+ statementCount: group.operation.statementCount,+ // CREATE TABLE has to precede the new parent's identity proof.+ prepare: () => (group.plan ? Promise.resolve(group.plan) : prepareOracleTriggerPlan(group.afterTableCreate!)),+ })),+ markAttempted: () => attemptedStructurePlans.add(plan),+ },+ options,+ );+}++export interface OracleTriggerDropBatchEntry {+ id: string;+ sql: string;+ triggerPlan?: OracleTriggerPlan;+ executionSchema?: string;+}+export interface OracleTriggerDropBatchPlan {+ target: Readonly<Pick<OracleTriggerTarget, "connectionId" | "database" | "catalog" | "executionSchema">>;+ entries: readonly Readonly<OracleTriggerDropBatchEntry>[];+ engine: OracleTriggerMetadata["engine"];+}+const dropBatchConnections = new WeakMap<OracleTriggerDropBatchPlan, ConnectionIdentity>();+const attemptedDropBatches = new WeakSet<OracleTriggerDropBatchPlan>();++/** Bind generated non-trigger SQL and authoritative trigger plans before confirmation. */+export function prepareOracleTriggerDropBatchPlan(input: OracleTriggerDropBatchPlan): OracleTriggerDropBatchPlan {+ const target = Object.freeze({ ...input.target });+ const connection = connectionIdentity(target);+ const ids = new Set<string>();+ let triggerCount = 0;+ const entries = input.entries.map((entry) => {+ if (!entry.sql.trim() || ids.has(entry.id)) throw new Error("Regenerate the complete object deletion preview");+ ids.add(entry.id);+ if (entry.triggerPlan) {+ const trigger = entry.triggerPlan;+ const originalConnection = planConnections.get(trigger);+ if (+ !originalConnection ||+ trigger.action !== "delete" ||+ trigger.steps.length !== 1 ||+ trigger.steps[0].sql !== entry.sql ||+ trigger.before.metadata.engine !== input.engine ||+ trigger.target.connectionId !== target.connectionId ||+ trigger.target.database !== target.database ||+ trigger.target.catalog !== target.catalog+ )+ throw new Error("The trigger deletion differs from the confirmed object selection");+ assertConnection(target, originalConnection);+ assertSourceIdentity(trigger.before.identity);+ triggerCount++;+ }+ return Object.freeze({ ...entry });+ });+ if (!triggerCount) throw new Error("Use the existing object deletion path for a selection without exact triggers");+ const plan = Object.freeze({ target, entries: Object.freeze(entries), engine: input.engine });+ dropBatchConnections.set(plan, connection);+ return plan;+}++export async function executeOracleTriggerDropBatchPlan(plan: OracleTriggerDropBatchPlan, options: { confirmed: boolean; confirmationScope?: string; isCurrent: () => boolean; timeoutSecs?: number; onProgress?: (completed: number) => void }): Promise<OracleTriggerStructureExecutionResult> {+ const connection = dropBatchConnections.get(plan);+ if (!connection || attemptedDropBatches.has(plan)) throw new Error("Reread the objects and preview only the remaining deletions");+ return executeTriggerSequence(+ {+ target: plan.target,+ connection,+ engine: plan.engine,+ statements: plan.entries.map((entry) => entry.sql),+ statementSchemas: plan.entries.map((entry) => (Object.prototype.hasOwnProperty.call(entry, "executionSchema") ? entry.executionSchema : plan.target.executionSchema)),+ groups: plan.entries.flatMap((entry, statementIndex) => (entry.triggerPlan ? [{ id: entry.id, action: "delete" as const, statementIndex, statementCount: 1, prepare: () => Promise.resolve(entry.triggerPlan!) }] : [])),+ markAttempted: () => attemptedDropBatches.add(plan),+ },+ options,+ );+}++/** Shared serial seam: one production/readonly confirmation, stop on unknown. */+async function executeTriggerSequence(+ sequence: {+ target: Pick<OracleTriggerTarget, "connectionId" | "database" | "catalog" | "executionSchema">;+ connection: ConnectionIdentity;+ engine: OracleTriggerMetadata["engine"];+ statements: readonly string[];+ statementSchemas?: readonly (string | undefined)[];+ groups: { id: string; action: OracleTriggerAction; statementIndex: number; statementCount: number; prepare: () => Promise<OracleTriggerPlan> }[];+ markAttempted: () => unknown;+ },+ options: { confirmed: boolean; confirmationScope?: string; isCurrent: () => boolean; timeoutSecs?: number; preflight?: () => Promise<void>; onProgress?: (completed: number) => void },+): Promise<OracleTriggerStructureExecutionResult> {+ const result: OracleTriggerStructureExecutionResult = { steps: sequence.statements.map((sql, statementIndex) => ({ statementIndex, sql, state: "notExecuted" })), triggerResults: [] };+ if (!options.confirmed || !options.isCurrent()) return { ...result, cancelled: true };+ const fixed = sequence.target;+ const run = async () => {+ if (!options.isCurrent()) return { ...result, cancelled: true };+ try {+ await options.preflight?.();+ } catch (error) {+ if (result.steps[0]) result.steps[0].error = formatError(error);+ return result;+ }+ for (let index = 0; index < sequence.statements.length;) {+ if (!options.isCurrent()) break;+ const row = result.steps[index];+ try {+ assertConnection(fixed, sequence.connection);+ const group = sequence.groups.find((item) => item.statementIndex === index);+ if (group) {+ const triggerPlan = await group.prepare();+ if (triggerPlan.steps.length !== group.statementCount || triggerPlan.steps.some((step, offset) => step.sql !== sequence.statements[index + offset])) throw new Error("The trigger SQL differs from the confirmed preview; regenerate it");+ sequence.markAttempted();+ const outcome = await executePreparedTriggerPlan(triggerPlan, { confirmed: true, isCurrent: options.isCurrent, timeoutSecs: options.timeoutSecs }, false);+ result.triggerResults.push({ draftId: group.id, action: group.action, result: outcome });+ outcome.steps.forEach((step, offset) => Object.assign(result.steps[index + offset], { state: step.state, error: step.error || step.readbackError, trigger: step }));+ options.onProgress?.(index + outcome.steps.filter((step) => step.state !== "notExecuted").length);+ if (outcome.cancelled || outcome.steps.some((step) => step.state !== "committed" || step.verification === "invalid")) break;+ index += group.statementCount;+ } else {+ sequence.markAttempted();+ const startedAt = Date.now();+ let dispatched = false;+ try {+ dispatched = true;+ const receipt = await api.executeQuery(fixed.connectionId, fixed.database, row.sql, sequence.statementSchemas ? sequence.statementSchemas[index] : fixed.executionSchema, undefined, { catalog: fixed.catalog, timeoutSecs: options.timeoutSecs });+ if (receipt.execution_error) throw new BackendErrorException(receipt.error || "Structure statement failed");+ row.state = "committed";+ } catch (error) {+ const refusal = knownReceiptFailure(error, sequence.engine);+ row.state = !dispatched || refusal === "notStarted" ? "notExecuted" : refusal === "rejected" ? "rejected" : "unknown";+ row.error = formatError(error);+ break;+ } finally {+ row.elapsedMs = Date.now() - startedAt;+ }+ index++;+ options.onProgress?.(index);+ }+ } catch (error) {+ row.error = formatError(error);+ break;+ }+ }+ return result;+ };+ return (await executeWithProductionSqlGuard({ connection: useConnectionStore().getConfig(fixed.connectionId), database: fixed.database, sql: sequence.statements.join("\n\n"), scopeId: options.confirmationScope, execute: run })) ?? { ...result, cancelled: true };+}++function samePhysicalTrigger(before: OracleTriggerSnapshot, after: OracleTriggerSnapshot): boolean {+ const a = before.metadata,+ b = after.metadata;+ return (+ before.exists &&+ after.exists &&+ a.objectId === b.objectId &&+ a.engine === b.engine &&+ a.engineVersion === b.engineVersion &&+ a.scope === b.scope &&+ (a.scopeOwner ?? null) === (b.scopeOwner ?? null) &&+ (a.parent?.owner ?? null) === (b.parent?.owner ?? null) &&+ (a.parent?.name ?? null) === (b.parent?.name ?? null) &&+ (a.parent?.objectType ?? null) === (b.parent?.objectType ?? null) &&+ (a.parent?.objectId ?? null) === (b.parent?.objectId ?? null)+ );+}++function sameSnapshot(before: OracleTriggerSnapshot, after: OracleTriggerSnapshot): boolean {+ return (+ (before.exists ? samePhysicalTrigger(before, after) : !after.exists && before.metadata.engine === after.metadata.engine && before.metadata.engineVersion === after.metadata.engineVersion) &&+ (before.metadata.lastDdlTime ?? null) === (after.metadata.lastDdlTime ?? null) &&+ (before.raw.trigger?.enabled ?? null) === (after.raw.trigger?.enabled ?? null) &&+ (before.raw.trigger?.valid ?? null) === (after.raw.trigger?.valid ?? null) &&+ before.raw.source === after.raw.source+ );+}++function sameTarget(a: OracleTriggerTarget, b: OracleTriggerTarget): boolean {+ return a.connectionId === b.connectionId && a.database === b.database && a.catalog === b.catalog && a.owner === b.owner && a.name === b.name;+}++function assertActionReadability(snapshot: OracleTriggerSnapshot, action: OracleTriggerAction): void {+ const metadata = snapshot.metadata;+ const relation = metadata.scope === "TABLE" || metadata.scope === "VIEW";+ if ((action === "enable" || action === "disable") && (metadata.reads.scope?.state !== "available" || (relation && (metadata.reads.parent?.state !== "available" || !metadata.parent || metadata.parent.objectType !== metadata.scope))))+ throw new Error("Verify the trigger scope and owning object before preparing this action");+ if (action === "replace" && (!metadata.definition?.complete || metadata.reads.definition?.state !== "available" || metadata.reads.enabled?.state !== "available" || typeof snapshot.raw.trigger?.enabled !== "boolean"))+ throw new Error("The complete trigger definition or enabled state is unavailable; keep the draft and reload");+}++function candidateBinding(prepared: PreparedOracleTriggerSql, selection?: OracleTriggerSqlBinding): OracleTriggerSqlBinding {+ const header = prepared.header;+ if (header.scope === "RELATION") {+ if (selection && (selection.scope === "TABLE" || selection.scope === "VIEW") && selection.name === header.name && (header.owner === undefined || header.owner === null || header.owner === selection.owner)) return { ...selection, pluggable: false };+ if (header.owner && header.name) return { scope: header.viewOnly ? "VIEW" : "TABLE", owner: header.owner, name: header.name, pluggable: false };+ } else if (header.scope === "SCHEMA") {+ const owner = header.owner ?? (selection?.scope === "SCHEMA" ? selection.owner : undefined);+ if (owner) return { scope: "SCHEMA", owner, pluggable: false };+ } else if (header.scope === "DATABASE" || header.scope === "TIMER") return { scope: header.scope, pluggable: header.pluggable };+ throw new Error("Select or explicitly qualify the candidate's actual owning object/scope before preparing a write");+}++function matchesBinding(metadata: Readonly<OracleTriggerMetadata>, binding: Readonly<OracleTriggerSqlBinding>): boolean {+ if (metadata.scope !== binding.scope) return false;+ if (binding.scope === "TABLE" || binding.scope === "VIEW") return metadata.parent?.owner === binding.owner && metadata.parent?.name === binding.name && metadata.parent?.objectType === binding.scope;+ if (binding.scope === "SCHEMA") return metadata.scopeOwner === binding.owner;+ return true;+}++function sqlString(value: string): string {+ return `'${value.replaceAll("'", "''")}'`;+}++async function metadataQuery(target: Readonly<OracleTriggerTarget>, sql: string): Promise<QueryResult> {+ const result = await api.executeQuery(target.connectionId, target.database, sql, target.executionSchema, undefined, { catalog: target.catalog, maxRows: 2 });+ if (result.execution_error) throw new BackendErrorException(result.error || "Trigger metadata query failed");+ if (result.truncated || result.has_more || result.rows.length > 1 || result.large_value_cells?.length) throw new Error("Trigger metadata is incomplete or ambiguous; keep the draft and reload");+ return result;+}++/** Only action-relevant scope queries run: TABLE/VIEW never require a database-wide privilege. */+async function verifyBinding(target: Readonly<OracleTriggerTarget>, engine: OracleTriggerMetadata["engine"], binding: Readonly<OracleTriggerSqlBinding>): Promise<string[]> {+ let sql: string;+ let expected: (string | undefined)[];+ if (binding.scope === "TABLE" || binding.scope === "VIEW") {+ if (!binding.owner || !binding.name) throw new Error("Select the exact owning object");+ sql = `SELECT OWNER, OBJECT_NAME, OBJECT_TYPE, TO_CHAR(OBJECT_ID) AS OBJECT_ID FROM ALL_OBJECTS WHERE OWNER = ${sqlString(binding.owner)} AND OBJECT_NAME = ${sqlString(binding.name)} AND OBJECT_TYPE = ${sqlString(binding.scope)}`;+ expected = [binding.owner, binding.name, binding.scope];+ } else if (binding.scope === "SCHEMA") {+ if (!binding.owner) throw new Error("Select the actual scope owner, not the trigger owner or execution schema");+ sql = engine === "dm" ? `SELECT NAME, TO_CHAR(ID) AS SCHEMA_ID FROM SYS.SYSOBJECTS WHERE TYPE$ = 'SCH' AND NAME = ${sqlString(binding.owner)}` : `SELECT USERNAME, TO_CHAR(USER_ID) AS SCHEMA_ID FROM ALL_USERS WHERE USERNAME = ${sqlString(binding.owner)}`;+ expected = [binding.owner];+ } else {+ sql = engine === "dm" ? "SELECT NAME, TO_CHAR(CREATE_TIME, 'YYYY-MM-DD HH24:MI:SS') AS CREATED FROM V$DATABASE" : "SELECT SYS_CONTEXT('USERENV','DB_UNIQUE_NAME') AS DATABASE_NAME, SYS_CONTEXT('USERENV','CON_ID') AS CONTAINER_ID, SYS_CONTEXT('USERENV','CON_NAME') AS CONTAINER_NAME FROM DUAL";+ expected = [];+ }+ const result = await metadataQuery(target, sql);+ const row = result.rows[0];+ if (!row || row.some((value) => typeof value !== "string" || !value.length) || expected.some((value, index) => row[index] !== value) || row.length !== (binding.scope === "TABLE" || binding.scope === "VIEW" ? 4 : binding.scope === "SCHEMA" || engine === "dm" ? 2 : 3))+ throw new Error("The actual owning object or scope could not be verified");+ if (binding.pluggable && (engine !== "oracle" || row[1] === "0" || row[1] === "1")) throw new Error("The current pluggable database context could not be verified");+ return row as string[];+}++function sameProof(a: readonly string[], b: readonly string[]): boolean {+ return a.length === b.length && a.every((value, index) => value === b[index]);+}++async function verifyStep(plan: OracleTriggerPlan, step: Readonly<OracleTriggerStep>, before: OracleTriggerSnapshot, after: OracleTriggerSnapshot, index: number): Promise<OracleTriggerStepResult["verification"]> {+ if (step.action === "delete") {+ if (after.exists) return "mismatch";+ await verifyDeleted(plan.target, after.metadata.engine);+ if (before.metadata.scope === "TABLE" || before.metadata.scope === "VIEW") {+ const binding = oracleTriggerSourceBinding(before.metadata);+ if (!binding) throw new Error("The owning object could not be verified after deletion");+ const proof = await verifyBinding(plan.target, before.metadata.engine, binding);+ if (plan.parentBefore && !sameProof(plan.parentBefore, proof)) return "mismatch";+ }+ return "deleted";+ }+ if (!after.exists || after.metadata.engine !== before.metadata.engine || after.metadata.engineVersion !== before.metadata.engineVersion) return "unverified";+ if (step.action !== "create" && before.metadata.objectId !== after.metadata.objectId) return "mismatch";+ if (step.action === "create" || step.action === "replace") {+ const expected = plan.expectedAfter!;+ if (!matchesBinding(after.metadata, expected.binding) || !sameProof(expected.proof, await verifyBinding(plan.target, after.metadata.engine, expected.binding))) return "mismatch";+ const inspected = await inspectExactOracleTriggerSource(after.raw, plan.target.owner, plan.target.name);+ if (!inspected.triggerSource.complete) return "unverified";+ const databaseType = after.metadata.engine === "dm" ? "dameng" : after.metadata.engine;+ const prepared = await api.prepareOracleTriggerSql({ databaseType, owner: plan.target.owner, name: plan.target.name, source: inspected.editableSource, purpose: "replace", binding: expected.binding, enabled: plan.expectedEnabled });+ if (typeof prepared.comparisonSource !== "string") return "unverified";+ if (prepared.comparisonSource !== expected.comparisonSource) return "mismatch";+ const restorePending = plan.steps.slice(index + 1).some((next) => next.action === "disable");+ if (after.metadata.reads.enabled?.state !== "available" || typeof after.raw.trigger?.enabled !== "boolean") return "unverified";+ if (!restorePending && after.raw.trigger.enabled !== plan.expectedEnabled) return "mismatch";+ return after.metadata.reads.validity?.state === "available" && after.raw.trigger?.valid === false ? "invalid" : "applied";+ }+ if (!samePhysicalTrigger(before, after)) return "mismatch";+ const preserved = await preservedTriggerSource(before, after);+ if (preserved !== true) return preserved === false ? "mismatch" : "unverified";+ if (step.action === "compile") return after.metadata.reads.validity?.state !== "available" || typeof after.raw.trigger?.valid !== "boolean" ? "unverified" : after.raw.trigger.valid ? "valid" : "invalid";+ return after.metadata.reads.enabled?.state !== "available" || typeof after.raw.trigger?.enabled !== "boolean" ? "unverified" : after.raw.trigger.enabled === (step.action === "enable") ? "applied" : "mismatch";+}++async function preservedTriggerSource(before: OracleTriggerSnapshot, after: OracleTriggerSnapshot): Promise<boolean | undefined> {+ if (!before.metadata.definition?.complete || before.metadata.reads.definition?.state !== "available") return true; // Native actions do not require a replaceable body.+ const previous = await inspectExactOracleTriggerSource(before.raw, before.target.owner, before.target.name);+ const current = await inspectExactOracleTriggerSource(after.raw, after.target.owner, after.target.name);+ if (!previous.triggerSource.complete || !current.triggerSource.complete || !previous.triggerSource.prepared || !current.triggerSource.prepared) return;+ const binding = candidateBinding(previous.triggerSource.prepared, oracleTriggerSourceBinding(before.metadata));+ const databaseType = before.metadata.engine === "dm" ? "dameng" : before.metadata.engine;+ // Only the already-validated CREATE/owner/state export wrapper is controlled.+ // The actual header clauses, comments, body and literal whitespace stay in+ // the whole definition comparison; no token fingerprint or newline folding.+ const normalized = await Promise.all([previous.editableSource, current.editableSource].map((source) => api.prepareOracleTriggerSql({ databaseType, owner: before.target.owner, name: before.target.name, source, purpose: "replace", binding, enabled: false })));+ if (normalized.some((definition) => typeof definition.comparisonSource !== "string")) return;+ return normalized[0].comparisonSource === normalized[1].comparisonSource;+}++async function verifyDeleted(target: Readonly<OracleTriggerTarget>, engine: OracleTriggerMetadata["engine"]): Promise<void> {+ if (engine !== "dm") {+ const own = await metadataQuery(target, "SELECT USER AS SESSION_USER FROM DUAL");+ if (own.rows[0]?.[0] === target.owner) return; // Successful exact empty read covers this user's own objects.+ }+ // Cross-owner ALL_* visibility can disappear after permission changes. Only+ // a readable global catalog can prove absence, never the connection username.+ const sql = `SELECT OWNER, OBJECT_NAME FROM DBA_OBJECTS WHERE OWNER = ${sqlString(target.owner)} AND OBJECT_NAME = ${sqlString(target.name)} AND OBJECT_TYPE = 'TRIGGER'`;+ if ((await metadataQuery(target, sql)).rows.length) throw new Error("The trigger still exists in the global dictionary");+}++export async function verifyOracleTriggerDeletion(target: OracleTriggerTarget, plan?: OracleTriggerPlan): Promise<void> {+ const connection = plan && planConnections.get(plan);+ if (plan) {+ if (!connection || plan.action !== "delete" || !sameTarget(target, plan.target)) throw new Error("Reload the original trigger deletion target");+ assertConnection(target, connection);+ }+ const current = await readOracleTriggerSnapshot(target);+ if (current.exists) throw new Error("The trigger still exists; retain its delete draft");+ if (plan) {+ if ((await verifyStep(plan, plan.steps[0], plan.before, current, 0)) !== "deleted") throw new Error("The owning object changed; retain the deletion result and refresh its identity");+ assertConnection(target, connection!);+ } else await verifyDeleted(current.target, current.metadata.engine);+}++function knownReceiptFailure(error: unknown, engine: OracleTriggerMetadata["engine"]): "notStarted" | "rejected" | "unknown" {+ const normalized = normalizeBackendError(error);+ if (normalized?.operationOutcome === "not_started") return "notStarted";+ const diagnostics = normalized?.diagnostics;+ if (normalized?.origin?.subsystem !== "database" || diagnostics?.category !== "sql" || diagnostics.stage !== "execute") return "unknown";+ // A permission code in a transport/fetch error or in the submitted source is+ // not a native SQL rejection. Inspect only the structured native SQL origin.+ const vendor = typeof diagnostics.vendorCode === "number" ? Math.abs(diagnostics.vendorCode) : undefined;+ const oraclePermission = engine !== "dm" && (vendor === 1031 || (vendor === undefined && /^\s*ORA-01031\b/.test(normalized.detail ?? "")));+ return oraclePermission || (diagnostics.sqlState === "42501" && vendor !== 24344) ? "rejected" : "unknown";+}diff --git a/apps/desktop/src/lib/database/oracleTriggerSql.ts b/apps/desktop/src/lib/database/oracleTriggerSql.tsnew file mode 100644index 0000000000..48c872f4e5--- /dev/null+++ b/apps/desktop/src/lib/database/oracleTriggerSql.ts@@ -0,0 +1,80 @@+import type { DatabaseType, OracleTriggerMetadata } from "@/types/database";++export type OracleTriggerDatabaseType = Extract<DatabaseType, "oracle" | "oceanbase-oracle" | "dameng">;++export type OracleTriggerSqlBinding = {+ scope: "TABLE" | "VIEW" | "SCHEMA" | "DATABASE" | "TIMER";+ owner?: string | null;+ name?: string | null;+ pluggable?: boolean;+};++export type OracleTriggerSqlHeader = {+ scope: "RELATION" | "SCHEMA" | "DATABASE" | "TIMER";+ owner?: string | null;+ name?: string | null;+ viewOnly: boolean;+ pluggable: boolean;+};++export type OracleTriggerSqlInput = {+ databaseType: OracleTriggerDatabaseType;+ owner: string;+ name: string;+ source: string;+ purpose: "inspect" | "create" | "replace";+ binding?: OracleTriggerSqlBinding;+ enabled?: boolean;+ allowExportAppendix?: boolean;+};++export type PreparedOracleTriggerSql = {+ definition: string;+ /** Comparison only: declaration wrapper canonicalized, header/body text preserved. */+ comparisonSource: string;+ header: OracleTriggerSqlHeader;+ inlineEnabled?: boolean | null;+ exportEnabled?: boolean | null;+ requiresStateRestore: boolean;+ structuredEditable?: boolean;+};++export function oracleTriggerDefinitionScopes(profile: Pick<OracleTriggerMetadata, "engine" | "engineVersion">): readonly OracleTriggerSqlBinding["scope"][] {+ if (profile.engine === "oracle") return ["TABLE", "VIEW", "SCHEMA", "DATABASE"];+ if (profile.engine === "oceanbase-oracle" && /(?:^|[^0-9])4\.2\.5\.7(?:[^0-9]|$)/.test(profile.engineVersion ?? "")) return ["TABLE", "VIEW"];+ if (profile.engine === "dm" && /(?:^|\D)8\./.test(profile.engineVersion ?? "")) return ["TABLE", "VIEW", "SCHEMA", "DATABASE", "TIMER"];+ return [];+}++/** A starting definition only. The SQL provider and write plan still verify it. */+export function buildOracleTriggerCreateDraft(profile: OracleTriggerMetadata, owner: string, name: string, binding: OracleTriggerSqlBinding): string {+ if (!owner.length || !name.length) throw new Error("Enter the exact trigger owner and name");+ if (!oracleTriggerDefinitionScopes(profile).includes(binding.scope)) throw new Error("Trigger creation for this scope has not been verified for the connected engine/version");+ const quote = (value: string) => `"${value.replaceAll('"', '""')}"`;+ let header: string;+ if (binding.scope === "TABLE" || binding.scope === "VIEW") {+ if (!binding.owner?.length || !binding.name?.length) throw new Error("Select the exact owning table or view");+ header = `${binding.scope === "VIEW" ? "INSTEAD OF" : "BEFORE"} INSERT ON ${quote(binding.owner)}.${quote(binding.name)}\nFOR EACH ROW`;+ } else if (binding.scope === "SCHEMA") {+ if (!binding.owner?.length) throw new Error("Select the actual scope owner");+ header = `AFTER CREATE ON ${quote(binding.owner)}.SCHEMA`;+ } else if (binding.scope === "TIMER") {+ // DM's native trigger syntax, not a Job/Scheduler object.+ header = "AFTER TIMER ON DATABASE\nFOR EACH 1 DAY FOR EACH 1 MINUTE";+ } else header = `AFTER CREATE ON ${binding.pluggable ? "PLUGGABLE " : ""}DATABASE`;+ return `CREATE TRIGGER ${quote(owner)}.${quote(name)}\n${header}\nBEGIN\n NULL;\nEND;`;+}++/** Database/container context is verified separately by the execution plan. */+export function oracleTriggerSourceBinding(metadata: OracleTriggerMetadata): OracleTriggerSqlBinding | undefined {+ if ((metadata.scope === "TABLE" || metadata.scope === "VIEW") && metadata.parent?.objectType === metadata.scope) {+ return { scope: metadata.scope, owner: metadata.parent.owner, name: metadata.parent.name };+ }+ if (metadata.scope === "SCHEMA" && metadata.scopeOwner) return { scope: "SCHEMA", owner: metadata.scopeOwner };+}++export function oracleTriggerSourceScopeMatches(metadata: OracleTriggerMetadata, header: OracleTriggerSqlHeader): boolean {+ if (metadata.scope === "TABLE" || metadata.scope === "VIEW") return header.scope === "RELATION" && (!header.viewOnly || metadata.scope === "VIEW");+ if (metadata.scope === "SCHEMA" || metadata.scope === "DATABASE" || metadata.scope === "TIMER") return header.scope === metadata.scope;+ return true; // Unknown summary scope is still unavailable to a write plan.+}diff --git a/apps/desktop/src/lib/database/oracleTriggerStructurePlan.ts b/apps/desktop/src/lib/database/oracleTriggerStructurePlan.tsnew file mode 100644index 0000000000..189252ca58--- /dev/null+++ b/apps/desktop/src/lib/database/oracleTriggerStructurePlan.ts@@ -0,0 +1,170 @@+import * as api from "@/lib/backend/api";+import { connectionConfigFingerprint } from "@/lib/connection/connectionDatabaseInfo";+import { exactOracleTriggerMetadata } from "./oracleTriggerIdentity";+import { assertTriggerStructureSql, prepareOracleTriggerPlan, readOracleTriggerSnapshot, type OracleTriggerPlan, type OracleTriggerPlanInput, type OracleTriggerTarget } from "./oracleTriggerPlan";+import { oracleTriggerDefinitionScopes, type OracleTriggerDatabaseType } from "./oracleTriggerSql";+import type { EditableStructureTrigger, OracleTriggerStructureOperation } from "@/lib/table/tableStructureEditorSql";+import { useConnectionStore } from "@/stores/connectionStore";+import { buildTriggerToggleSql } from "./triggerToggleSql";+import { inspectExactOracleTriggerSource } from "@/lib/table/objectSourceLoad";+import type { ColumnInfo, ConstraintInfo, ForeignKeyInfo, IndexInfo, TableStructureEditorDraft, TriggerInfo } from "@/types/database";+import { createColumnDrafts, createForeignKeyDrafts, createIndexDrafts, createTriggerDrafts, foldCreatedTableName } from "@/lib/table/tableStructureEditorState";++export interface OracleTriggerStructureTarget extends Omit<OracleTriggerTarget, "name"> {+ tableName: string;+ parentType: "TABLE" | "VIEW";+ databaseType: OracleTriggerDatabaseType;+ newTable: boolean;+}+export interface OracleTriggerStructureGroup {+ operation: Readonly<OracleTriggerStructureOperation>;+ plan?: OracleTriggerPlan;+ /** A new table has no object ID before CREATE TABLE. Verify it before sending its trigger. */+ afterTableCreate?: Readonly<OracleTriggerPlanInput>;+}+export interface OracleTriggerStructurePlan {+ target: Readonly<OracleTriggerStructureTarget>;+ statements: readonly string[];+ groups: readonly Readonly<OracleTriggerStructureGroup>[];+ revision: number;+ configFingerprint: string;+}++export async function prepareOracleTriggerStructurePlan(input: { target: OracleTriggerStructureTarget; statements: readonly string[]; operations: readonly OracleTriggerStructureOperation[]; triggers: readonly EditableStructureTrigger[] }): Promise<OracleTriggerStructurePlan> {+ const target = Object.freeze({ ...input.target });+ const statements = Object.freeze([...input.statements]);+ const drafts: EditableStructureTrigger[] = JSON.parse(JSON.stringify(input.triggers));+ const operations = input.operations.map((operation) => Object.freeze({ ...operation }));+ const store = useConnectionStore();+ const revision = store.connectionStateRevision(target.connectionId);+ const config = store.getConfig(target.connectionId);+ if (!config || !store.connectedIds.has(target.connectionId)) throw new Error("Reconnect before preparing the table/trigger preview");+ const fingerprint = connectionConfigFingerprint(config);+ const groups: OracleTriggerStructureGroup[] = [];+ let end = 0;+ for (const operation of operations) {+ const draft = drafts.find((item) => item.id === operation.draftId);+ if (+ !draft?.oracleExact ||+ draft.oracleExact.owner !== operation.owner ||+ !Number.isInteger(operation.statementIndex) ||+ !Number.isInteger(operation.statementCount) ||+ operation.statementIndex < end ||+ operation.statementCount < 1 ||+ operation.statementIndex + operation.statementCount > statements.length+ )+ throw new Error("Regenerate the trigger operation mapping before saving");+ end = operation.statementIndex + operation.statementCount;+ const expectedName = operation.action === "create" ? (target.newTable ? foldCreatedTableName(draft.name, target.databaseType) : draft.name.trim()) : draft.original?.name;+ if (operation.name !== expectedName) throw new Error("The generated trigger target differs from its table draft");+ const selected = Object.freeze({ scope: draft.oracleExact.parentType, owner: target.owner, name: target.tableName, pluggable: false } as const);+ const triggerTarget: OracleTriggerTarget = Object.freeze({ connectionId: target.connectionId, database: target.database, catalog: target.catalog, owner: operation.owner, name: operation.name, executionSchema: target.executionSchema });+ const before = await readOracleTriggerSnapshot(triggerTarget);+ if (operation.action !== "create") {+ const loaded = exactOracleTriggerMetadata(draft.original);+ const actual = before.metadata;+ // This fresh snapshot cannot silently replace the version the form loaded.+ if (+ !loaded ||+ loaded.objectId !== actual.objectId ||+ loaded.owner !== actual.owner ||+ loaded.name !== actual.name ||+ loaded.scope !== actual.scope ||+ loaded.lastDdlTime !== actual.lastDdlTime ||+ JSON.stringify(loaded.parent) !== JSON.stringify(actual.parent) ||+ draft.original?.enabled !== before.raw.trigger?.enabled ||+ draft.original?.statement !== before.raw.trigger?.statement ||+ draft.original?.timing !== before.raw.trigger?.timing ||+ draft.original?.event !== before.raw.trigger?.event ||+ draft.original?.condition !== before.raw.trigger?.condition+ )+ throw new Error("The trigger changed since the table draft was loaded; keep the draft and reread it");+ if ((operation.action === "replace" || (operation.action === "delete" && !draft.markedForDrop)) && (draft.loadedOracleSource === undefined || draft.loadedOracleSource !== before.raw.source))+ throw new Error("Reload the complete trigger baseline before applying a structured edit; the current draft is retained");+ if (operation.action === "replace" || (operation.action === "delete" && !draft.markedForDrop)) {+ const inspected = await inspectExactOracleTriggerSource(before.raw, operation.owner, operation.name);+ if (!inspected.triggerSource.complete || inspected.triggerSource.prepared?.structuredEditable !== true) throw new Error("Edit the complete trigger source to preserve clauses outside the structured form");+ }+ }+ const request: OracleTriggerPlanInput = {+ target: triggerTarget,+ action: operation.action,+ ...(operation.action === "replace" ? { baseline: before } : {}),+ ...(operation.action === "create" || operation.action === "replace" ? { source: statements[operation.statementIndex], selection: selected, enabled: operation.enabled } : {}),+ expectedObjectId: operation.action === "create" || typeof before.metadata.objectId !== "string" ? undefined : before.metadata.objectId,+ };+ if (target.newTable && operation.action === "create") {+ if (before.exists || !oracleTriggerDefinitionScopes(before.metadata).includes(selected.scope)) throw new Error("The new trigger target or engine profile is unavailable");+ const prepared = await api.prepareOracleTriggerSql({ databaseType: target.databaseType, owner: operation.owner, name: operation.name, source: request.source!, purpose: "create", binding: selected, enabled: operation.enabled });+ const expected = [prepared.definition];+ if (prepared.requiresStateRestore) {+ const disable = buildTriggerToggleSql({ databaseType: target.databaseType, schema: operation.owner, triggerName: operation.name, enabled: false, identityMode: "exact", scope: selected.scope });+ if (!disable) throw new Error("The trigger's native state restoration is unavailable");+ expected.push(disable);+ }+ if (expected.length !== operation.statementCount || expected.some((sql, index) => sql !== statements[operation.statementIndex + index])) throw new Error("The trigger SQL no longer matches the table preview");+ groups.push({ operation, afterTableCreate: Object.freeze(request) });+ } else {+ const plan = await prepareOracleTriggerPlan(request);+ assertTriggerStructureSql(statements, operation, plan);+ groups.push({ operation, plan });+ }+ }+ const latest = store.getConfig(target.connectionId);+ if (!latest || !store.isCurrentConnectionStateRevision(target.connectionId, revision) || store.connectionStateRevision(target.connectionId) !== revision || connectionConfigFingerprint(latest) !== fingerprint) throw new Error("The connection changed; regenerate the table preview");+ return Object.freeze({ target, statements, groups: Object.freeze(groups.map((group) => Object.freeze(group))), revision, configFingerprint: fingerprint });+}++/** Explicit read/reconcile keeps the desired values; it never dispatches the saved SQL array. */+export function reconcileOracleTriggerStructureDraft(+ draft: TableStructureEditorDraft,+ current: { columns: ColumnInfo[]; indexes: IndexInfo[]; foreignKeys: ForeignKeyInfo[]; triggers: TriggerInfo[]; constraints: ConstraintInfo[]; comment: string },+ changed: { columns: Set<string>; indexes: Set<string>; foreignKeys: Set<string>; triggers: Set<string> },+ databaseType: OracleTriggerDatabaseType,+): TableStructureEditorDraft {+ const rebase = <T extends { id: string; name: string; original?: { name: string }; markedForDrop: boolean }>(pending: T[], actual: T[], edits: Set<string>, matches?: (item: T, row: T, original: boolean) => boolean): T[] => {+ const used = new Set<T>();+ const remaining: T[] = [];+ for (const item of pending) {+ const old = item.original && actual.find((row) => (matches ? matches(item, row, true) : row.name === item.original!.name));+ const names = new Set([item.name, foldCreatedTableName(item.name, databaseType)]);+ const candidates = actual.filter((row) => (matches ? matches(item, row, false) : names.has(row.name)));+ const next = candidates.find((row) => row !== old) ?? candidates[0];+ if ((old && next && old !== next) || candidates.length > 1) throw new Error(`Both names are present: ${item.original?.name ?? item.name} / ${item.name}. Resolve the name conflict before reconciling.`);+ const found = old || next;+ if (found) used.add(found);+ if (!edits.has(item.id)) {+ if (found) remaining.push({ ...found, id: item.id });+ } else if (!(item.markedForDrop && !found)) {+ const merged = { ...item, original: found?.original };+ if (found && candidates.includes(found) && found !== old) merged.name = found.name;+ remaining.push(merged);+ }+ }+ return [...remaining, ...actual.filter((row) => !used.has(row))];+ };+ const actualTriggers = createTriggerDrafts(current.triggers);+ const triggers = rebase(draft.triggers, actualTriggers, changed.triggers, (item, row, original) => {+ const owner = item.oracleExact?.owner ?? exactOracleTriggerMetadata(item.original)?.owner;+ if (owner !== exactOracleTriggerMetadata(row.original)?.owner) return false;+ const name = original || item.original?.name === item.name ? item.original!.name : draft.newTableName ? foldCreatedTableName(item.name, databaseType) : item.name.trim();+ return row.name === name;+ }).map((trigger) => {+ const previous = draft.triggers.find((item) => item.id === trigger.id);+ const metadata = exactOracleTriggerMetadata(previous?.original);+ const oracleExact = trigger.oracleExact ?? (metadata && (metadata.scope === "TABLE" || metadata.scope === "VIEW") ? { owner: metadata.owner, parentType: metadata.scope } : undefined);+ const bodyEdited = previous?.original && (previous.statement !== previous.original.statement || previous.timing !== previous.original.timing || previous.event !== previous.original.event);+ if (previous?.original && !bodyEdited && trigger.original) return { ...trigger, oracleExact, statement: trigger.original.statement ?? "", timing: trigger.original.timing, event: trigger.original.event, loadedOracleSource: undefined, loadedOracleStructured: undefined };+ return { ...trigger, oracleExact, loadedOracleSource: undefined, loadedOracleStructured: undefined };+ });+ return {+ ...draft,+ columns: rebase(draft.columns, createColumnDrafts(current.columns, databaseType), changed.columns),+ indexes: rebase(draft.indexes, createIndexDrafts(current.indexes), changed.indexes),+ foreignKeys: rebase(draft.foreignKeys, createForeignKeyDrafts(current.foreignKeys, databaseType), changed.foreignKeys),+ triggers,+ constraints: current.constraints,+ originalTableComment: current.comment,+ oracleTriggerStructureRecovery: undefined,+ };+}diff --git a/apps/desktop/src/lib/database/productionExecutionGuard.ts b/apps/desktop/src/lib/database/productionExecutionGuard.tsindex 5c225a2bb3..cfc9f5b6ce 100644--- a/apps/desktop/src/lib/database/productionExecutionGuard.ts+++ b/apps/desktop/src/lib/database/productionExecutionGuard.ts@@ -9,6 +9,8 @@ export interface ProductionSqlExecutionGuardOptions<T> {database?: string | null;sql: string;source?: string;+ /** Allows the owning editor to cancel only its pending confirmation on close/switch. */+ scopeId?: string;execute: () => Promise<T>;/** Offload large generated scripts while preserving the same safety assessment. */analyzeInBackground?: boolean;@@ -29,6 +31,7 @@ export async function executeWithProductionSqlGuard<T>(options: ProductionSqlExedatabase: options.database ?? undefined,productionDatabases: assessment.databases,source: options.source,+ scopeId: options.scopeId,});if (!confirmed) return undefined;}diff --git a/apps/desktop/src/lib/database/triggerToggleSql.ts b/apps/desktop/src/lib/database/triggerToggleSql.tsindex 70af1768fd..810829c87f 100644--- a/apps/desktop/src/lib/database/triggerToggleSql.ts+++ b/apps/desktop/src/lib/database/triggerToggleSql.ts@@ -1,4 +1,5 @@-import type { DatabaseType } from "@/types/database";+import type { DatabaseType, OracleTriggerMetadata } from "@/types/database";+import { quoteOracleLiteral } from "@/lib/database/oracleInvalidObjects";export interface TriggerToggleSqlOptions {databaseType?: DatabaseType;@@ -6,6 +7,8 @@ export interface TriggerToggleSqlOptions {tableName?: string;triggerName: string;enabled: boolean;+ identityMode?: "exact";+ scope?: OracleTriggerMetadata["scope"];}const SUPPORTED_TRIGGER_TOGGLE_DATABASES = new Set<DatabaseType>(["sqlserver", "oracle", "oceanbase-oracle", "dameng", "postgres", "kingbase", "opengauss", "vastbase", "highgo", "uxdb", "gaussdb", "kwdb", "xugu", "firebird"]);@@ -25,6 +28,15 @@ function quoteDouble(name: string): string {export function buildTriggerToggleSql(options: TriggerToggleSqlOptions): string | null {const { databaseType, schema, tableName, triggerName, enabled } = options;+ if (options.identityMode === "exact") {+ if (databaseType !== "oracle" && databaseType !== "oceanbase-oracle" && databaseType !== "dameng") return null;+ if (!schema?.length || !triggerName.length || schema.includes("\0") || triggerName.includes("\0")) return null;+ const relation = options.scope === "TABLE" || options.scope === "VIEW";+ const event = options.scope === "SCHEMA" || options.scope === "DATABASE" || options.scope === "TIMER";+ if ((!relation && !event) || (databaseType === "oceanbase-oracle" && !relation) || (databaseType === "oracle" && options.scope === "TIMER")) return null;+ if (databaseType === "dameng" && event) return `SP_ENABLE_EVT_TRIGGER(${quoteOracleLiteral(schema)}, ${quoteOracleLiteral(triggerName)}, ${enabled ? 1 : 0});`;+ return `ALTER TRIGGER ${quoteDouble(schema)}.${quoteDouble(triggerName)} ${enabled ? "ENABLE" : "DISABLE"};`;+ }const cleanTrigger = triggerName.trim();if (!cleanTrigger || !databaseType || !supportsTriggerToggle(databaseType)) return null;diff --git a/apps/desktop/src/lib/metadata/__tests__/objectBrowserRowsCache.spec.ts b/apps/desktop/src/lib/metadata/__tests__/objectBrowserRowsCache.spec.tsindex 77b96acc25..adb02d9964 100644--- a/apps/desktop/src/lib/metadata/__tests__/objectBrowserRowsCache.spec.ts+++ b/apps/desktop/src/lib/metadata/__tests__/objectBrowserRowsCache.spec.ts@@ -1,4 +1,5 @@import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { reactive } from "vue";import type { ObjectBrowserRow } from "@/lib/table/objectBrowserRows";import { cacheObjectBrowserRows, clearObjectBrowserRowsCache, createObjectBrowserRowsCacheWriteToken, getCachedObjectBrowserRows, getCachedObjectBrowserRowsForScaffold, invalidateObjectBrowserRowsCache } from "@/lib/table/objectBrowserRowsCache";@@ -44,6 +45,53 @@ describe("objectBrowserRowsCache", () => {expect(getCachedObjectBrowserRows(scope)?.[0].displayName).toBe("users");});+ it("separates the trigger exact contract from legacy scaffolds and preserves raw scopes", () => {+ const legacy = { connectionId: "c1", database: "db", schema: " Owner " };+ const exact = { ...legacy, oracleTriggerContract: 1 as const };+ cacheRows(legacy);+ expect(getCachedObjectBrowserRows(exact)).toBeUndefined();+ cacheRows(exact, [{ ...row, name: "Exact" }]);+ expect(getCachedObjectBrowserRows(legacy)?.[0].name).toBe("users");+ expect(getCachedObjectBrowserRows(exact)?.[0].name).toBe("Exact");+ expect(getCachedObjectBrowserRows({ ...exact, schema: "Owner" })).toBeUndefined();+ });++ it("does not share mutable nested trigger snapshots across a cache boundary", () => {+ const scope = { connectionId: "c1", database: "db", schema: " Owner ", oracleTriggerContract: 1 as const };+ const triggerRow: ObjectBrowserRow = {+ ...row,+ type: "TRIGGER",+ trigger: {+ name: " Trigger ",+ event: "INSERT",+ timing: "BEFORE",+ enabled: false,+ oracle_metadata: { contractVersion: 1, identityMode: "exact", owner: " Owner ", name: " Trigger ", engine: "oracle", scope: "VIEW", parent: { owner: "ParentOwner", name: "Parent", objectType: "VIEW" }, reads: { identity: { state: "available" } } },+ },+ };+ cacheRows(scope, [reactive(triggerRow)]);+ triggerRow.trigger!.oracle_metadata!.parent!.name = "changed at producer";+ const cached = getCachedObjectBrowserRows(scope)!;+ expect(cached[0].trigger!.oracle_metadata!.parent!.name).toBe("Parent");+ cached[0].trigger!.oracle_metadata!.reads.identity!.state = "error";+ expect(getCachedObjectBrowserRows(scope)![0].trigger!.oracle_metadata!.reads.identity!.state).toBe("available");+ });++ it("invalidates both trigger contracts only in the affected raw schema and rejects their late writers", () => {+ const exact = { connectionId: "c1", database: "db", schema: " Owner ", oracleTriggerContract: 1 as const };+ const legacy = { connectionId: "c1", database: "db", schema: " Owner " };+ const other = { ...exact, schema: "Owner" };+ const exactToken = createObjectBrowserRowsCacheWriteToken(exact);+ const legacyToken = createObjectBrowserRowsCacheWriteToken(legacy);+ cacheRows(exact);+ cacheRows(legacy);+ cacheRows(other);+ expect(invalidateObjectBrowserRowsCache({ connectionId: "c1", database: "db", schema: " Owner " })).toBe(2);+ expect(cacheObjectBrowserRows(exactToken, [row])).toBeUndefined();+ expect(cacheObjectBrowserRows(legacyToken, [row])).toBeUndefined();+ expect(getCachedObjectBrowserRows(other)).toEqual([row]);+ });+it("restores fresh rows when a remounted component reads the shared cache", () => {vi.useFakeTimers();vi.setSystemTime(new Date("2026-07-28T00:00:00Z"));diff --git a/apps/desktop/src/lib/metadata/__tests__/objectMetadataCache.spec.ts b/apps/desktop/src/lib/metadata/__tests__/objectMetadataCache.spec.tsindex 8ebb442a84..23dd0241ab 100644--- a/apps/desktop/src/lib/metadata/__tests__/objectMetadataCache.spec.ts+++ b/apps/desktop/src/lib/metadata/__tests__/objectMetadataCache.spec.ts@@ -9,7 +9,7 @@ const mocks = vi.hoisted(() => ({vi.mock("@/lib/backend/api", () => mocks);-import { cancelObjectMetadataLoadsForConnection, getObjectMetadataCacheDebugStateForTests, invalidateObjectMetadataCache, loadObjectMetadataFacet } from "@/lib/metadata/objectMetadataCache";+import { cancelObjectMetadataLoadsForConnection, getObjectMetadataCacheDebugStateForTests, invalidateObjectMetadataCache, invalidateObjectMetadataFacet, loadObjectMetadataFacet } from "@/lib/metadata/objectMetadataCache";import { isObjectCacheInvalidationError } from "@/lib/metadata/objectCacheInvalidationError";import { clearMetadataRuntimeCache } from "@/lib/metadata/metadataRuntimeCache";@@ -134,6 +134,55 @@ describe("objectMetadataCache", () => {expect(viewLoader).toHaveBeenCalledTimes(1);});+ it("separates exact trigger snapshots without changing other facet keys and invalidates both modes together", async () => {+ const exactRequest = { ...request, oracleTriggerContract: 1 as const };+ const oldLoader = vi.fn().mockResolvedValue(["legacy-body"]);+ const exactLoader = vi.fn().mockResolvedValue(["exact-metadata"]);+ expect((await loadObjectMetadataFacet(request, "triggers", oldLoader)).value).toEqual(["legacy-body"]);+ expect((await loadObjectMetadataFacet(exactRequest, "triggers", exactLoader)).value).toEqual(["exact-metadata"]);+ expect(exactLoader).toHaveBeenCalledTimes(1);+ const columns = vi.fn().mockResolvedValue(["column"]);+ await loadObjectMetadataFacet(request, "columns", columns);+ await loadObjectMetadataFacet(exactRequest, "columns", columns);+ expect(columns).toHaveBeenCalledTimes(1);+ await invalidateObjectMetadataCache(request);+ await loadObjectMetadataFacet(exactRequest, "triggers", exactLoader);+ await loadObjectMetadataFacet(request, "triggers", oldLoader);+ expect(exactLoader).toHaveBeenCalledTimes(2);+ expect(oldLoader).toHaveBeenCalledTimes(2);+ });++ it.each([false, true])("retires all trigger identity and contract variants from an exact=%s facet request", async (exactIdentity) => {+ const variants = [request, { ...request, oracleTriggerContract: 1 as const }, { ...request, exactIdentity: true }, { ...request, exactIdentity: true, oracleTriggerContract: 1 as const }];+ for (const variant of variants) await loadObjectMetadataFacet(variant, "triggers", async () => ["old"]);+ await loadObjectMetadataFacet(request, "columns", async () => ["column"]);+ await loadObjectMetadataFacet({ ...request, catalog: "other" }, "triggers", async () => ["other"]);+ await invalidateObjectMetadataFacet({ ...request, exactIdentity }, "triggers", { strict: true });+ for (const variant of variants) expect((await loadObjectMetadataFacet(variant, "triggers", async () => ["new"])).value).toEqual(["new"]);+ expect((await loadObjectMetadataFacet(request, "columns", async () => ["wrong"])).value).toEqual(["column"]);+ expect((await loadObjectMetadataFacet({ ...request, catalog: "other" }, "triggers", async () => ["wrong"])).value).toEqual(["other"]);+ });++ it("retires exact in-flight trigger loads even when persisted deletion fails", async () => {+ const exact = { ...request, exactIdentity: true, oracleTriggerContract: 1 as const };+ let resolve!: (value: string[]) => void;+ const loader = vi.fn(+ () =>+ new Promise<string[]>((done) => {+ resolve = done;+ }),+ );+ const pending = loadObjectMetadataFacet(exact, "triggers", loader);+ const retired = expect(pending).rejects.toThrow();+ await vi.waitFor(() => expect(loader).toHaveBeenCalledOnce());+ mocks.deleteSchemaCachePrefix.mockRejectedValueOnce(new Error("storage unavailable"));+ await expect(invalidateObjectMetadataFacet(request, "triggers", { strict: true })).rejects.toMatchObject({ name: "ObjectCacheInvalidationError" });+ await retired;+ resolve(["late"]);+ await Promise.resolve();+ expect((await loadObjectMetadataFacet(exact, "triggers", async () => ["fresh"])).value).toEqual(["fresh"]);+ });+it("persists a remote facet and force bypasses disk", async () => {mocks.loadSchemaCache.mockResolvedValue({ version: 1, cachedAt: new Date().toISOString(), value: ["old"] });const loader = vi.fn().mockResolvedValue(["new"]);diff --git a/apps/desktop/src/lib/metadata/objectDdlCache.ts b/apps/desktop/src/lib/metadata/objectDdlCache.tsindex 07b7c8aa02..2ba8ed65b3 100644--- a/apps/desktop/src/lib/metadata/objectDdlCache.ts+++ b/apps/desktop/src/lib/metadata/objectDdlCache.ts@@ -259,20 +259,26 @@ export async function invalidateObjectDdlCache(match: MetadataCacheInvalidation,if (metaSettled.status === "rejected") throw toObjectCacheInvalidationError(metaSettled.reason, prefix);}-export async function invalidateObjectDdl(request: ObjectDdlRequest): Promise<void> {+export async function invalidateObjectDdl(request: ObjectDdlRequest, options?: ObjectCacheInvalidationOptions & { metadata?: boolean }): Promise<void> {const cacheKey = objectDdlCacheKey(request);activeCacheReads.invalidatePrefix(cacheKey);invalidateRemoteLoad(cacheKey);invalidateMetadataRuntimeCachePrefix(cacheKey);- await Promise.allSettled([+ const results = await Promise.allSettled([invalidatePersistedPrefix(cacheKey),- invalidateObjectMetadataCache({- connectionId: request.connectionId,- database: request.database,- schema: request.schema,- tableName: request.tableName,- }),+ options?.metadata === false+ ? Promise.resolve()+ : invalidateObjectMetadataCache(+ {+ connectionId: request.connectionId,+ database: request.database,+ schema: request.schema,+ tableName: request.tableName,+ },+ options,+ ),]);+ if (options?.strict) for (const result of results) if (result.status === "rejected") throw toObjectCacheInvalidationError(result.reason, cacheKey);}/** Invalidate active loads for a disconnected connection without deleting its persisted snapshot. */diff --git a/apps/desktop/src/lib/metadata/objectMetadataCache.ts b/apps/desktop/src/lib/metadata/objectMetadataCache.tsindex 9ca85af15d..027ac39506 100644--- a/apps/desktop/src/lib/metadata/objectMetadataCache.ts+++ b/apps/desktop/src/lib/metadata/objectMetadataCache.ts@@ -45,13 +45,15 @@ async function saveSchemaCacheSafe(cacheKey: string, payload: unknown): Promise<}export type ObjectMetadataFacet = "columns" | "indexes" | "foreign-keys" | "constraints" | "triggers" | "partitions" | "comment" | "owner";+export type ObjectMetadataRequest = ObjectDdlRequest & { oracleTriggerContract?: 1 };function cacheSegment(value: string | undefined): string {return encodeURIComponent(value ?? "");}-function facetKey(request: ObjectDdlRequest, facet: ObjectMetadataFacet): string {- return `${[OBJECT_METADATA_CACHE_PREFIX, cacheSegment(request.connectionId), cacheSegment(request.database), cacheSegment(request.schema), cacheSegment(request.tableName), cacheSegment(request.catalog), cacheSegment(request.objectType ?? "TABLE"), ...(request.exactIdentity ? ["exact-v1"] : []), facet].join(":")}:`;+function facetKey(request: ObjectMetadataRequest, facet: ObjectMetadataFacet): string {+ const contract = facet === "triggers" && request.oracleTriggerContract === 1 ? ":oracle-trigger-exact-v1" : "";+ return `${[OBJECT_METADATA_CACHE_PREFIX, cacheSegment(request.connectionId), cacheSegment(request.database), cacheSegment(request.schema), cacheSegment(request.tableName), cacheSegment(request.catalog), cacheSegment(request.objectType ?? "TABLE"), ...(request.exactIdentity ? ["exact-v1"] : []), facet].join(":")}${contract}:`;}function invalidationPrefix(match: MetadataCacheInvalidation): string {@@ -123,7 +125,7 @@ function invalidatePersistedPrefix(prefix: string): Promise<void> {return deletion;}-export async function loadObjectMetadataFacet<T>(request: ObjectDdlRequest, facet: ObjectMetadataFacet, loader: () => Promise<T>, options?: { force?: boolean }): Promise<{ value: T; cacheStatus: "memory" | "disk" | "remote" }> {+export async function loadObjectMetadataFacet<T>(request: ObjectMetadataRequest, facet: ObjectMetadataFacet, loader: () => Promise<T>, options?: { force?: boolean }): Promise<{ value: T; cacheStatus: "memory" | "disk" | "remote" }> {const token = activeLoads.begin(facetKey(request, facet));try {return await waitForMetadata(loadObjectMetadataFacetInternal(request, facet, loader, token.controller.signal, options), metadataLoadBudgetMs(request.queryTimeoutSecs), token.controller.signal);@@ -135,7 +137,7 @@ export async function loadObjectMetadataFacet<T>(request: ObjectDdlRequest, face}}-async function loadObjectMetadataFacetInternal<T>(request: ObjectDdlRequest, facet: ObjectMetadataFacet, loader: () => Promise<T>, signal: AbortSignal, options?: { force?: boolean }): Promise<{ value: T; cacheStatus: "memory" | "disk" | "remote" }> {+async function loadObjectMetadataFacetInternal<T>(request: ObjectMetadataRequest, facet: ObjectMetadataFacet, loader: () => Promise<T>, signal: AbortSignal, options?: { force?: boolean }): Promise<{ value: T; cacheStatus: "memory" | "disk" | "remote" }> {const cacheKey = facetKey(request, facet);if (options?.force) {const existing = inFlightLoads.get(cacheKey);@@ -216,6 +218,17 @@ async function loadObjectMetadataFacetInternal<T>(request: ObjectDdlRequest, facexport async function invalidateObjectMetadataCache(match: MetadataCacheInvalidation, options?: ObjectCacheInvalidationOptions): Promise<void> {const prefix = invalidationPrefix(match);+ return invalidateFacetPrefix(prefix, options);+}++/** One physical object/facet, including legacy and exact variants of that facet. */+export async function invalidateObjectMetadataFacet(request: ObjectMetadataRequest, facet: ObjectMetadataFacet, options?: ObjectCacheInvalidationOptions): Promise<void> {+ const prefixes = [false, true].map((exactIdentity) => facetKey({ ...request, exactIdentity, oracleTriggerContract: undefined }, facet));+ for (const prefix of prefixes) activeLoads.cancelPrefix(prefix);+ await Promise.all(prefixes.map((prefix) => invalidateFacetPrefix(prefix, options)));+}++async function invalidateFacetPrefix(prefix: string, options?: ObjectCacheInvalidationOptions): Promise<void> {activeCacheReads.invalidatePrefix(prefix);for (const cacheKey of [...inFlightLoads.keys()]) if (cacheKey.startsWith(prefix)) invalidateInFlightLoad(cacheKey);invalidateMetadataRuntimeCachePrefix(prefix);diff --git a/apps/desktop/src/lib/sidebar/sidebarActiveTabTarget.ts b/apps/desktop/src/lib/sidebar/sidebarActiveTabTarget.tsindex 3054059975..63fd263b70 100644--- a/apps/desktop/src/lib/sidebar/sidebarActiveTabTarget.ts+++ b/apps/desktop/src/lib/sidebar/sidebarActiveTabTarget.ts@@ -10,7 +10,7 @@ export type ActiveTabSidebarTarget =| {type: "management";connectionId: string;- nodeType: "user-admin" | "xugu-user-admin" | "dameng-users" | "dameng-roles" | "dameng-job-admin";+ nodeType: "user-admin" | "xugu-user-admin" | "dameng-users" | "dameng-roles" | "dameng-job-admin" | "database-job-admin";}| {type: "table";@@ -131,6 +131,7 @@ export function activeTabSidebarTarget(tab: QueryTab | undefined | null): Active"dameng-users": "dameng-users","dameng-roles": "dameng-roles","dameng-jobs": "dameng-job-admin",+ "database-jobs": "database-job-admin",} as const;if (Object.prototype.hasOwnProperty.call(managementNodeTypes, tab.mode)) {if (!tab.connectionId) return null;diff --git a/apps/desktop/src/lib/sidebar/sidebarRemoteSearch.ts b/apps/desktop/src/lib/sidebar/sidebarRemoteSearch.tsindex 4d2370ddb5..040945368a 100644--- a/apps/desktop/src/lib/sidebar/sidebarRemoteSearch.ts+++ b/apps/desktop/src/lib/sidebar/sidebarRemoteSearch.ts@@ -3,6 +3,7 @@ import { objectTypesForGroupNode } from "@/lib/table/tableTree";import { sidebarIndexedObjectGroupTypes } from "@/lib/sidebar/sidebarGlobalSearchIndex";import { isSidebarSearchPrunedDatabaseNode } from "@/lib/sidebar/sidebarSearchDatabaseScope";import { nodeMatchesRegexScopeIdentity, type SidebarRegexScopeIdentity } from "@/lib/sidebar/sidebarSearchTree";+import { exactOracleTriggerNodeMetadata } from "@/lib/database/oracleTriggerIdentity";export interface SidebarRemoteSearchResult extends SidebarRegexScopeIdentity {parentNodeId: string;@@ -76,3 +77,15 @@ export function mergeSidebarRemoteSearchResults(nodes: TreeNode[], results: readreturn { ...node, children: merged };});}++export function removeVerifiedSidebarTriggerSearchResult(results: readonly SidebarRemoteSearchResult[], node: TreeNode): SidebarRemoteSearchResult[] {+ const expected = exactOracleTriggerNodeMetadata(node);+ if (!expected?.objectId) return [...results];+ return results.map((result) => ({+ ...result,+ children: result.children.filter((child) => {+ const actual = exactOracleTriggerNodeMetadata(child);+ return child.connectionId !== node.connectionId || child.database !== node.database || child.catalog !== node.catalog || actual?.owner !== expected.owner || actual?.name !== expected.name || actual?.objectId !== expected.objectId;+ }),+ }));+}diff --git a/apps/desktop/src/lib/sidebar/sidebarTreeContext.ts b/apps/desktop/src/lib/sidebar/sidebarTreeContext.tsindex 0a543ae1ce..19a55e416a 100644--- a/apps/desktop/src/lib/sidebar/sidebarTreeContext.ts+++ b/apps/desktop/src/lib/sidebar/sidebarTreeContext.ts@@ -7,6 +7,7 @@ export interface SidebarTreeContext {getVisibleNodeIndex: (id: string) => number;getProjectedConnectionIds?: () => ReadonlySet<string> | null;isSearchProjectionActive?: () => boolean;+ removeVerifiedTriggerNode?: (node: TreeNode) => void;getTreeLoadSearchOptions?: (node: TreeNode) => { searchFilter: string; allowGlobalSearchMismatch: true; expectedSidebarSearchQuery: string } | undefined;setTableSearchQuery?: (parentNodeId: string, query: string, local: boolean) => void;refreshTableSearchIndex?: (parentNodeId: string) => void;diff --git a/apps/desktop/src/lib/sidebar/sidebarTreeLabel.ts b/apps/desktop/src/lib/sidebar/sidebarTreeLabel.tsindex 7b30eb0e22..572a9800dd 100644--- a/apps/desktop/src/lib/sidebar/sidebarTreeLabel.ts+++ b/apps/desktop/src/lib/sidebar/sidebarTreeLabel.ts@@ -17,7 +17,7 @@ export function sidebarTreeDisplayLabel(node: TreeNode, t: SidebarTreeTranslate,// Use the canonical key for persisted trees created before this label was// internationalized; those nodes may still contain the old Chinese text.if (node.type === "nacos-access-control") return t("nacos.accessControlSidebarLabel");- if (node.type === "user-admin" || node.type === "xugu-user-admin" || node.type === "dameng-users" || node.type === "dameng-roles" || node.type === "dameng-job-admin" || node.type === "meilisearch-system") return t(node.label);+ if (node.type === "user-admin" || node.type === "xugu-user-admin" || node.type === "dameng-users" || node.type === "dameng-roles" || node.type === "dameng-job-admin" || node.type === "database-job-admin" || node.type === "meilisearch-system") return t(node.label);if (node.type === "oracle-db-links" || node.type === "linked-server-root") return t(node.label);if (node.type === "saved-sql-root") return t(node.label);if (node.type === "mqtt-topic" && node.id.endsWith(":mqtt-topic:__console__")) return t(node.label);diff --git a/apps/desktop/src/lib/sidebar/treeNodeClick.ts b/apps/desktop/src/lib/sidebar/treeNodeClick.tsindex 6eda8e7564..c8ab9f196b 100644--- a/apps/desktop/src/lib/sidebar/treeNodeClick.ts+++ b/apps/desktop/src/lib/sidebar/treeNodeClick.ts@@ -45,11 +45,13 @@ const toggleLeafNodeTypes = new Set<TreeNodeType>(["user-admin","dameng-users","dameng-roles",+ "dameng-job-admin",+ "database-job-admin",]);// These are application entry points rather than database objects. They should// always navigate on a single click, even when the user prefers double-click// activation for ordinary tree objects.-const directNavigationTreeNodeTypes = new Set<TreeNodeType>(["consul-root", "consul-overview", "etcd-root", "etcd-dashboard", "etcd-access-control", "nacos-namespace", "nacos-access-control", "meilisearch-system"]);+const directNavigationTreeNodeTypes = new Set<TreeNodeType>(["consul-root", "consul-overview", "etcd-root", "etcd-dashboard", "etcd-access-control", "nacos-namespace", "nacos-access-control", "meilisearch-system", "dameng-job-admin", "database-job-admin"]);const repeatableNavigationTreeNodeTypes = new Set<TreeNodeType>(["etcd-root", "etcd-dashboard", "etcd-access-control", "nacos-namespace", "nacos-access-control"]);export function isDirectNavigationTreeNode(type: TreeNodeType): boolean {diff --git a/apps/desktop/src/lib/sidebar/treeNodeIcon.ts b/apps/desktop/src/lib/sidebar/treeNodeIcon.tsindex 42fa150adb..862bd5b1c6 100644--- a/apps/desktop/src/lib/sidebar/treeNodeIcon.ts+++ b/apps/desktop/src/lib/sidebar/treeNodeIcon.ts@@ -122,6 +122,8 @@ export function getTreeNodeIconInfo(node: TreeNode): TreeNodeIconInfo | null {case "synonym":return { icon: Link2, colorClass: "text-sky-500" };case "job":+ case "dameng-job-admin":+ case "database-job-admin":return { icon: Clock, colorClass: "text-orange-400" };case "package":return { icon: Package, colorClass: "text-cyan-500" };diff --git a/apps/desktop/src/lib/table/__tests__/objectSourceLoad.spec.ts b/apps/desktop/src/lib/table/__tests__/objectSourceLoad.spec.tsindex 0edf96de50..9821778dc2 100644--- a/apps/desktop/src/lib/table/__tests__/objectSourceLoad.spec.ts+++ b/apps/desktop/src/lib/table/__tests__/objectSourceLoad.spec.ts@@ -1,8 +1,11 @@-import { describe, expect, it, vi } from "vitest";+import { beforeEach, describe, expect, it, vi } from "vitest";import { loadEditableObjectSourceForEditor, loadObjectSourceWithRoutineFallback } from "@/lib/table/objectSourceLoad";import { jdbcRoutineMetadata } from "@/lib/table/routineParameters";import type { ObjectSource } from "@/types/database";+const mocks = vi.hoisted(() => ({ prepare: vi.fn() }));+vi.mock("@/lib/backend/api", () => ({ prepareOracleTriggerSql: mocks.prepare }));+function source(text: string): ObjectSource {return { name: "x", object_type: "PROCEDURE", schema: "APP", source: text };}@@ -87,3 +90,128 @@ describe("loadEditableObjectSourceForEditor", () => {);});});++describe("exact trigger source loading", () => {+ const options = { connectionId: "c1", database: "catalog", schema: " Owner ", name: " Trigger ", objectType: "TRIGGER", databaseType: "oceanbase-oracle", metadataReadOptions: { identityMode: "exact", catalog: "catalog" } } as const;+ function rawTrigger(): ObjectSource {+ return {+ name: options.name,+ schema: options.schema,+ object_type: "TRIGGER",+ source: "TRIGGER ... /* 中文😀 */",+ trigger: {+ name: options.name,+ event: "INSERT",+ timing: "BEFORE EACH ROW",+ enabled: false,+ valid: false,+ oracle_metadata: {+ contractVersion: 1,+ identityMode: "exact",+ engine: "oceanbase-oracle",+ owner: options.schema,+ name: options.name,+ scope: "VIEW",+ parent: { owner: " Parent Owner ", name: " View ", objectType: "VIEW" },+ objectId: "9007199254740993",+ definition: { origin: "ALL_SOURCE", format: "declaration", complete: true },+ reads: { identity: { state: "available" }, definition: { state: "available" } },+ },+ },+ };+ }+ beforeEach(() => {+ mocks.prepare.mockReset();+ mocks.prepare.mockResolvedValue({ definition: "CREATE TRIGGER ... /* 中文😀 */;", header: { scope: "RELATION", owner: " Parent Owner ", name: " View ", viewOnly: true, pluggable: false }, requiresStateRestore: false });+ });++ it("keeps raw metadata and source and forwards exact read options to the existing source API", async () => {+ const raw = rawTrigger();+ const read = vi.fn().mockResolvedValue(raw);+ const legacyFormatter = vi.fn();+ const loaded = await loadEditableObjectSourceForEditor(read, legacyFormatter, options);+ expect(read).toHaveBeenCalledWith("c1", "catalog", " Owner ", " Trigger ", "TRIGGER", undefined, undefined, options.metadataReadOptions);+ expect(loaded.raw).toBe(raw);+ expect(loaded.triggerSource?.complete).toBe(true);+ expect(loaded.editableSource).toBe("CREATE TRIGGER ... /* 中文😀 */;");+ expect(mocks.prepare).toHaveBeenCalledWith(expect.objectContaining({ owner: " Owner ", name: " Trigger ", source: raw.source, purpose: "inspect", binding: { scope: "VIEW", owner: " Parent Owner ", name: " View " }, allowExportAppendix: false }));+ expect(legacyFormatter).not.toHaveBeenCalled();+ });++ it("allows only a metadata DDL export to carry its same-target state appendix", async () => {+ const raw = rawTrigger();+ raw.source = "CREATE TRIGGER ...; ALTER TRIGGER ... DISABLE;";+ raw.trigger!.oracle_metadata!.definition = { origin: "DBMS_METADATA", format: "ddl", complete: true };+ await loadEditableObjectSourceForEditor(vi.fn().mockResolvedValue(raw), vi.fn(), options);+ expect(mocks.prepare).toHaveBeenCalledWith(expect.objectContaining({ source: raw.source, allowExportAppendix: true }));+ });++ it("retains a body-only or old provider response without promoting a generic formatter result", async () => {+ const bodyMetadata = rawTrigger().trigger!.oracle_metadata!;+ bodyMetadata.definition = { origin: "catalog-body", format: "body", complete: false };+ for (const metadata of [undefined, bodyMetadata]) {+ const raw = rawTrigger();+ raw.source = "BEGIN NULL; END;";+ raw.trigger!.oracle_metadata = metadata;+ const formatter = vi.fn().mockResolvedValue("CREATE TRIGGER guessed ...");+ const loaded = await loadEditableObjectSourceForEditor(vi.fn().mockResolvedValue(raw), formatter, options);+ expect(loaded.editableSource).toBe(raw.source);+ expect(loaded.triggerSource?.complete).toBe(false);+ expect(loaded.triggerSource?.error).toBeTruthy();+ expect(formatter).not.toHaveBeenCalled();+ }+ expect(mocks.prepare).not.toHaveBeenCalled();+ });++ it("manual completion cannot replace an incomplete or unreadable authoritative baseline", async () => {+ for (const failure of ["incomplete", "denied", "error"] as const) {+ const raw = rawTrigger();+ raw.trigger!.oracle_metadata!.reads.definition = { state: failure };+ const loaded = await loadEditableObjectSourceForEditor(vi.fn().mockResolvedValue(raw), vi.fn(), options);+ expect(loaded.triggerSource?.prepared).toBeDefined();+ expect(loaded.triggerSource?.complete).toBe(false);+ expect(loaded.raw.source).toBe(raw.source);+ }+ });++ it("keeps the candidate available when strict source or ON validation fails", async () => {+ const raw = rawTrigger();+ mocks.prepare.mockRejectedValue(new Error("ON target mismatch"));+ const loaded = await loadEditableObjectSourceForEditor(vi.fn().mockResolvedValue(raw), vi.fn(), options);+ expect(loaded.editableSource).toBe(raw.source);+ expect(loaded.triggerSource).toEqual({ complete: false, error: "ON target mismatch" });+ });++ it("does not bless a table definition for a dictionary database or timer scope", async () => {+ for (const scope of ["DATABASE", "TIMER"] as const) {+ const raw = rawTrigger();+ raw.trigger!.oracle_metadata!.scope = scope;+ raw.trigger!.oracle_metadata!.parent = null;+ const loaded = await loadEditableObjectSourceForEditor(vi.fn().mockResolvedValue(raw), vi.fn(), options);+ expect(loaded.triggerSource?.complete).toBe(false);+ expect(loaded.triggerSource?.error).toContain("scope does not match");+ expect(loaded.editableSource).toBe(raw.source);+ }+ });++ it("does not accept a near-name or parent owner as the trigger source identity", async () => {+ for (const wrong of ["Owner", " Parent Owner "]) {+ const raw = rawTrigger();+ raw.schema = wrong;+ const loaded = await loadEditableObjectSourceForEditor(vi.fn().mockResolvedValue(raw), vi.fn(), options);+ expect(loaded.triggerSource?.complete).toBe(false);+ expect(loaded.editableSource).toBe(raw.source);+ }+ expect(mocks.prepare).not.toHaveBeenCalled();+ });++ it("leaves default trigger callers on their original formatter contract", async () => {+ const read = vi.fn().mockResolvedValue(rawTrigger());+ const formatter = vi.fn().mockResolvedValue("legacy formatted trigger");+ const loaded = await loadEditableObjectSourceForEditor(read, formatter, { ...options, metadataReadOptions: undefined });+ expect(read.mock.calls[0]).toHaveLength(7);+ expect(loaded.editableSource).toBe("legacy formatted trigger");+ expect(loaded.triggerSource).toBeUndefined();+ expect(mocks.prepare).not.toHaveBeenCalled();+ });+});diff --git a/apps/desktop/src/lib/table/objectBrowserRows.ts b/apps/desktop/src/lib/table/objectBrowserRows.tsindex cdb39ea6d2..0cb5e5a12d 100644--- a/apps/desktop/src/lib/table/objectBrowserRows.ts+++ b/apps/desktop/src/lib/table/objectBrowserRows.ts@@ -1,9 +1,10 @@-import type { MongoCollectionKind, ObjectBrowserFilter, ObjectInfo, TreeNode, TreeNodeType } from "@/types/database";+import type { MongoCollectionKind, ObjectBrowserFilter, ObjectInfo, TreeNode, TreeNodeType, TriggerInfo } from "@/types/database";export type { ObjectBrowserFilter } from "@/types/database";import { pinnedTreeNodeIdentityMatches, type PinnedTreeNodeIdentity } from "@/lib/app/pinnedItems";import { toMongoCollectionKind } from "@/lib/sidebar/mongoCollectionMutation";import { buildGroupedObjectTreeNodes, buildSimpleObjectTreeNodes, buildTableTreeNodes, compareDatabaseObjectNames, normalizeDatabaseObjectName } from "@/lib/table/tableTree";import { parseSlashDelimitedRegexQuery } from "@/lib/common/searchPattern";+import { exactOracleTriggerMetadata, exactOracleTriggerObjectMetadata, oracleTriggerIdentityKey } from "@/lib/database/oracleTriggerIdentity";export type ObjectBrowserRow = {id: string;@@ -15,6 +16,7 @@ export type ObjectBrowserRow = {parentName?: string;collectionKind?: MongoCollectionKind;valid?: boolean | null;+ trigger?: TriggerInfo | null;signature?: string | null;comment?: string | null;created_at?: string | null;@@ -80,7 +82,7 @@ export function objectBrowserRowPinnedTreeNodeIdentity(row: ObjectBrowserRow, co}export function objectBrowserRowMatchesPinnedTreeNode(row: ObjectBrowserRow, identity: PinnedTreeNodeIdentity, context: ObjectBrowserPinnedTreeNodeContext): boolean {- return pinnedTreeNodeIdentityMatches(identity, objectBrowserRowPinnedTreeNodeIdentity(row, context), canonicalizeObjectBrowserPinnedTreeNodeIdentity(context));+ return pinnedTreeNodeIdentityMatches(identity, objectBrowserRowPinnedTreeNodeIdentity(row, context), exactOracleTriggerMetadata(row.trigger) ? undefined : canonicalizeObjectBrowserPinnedTreeNodeIdentity(context));}function flattenTreeNodeIds(nodes: readonly TreeNode[]): string[] {@@ -94,12 +96,15 @@ function objectBrowserRowObjectInfo(row: ObjectBrowserRow, schema?: string): Objschema,valid: row.valid,signature: row.signature || undefined,+ trigger: row.trigger,parent_schema: row.type === "INDEX" ? row.parentSchema : row.partitionParentSchema,parent_name: row.type === "INDEX" ? row.parentName : row.partitionParentName,};}function legacySchemaCandidates(row: ObjectBrowserRow, context: ObjectBrowserPinnedTreeNodeContext): Array<string | undefined> {+ const trigger = exactOracleTriggerMetadata(row.trigger);+ if (trigger) return [trigger.owner];const identity = objectBrowserRowPinnedTreeNodeIdentity(row, context);const canonicalIdentity = canonicalizeObjectBrowserPinnedTreeNodeIdentity(context)(identity);return [...new Set([row.schema, context.schema, canonicalIdentity.schema, undefined].map((schema) => schema?.trim() || undefined))];@@ -163,7 +168,27 @@ export function normalizeObjectBrowserType(type: string): ObjectBrowserRow["typeexport function buildObjectBrowserRows(options: { objects: ObjectInfo[]; database: string; fallbackSchema: string; rowSchema?: string }): ObjectBrowserRow[] {const seen = new Map<string, number>();- const rows = options.objects.flatMap((object) => {+ const rows = options.objects.flatMap<ObjectBrowserRow>((object) => {+ const exactTrigger = exactOracleTriggerObjectMetadata(object);+ if (exactTrigger) {+ const baseId = oracleTriggerIdentityKey(exactTrigger);+ const index = seen.get(baseId) ?? 0;+ seen.set(baseId, index + 1);+ return [+ {+ id: `${baseId}:${index}`,+ name: exactTrigger.name,+ displayName: exactTrigger.name,+ schema: exactTrigger.owner,+ type: "TRIGGER" as const,+ valid: object.trigger?.valid ?? object.valid,+ trigger: object.trigger,+ comment: object.comment,+ created_at: object.created_at,+ updated_at: object.updated_at,+ },+ ];+ }const type = normalizeObjectBrowserType(object.object_type);const name = type === "INDEX" ? object.name : normalizeDatabaseObjectName(object.name);if (!name) return [];@@ -187,6 +212,7 @@ export function buildObjectBrowserRows(options: { objects: ObjectInfo[]; databascomment: object.comment,created_at: object.created_at,updated_at: object.updated_at,+ trigger: object.trigger,parentSchema: type === "INDEX" ? (object.parent_schema ?? undefined) : undefined,parentName: type === "INDEX" ? (object.parent_name ?? undefined) : undefined,partitionParentSchema: type !== "INDEX" && object.parent_schema ? normalizeDatabaseObjectName(object.parent_schema) : undefined,diff --git a/apps/desktop/src/lib/table/objectBrowserRowsCache.ts b/apps/desktop/src/lib/table/objectBrowserRowsCache.tsindex 9fad5d4ffe..a7d8e215d7 100644--- a/apps/desktop/src/lib/table/objectBrowserRowsCache.ts+++ b/apps/desktop/src/lib/table/objectBrowserRowsCache.ts@@ -11,6 +11,7 @@ export interface ObjectBrowserRowsCacheScope {database: string;schema: string;catalog?: string;+ oracleTriggerContract?: 1;exactIdentity?: boolean;}@@ -38,12 +39,31 @@ function objectBrowserRowsScope(scope: ObjectBrowserRowsCacheScope): MetadataScoconnectionId: scope.connectionId,database: scope.database,schema: scope.schema,- extra: scope.catalog || scope.exactIdentity ? { catalog: scope.catalog, ...(scope.exactIdentity ? { exactIdentity: true } : {}) } : undefined,+ extra:+ scope.catalog || scope.exactIdentity || scope.oracleTriggerContract !== undefined ? { catalog: scope.catalog, ...(scope.exactIdentity ? { exactIdentity: true } : {}), ...(scope.oracleTriggerContract !== undefined ? { oracleTriggerContract: scope.oracleTriggerContract } : {}) } : undefined,};}function cloneRows(rows: readonly ObjectBrowserRow[]): ObjectBrowserRow[] {- return rows.map((row) => ({ ...row }));+ return rows.map((row) => {+ if (!row.trigger) return { ...row };+ const metadata = row.trigger.oracle_metadata;+ return {+ ...row,+ trigger: {+ ...row.trigger,+ oracle_metadata: metadata+ ? {+ ...metadata,+ parent: metadata.parent ? { ...metadata.parent } : metadata.parent,+ definition: metadata.definition ? { ...metadata.definition } : metadata.definition,+ errors: metadata.errors?.map((error) => ({ ...error })) ?? metadata.errors,+ reads: Object.fromEntries(Object.entries(metadata.reads).map(([field, value]) => [field, value ? { ...value } : value])),+ }+ : metadata,+ },+ };+ });}function objectBrowserRowsCacheGeneration(scope: ObjectBrowserRowsCacheScope): ObjectBrowserRowsCacheGeneration {diff --git a/apps/desktop/src/lib/table/objectSourceEditor.ts b/apps/desktop/src/lib/table/objectSourceEditor.tsindex f05ecc2df8..f7daa53a81 100644--- a/apps/desktop/src/lib/table/objectSourceEditor.ts+++ b/apps/desktop/src/lib/table/objectSourceEditor.ts@@ -14,12 +14,10 @@ export type BuildEditableObjectSourceSqlInput = {};export type ValidateOracleExecutableObjectSourceInput = {- databaseType: Extract<DatabaseType, "oracle" | "oceanbase-oracle">;- objectType: Extract<ObjectSourceKind, "PROCEDURE" | "FUNCTION" | "PACKAGE" | "PACKAGE_BODY">;schema?: string | null;name: string;source: string;-};+} & ({ databaseType: Extract<DatabaseType, "oracle" | "oceanbase-oracle">; objectType: Extract<ObjectSourceKind, "PROCEDURE" | "FUNCTION" | "PACKAGE" | "PACKAGE_BODY" | "TRIGGER"> } | { databaseType: "dameng"; objectType: "TRIGGER" });export type FingerprintOracleRoutineObjectSourceInput = {databaseType: Extract<DatabaseType, "oracle" | "oceanbase-oracle">;diff --git a/apps/desktop/src/lib/table/objectSourceLoad.ts b/apps/desktop/src/lib/table/objectSourceLoad.tsindex d644fa52eb..e74fbefc67 100644--- a/apps/desktop/src/lib/table/objectSourceLoad.ts+++ b/apps/desktop/src/lib/table/objectSourceLoad.ts@@ -1,9 +1,62 @@-import type { DatabaseType, ObjectSource, ObjectSourceKind } from "@/types/database";+import type { DatabaseType, MetadataReadOptions, ObjectSource, ObjectSourceKind } from "@/types/database";+import * as api from "@/lib/backend/api";+import { exactOracleTriggerMetadata } from "@/lib/database/oracleTriggerIdentity";+import { oracleTriggerSourceBinding, oracleTriggerSourceScopeMatches, type OracleTriggerDatabaseType, type PreparedOracleTriggerSql } from "@/lib/database/oracleTriggerSql";+import { tokenizeSqlSemantic } from "@/lib/sql/semantic/tokens";-export type GetObjectSourceFn = (connectionId: string, database: string, schema: string, name: string, objectType: ObjectSourceKind, signature?: string, relationName?: string) => Promise<ObjectSource>;+export type GetObjectSourceFn = (connectionId: string, database: string, schema: string, name: string, objectType: ObjectSourceKind, signature?: string, relationName?: string, options?: MetadataReadOptions) => Promise<ObjectSource>;export type BuildEditableObjectSourceFn = (input: { databaseType: DatabaseType; objectType: ObjectSourceKind; schema?: string; name: string; source: string }) => Promise<string>;+export type OracleTriggerSourceInspection = { complete: boolean; prepared?: PreparedOracleTriggerSql; error?: string };++/** Keep raw/partial source available for manual correction; never promote it to+ * a replacement baseline merely because the generic formatter adds CREATE. */+export async function inspectExactOracleTriggerSource(raw: ObjectSource, owner: string, name: string): Promise<{ editableSource: string; triggerSource: OracleTriggerSourceInspection }> {+ const metadata = exactOracleTriggerMetadata(raw.trigger);+ if (!metadata || metadata.owner !== owner || metadata.name !== name || raw.name !== name || raw.schema !== owner || raw.object_type !== "TRIGGER") {+ return { editableSource: raw.source, triggerSource: { complete: false, error: "Exact trigger identity was not verified; reload with the current provider" } };+ }+ if (metadata.definition?.format === "body") return { editableSource: raw.source, triggerSource: { complete: false, error: "Only the trigger body is available; reload the complete declaration before replacing it" } };+ try {+ const databaseType: OracleTriggerDatabaseType = metadata.engine === "dm" ? "dameng" : metadata.engine;+ const prepared = await api.prepareOracleTriggerSql({ databaseType, owner, name, source: raw.source, purpose: "inspect", binding: oracleTriggerSourceBinding(metadata), allowExportAppendix: metadata.definition?.origin === "DBMS_METADATA" && metadata.definition.format === "ddl" });+ if (!oracleTriggerSourceScopeMatches(metadata, prepared.header)) throw new Error("The source ON scope does not match the trigger dictionary; keep the draft and reload");+ const complete = metadata.definition?.complete === true && metadata.reads.identity?.state === "available" && metadata.reads.definition?.state === "available" && typeof metadata.objectId === "string" && metadata.objectId.length > 0;+ return { editableSource: prepared.definition, triggerSource: { complete, prepared, ...(!complete ? { error: "The complete trigger snapshot could not be verified; keep the draft and reload" } : {}) } };+ } catch (error) {+ return { editableSource: raw.source, triggerSource: { complete: false, error: error instanceof Error ? error.message : String(error) } };+ }+}++export function oracleTriggerErrorEditorOffset(raw: Readonly<ObjectSource>, editorSource: string, error: { line?: number | null; position?: number | null }): number | undefined {+ const metadata = exactOracleTriggerMetadata(raw.trigger);+ // ALL_ERRORS coordinates describe the stored unit. GET_DDL may reconstruct+ // its header/spacing, so that export alone does not establish a position map.+ if (!metadata || raw.object_type !== "TRIGGER" || raw.name !== metadata.name || raw.schema !== metadata.owner || metadata.definition?.origin !== "ALL_SOURCE" || metadata.definition.format !== "declaration" || !metadata.definition.complete || metadata.reads.definition?.state !== "available")+ return;+ const line = error.line,+ column = error.position;+ if (typeof line !== "number" || !Number.isSafeInteger(line) || line < 1 || typeof column !== "number" || !Number.isSafeInteger(column) || column < 1) return;+ const source = raw.source.replace(/\r\n?/g, "\n");+ const lines = source.split("\n");+ const sourceLine = lines[line - 1];+ if (sourceLine === undefined) return;+ const characters = Array.from(sourceLine);+ if (column > characters.length + 1) return;+ const sourceOffset = lines.slice(0, line - 1).reduce((length, value) => length + value.length + 1, 0) + characters.slice(0, column - 1).join("").length;+ const storedUnit = source.trim();+ if (!storedUnit) return;+ const unitStart = source.indexOf(storedUnit);+ if (sourceOffset < unitStart || sourceOffset > unitStart + storedUnit.length) return;+ const editor = editorSource.replace(/\r\n?/g, "\n");+ const start = editor.indexOf(storedUnit);+ if (start < 0 || editor.indexOf(storedUnit, start + 1) >= 0) return;+ const head = tokenizeSqlSemantic(editor, "oracle").find((token) => token.span.start <= start && start < token.span.end);+ if (head?.kind !== "word" || head.span.start !== start) return;+ return start + sourceOffset - unitStart;+}+/*** Load object source, retrying common routine type mismatches.* Optimistic Ctrl/Cmd+click often assumes PROCEDURE; Oracle functions and package bodies need a second try.@@ -17,8 +70,9 @@ export async function loadObjectSourceWithRoutineFallback(objectType: ObjectSourceKind,signature?: string,relationName?: string,+ options?: MetadataReadOptions,): Promise<{ source: ObjectSource; objectType: ObjectSourceKind }> {- const primary = await getObjectSource(connectionId, database, schema, name, objectType, signature, relationName);+ const primary = options ? await getObjectSource(connectionId, database, schema, name, objectType, signature, relationName, options) : await getObjectSource(connectionId, database, schema, name, objectType, signature, relationName);if (primary.source?.trim() || primary.routine_parameters !== undefined) {return { source: primary, objectType };}@@ -27,7 +81,7 @@ export async function loadObjectSourceWithRoutineFallback(for (const fallbackType of fallbacks) {try {- const alternate = await getObjectSource(connectionId, database, schema, name, fallbackType, signature, relationName);+ const alternate = options ? await getObjectSource(connectionId, database, schema, name, fallbackType, signature, relationName, options) : await getObjectSource(connectionId, database, schema, name, fallbackType, signature, relationName);if (alternate.source?.trim() || alternate.routine_parameters !== undefined) {return { source: alternate, objectType: fallbackType };}@@ -58,9 +112,14 @@ export async function loadEditableObjectSourceForEditor(databaseType: DatabaseType;signature?: string;relationName?: string;+ metadataReadOptions?: MetadataReadOptions;},-): Promise<{ raw: ObjectSource; editableSource: string; objectType: ObjectSourceKind }> {- const { source: raw, objectType: resolvedType } = await loadObjectSourceWithRoutineFallback(getObjectSource, options.connectionId, options.database, options.schema, options.name, options.objectType, options.signature, options.relationName);+): Promise<{ raw: ObjectSource; editableSource: string; objectType: ObjectSourceKind; triggerSource?: OracleTriggerSourceInspection }> {+ const { source: raw, objectType: resolvedType } = await loadObjectSourceWithRoutineFallback(getObjectSource, options.connectionId, options.database, options.schema, options.name, options.objectType, options.signature, options.relationName, options.metadataReadOptions);++ if (resolvedType === "TRIGGER" && options.metadataReadOptions?.identityMode === "exact") {+ return { raw, objectType: resolvedType, ...(await inspectExactOracleTriggerSource(raw, options.schema, options.name)) };+ }const editableSource = await buildEditableObjectSource({databaseType: options.databaseType,diff --git a/apps/desktop/src/lib/table/objectSourceTabSave.ts b/apps/desktop/src/lib/table/objectSourceTabSave.tsindex a07921d917..6c9a587f89 100644--- a/apps/desktop/src/lib/table/objectSourceTabSave.ts+++ b/apps/desktop/src/lib/table/objectSourceTabSave.ts@@ -9,7 +9,7 @@ import { requestOracleTypeManagement } from "@/lib/table/oracleTypeManagementReqinterface ObjectSourceTabSaveContext {connection?: ConnectionConfig;- queryStore: Pick<ReturnType<typeof useQueryStore>, "tabs" | "getObjectSourceIdentitySnapshot" | "markTabClean">;+ queryStore: Pick<ReturnType<typeof useQueryStore>, "tabs" | "getObjectSourceIdentitySnapshot" | "markTabClean" | "runOracleTriggerSourceAction">;t: (key: string, values?: Record<string, unknown>) => string;toast: (message: string, duration?: number) => void;}@@ -43,6 +43,7 @@ export async function saveObjectSourceTab(tab: QueryTab, { connection, queryStorconst { connectionId, database } = tab;const schema = source.schema || tab.schema || database;const sql = tab.sql;+ if (source.objectType === "TRIGGER" && ["oracle", "oceanbase-oracle", "dameng"].includes(databaseType)) return await queryStore.runOracleTriggerSourceAction(tab.id);const statements = await buildExecutableObjectSourceStatements({ databaseType, objectType: source.objectType, schema, name: source.name, source: sql });save = await prepareObjectSourceSave(connectionId, database, databaseType, statements, schema, { objectType: source.objectType, name: source.name });const preparedSave = save;diff --git a/apps/desktop/src/lib/table/tableStructureEditorSql.ts b/apps/desktop/src/lib/table/tableStructureEditorSql.tsindex d1e2742c1d..5dfee642f3 100644--- a/apps/desktop/src/lib/table/tableStructureEditorSql.ts+++ b/apps/desktop/src/lib/table/tableStructureEditorSql.ts@@ -153,6 +153,11 @@ export interface EditableStructureTrigger {event: string;statement: string;enabled?: boolean;+ /** Explicit exact trigger workflow; omitted callers keep the existing SQL contract. */+ oracleExact?: { owner: string; parentType: "TABLE" | "VIEW" };+ /** Full authoritative source captured before a structured edit; retained with a failed draft. */+ loadedOracleSource?: string;+ loadedOracleStructured?: boolean;original?: TriggerInfo;markedForDrop: boolean;}@@ -223,6 +228,18 @@ export interface TranswarpCreateTableOptions {export interface TableStructureChangeSql {statements: string[];warnings: string[];+ triggerOperations?: OracleTriggerStructureOperation[];+ oracleTriggerContract?: 1;+}++export interface OracleTriggerStructureOperation {+ draftId: string;+ action: "create" | "replace" | "delete" | "enable" | "disable";+ owner: string;+ name: string;+ statementIndex: number;+ statementCount: number;+ enabled?: boolean;}/** Explicit partition maintenance operations (PostgreSQL only). */diff --git a/apps/desktop/src/lib/table/tableStructureEditorState.ts b/apps/desktop/src/lib/table/tableStructureEditorState.tsindex 073f54d2dd..65134b12ad 100644--- a/apps/desktop/src/lib/table/tableStructureEditorState.ts+++ b/apps/desktop/src/lib/table/tableStructureEditorState.ts@@ -1,6 +1,7 @@import type { ColumnInfo, DatabaseConnectionInfo, DatabaseType, ForeignKeyInfo, IndexInfo, TriggerInfo } from "@/types/database.ts";import type { ColumnExtra, EditableStructureColumn, EditableStructureForeignKey, EditableStructureIndex, EditableStructureTrigger } from "@/lib/table/tableStructureEditorSql.ts";import { getStarRocksCapabilities, STARROCKS_DATA_TYPES } from "@/lib/table/starrocksCapabilities";+import { exactOracleTriggerMetadata, oracleTriggerIdentityKey } from "@/lib/database/oracleTriggerIdentity";export interface CopySourceColumnDetails {/** Column default as shown in the copy-fields dialog, or null when there is none. */@@ -1357,7 +1358,7 @@ export function createForeignKeyDrafts(foreignKeys: ForeignKeyInfo[], databaseTyexport function createTriggerDrafts(triggers: TriggerInfo[]): EditableStructureTrigger[] {return triggers.map((trigger) => ({- id: `existing:${trigger.name}`,+ id: exactOracleTriggerMetadata(trigger) ? `existing:exact:${oracleTriggerIdentityKey(exactOracleTriggerMetadata(trigger)!)}` : `existing:${trigger.name}`,name: trigger.name,timing: trigger.timing,event: trigger.event,@@ -1375,7 +1376,8 @@ export function canEditStructuredTriggerDraft(databaseType: DatabaseType | undef// REFERENCING, FOLLOWS, ...) that the timing/event/body form would drop on CREATE OR REPLACE.// Dameng reports a plain body plus a separate `WHEN` clause, so the same guard applies: the// structured form can only rebuild triggers that have neither of those extra clauses.- if (databaseType !== "oracle" && databaseType !== "dameng") return true;+ if (databaseType !== "oracle" && databaseType !== "oceanbase-oracle" && databaseType !== "dameng") return true;+ if (exactOracleTriggerMetadata(trigger.original) && trigger.loadedOracleStructured !== true) return false;return isStructuredOracleTriggerSource(trigger.original.statement) && !trigger.original.condition?.trim();}diff --git a/apps/desktop/src/lib/table/tableTree.ts b/apps/desktop/src/lib/table/tableTree.tsindex 1342b1b1f0..5acfc119c9 100644--- a/apps/desktop/src/lib/table/tableTree.ts+++ b/apps/desktop/src/lib/table/tableTree.ts@@ -1,5 +1,6 @@-import type { DatabaseType, ObjectInfo, TableInfo, TreeNode, TreeNodeType } from "@/types/database";+import type { DatabaseType, ObjectInfo, OracleTriggerMetadata, TableInfo, TreeNode, TreeNodeType, TriggerInfo } from "@/types/database";import { normalizeSidebarObjectKind, supportsSchemaIndexManagement, type SidebarObjectKind } from "@/lib/database/databaseObjectCapabilities";+import { exactOracleTriggerMetadata, exactOracleTriggerObjectMetadata, oracleTriggerIdentityKey } from "@/lib/database/oracleTriggerIdentity";const databaseObjectNameCollator = new Intl.Collator(undefined, { numeric: true, sensitivity: "base" });@@ -120,7 +121,9 @@ function foldedPartitionObjectLookupKey(objectType: string, schema: string | und* purpose: an anchor must never look "changed" because the server cased a name* differently between two responses.*/-export function tablePageRowAnchorKey(name: string, schema?: string | null, parentName?: string | null) {+export function tablePageRowAnchorKey(name: string, schema?: string | null, parentName?: string | null, trigger?: TriggerInfo | null) {+ const metadata = exactOracleTriggerMetadata(trigger);+ if (metadata && metadata.name === name) return JSON.stringify(["oracle-trigger/v1", metadata.owner, metadata.name, metadata.objectId ?? null]);return `${(schema || "").toLowerCase()}\0${(parentName || "").toLowerCase()}\0${name.toLowerCase()}`;}@@ -679,12 +682,20 @@ function coalesceXuguPackageObjects(objects: readonly ObjectInfo[], databaseTypereturn result;}-export function buildSimpleObjectTreeNodes({ nodeId, connectionId, database, schema, objects, databaseType }: { nodeId: string; connectionId: string; database: string; schema?: string; objects: ObjectInfo[]; databaseType?: DatabaseType }): TreeNode[] {+export function buildSimpleObjectTreeNodes({ nodeId, connectionId, database, schema, catalog, objects, databaseType }: { nodeId: string; connectionId: string; database: string; schema?: string; catalog?: string; objects: ObjectInfo[]; databaseType?: DatabaseType }): TreeNode[] {const seen = new Set<string>();const tableEntries: TableTreeEntry[] = [];const objectNodes: TreeNode[] = [];for (const obj of coalesceXuguPackageObjects(objects, databaseType)) {+ const exactTrigger = exactOracleTriggerObjectMetadata(obj);+ if (exactTrigger) {+ const key = oracleTriggerIdentityKey(exactTrigger, catalog);+ if (seen.has(key)) continue;+ seen.add(key);+ objectNodes.push(exactTriggerTreeNode(nodeId, connectionId, database, obj, exactTrigger, catalog));+ continue;+ }const objectType = normalizeObjectType(obj.object_type);const schemaIndex = objectType === "INDEX" && supportsSchemaIndexManagement(databaseType);if (!schemaIndex && !["TABLE", "VIEW", "MATERIALIZED_VIEW", "PROCEDURE", "FUNCTION", "TRIGGER", "EVENT", "SEQUENCE", "SYNONYM", "PACKAGE", "PACKAGE_BODY", "TYPE", "TYPE_BODY"].includes(objectType)) {@@ -753,6 +764,29 @@ export function buildSimpleObjectTreeNodes({ nodeId, connectionId, database, schreturn [...buildPartitionTree(tableEntries, connectionId, database), ...sortDatabaseObjectsByName(objectNodes, (node) => node.label)];}+function exactTriggerTreeNode(nodeId: string, connectionId: string, database: string, object: ObjectInfo, metadata: OracleTriggerMetadata, catalog?: string): TreeNode {+ const parent = metadata.scope === "TABLE" || metadata.scope === "VIEW" ? metadata.parent : undefined;+ return {+ id: `${nodeId}:${oracleTriggerIdentityKey(metadata, catalog)}`,+ label: parent ? `${metadata.name} (${parent.name})` : metadata.name,+ type: "trigger",+ connectionId,+ database,+ catalog,+ schema: metadata.owner,+ objectName: metadata.name,+ parentSchema: parent?.owner,+ parentName: parent?.name,+ parentType: parent?.objectType === "VIEW" ? "view" : parent?.objectType === "TABLE" ? "table" : undefined,+ tableName: parent?.name,+ valid: object.trigger?.valid ?? object.valid,+ comment: object.comment,+ meta: object.trigger ?? undefined,+ isExpanded: false,+ children: undefined,+ };+}+function simpleObjectNodeType(objectType: DatabaseObjectTreeKind): TreeNodeType {if (objectType === "VIEW") return "view";if (objectType === "MATERIALIZED_VIEW") return "materialized_view";@@ -944,10 +978,38 @@ export function objectTypesForGroupNode(type: TreeNodeType): DatabaseObjectTreeKreturn groupDefs.find((def) => def.nodeType === type)?.objectTypes ?? null;}-export function buildGroupedObjectTreeNodes({ nodeId, connectionId, database, schema, objects, databaseType, groupNodeType }: { nodeId: string; connectionId: string; database: string; schema?: string; objects: ObjectInfo[]; databaseType?: DatabaseType; groupNodeType?: TreeNodeType }): TreeNode[] {+export function buildGroupedObjectTreeNodes({+ nodeId,+ connectionId,+ database,+ schema,+ catalog,+ objects,+ databaseType,+ groupNodeType,+}: {+ nodeId: string;+ connectionId: string;+ database: string;+ schema?: string;+ catalog?: string;+ objects: ObjectInfo[];+ databaseType?: DatabaseType;+ groupNodeType?: TreeNodeType;+}): TreeNode[] {const buckets = new Map<string, ObjectInfo[]>();const seen = new Set<string>();for (const obj of coalesceXuguPackageObjects(objects, databaseType)) {+ const exactTrigger = exactOracleTriggerObjectMetadata(obj);+ if (exactTrigger) {+ const key = oracleTriggerIdentityKey(exactTrigger, catalog);+ if (seen.has(key)) continue;+ seen.add(key);+ const bucket = buckets.get("TRIGGER") ?? [];+ bucket.push(obj);+ buckets.set("TRIGGER", bucket);+ continue;+ }const t = normalizeObjectType(obj.object_type);const schemaIndex = t === "INDEX" && supportsSchemaIndexManagement(databaseType);const name = schemaIndex ? obj.name : normalizeDatabaseObjectName(obj.name);@@ -979,6 +1041,8 @@ export function buildGroupedObjectTreeNodes({ nodeId, connectionId, database, scobjectType: def.objectTypes[0] as "TABLE" | "VIEW" | "MATERIALIZED_VIEW",}): sortDatabaseObjectsByName(items, (obj) => obj.name).map((obj) => {+ const exactTrigger = exactOracleTriggerObjectMetadata(obj);+ if (exactTrigger) return exactTriggerTreeNode(`${nodeId}:${def.key}`, connectionId, database, obj, exactTrigger, catalog);const objectType = normalizeObjectType(obj.object_type);const schemaIndex = objectType === "INDEX" && supportsSchemaIndexManagement(databaseType);const childSchema = schemaIndex ? (obj.schema ?? schema) : obj.schema ? normalizeDatabaseObjectName(obj.schema) : schema;diff --git a/apps/desktop/src/stores/__tests__/connectionStore.metadataLoading.spec.ts b/apps/desktop/src/stores/__tests__/connectionStore.metadataLoading.spec.tsindex c4dc6f2140..baad8226ba 100644--- a/apps/desktop/src/stores/__tests__/connectionStore.metadataLoading.spec.ts+++ b/apps/desktop/src/stores/__tests__/connectionStore.metadataLoading.spec.ts@@ -176,6 +176,43 @@ describe("connectionStore metadata loading", () => {setActivePinia(createPinia());});+ it.each([+ ["oracle", "group-triggers"],+ ["oceanbase-oracle", "group-triggers"],+ ["dameng", "group-triggers"],+ ["jdbc", "group-triggers"],+ ["oracle", "schema"],+ ["oceanbase-oracle", "schema"],+ ["dameng", "schema"],+ ["jdbc", "schema"],+ ] as const)(+ "keeps exact trigger identity in remote sidebar search (%s/%s)",+ async (dbType, nodeType) => {+ const owner = " Trigger.Owner ",+ name = ' Tr"igger ';+ const metadata = { contractVersion: 1, identityMode: "exact", engine: dbType === "dameng" ? "dm" : dbType === "jdbc" ? "oracle" : dbType, owner, name, objectId: "9007199254740993", scope: "SCHEMA", parent: null };+ const row = { ...procedure(name), name, schema: owner, object_type: "TRIGGER", trigger: { name, oracle_metadata: metadata } } as ObjectInfo;+ const listObjects = vi.fn().mockResolvedValue([row]);+ vi.doMock("@/lib/backend/tauriRuntime", () => ({ isTauriRuntime: () => false }));+ vi.doMock("@/lib/backend/api", () => ({ listObjects, cancelQuery: vi.fn(), listInstalledAgents: vi.fn().mockResolvedValue([]) }));+ const { MetadataResultCache } = await import("@/lib/metadata/metadataResultCache");+ const cachedRead = vi.spyOn(MetadataResultCache.prototype, "get");+ const { useConnectionStore } = await import("@/stores/connectionStore");+ const store = useConnectionStore();+ const connection = { ...postgresConnection(), id: "remote-trigger", db_type: dbType, ...(dbType === "jdbc" ? { database_info: { productName: "Oracle" } } : {}) } as ConnectionConfig;+ store.connections = [connection];+ store.connectedIds.add(connection.id);+ const node: TreeNode = { id: "trigger-group", label: "Triggers", type: nodeType, connectionId: connection.id, database: "service", schema: owner, catalog: "catalog-a" };+ const children = await store.searchSidebarObjects(node, "igger", new AbortController().signal);+ expect(listObjects).toHaveBeenCalledWith(connection.id, "service", owner, expect.arrayContaining(["TRIGGER"]), "igger", expect.any(Number), 0, "catalog-a", undefined, expect.stringMatching(/^sidebar-search-/), { identityMode: "exact", catalog: "catalog-a" });+ expect(children).toHaveLength(1);+ expect(children[0]).toMatchObject({ objectName: name, schema: owner, catalog: "catalog-a", meta: { oracle_metadata: metadata } });+ expect(cachedRead).toHaveBeenCalledWith(expect.objectContaining({ kind: "sidebar-object-search-page", extra: { catalog: "catalog-a", oracleTriggerContract: 1 } }), { allowStale: true });+ cachedRead.mockRestore();+ },+ 15_000,+ );+// Dynamic import of the merged connectionStore plus the scoped metadata// load can exceed Vitest's 5s default on slower CI runners; the assertion// is deterministic, so allow a wider timeout.@@ -856,6 +893,7 @@ describe("connectionStore metadata loading", () => {["schema", "DBX_TEST", "DBX_TEST", "DBX_TEST"],["oracle-db-links", "tree.databaseLinks", "", undefined],["user-admin", "tree.userAdmin", "", undefined],+ ["database-job-admin", "tree.nativeJobs", "", undefined],]);const linkRoot = connectionNode.children!.find((node) => node.type === "oracle-db-links")!;@@ -911,6 +949,7 @@ describe("connectionStore metadata loading", () => {expect(connectionNode.children?.map((node) => [node.type, node.label])).toEqual([["schema", "DBX_TEST"],["user-admin", "tree.userAdmin"],+ ["database-job-admin", "tree.nativeJobs"],]);});@@ -1271,7 +1310,7 @@ describe("connectionStore metadata loading", () => {expect(storedViewGroup?.type).toBe("group-views");await store.loadObjectGroupChildren(storedViewGroup!);- expect(loadSchemaCache).toHaveBeenCalledWith("oracle-1:XE:DIP:group-views:objects-v8");+ expect(loadSchemaCache).toHaveBeenCalledWith("oracle-1:XE:DIP:group-views:objects-v8-oracle-trigger-exact-v1");expect(listTables).toHaveBeenCalledWith(connection.id, "XE", "DIP", undefined, 201, 0, ["VIEW"]);expect(storedViewGroup?.children?.map((node) => node.label)).toEqual(["V_ONE", "V_THREE", "V_TWO"]);});diff --git a/apps/desktop/src/stores/__tests__/connectionStore.oceanbasePaging.spec.ts b/apps/desktop/src/stores/__tests__/connectionStore.oceanbasePaging.spec.tsindex 2b7f719ea1..1c745d5755 100644--- a/apps/desktop/src/stores/__tests__/connectionStore.oceanbasePaging.spec.ts+++ b/apps/desktop/src/stores/__tests__/connectionStore.oceanbasePaging.spec.ts@@ -14,13 +14,14 @@ beforeEach(() => {setActivePinia(createPinia());});-async function setup(listObjects: ReturnType<typeof vi.fn>, listTables?: ReturnType<typeof vi.fn>) {+async function setup(listObjects: ReturnType<typeof vi.fn>, listTables?: ReturnType<typeof vi.fn>, listTriggers = vi.fn().mockResolvedValue([])) {vi.doMock("@/lib/backend/tauriRuntime", () => ({ isTauriRuntime: () => false }));vi.doMock("@/lib/backend/api", () => ({checkConnectionHealth: vi.fn().mockResolvedValue(undefined),disconnectDb: vi.fn().mockResolvedValue(undefined),deleteSchemaCachePrefix: vi.fn().mockResolvedValue(undefined),listObjects,+ listTriggers,listTables: listTables ?? vi.fn().mockResolvedValue([]),listInstalledAgents: vi.fn().mockResolvedValue([]),loadSchemaCache: vi.fn().mockResolvedValue(null),@@ -77,6 +78,98 @@ function findMore(nodes: TreeNode[]): TreeNode | undefined {}describe("OceanBase Oracle sidebar paging (#11418)", () => {+ function trigger(name: string, id: string): ObjectInfo {+ return {+ name,+ schema: " Trigger Owner ",+ object_type: "TRIGGER",+ trigger: {+ name,+ event: "UPDATE",+ timing: "INSTEAD OF",+ enabled: false,+ valid: true,+ oracle_metadata: {+ contractVersion: 1,+ identityMode: "exact",+ engine: "oceanbase-oracle",+ engineVersion: "4.2.5.7",+ owner: " Trigger Owner ",+ name,+ objectId: id,+ scope: "VIEW",+ parent: { owner: " Parent Owner ", name: " Parent ", objectType: "VIEW" },+ reads: { identity: { state: "available" } },+ },+ },+ };+ }++ it("uses exact trigger reads and re-reads a shifted page instead of merging a recreated anchor", async () => {+ const first = [trigger(" A ", "1"), trigger(" A", "2"), trigger(" a ", "3")];+ const replaced = trigger(" a ", "99");+ const last = trigger(" D ", "4");+ const listObjects = vi.fn().mockResolvedValueOnce(first).mockResolvedValueOnce([replaced, last]).mockResolvedValueOnce([first[0], first[1], replaced, last]);+ const { store, group } = await setup(listObjects);+ group.type = "group-triggers";+ group.label = "tree.triggers";+ group.catalog = " Catalog ";+ await store.loadObjectGroupChildren(group, { force: true });+ expect(listObjects.mock.calls[0][10]).toEqual({ identityMode: "exact", catalog: " Catalog " });+ expect(group.children!.slice(0, 2).map((node) => node.objectName)).toEqual([" A", " A "]);+ await store.loadMoreObjectGroupChildren(group.children!.at(-1)!);+ expect(listObjects.mock.calls.map((args) => args[6])).toEqual([0, 2, 0]);+ expect(listObjects.mock.calls[2][5]).toBe(5);+ expect(group.children).toHaveLength(4);+ expect(new Set(group.children!.map((node) => node.id)).size).toBe(4);+ expect(group.children!.every((node) => node.schema === " Trigger Owner " && node.parentSchema === " Parent Owner " && node.catalog === " Catalog ")).toBe(true);+ });++ it.each(["oracle", "dameng"] as const)("uses the same bounded trigger stream in %s simple mode", async (db_type) => {+ const listObjects = vi.fn().mockImplementation(async (...args: unknown[]) => (args[10] === true ? [] : [trigger(" Trigger ", "1")]));+ const listTables = vi.fn().mockResolvedValue([]);+ const { store } = await setup(listObjects, listTables);+ store.connections = [{ ...connection, db_type }];+ const { useSettingsStore } = await import("@/stores/settingsStore");+ useSettingsStore().editorSettings.sidebarObjectDisplay = "simple";+ const schema = store.treeNodes[0].children![0].children![0];+ schema.children = [];+ await store.loadTables(connection.id, "APP", "APP", { force: true });+ expect(listObjects.mock.calls.filter((args) => args[10] !== true)).toHaveLength(1);+ expect(listObjects.mock.calls[0][3]).toContain("TRIGGER");+ expect(listObjects.mock.calls[0][10]).toEqual({ identityMode: "exact" });+ expect(listTables).not.toHaveBeenCalled();+ expect(schema.children![0]).toMatchObject({ type: "trigger", objectName: " Trigger ", schema: " Trigger Owner ", parentSchema: " Parent Owner " });+ });++ it("keeps the parent entry bound to the returned trigger owner rather than the table owner", async () => {+ const info = trigger(" Trigger ", "1").trigger!;+ const listTriggers = vi.fn().mockResolvedValue([info]);+ const { store, group } = await setup(vi.fn(), undefined, listTriggers);+ group.type = "group-triggers";+ group.tableName = " Parent ";+ await store.loadTriggers(connection.id, "APP", " Parent ", " Parent Owner ", group.id, " Catalog ");+ expect(listTriggers).toHaveBeenCalledWith(connection.id, "APP", " Parent Owner ", " Parent ", " Catalog ", { identityMode: "exact", catalog: " Catalog " });+ expect(group.children![0]).toMatchObject({ type: "trigger", schema: " Trigger Owner ", objectName: " Trigger ", parentSchema: " Parent Owner ", parentName: " Parent ", parentType: "view", catalog: " Catalog " });+ });++ it("does not impose exact metadata on old mixed-object reads because of an Oracle-compatible JDBC label", async () => {+ const listObjects = vi.fn().mockImplementation(async (...args: unknown[]) => (args[10] === true ? [] : [procedure("P")]));+ const listTables = vi.fn().mockResolvedValue([{ name: "T", table_type: "TABLE" }]);+ const { store } = await setup(listObjects, listTables);+ store.connections = [{ ...connection, db_type: "jdbc", driver_label: "Oracle-compatible Yashan", connection_string: "jdbc:yasdb://fixture", database_info: { productName: "YashanDB" } }];+ const { useSettingsStore } = await import("@/stores/settingsStore");+ useSettingsStore().editorSettings.sidebarObjectDisplay = "simple";+ const schema = store.treeNodes[0].children![0].children![0];+ schema.children = [];+ await store.loadTables(connection.id, "APP", "APP", { force: true });+ await vi.waitFor(() => expect(listObjects).toHaveBeenCalledWith(connection.id, "APP", "APP", ["INDEX"], undefined, 3, 0, undefined, undefined, undefined, true));+ expect(listTables).toHaveBeenCalled();+ const ordinaryCalls = listObjects.mock.calls.filter((args) => !args[3]?.includes("INDEX"));+ expect(ordinaryCalls).toHaveLength(1);+ expect(ordinaryCalls[0][10]).toBeUndefined();+ });+it.each(["oracle", "oceanbase-oracle", "dameng"] as const)("adds exact %s indexes to the flat tree without changing the legacy table request", async (dbType) => {const listObjects = vi.fn().mockImplementation(async (...args: unknown[]) => (args[10] === true ? [{ name: " Ix(a) ", object_type: "INDEX", schema: " Mixed ", parent_schema: " Other ", parent_name: " T(a) " }] : []));const { store } = await setup(listObjects);@@ -105,6 +198,7 @@ describe("OceanBase Oracle sidebar paging (#11418)", () => {useSettingsStore().editorSettings.sidebarObjectDisplay = "simple";const schema = store.treeNodes[0].children![0].children![0];schema.children = [];+ store.setSidebarTableNameFilter(store.tableNameFilterScopeKey({ connectionId: connection.id, database: "APP", schema: "APP", nodeKind: "simple-tables" }), { includePatterns: ["%"], excludePatterns: [] });await store.loadTables(connection.id, "APP", "APP", { force: true });await vi.waitFor(() => expect(schema.children?.filter((node) => node.type === "load-more")).toHaveLength(2));const markers = schema.children!.filter((node) => node.type === "load-more");@@ -204,6 +298,7 @@ describe("OceanBase Oracle sidebar paging (#11418)", () => {useSettingsStore().editorSettings.sidebarObjectDisplay = "simple";const schema = store.treeNodes[0].children![0].children![0];schema.children = [];+ store.setSidebarTableNameFilter(store.tableNameFilterScopeKey({ connectionId: connection.id, database: "APP", schema: "APP", nodeKind: "simple-tables" }), { includePatterns: ["%"], excludePatterns: [] });await store.loadTables(connection.id, "APP", "APP", { force: true });await vi.waitFor(() => expect(ordinaryCalls).toBe(1));await store.loadTables(connection.id, "APP", "APP", { force: true });@@ -223,6 +318,7 @@ describe("OceanBase Oracle sidebar paging (#11418)", () => {useSettingsStore().editorSettings.sidebarObjectDisplay = "simple";const schema = store.treeNodes[0].children![0].children![0];schema.children = [];+ store.setSidebarTableNameFilter(store.tableNameFilterScopeKey({ connectionId: connection.id, database: "APP", schema: "APP", nodeKind: "simple-tables" }), { includePatterns: ["%"], excludePatterns: [] });await store.loadTables(connection.id, "APP", "APP", { force: true });await vi.waitFor(() => expect(schema.children?.find((node) => node.loadMore?.objectType === "INDEX")).toBeDefined());await store.loadMoreObjectGroupChildren(schema.children!.find((node) => node.loadMore?.objectType === "INDEX")!);diff --git a/apps/desktop/src/stores/__tests__/connectionStore.savePassword.spec.ts b/apps/desktop/src/stores/__tests__/connectionStore.savePassword.spec.tsindex b21932e981..575bcb5e7d 100644--- a/apps/desktop/src/stores/__tests__/connectionStore.savePassword.spec.ts+++ b/apps/desktop/src/stores/__tests__/connectionStore.savePassword.spec.ts@@ -80,6 +80,121 @@ describe("connectionStore save_password opt-out", () => {vi.restoreAllMocks();});+ it.each(["connect", "ensureConnected"] as const)("installs late OceanBase mode after %s finishes without saving the prompted password", async (entry) => {+ const metadata = deferred<{ productName: string; compatibilityMode: string }>();+ const saveInfo = vi.fn().mockResolvedValue(undefined);+ installApiMocks({ connectionDatabaseInfo: vi.fn(() => metadata.promise), saveConnectionDatabaseInfo: saveInfo });+ installPasswordPromptMock();+ requestPassword.mockResolvedValue({ password: "one-time-input", rememberPassword: false });+ const { useConnectionStore } = await import("@/stores/connectionStore");+ const store = useConnectionStore();+ const config = postgresConnection({ db_type: "jdbc", connection_string: "jdbc:oceanbase://localhost/db", save_password: false });+ store.connections = [config];+ store.treeNodes = [{ id: config.id, label: config.name, type: "connection", connectionId: config.id, children: [] }];+ if (entry === "connect") await store.connect(config);+ else await store.ensureConnected(config.id);+ expect(store.connectingIds.has(config.id)).toBe(false);+ expect(store.getConfig(config.id)?.password).toBe("");+ metadata.resolve({ productName: "OceanBase", compatibilityMode: "oracle" });+ await vi.waitFor(() => expect(saveInfo).toHaveBeenCalledExactlyOnceWith(config.id, expect.objectContaining({ compatibilityMode: "oracle" })));+ expect(store.getConfig(config.id)?.database_info?.compatibilityMode).toBe("oracle");+ expect(store.getConfig(config.id)?.password).toBe("");+ expect(store.treeNodes[0]?.children?.filter((node) => node.type === "database-job-admin")).toHaveLength(1);+ });++ it.each(["saved", "save-failed"] as const)("uses the exact persistent identity after remember-password is %s", async (result) => {+ const metadata = deferred<{ productName: string; compatibilityMode: string }>();+ const saveInfo = vi.fn().mockResolvedValue(undefined);+ installApiMocks({ connectionDatabaseInfo: vi.fn(() => metadata.promise), saveConnectionDatabaseInfo: saveInfo, ...(result === "save-failed" ? { saveConnections: vi.fn().mockRejectedValue(new Error("save_failed")) } : {}) });+ installPasswordPromptMock();+ requestPassword.mockResolvedValue({ password: "remembered-input", rememberPassword: true });+ const { useConnectionStore } = await import("@/stores/connectionStore");+ const store = useConnectionStore();+ const config = postgresConnection({ db_type: "jdbc", connection_string: "jdbc:oceanbase://localhost/db", save_password: false });+ store.connections = [config];+ await store.connect(config);+ metadata.resolve({ productName: "OceanBase", compatibilityMode: "oracle" });+ await vi.waitFor(() => expect(saveInfo).toHaveBeenCalledTimes(1));+ expect(store.getConfig(config.id)?.password).toBe(result === "saved" ? "remembered-input" : "");+ expect(store.getConfig(config.id)?.database_info?.compatibilityMode).toBe("oracle");+ });++ it.each(["host", "username", "disconnect", "new-attempt"] as const)("rejects late mode after %s changes the successful connection identity", async (change) => {+ const metadata = deferred<{ productName: string; compatibilityMode: string }>();+ const saveInfo = vi.fn().mockResolvedValue(undefined);+ installApiMocks({ connectionDatabaseInfo: vi.fn().mockReturnValueOnce(metadata.promise).mockResolvedValue(undefined), saveConnectionDatabaseInfo: saveInfo });+ installPasswordPromptMock();+ requestPassword.mockResolvedValue({ password: "one-time-input", rememberPassword: false });+ const { useConnectionStore } = await import("@/stores/connectionStore");+ const store = useConnectionStore();+ const config = postgresConnection({ db_type: "jdbc", connection_string: "jdbc:oceanbase://localhost/db", save_password: false });+ store.connections = [config];+ await store.connect(config);+ if (change === "disconnect") await store.disconnect(config.id);+ else if (change === "new-attempt") await store.connect(config);+ else store.getConfig(config.id)![change] = "changed";+ metadata.resolve({ productName: "OceanBase", compatibilityMode: "oracle" });+ await new Promise((resolve) => setTimeout(resolve, 0));+ if (change === "new-attempt") expect(saveInfo).toHaveBeenCalledExactlyOnceWith(config.id, expect.objectContaining({ productName: "jdbc", compatibilityMode: undefined }));+ else expect(saveInfo).not.toHaveBeenCalled();+ expect(store.getConfig(config.id)?.database_info?.compatibilityMode).toBeUndefined();+ expect(store.getConfig(config.id)?.password).toBe("");+ });++ it("does not install metadata when disconnect happens during its asynchronous save", async () => {+ const metadata = deferred<{ productName: string; compatibilityMode: string }>();+ const saved = deferred<void>();+ const saveInfo = vi.fn(() => saved.promise);+ installApiMocks({ connectionDatabaseInfo: vi.fn(() => metadata.promise), saveConnectionDatabaseInfo: saveInfo });+ installPasswordPromptMock();+ requestPassword.mockResolvedValue({ password: "one-time-input", rememberPassword: false });+ const { useConnectionStore } = await import("@/stores/connectionStore");+ const store = useConnectionStore();+ const config = postgresConnection({ db_type: "jdbc", save_password: false });+ store.connections = [config];+ await store.connect(config);+ metadata.resolve({ productName: "OceanBase", compatibilityMode: "oracle" });+ await vi.waitFor(() => expect(saveInfo).toHaveBeenCalledTimes(1));+ await store.disconnect(config.id);+ saved.resolve();+ await new Promise((resolve) => setTimeout(resolve, 0));+ expect(store.getConfig(config.id)?.database_info).toBeUndefined();+ });++ it("discards before-ready metadata after the connection attempt is cancelled", async () => {+ const metadata = deferred<{ productName: string; compatibilityMode: string }>();+ const saveInfo = vi.fn().mockResolvedValue(undefined);+ const readInfo = vi.fn(() => metadata.promise);+ installApiMocks({ connectionDatabaseInfo: readInfo, saveConnectionDatabaseInfo: saveInfo });+ installPasswordPromptMock();+ requestPassword.mockResolvedValue({ password: "one-time-input", rememberPassword: false });+ const { useConnectionStore } = await import("@/stores/connectionStore");+ const store = useConnectionStore();+ const config = postgresConnection({ db_type: "kingbase", save_password: false });+ store.connections = [config];+ const connecting = store.connect(config);+ const cancelled = expect(connecting).rejects.toThrow();+ await vi.waitFor(() => expect(readInfo).toHaveBeenCalledTimes(1));+ await store.cancelConnecting(config.id);+ metadata.resolve({ productName: "KingbaseES", compatibilityMode: "oracle" });+ await cancelled;+ expect(saveInfo).not.toHaveBeenCalled();+ expect(store.getConfig(config.id)?.database_info).toBeUndefined();+ });++ it("keeps the ordinary connection usable when optional metadata fails", async () => {+ installApiMocks({ connectionDatabaseInfo: vi.fn().mockRejectedValue(new Error("metadata_unavailable")) });+ installPasswordPromptMock();+ requestPassword.mockResolvedValue({ password: "one-time-input", rememberPassword: false });+ const { useConnectionStore } = await import("@/stores/connectionStore");+ const store = useConnectionStore();+ const config = postgresConnection({ db_type: "jdbc", save_password: false });+ store.connections = [config];+ await expect(store.connect(config)).resolves.toBe(config.id);+ expect(store.connectedIds.has(config.id)).toBe(true);+ expect(store.getConfig(config.id)?.password).toBe("");+ });+it.each(["postgres", "mysql", "redis"] as const)("ordinary close retires the %s transient password before disconnect", async (db_type) => {const calls: string[] = [];installApiMocks({diff --git a/apps/desktop/src/stores/__tests__/connectionStore.sidebarTableStorage.spec.ts b/apps/desktop/src/stores/__tests__/connectionStore.sidebarTableStorage.spec.tsindex 6cb5ac4b07..f66e198adf 100644--- a/apps/desktop/src/stores/__tests__/connectionStore.sidebarTableStorage.spec.ts+++ b/apps/desktop/src/stores/__tests__/connectionStore.sidebarTableStorage.spec.ts@@ -40,7 +40,10 @@ describe("connectionStore sidebar table storage", () => {checkConnectionHealth: vi.fn().mockResolvedValue(undefined),deleteSchemaCachePrefix: vi.fn().mockResolvedValue(undefined),listInstalledAgents: vi.fn().mockResolvedValue([]),- listObjects: vi.fn().mockResolvedValue([]),+ listObjects: vi.fn().mockResolvedValue([+ { name: "EXISTING_TABLE", schema: "APP", object_type: "TABLE" },+ { name: "NEW_TABLE", schema: "APP", object_type: "TABLE" },+ ]),listObjectStatistics,listTables,loadSchemaCache: vi.fn().mockResolvedValue(null),diff --git a/apps/desktop/src/stores/__tests__/nativeJobAdmin.navigation.spec.ts b/apps/desktop/src/stores/__tests__/nativeJobAdmin.navigation.spec.tsnew file mode 100644index 0000000000..c205f06826--- /dev/null+++ b/apps/desktop/src/stores/__tests__/nativeJobAdmin.navigation.spec.ts@@ -0,0 +1,108 @@+import { createPinia, setActivePinia } from "pinia";+import { beforeEach, describe, expect, it, vi } from "vitest";+import type { ConnectionConfig } from "@/types/database";+import { activeTabSidebarTarget } from "@/lib/sidebar/sidebarActiveTabTarget";+import { treeNodeRowAction } from "@/lib/sidebar/treeNodeClick";+import { connectionConfigFingerprint } from "@/lib/connection/connectionDatabaseInfo";++const mocks = vi.hoisted(() => ({+ saveOpenTabsState: vi.fn().mockResolvedValue(undefined),+ loadSchemaCache: vi.fn().mockResolvedValue(null),+ saveSchemaCache: vi.fn().mockResolvedValue(undefined),+ listSchemas: vi.fn().mockResolvedValue(["Owner"]),+ listDatabases: vi.fn().mockResolvedValue([{ name: "DB" }]),+ saveSidebarLayout: vi.fn().mockResolvedValue(undefined),+ checkConnectionHealth: vi.fn().mockResolvedValue(undefined),+ listInstalledAgents: vi.fn().mockResolvedValue([]),+ deleteSchemaCachePrefix: vi.fn().mockResolvedValue(undefined),+ saveConnectionDatabaseInfo: vi.fn().mockResolvedValue(undefined),+}));+vi.mock("@/lib/backend/api", () => mocks);+vi.mock("@/lib/backend/tauriRuntime", () => ({ isTauriRuntime: () => false }));++beforeEach(() => {+ vi.clearAllMocks();+ vi.stubGlobal("localStorage", { getItem: () => null, setItem: vi.fn(), removeItem: vi.fn() });+ setActivePinia(createPinia());+});++describe("native Job navigation through the real stores", () => {+ async function stores(db_type: ConnectionConfig["db_type"], overrides: Partial<ConnectionConfig> = {}) {+ const { useConnectionStore } = await import("@/stores/connectionStore");+ const { useQueryStore } = await import("@/stores/queryStore");+ const connection = { id: "c", name: "Test", db_type, host: "localhost", port: 1521, username: "Owner", password: "", database: "Service-not-owner", ...overrides };+ const connections = useConnectionStore();+ connections.addEphemeralConnection(connection);+ connections.treeNodes = [{ id: "c", label: "Test", type: "connection", connectionId: "c", children: [] }];+ return { connections, queries: useQueryStore() };+ }+ it("reuses one connection-level tab and sends new exact selections without mutating the caller", async () => {+ const { queries } = await stores("oracle");+ const first = { kind: "scheduler" as const, owner: "Owner.One", name: 'Job,"One' };+ const id = queries.openDatabaseJobAdmin("c", first);+ first.owner = "Changed outside";+ expect(queries.tabs[0]).toMatchObject({ id, mode: "database-jobs", database: "", nativeJobAdmin: { owner: "Owner.One", name: 'Job,"One' } });+ const again = queries.openDatabaseJobAdmin("c", { kind: "legacy", jobId: "900719925474099312345" });+ expect(again).toBe(id);+ expect(queries.tabs).toHaveLength(1);+ expect(queries.tabs[0]?.nativeJobAdmin).toEqual({ kind: "legacy", jobId: "900719925474099312345" });+ expect(activeTabSidebarTarget(queries.tabs[0])).toEqual({ type: "management", connectionId: "c", nodeType: "database-job-admin" });+ expect(treeNodeRowAction("database-job-admin", false, "double", "oracle")).toBe("toggle");+ }, 30_000);+ it("keeps the existing Dameng tab entry and does not create a second parallel page", async () => {+ const { queries } = await stores("dameng");+ const old = queries.openDamengJobAdmin("c");+ expect(queries.openDatabaseJobAdmin("c")).toBe(old);+ expect(queries.tabs).toHaveLength(1);+ expect(queries.tabs[0]?.mode).toBe("dameng-jobs");+ });+ it("replaces the Job utility category after actual JDBC metadata without replacing loaded nodes", async () => {+ const { connections, queries } = await stores("jdbc", { driver_label: "Dameng", connection_string: "jdbc:oceanbase://host/db" });+ await connections.loadDatabases("c", { force: true });+ const node = connections.treeNodes[0]!;+ node.isExpanded = true;+ const metadataChild = node.children!.find((child) => child.type !== "dameng-job-admin")!;+ expect(node.children!.some((child) => child.type === "dameng-job-admin")).toBe(true);+ await connections.updateConnectionDatabaseInfo("c", { productName: "OceanBase", compatibilityMode: "oracle" });+ expect(connections.treeNodes[0]).toBe(node);+ expect(node.isExpanded).toBe(true);+ expect(node.children).toContain(metadataChild);+ expect(node.children!.filter((child) => child.type === "database-job-admin" || child.type === "dameng-job-admin").map((child) => child.type)).toEqual(["database-job-admin"]);+ queries.openDatabaseJobAdmin("c");+ expect(queries.tabs[0]?.mode).toBe("database-jobs");+ await connections.updateConnectionDatabaseInfo("c", { productName: "OceanBase" });+ expect(connections.treeNodes[0]).toBe(node);+ expect(node.children).toContain(metadataChild);+ expect(node.children!.some((child) => child.type === "database-job-admin" || child.type === "dameng-job-admin")).toBe(false);+ });+ it("adds JDBC Job access when background mode arrives and ignores a changed-config response", async () => {+ const { connections } = await stores("jdbc", { connection_string: "jdbc:oceanbase://host/db" });+ await connections.loadDatabases("c", { force: true });+ const node = connections.treeNodes[0]!;+ expect(node.children!.some((child) => child.type === "database-job-admin")).toBe(false);+ await connections.updateConnectionDatabaseInfo("c", { productName: "OceanBase", compatibilityMode: "oracle" });+ expect(node.children!.filter((child) => child.type === "database-job-admin")).toHaveLength(1);+ const config = connections.getConfig("c")!;+ const fingerprint = connectionConfigFingerprint(config);+ let finish!: () => void;+ mocks.saveConnectionDatabaseInfo.mockImplementationOnce(+ () =>+ new Promise<void>((resolve) => {+ finish = resolve;+ }),+ );+ const pending = connections.updateConnectionDatabaseInfo("c", { productName: "OceanBase", compatibilityMode: "mysql" }, fingerprint);+ config.username = "Changed";+ finish();+ await pending;+ expect(connections.getConfig("c")?.database_info?.compatibilityMode).toBe("oracle");+ expect(node.children!.filter((child) => child.type === "database-job-admin")).toHaveLength(1);+ });+ it.each(["oracle", "oceanbase-oracle", "dameng", "xugu"] as const)("adds only the intended utility entry for %s and never duplicates it on reload", async (type) => {+ const { connections } = await stores(type);+ await connections.loadDatabases("c", { force: true });+ await connections.loadDatabases("c", { force: true });+ const entries = connections.treeNodes[0]?.children?.filter((node) => node.type === "database-job-admin" || node.type === "dameng-job-admin");+ expect(entries?.map((node) => node.type)).toEqual(type === "dameng" ? ["dameng-job-admin"] : type === "xugu" ? [] : ["database-job-admin"]);+ });+});diff --git a/apps/desktop/src/stores/__tests__/queryStore.oracleTriggerSource.spec.ts b/apps/desktop/src/stores/__tests__/queryStore.oracleTriggerSource.spec.tsnew file mode 100644index 0000000000..c63bae18a1--- /dev/null+++ b/apps/desktop/src/stores/__tests__/queryStore.oracleTriggerSource.spec.ts@@ -0,0 +1,356 @@+import { createPinia, setActivePinia } from "pinia";+import { beforeEach, describe, expect, it, vi } from "vitest";+import type { ConnectionConfig, ObjectSource, TreeNode, TriggerInfo } from "@/types/database";++const rpc = vi.hoisted(() => ({+ getObjectSource: vi.fn(),+ executeQuery: vi.fn(),+ prepareOracleTriggerSql: vi.fn(),+ checkConnectionHealth: vi.fn(async () => undefined),+ loadSchemaCache: vi.fn(async () => null),+ saveSchemaCache: vi.fn(async () => undefined),+ deleteSchemaCachePrefix: vi.fn(async () => undefined),+ saveOpenTabsState: vi.fn(async () => undefined),+ closeQuerySession: vi.fn(async () => undefined),+ closeClientConnectionSession: vi.fn(async () => undefined),+ listInstalledAgents: vi.fn(async () => []),+}));+vi.mock("@/lib/backend/api", () => rpc);+const ddl = 'CREATE OR REPLACE TRIGGER "Owner"."Trigger" BEFORE UPDATE ON "Parent"."T" DISABLE BEGIN NULL; END;';+let raw: ObjectSource;+beforeEach(async () => {+ vi.resetModules();+ vi.clearAllMocks();+ const storage = new Map<string, string>();+ vi.stubGlobal("localStorage", { getItem: (key: string) => storage.get(key) ?? null, setItem: (key: string, value: string) => storage.set(key, value), removeItem: (key: string) => storage.delete(key) });+ setActivePinia(createPinia());+ const { useConnectionStore } = await import("@/stores/connectionStore");+ const connections = useConnectionStore();+ connections.connections = [{ id: "source-trigger", name: "test", db_type: "oceanbase-oracle", username: "Owner", database: "service" } as ConnectionConfig];+ connections.connectedIds.add("source-trigger");+ raw = {+ name: "Trigger",+ schema: "Owner",+ object_type: "TRIGGER",+ source: ddl,+ editable: false,+ trigger: {+ name: "Trigger",+ event: "UPDATE",+ timing: "BEFORE",+ enabled: false,+ valid: true,+ oracle_metadata: {+ contractVersion: 1,+ identityMode: "exact",+ engine: "oceanbase-oracle",+ engineVersion: "4.2.5.7_107",+ owner: "Owner",+ name: "Trigger",+ objectId: "9007199254740993",+ scope: "TABLE",+ parent: { owner: "Parent", name: "T", objectType: "TABLE" },+ definition: { origin: "DBMS_METADATA", format: "ddl", complete: true },+ reads: { identity: { state: "available" }, scope: { state: "available" }, parent: { state: "available" }, enabled: { state: "available" }, validity: { state: "available" }, definition: { state: "available" }, errors: { state: "available" } },+ errors: [],+ },+ },+ };+ rpc.getObjectSource.mockImplementation(async () => JSON.parse(JSON.stringify(raw)));+ rpc.prepareOracleTriggerSql.mockImplementation(async (input) => ({ definition: input.source, comparisonSource: input.source, header: { scope: "RELATION", owner: "Parent", name: "T", viewOnly: false, pluggable: false }, requiresStateRestore: false }));+ rpc.executeQuery.mockImplementation(async (_id, _db, sql) => (sql.startsWith("SELECT") ? { columns: ["OWNER", "OBJECT_NAME", "OBJECT_TYPE", "OBJECT_ID"], rows: [["Parent", "T", "TABLE", "parent-id"]] } : { columns: [], rows: [] }));+});+async function open() {+ const { useQueryStore } = await import("@/stores/queryStore");+ const store = useQueryStore();+ const id = store.openObjectSourceTabPending({ connectionId: "source-trigger", database: "service", schema: "Owner", title: "Trigger", request: { name: "Trigger", objectType: "TRIGGER" } });+ await vi.waitFor(() => expect(store.tabs.find((tab) => tab.id === id)?.objectSource).toBeDefined());+ return { store, id, tab: store.tabs.find((tab) => tab.id === id)! };+}+describe("exact trigger bound source tabs", () => {+ it("does not let a delayed native readback overwrite the next container's verified tree state", async () => {+ const { store, id, tab } = await open();+ const { useConnectionStore } = await import("@/stores/connectionStore");+ const { buildSimpleObjectTreeNodes } = await import("@/lib/table/tableTree");+ const connections = useConnectionStore();+ connections.treeNodes = buildSimpleObjectTreeNodes({ nodeId: "schema", connectionId: "source-trigger", database: "service", schema: "Owner", objects: [{ name: raw.name, schema: raw.schema, object_type: "TRIGGER", trigger: structuredClone(raw.trigger) }] });+ store.updateSql(id, ddl + "\n-- keep my draft");+ let release!: () => void;+ const invalidation = vi+ .spyOn(connections, "invalidateOracleTriggerLists")+ .mockImplementationOnce(+ () =>+ new Promise<void>((resolve) => {+ release = resolve;+ }),+ )+ .mockResolvedValue(undefined);+ rpc.executeQuery.mockImplementation(async (_id, _db, sql) => {+ raw.trigger!.enabled = sql.endsWith(" ENABLE;");+ return { columns: [], rows: [] };+ });+ const { useSqlExecutionDangerStore } = await import("@/stores/sqlExecutionDangerStore");+ const danger = useSqlExecutionDangerStore();+ const first = store.runOracleTriggerSourceAction(id, "enable");+ await vi.waitFor(() => expect(danger.pending).toBeDefined());+ danger.confirm();+ await vi.waitFor(() => expect(release).toBeDefined());+ const { prepareOracleTriggerPlan, executeOracleTriggerPlan } = await import("@/lib/database/oracleTriggerPlan");+ const secondPlan = await prepareOracleTriggerPlan({ target: { connectionId: "source-trigger", database: "service", owner: "Owner", name: "Trigger", executionSchema: "Owner" }, action: "disable" });+ const second = await executeOracleTriggerPlan(secondPlan, { confirmed: true, isCurrent: () => true });+ expect(second.steps[0].state).toBe("committed");+ expect((connections.treeNodes[0].meta as TriggerInfo).enabled).toBe(false);+ release();+ expect(await first).toBe(true);+ expect(store.oracleTriggerSourceState(id)?.result?.steps[0]).toMatchObject({ state: "committed", verification: "applied" });+ expect((connections.treeNodes[0].meta as TriggerInfo).enabled).toBe(false);+ expect(rpc.executeQuery.mock.calls.map((call) => call[2])).toEqual(['ALTER TRIGGER "Owner"."Trigger" ENABLE;', 'ALTER TRIGGER "Owner"."Trigger" DISABLE;']);+ expect(tab.sql).toBe(ddl + "\n-- keep my draft");+ invalidation.mockRestore();+ });++ it.each(["committed", "unknown", "recreated"])("updates only the verified physical tree entries after a bound native action (%s)", async (outcome) => {+ const { store, id, tab } = await open();+ const { useConnectionStore } = await import("@/stores/connectionStore");+ const { buildSimpleObjectTreeNodes } = await import("@/lib/table/tableTree");+ const connections = useConnectionStore();+ const node = buildSimpleObjectTreeNodes({ nodeId: "schema", connectionId: "source-trigger", database: "service", schema: "Owner", objects: [{ name: raw.name, schema: raw.schema, object_type: "TRIGGER", trigger: structuredClone(raw.trigger) }] })[0];+ const parentCopy = { ...structuredClone(node), id: "parent-copy" };+ const recreated = { ...structuredClone(node), id: "new-physical" };+ (recreated.meta as TriggerInfo).oracle_metadata!.objectId = "other-id";+ const otherCatalog = { ...structuredClone(node), id: "other-catalog", catalog: "Other" };+ const otherOwner = { ...structuredClone(node), id: "other-owner", schema: "Other" };+ (otherOwner.meta as TriggerInfo).oracle_metadata!.owner = "Other";+ connections.treeNodes = [{ id: "root", type: "connection", label: "test", children: [node, parentCopy, recreated, otherCatalog, otherOwner] } as TreeNode];+ store.updateSql(id, ddl + "\n-- keep my draft");+ rpc.executeQuery.mockImplementation(async (_id, _db, sql) => {+ if (sql.startsWith("SELECT")) return { columns: ["OWNER", "OBJECT_NAME", "OBJECT_TYPE", "OBJECT_ID"], rows: [["Parent", "T", "TABLE", "parent-id"]] };+ raw.trigger!.enabled = true;+ raw.trigger!.valid = false;+ if (outcome === "unknown") throw new Error("reply lost");+ if (outcome === "recreated") raw.trigger!.oracle_metadata!.objectId = "replacement-id";+ return { columns: [], rows: [] };+ });+ const { useSqlExecutionDangerStore } = await import("@/stores/sqlExecutionDangerStore");+ const danger = useSqlExecutionDangerStore();+ const pending = store.runOracleTriggerSourceAction(id, "enable");+ await vi.waitFor(() => expect(danger.pending).toBeDefined());+ danger.confirm();+ await pending;+ const children = connections.treeNodes[0].children!;+ for (const index of [0, 1]) {+ expect(children[index]).toMatchObject({ valid: outcome !== "committed", meta: { enabled: outcome === "committed", valid: outcome !== "committed" } });+ if (outcome === "committed") expect(children[index]).not.toBe(index === 0 ? node : parentCopy);+ }+ expect(children.slice(2)).toEqual([recreated, otherCatalog, otherOwner]);+ expect(tab.sql).toBe(ddl + "\n-- keep my draft");+ expect(rpc.executeQuery.mock.calls.filter((call) => !call[2].startsWith("SELECT"))).toHaveLength(1);+ });++ it("rejects a native action on a same-name replacement before opening confirmation", async () => {+ const { store, id, tab } = await open();+ raw.trigger!.oracle_metadata!.objectId = "replacement-id";+ const { useSqlExecutionDangerStore } = await import("@/stores/sqlExecutionDangerStore");+ const danger = useSqlExecutionDangerStore();+ let settled = false;+ const pending = store.runOracleTriggerSourceAction(id, "compile").finally(() => {+ settled = true;+ });+ await vi.waitFor(() => expect(settled || !!danger.pending).toBe(true));+ const confirmed = !!danger.pending;+ danger.cancelAll();+ await pending;+ expect(confirmed).toBe(false);+ expect(store.oracleTriggerSourceState(id)?.baseline?.metadata.objectId).toBe("9007199254740993");+ expect(tab.sql).toBe(ddl);+ expect(rpc.executeQuery).not.toHaveBeenCalled();+ });++ it.each(["identity", "definition"])("retains the loaded baseline when native readback finds changed %s after dispatch", async (change) => {+ const { store, id, tab } = await open();+ store.updateSql(id, ddl + "\n-- keep my draft");+ const draft = tab.sql;+ rpc.executeQuery.mockImplementation(async () => {+ if (change === "identity") raw.trigger!.oracle_metadata!.objectId = "replacement-id";+ else raw.source = ddl.replace("NULL;", "other_session_proc;");+ return { columns: [], rows: [] };+ });+ const { useSqlExecutionDangerStore } = await import("@/stores/sqlExecutionDangerStore");+ const danger = useSqlExecutionDangerStore();+ const pending = store.runOracleTriggerSourceAction(id, "compile");+ await vi.waitFor(() => expect(danger.pending).toBeDefined());+ danger.confirm();+ await expect(pending).resolves.toBe(false);+ expect(store.oracleTriggerSourceState(id)?.result?.steps[0]).toMatchObject({ state: "unknown", verification: "mismatch" });+ expect(store.oracleTriggerSourceState(id)?.baseline?.metadata.objectId).toBe("9007199254740993");+ expect(store.oracleTriggerSourceState(id)?.baseline?.raw.source).toBe(ddl);+ expect(store.oracleTriggerSourceState(id)?.error).toContain("reload");+ expect(tab.sql).toBe(draft);+ expect(store.isTabDirty(tab)).toBe(true);+ expect(rpc.executeQuery).toHaveBeenCalledOnce();+ });++ it.each([false, true])("keeps dispatched native results on the originating read generation (refresh=%s)", async (refresh) => {+ const { store, id, tab } = await open();+ store.updateSql(id, ddl + "\n-- original dirty draft");+ const draft = tab.sql;+ let finish!: () => void;+ rpc.executeQuery.mockImplementation(+ () =>+ new Promise((resolve) => {+ finish = () => resolve({ columns: [], rows: [] });+ }),+ );+ const { useSqlExecutionDangerStore } = await import("@/stores/sqlExecutionDangerStore");+ const danger = useSqlExecutionDangerStore();+ const pending = store.runOracleTriggerSourceAction(id, "compile");+ await vi.waitFor(() => expect(danger.pending).toBeDefined());+ danger.confirm();+ await vi.waitFor(() => expect(finish).toBeDefined());+ const otherId = store.createTab("source-trigger", "service", "Other", "query", "Other", "SELECT 42");+ if (refresh) {+ store.refreshObjectSourceTab(id);+ // The existing physical source lock rejects a reload while DDL is in flight.+ await vi.waitFor(() => expect(tab.sourceLoad?.error).toBeTruthy());+ }+ finish();+ await expect(pending).resolves.toBe(true);+ if (refresh) expect(store.oracleTriggerSourceState(id)?.result).toBeUndefined();+ else expect(store.oracleTriggerSourceState(id)?.result?.steps[0]).toMatchObject({ state: "committed", verification: "valid" });+ expect(tab.sql).toBe(draft);+ expect(store.isTabDirty(tab)).toBe(true);+ expect(store.tabs.find((item) => item.id === otherId)?.sql).toBe("SELECT 42");+ expect(store.oracleTriggerSourceState(otherId)).toBeUndefined();+ expect(rpc.executeQuery).toHaveBeenCalledOnce();+ if (refresh) {+ store.refreshObjectSourceTab(id);+ await vi.waitFor(() => expect(tab.sourceLoad).toBeUndefined());+ expect(tab.sql).toBe(draft);+ expect(store.oracleTriggerSourceState(id)?.result).toBeUndefined();+ }+ });++ it("invalidates unissued native confirmation as soon as a source refresh starts", async () => {+ const { store, id, tab } = await open();+ const { useSqlExecutionDangerStore } = await import("@/stores/sqlExecutionDangerStore");+ const danger = useSqlExecutionDangerStore();+ const pending = store.runOracleTriggerSourceAction(id, "compile");+ await vi.waitFor(() => expect(danger.pending).toBeDefined());+ let finish!: () => void;+ rpc.getObjectSource.mockImplementation(+ () =>+ new Promise((resolve) => {+ finish = () => resolve(JSON.parse(JSON.stringify(raw)));+ }),+ );+ store.refreshObjectSourceTab(id);+ const confirmationStillOpen = !!danger.pending;+ danger.cancelAll();+ await expect(pending).resolves.toBe(false);+ await vi.waitFor(() => expect(finish).toBeDefined());+ finish();+ await vi.waitFor(() => expect(tab.sourceLoad).toBeUndefined());+ expect(confirmationStillOpen).toBe(false);+ expect(rpc.executeQuery).not.toHaveBeenCalled();+ });++ it("uses the existing one-shot editor reveal without changing a dirty source or guessing a replacement identity", async () => {+ raw.source = raw.source.replace("CREATE OR REPLACE ", "");+ raw.trigger!.oracle_metadata!.definition = { origin: "ALL_SOURCE", format: "declaration", complete: true };+ const { store, id, tab } = await open();+ store.updateSql(id, "-- unsaved comment\nCREATE OR REPLACE " + raw.source);+ const draft = tab.sql;+ const position = raw.source.indexOf("BEGIN") + 1;+ expect(store.revealOracleTriggerSourceError(id, { line: 1, position }, "9007199254740993")).toBe(true);+ expect(tab.editorRevealRequest).toMatchObject({ line: 2, column: tab.sql.split("\n")[1].indexOf("BEGIN") + 1 });+ expect(tab.sql).toBe(draft);+ expect(store.isTabDirty(tab)).toBe(true);+ tab.editorRevealRequest = undefined;+ expect(store.revealOracleTriggerSourceError(id, { line: 1, position }, "replacement-id")).toBe(false);+ expect(tab.editorRevealRequest).toBeUndefined();+ expect(rpc.executeQuery).not.toHaveBeenCalled();+ });++ it.each([false, true])("keeps diagnostic readback on its original tab and preserves the loaded baseline when external source changed (%s)", async (changed) => {+ const { store, id, tab } = await open();+ const loaded = store.oracleTriggerSourceState(id)!.baseline!;+ store.updateSql(id, tab.sql + "\n-- keep my draft");+ const draft = tab.sql;+ if (changed) raw.source += "\n-- another session's source";+ const { prepareOracleTriggerPlan, executeOracleTriggerPlan } = await import("@/lib/database/oracleTriggerPlan");+ const plan = await prepareOracleTriggerPlan({ target: loaded.target, action: "compile", expectedObjectId: loaded.metadata.objectId! });+ const otherId = store.createTab("source-trigger", "service", "Other", "query", "Other", "SELECT 42");+ const other = store.tabs.find((item) => item.id === otherId)!;+ const result = await executeOracleTriggerPlan(plan, { confirmed: true, isCurrent: () => true });+ const readVersion = store.oracleTriggerSourceState(id)?.readVersion;+ store.acceptOracleTriggerDiagnosticResult(id, result, plan.before, readVersion);+ expect(store.oracleTriggerSourceState(id)?.result?.steps[0].state).toBe("committed");+ expect(store.oracleTriggerSourceState(id)?.baseline?.raw.source).toBe(changed ? loaded.raw.source : result.snapshot!.raw.source);+ if (changed) expect(store.oracleTriggerSourceState(id)?.error).toContain("reload");+ expect(store.oracleTriggerSourceState(id)?.readVersion).toBe(readVersion);+ expect(tab.sql).toBe(draft);+ expect(store.isTabDirty(tab)).toBe(true);+ expect(other.sql).toBe("SELECT 42");+ expect(store.oracleTriggerSourceState(otherId)).toBeUndefined();+ const previousResult = store.oracleTriggerSourceState(id)!.result;+ store.refreshObjectSourceTab(id);+ store.acceptOracleTriggerDiagnosticResult(id, { ...result, refreshError: "late stale feedback" }, plan.before, readVersion);+ expect(store.oracleTriggerSourceState(id)?.result).toBe(previousResult);+ await vi.waitFor(() => expect(tab.sourceLoad).toBeUndefined());+ expect(store.oracleTriggerSourceState(id)?.result).toBeUndefined();+ expect(tab.sql).toBe(draft);+ });++ it("uses the same plan and SQL confirmation for Save and a direct full-definition Run, never the generic query executor", async () => {+ const { store, id, tab } = await open();+ const { useSqlExecutionDangerStore } = await import("@/stores/sqlExecutionDangerStore");+ const danger = useSqlExecutionDangerStore();+ expect(store.oracleTriggerSourceState(id)?.baseline?.metadata.parent?.owner).toBe("Parent");+ const pending = store.executeTabSql(id, tab.sql);+ await vi.waitFor(() => expect(danger.pending).toBeDefined());+ expect(danger.pending?.sql).toBe(ddl);+ danger.confirm();+ await pending;+ expect(store.oracleTriggerSourceState(id)?.result?.steps[0]).toMatchObject({ state: "committed", verification: "applied" });+ expect(rpc.executeQuery.mock.calls.filter((call) => !call[2].startsWith("SELECT"))).toHaveLength(1);+ const second = store.runOracleTriggerSourceAction(id);+ await vi.waitFor(() => expect(danger.pending).toBeDefined());+ danger.cancel();+ await second;+ expect(rpc.executeQuery.mock.calls.filter((call) => !call[2].startsWith("SELECT"))).toHaveLength(1);+ });++ it("blocks arbitrary/partial SQL on a bound exact trigger tab and leaves its draft intact", async () => {+ const { store, id, tab } = await open();+ await store.executeTabSql(id, "DROP TABLE Parent.T");+ expect(store.oracleTriggerSourceState(id)?.error).toBeTruthy();+ expect(tab.sql).toBe(ddl);+ expect(rpc.executeQuery).not.toHaveBeenCalled();+ });++ it("cancels the source confirmation on tab switch without executing its DDL", async () => {+ const { store, id, tab } = await open();+ const { useSqlExecutionDangerStore } = await import("@/stores/sqlExecutionDangerStore");+ const danger = useSqlExecutionDangerStore();+ const pending = store.runOracleTriggerSourceAction(id);+ await vi.waitFor(() => expect(danger.pending).toBeDefined());+ store.createTab("source-trigger", "service", "Other query");+ await expect(pending).resolves.toBe(false);+ expect(danger.pending).toBeUndefined();+ expect(tab.sql).toBe(ddl);+ expect(rpc.executeQuery.mock.calls.every((call) => call[2].startsWith("SELECT"))).toBe(true);+ });++ it("keeps a dirty manual correction through an explicit authority refresh", async () => {+ const { store, id, tab } = await open();+ const draft = `${ddl}\n-- unfinished correction`;+ store.updateSql(id, draft);+ raw.source = `${ddl}\n-- latest server source`;+ expect(store.refreshObjectSourceTab(id)).toBe(true);+ await vi.waitFor(() => expect(tab.sourceLoad).toBeUndefined());+ expect(tab.sql).toBe(draft);+ expect(store.isTabDirty(tab)).toBe(true);+ expect(store.oracleTriggerSourceState(id)?.baseline?.raw.source).toBe(raw.source);+ expect(rpc.executeQuery).not.toHaveBeenCalled();+ });+});diff --git a/apps/desktop/src/stores/connectionStore.ts b/apps/desktop/src/stores/connectionStore.tsindex f5e8eb04eb..0c40bd0a44 100644--- a/apps/desktop/src/stores/connectionStore.ts+++ b/apps/desktop/src/stores/connectionStore.ts@@ -6,6 +6,8 @@ import { containsHan, orderedSubsequenceSpan, pinyinFirstLetters } from "@/lib/cimport { ref, computed, watch, markRaw, reactive } from "vue";import { DEFAULT_QUERY_TIMEOUT_SECS, normalizeManualTransactionTimeoutSecs } from "@/lib/connection/timeoutLimits";import { gaussdbConnectionMode } from "@/lib/database/jdbcDialect";+import { exactOracleTriggerMetadata, exactOracleTriggerNodeMetadata, oracleTriggerIdentityKey, oracleTriggerReadOptions, oracleTriggerObjectReadOptions } from "@/lib/database/oracleTriggerIdentity";+import { nativeJobAdminEngine } from "@/lib/database/nativeJobAdmin";import { supportsSchemaIndexManagement } from "@/lib/database/databaseObjectCapabilities";import { notifyComponentUpdatesChanged } from "@/lib/updates/componentUpdateEvents";import type {@@ -30,6 +32,7 @@ import type {TableNameFilter,TableInfo,TreeNode,+ TriggerInfo,VectorCollectionMeta,} from "@/types/database";import {@@ -1966,7 +1969,17 @@ export const useConnectionStore = defineStore("connection", () => {// as metadata children, withConnectionUtilityNodes would keep the old copies// AND append fresh ones on every useCachedChildren pass, duplicating the// 用户/角色 menus once per refresh cycle.- return node.type === "oracle-db-links" || node.type === "user-admin" || node.type === "xugu-user-admin" || node.type === "dameng-users" || node.type === "dameng-roles" || node.type === "dameng-job-admin" || node.type === "group-tablespaces" || node.type === "saved-sql-root";+ return (+ node.type === "oracle-db-links" ||+ node.type === "user-admin" ||+ node.type === "xugu-user-admin" ||+ node.type === "dameng-users" ||+ node.type === "dameng-roles" ||+ node.type === "dameng-job-admin" ||+ node.type === "database-job-admin" ||+ node.type === "group-tablespaces" ||+ node.type === "saved-sql-root"+ );}function connectionMetadataChildren(children: TreeNode[] | undefined): TreeNode[] {@@ -2283,7 +2296,7 @@ export const useConnectionStore = defineStore("connection", () => {function buildDamengJobAdminNode(connectionId: string, existingConnectionNode?: TreeNode): TreeNode | undefined {const config = getConfig(connectionId);- if (effectiveDatabaseTypeForConnection(config) !== "dameng") return undefined;+ if (nativeJobAdminEngine(config) !== "dameng") return undefined;const existing = existingConnectionNode?.children?.find((child) => child.type === "dameng-job-admin");return {id: `${connectionId}:__dameng_jobs`,@@ -2295,6 +2308,13 @@ export const useConnectionStore = defineStore("connection", () => {};}+ function buildDatabaseJobAdminNode(connectionId: string): TreeNode | undefined {+ const config = getConfig(connectionId);+ const engine = nativeJobAdminEngine(config);+ if (!engine || engine === "dameng") return;+ return { id: `${connectionId}:__native_jobs`, label: "tree.nativeJobs", type: "database-job-admin", connectionId, database: "", isExpanded: false };+ }+function buildXuguTablespacesNode(connectionId: string, existingConnectionNode?: TreeNode): TreeNode | undefined {const config = getConfig(connectionId);if (effectiveDatabaseTypeForConnection(config) !== "xugu") return undefined;@@ -2367,7 +2387,7 @@ export const useConnectionStore = defineStore("connection", () => {const damengRoleNode = buildDamengRoleNode(connectionId, existingConnectionNode);const damengJobAdminNode = buildDamengJobAdminNode(connectionId, existingConnectionNode);const xuguTablespacesNode = buildXuguTablespacesNode(connectionId, existingConnectionNode);- return [...nonUtilityChildren, buildOracleDatabaseLinksNode(connectionId, existingConnectionNode), userAdminNode, xuguUserAdminNode, damengUserNode, damengRoleNode, damengJobAdminNode, xuguTablespacesNode].filter(Boolean) as TreeNode[];+ return [...nonUtilityChildren, buildOracleDatabaseLinksNode(connectionId, existingConnectionNode), userAdminNode, xuguUserAdminNode, damengUserNode, damengRoleNode, damengJobAdminNode, buildDatabaseJobAdminNode(connectionId), xuguTablespacesNode].filter(Boolean) as TreeNode[];}function withSavedSqlRoot(connectionId: string, children: TreeNode[], existingConnectionNode?: TreeNode): TreeNode[] {@@ -2425,6 +2445,7 @@ export const useConnectionStore = defineStore("connection", () => {if (config?.db_type === "opengauss" && databaseCompatibilityMode(config.id, database)?.trim().toUpperCase() === "A") {scopedVersion = `${scopedVersion}-a-packages-v1`;}+ if (oracleTriggerReadOptions(effectiveDatabaseTypeForConnection(config))) scopedVersion += "-oracle-trigger-exact-v1";return ownerAwareMetadataCacheVersion(config, scopedVersion, schema);}@@ -2609,6 +2630,10 @@ export const useConnectionStore = defineStore("connection", () => {return connectionId ? metadataDriverProfile(getConfig(connectionId)) : undefined;}+ function triggerObjectReadOptions(connectionId: string, objectTypes?: readonly string[], catalog?: string) {+ return oracleTriggerObjectReadOptions(getConfig(connectionId), objectTypes, catalog);+ }+function metadataListCacheScope(options: {kind: string;connectionId?: string | null;@@ -2622,6 +2647,7 @@ export const useConnectionStore = defineStore("connection", () => {sidebarDisplayMode?: string | null;extra?: MetadataScopeInput["extra"];}): MetadataScopeInput {+ const extra = ["object-list-page", "sidebar-object-search-page"].includes(options.kind) && options.connectionId && triggerObjectReadOptions(options.connectionId, options.objectTypes ?? undefined) ? { ...options.extra, oracleTriggerContract: 1 } : options.extra;return {kind: options.kind,connectionId: options.connectionId,@@ -2634,7 +2660,7 @@ export const useConnectionStore = defineStore("connection", () => {offset: options.offset,sidebarDisplayMode: options.sidebarDisplayMode,driverProfile: metadataListDriverProfile(options.connectionId || undefined),- extra: options.extra?.exactIdentity === true && options.connectionId ? { ...options.extra, connectionRevision: connectionStateRevision(options.connectionId), metadataGeneration: metadataGenerationFor(options.connectionId, options.database ?? undefined) } : options.extra,+ extra: extra?.exactIdentity === true && options.connectionId ? { ...extra, connectionRevision: connectionStateRevision(options.connectionId), metadataGeneration: metadataGenerationFor(options.connectionId, options.database ?? undefined) } : extra,};}@@ -2746,6 +2772,55 @@ export const useConnectionStore = defineStore("connection", () => {void invalidateObjectDdlCache(match);}+ function syncOracleTriggerNodeState(target: { connectionId: string; database: string; catalog?: string; owner: string; name: string }, trigger: TriggerInfo) {+ const metadata = exactOracleTriggerMetadata(trigger);+ if (!metadata?.objectId || metadata.owner !== target.owner || metadata.name !== target.name) return;+ const enabled = metadata.reads.enabled?.state === "available" && typeof trigger.enabled === "boolean" ? trigger.enabled : undefined;+ const valid = metadata.reads.validity?.state === "available" && typeof trigger.valid === "boolean" ? trigger.valid : undefined;+ const visit = (nodes: TreeNode[]) => {+ for (let index = 0; index < nodes.length; index++) {+ const node = nodes[index];+ const current = exactOracleTriggerNodeMetadata(node);+ if (node.connectionId === target.connectionId && node.database === target.database && node.catalog === target.catalog && current?.owner === metadata.owner && current.name === metadata.name && current.objectId === metadata.objectId) {+ // Trigger leaves are raw; replace the leaf so both tree layouts and pins render the readback.+ nodes.splice(index, 1, markRaw({ ...node, valid, meta: { ...(node.meta as TriggerInfo), enabled, valid, oracle_metadata: JSON.parse(JSON.stringify(metadata)) } }));+ } else if (node.children) visit(node.children);+ }+ };+ visit(treeNodes.value);+ }++ async function invalidateOracleTriggerLists(target: { connectionId: string; database: string; catalog?: string; owner: string }, parents: readonly { owner: string; name: string }[]) {+ // Invalidate discovery lists, not table columns/indexes/constraints or editor drafts.+ for (const schema of new Set([target.owner, ...parents.map((parent) => parent.owner)])) {+ const match = { connectionId: target.connectionId, database: target.database, schema };+ metadataListPageCache.invalidate(match);+ invalidateObjectBrowserRowsCache(match);+ }+ const prefixes = new Set<string>();+ const visit = (nodes: TreeNode[]) => {+ for (const node of nodes) {+ if (+ node.connectionId === target.connectionId &&+ node.database === target.database &&+ node.catalog === target.catalog &&+ node.type === "group-triggers" &&+ (node.tableName ? parents.some((parent) => parent.owner === node.schema && parent.name === node.tableName) : node.schema === target.owner)+ ) {+ clearLoadedChildrenCache(node.id, { deletePersisted: false, skipMetadataInvalidation: true });+ treeNodeLoads.invalidatePrefix(node.id);+ prefixes.add(`${node.id}:`);+ prefixes.add(`${schemaCacheKey(node.id)}:`);+ }+ if (node.children) visit(node.children);+ if (node.hiddenChildren) visit(node.hiddenChildren);+ }+ };+ visit(treeNodes.value);+ const results = await Promise.allSettled([...prefixes].map((prefix) => api.deleteSchemaCachePrefix(prefix)));+ for (const result of results) if (result.status === "rejected") throw result.reason;+ }+type PagedTableWindow = {children: TreeNode[];objectCount: number;@@ -2764,11 +2839,12 @@ export const useConnectionStore = defineStore("connection", () => {schema?: string | null;parent_schema?: string | null;parent_name?: string | null;+ trigger?: TriggerInfo | null;};function tablePageAnchorKeyOf(row: PagedRowIdentity, fallbackSchema?: string) {// Partitioned tables need the parent in the key: their child tables may share a name.- return tablePageRowAnchorKey(row.name, row.parent_schema ?? row.schema ?? fallbackSchema, row.parent_name);+ return tablePageRowAnchorKey(row.name, row.parent_schema ?? row.schema ?? fallbackSchema, row.parent_name, row.trigger);}/**@@ -2814,6 +2890,7 @@ export const useConnectionStore = defineStore("connection", () => {connectionId: parent.connectionId,database: parent.database,schema: parent.schema,+ catalog: parent.catalog,isLoading: false,loadMore: {parentId: parent.id,@@ -2837,6 +2914,7 @@ export const useConnectionStore = defineStore("connection", () => {connectionId: options.node.connectionId || "",database: options.node.database || "",schema: options.effectiveSchema,+ catalog: options.node.catalog,objects: options.objects.filter((object) => options.objectTypes.includes(normalizedObjectTreeKind(object.object_type))),databaseType,groupNodeType: options.node.type,@@ -2885,6 +2963,8 @@ export const useConnectionStore = defineStore("connection", () => {}function treeNodeObjectIdentity(node: TreeNode): string {+ const trigger = exactOracleTriggerNodeMetadata(node);+ if (trigger) return oracleTriggerIdentityKey(trigger, node.catalog);return `${node.type}\0${node.schema || ""}\0${node.label}`;}@@ -2897,6 +2977,7 @@ export const useConnectionStore = defineStore("connection", () => {const key = treeNodeObjectIdentity(child);const existingNode = existing.get(key);if (existingNode) {+ if (exactOracleTriggerNodeMetadata(child)) Object.assign(existingNode, child);if (child.type === "package" && child.xuguPackageBodyAvailable === true) {existingNode.xuguPackageBodyAvailable = true;existingNode.xuguPackageBodyValid = child.xuguPackageBodyValid;@@ -3020,7 +3101,8 @@ export const useConnectionStore = defineStore("connection", () => {catalog: options.node.catalog,});const tableNameFilter = effectiveTableNameFilterForNode(options.node, userTableNameFilter);- const paginate = exactIdentity || !searchFilter || getConfig(options.node.connectionId)?.db_type === "oceanbase-oracle";+ const readOptions = triggerObjectReadOptions(options.node.connectionId, options.objectTypes, options.node.catalog);+ const paginate = exactIdentity || !searchFilter || getConfig(options.node.connectionId)?.db_type === "oceanbase-oracle" || !!readOptions;const fetchLimit = paginate ? options.pageSize + 1 : undefined;const fetchOffset = paginate ? options.offset : undefined;const cacheOwner = exactIdentity ? treeNodeLoads.observe(options.node.id) : undefined;@@ -3041,9 +3123,11 @@ export const useConnectionStore = defineStore("connection", () => {() =>exactIdentity? api.listObjects(options.node.connectionId!, options.node.database!, querySchema, options.objectTypes, searchFilter, fetchLimit, fetchOffset, options.node.catalog, tableNameFilter, undefined, true)- : tableNameFilter || options.node.catalog- ? api.listObjects(options.node.connectionId!, options.node.database!, options.querySchema, options.objectTypes, searchFilter, fetchLimit, fetchOffset, options.node.catalog, tableNameFilter)- : api.listObjects(options.node.connectionId!, options.node.database!, options.querySchema, options.objectTypes, searchFilter, fetchLimit, fetchOffset),+ : readOptions+ ? api.listObjects(options.node.connectionId!, options.node.database!, querySchema, options.objectTypes, searchFilter, fetchLimit, fetchOffset, options.node.catalog, tableNameFilter, undefined, readOptions)+ : tableNameFilter || options.node.catalog+ ? api.listObjects(options.node.connectionId!, options.node.database!, options.querySchema, options.objectTypes, searchFilter, fetchLimit, fetchOffset, options.node.catalog, tableNameFilter)+ : api.listObjects(options.node.connectionId!, options.node.database!, options.querySchema, options.objectTypes, searchFilter, fetchLimit, fetchOffset),{ force: options.force, isCurrent: cacheOwner ? () => cacheOwner.isCurrent() : undefined },);const hasMore = paginate && objects.length > options.pageSize;@@ -3092,7 +3176,7 @@ export const useConnectionStore = defineStore("connection", () => {const childrenFromObjects = () => {const children = groupTypes? objectGroupChildrenFromObjects({ node, parentNodeId: objectGroupRefreshParentId(node) ?? node.id, effectiveSchema, objectTypes, objects })- : markPackageNodesExpandable(buildSimpleObjectTreeNodes({ nodeId: node.id, connectionId, database: node.database!, schema: effectiveSchema, objects, databaseType: effectiveDatabaseTypeForConnection(config) }));+ : markPackageNodesExpandable(buildSimpleObjectTreeNodes({ nodeId: node.id, connectionId, database: node.database!, schema: effectiveSchema, catalog: node.catalog, objects, databaseType: effectiveDatabaseTypeForConnection(config) }));return children.map((child) => ({ ...child, catalog: node.catalog, linkedServer: node.linkedServer, linkedCatalog: node.linkedCatalog, linkedSchema: node.linkedSchema }));};const publish = () => {@@ -3100,6 +3184,7 @@ export const useConnectionStore = defineStore("connection", () => {};for (const request of requestGroups) {if (!request.objectTypes.length) continue;+ const readOptions = triggerObjectReadOptions(connectionId, request.objectTypes, node.catalog);const groupStart = objects.length;const pageScope = (offset: number) =>metadataListCacheScope({@@ -3127,7 +3212,9 @@ export const useConnectionStore = defineStore("connection", () => {try {const rows = request.exactIdentity? await api.listObjects(connectionId, node.database!, request.schema, request.objectTypes, query, pageSize, offset, node.catalog, undefined, executionId, true)- : await api.listObjects(connectionId, node.database!, request.schema, request.objectTypes, query, pageSize, offset, node.catalog, undefined, executionId);+ : readOptions+ ? await api.listObjects(connectionId, node.database!, request.schema, request.objectTypes, query, pageSize, offset, node.catalog, undefined, executionId, readOptions)+ : await api.listObjects(connectionId, node.database!, request.schema, request.objectTypes, query, pageSize, offset, node.catalog, undefined, executionId);signal.throwIfAborted();if (revision !== sidebarObjectSearchRevision.value) throw new DOMException("Search metadata invalidated", "AbortError");return rows;@@ -3192,8 +3279,9 @@ export const useConnectionStore = defineStore("connection", () => {nodeKind: "simple-tables",});const sourceRevision = tableListSourceRevision(options.connectionId);- if (getConfig(options.connectionId)?.db_type === "oceanbase-oracle" && !tableNameFilter) {- const objectTypes = (["TABLE", ...options.nonTableObjectTypes] as DatabaseObjectTreeKind[]).filter((type) => ["TABLE", "VIEW", "PROCEDURE", "FUNCTION", "PACKAGE", "PACKAGE_BODY", "SEQUENCE", "SYNONYM"].includes(type));+ const readOptions = triggerObjectReadOptions(options.connectionId, options.nonTableObjectTypes);+ if ((getConfig(options.connectionId)?.db_type === "oceanbase-oracle" || readOptions) && !tableNameFilter) {+ const objectTypes = (["TABLE", ...options.nonTableObjectTypes] as DatabaseObjectTreeKind[]).filter((type) => ["TABLE", "VIEW", "MATERIALIZED_VIEW", "PROCEDURE", "FUNCTION", "TRIGGER", "PACKAGE", "PACKAGE_BODY", "SEQUENCE", "SYNONYM"].includes(type));const objects = await loadCachedMetadataListPage<ObjectInfo[]>(metadataListCacheScope({kind: "object-list-page",@@ -3208,7 +3296,10 @@ export const useConnectionStore = defineStore("connection", () => {sidebarDisplayMode: "simple",extra: tableNameFilterMetadataExtra(tableNameFilter, sourceRevision),}),- () => api.listObjects(options.connectionId, options.database, options.querySchema, objectTypes, searchFilter, options.pageSize + 1, options.offset),+ () =>+ readOptions+ ? api.listObjects(options.connectionId, options.database, options.querySchema, objectTypes, searchFilter, options.pageSize + 1, options.offset, undefined, undefined, undefined, readOptions)+ : api.listObjects(options.connectionId, options.database, options.querySchema, objectTypes, searchFilter, options.pageSize + 1, options.offset),{ force: options.force },);const hasMore = objects.length > options.pageSize;@@ -3218,7 +3309,8 @@ export const useConnectionStore = defineStore("connection", () => {const tables = pageObjects.filter((object) => object.object_type === "TABLE").map((object) => ({ name: object.name, table_type: "TABLE", comment: object.comment }));indexCompletionTables(options.connectionId, options.database, options.effectiveSchema, tableInfosToCompletionTables(tables, options.effectiveSchema));}- const anchor = (object: ObjectInfo | undefined) => (object ? JSON.stringify([object.schema ?? options.effectiveSchema, object.name, object.object_type, object.signature ?? ""]) : undefined);+ const anchor = (object: ObjectInfo | undefined) =>+ object ? (exactOracleTriggerMetadata(object.trigger) ? tablePageRowAnchorKey(object.name, object.schema, object.parent_name, object.trigger) : JSON.stringify([object.schema ?? options.effectiveSchema, object.name, object.object_type, object.signature ?? ""])) : undefined;return { children, objectCount: children.length, hasMore, nextOffset: options.offset + pageObjects.length, firstAnchor: anchor(objects[0]), nextAnchor: hasMore ? anchor(objects[options.pageSize]) : undefined };}const paginate = options.pagedSearch || !searchFilter || getConfig(options.connectionId)?.db_type === "oceanbase-oracle";@@ -3309,6 +3401,7 @@ export const useConnectionStore = defineStore("connection", () => {continue;}const querySchema = options.querySchema;+ const readOptions = triggerObjectReadOptions(options.connectionId, query.objectTypes, options.node.catalog);const objects = await loadCachedMetadataListPage<ObjectInfo[]>(metadataListCacheScope({kind: "object-list-page",@@ -3319,8 +3412,14 @@ export const useConnectionStore = defineStore("connection", () => {objectTypes: query.objectTypes,searchFilter,sidebarDisplayMode: "simple",+ extra: options.node.catalog ? { catalog: options.node.catalog } : undefined,}),- () => api.listObjects(options.connectionId, options.database, querySchema, query.objectTypes),+ () =>+ readOptions+ ? api.listObjects(options.connectionId, options.database, querySchema, query.objectTypes, undefined, undefined, undefined, options.node.catalog, undefined, undefined, readOptions)+ : options.node.catalog+ ? api.listObjects(options.connectionId, options.database, querySchema, query.objectTypes, undefined, undefined, undefined, options.node.catalog)+ : api.listObjects(options.connectionId, options.database, querySchema, query.objectTypes),{ force: options.loadOptions?.force },);const supplementalObjects = filterSimpleSidebarSupplementalObjects(objects);@@ -3330,6 +3429,7 @@ export const useConnectionStore = defineStore("connection", () => {connectionId: options.connectionId,database: options.database,schema: options.effectiveSchema,+ catalog: options.node.catalog,objects: supplementalObjects,databaseType,});@@ -4109,7 +4209,7 @@ export const useConnectionStore = defineStore("connection", () => {return current;}- function clearLoadedChildrenCache(prefix: string, options?: { deletePersisted?: boolean }) {+ function clearLoadedChildrenCache(prefix: string, options?: { deletePersisted?: boolean; skipMetadataInvalidation?: boolean }) {for (const id of loadedTreeNodeChildrenIds.value) {if (id === prefix || id.startsWith(`${prefix}:`)) {loadedTreeNodeChildrenIds.value.delete(id);@@ -4130,7 +4230,7 @@ export const useConnectionStore = defineStore("connection", () => {filteredObjectGroupChildrenSnapshots.delete(id);}}- invalidateMetadataCachesByTreePrefix(prefix);+ if (!options?.skipMetadataInvalidation) invalidateMetadataCachesByTreePrefix(prefix);if (options?.deletePersisted === false) return;deletePersistedSchemaCachePrefix(prefix);}@@ -4596,7 +4696,8 @@ export const useConnectionStore = defineStore("connection", () => {return true;}- async function updateConnectionDatabaseInfo(connectionId: string, databaseInfo: DatabaseConnectionInfo, expectedConfigFingerprint?: string): Promise<void> {+ async function updateConnectionDatabaseInfo(connectionId: string, databaseInfo: DatabaseConnectionInfo, expectedConfigFingerprint?: string, isCurrent?: () => boolean): Promise<void> {+ if (isCurrent && !isCurrent()) return;const normalized = normalizeDatabaseConnectionInfo(databaseInfo);if (!normalized) return;const current = connections.value.find((connection) => connection.id === connectionId);@@ -4604,14 +4705,22 @@ export const useConnectionStore = defineStore("connection", () => {if (expectedConfigFingerprint && connectionConfigFingerprint(current) !== expectedConfigFingerprint) return;if (JSON.stringify(current.database_info) === JSON.stringify(normalized)) return;const tableListSourceChanged = mysqlTableListSourceChanged(current, normalized);+ const jobEngine = nativeJobAdminEngine(current);await api.saveConnectionDatabaseInfo(connectionId, normalized);+ if (isCurrent && !isCurrent()) return;const index = connections.value.findIndex((connection) => connection.id === connectionId);if (index < 0) return;if (expectedConfigFingerprint && connectionConfigFingerprint(connections.value[index]) !== expectedConfigFingerprint) return;const nextConnections = [...connections.value];nextConnections[index] = { ...nextConnections[index], database_info: normalized };connections.value = nextConnections;+ const nextJobEngine = nativeJobAdminEngine(nextConnections[index]);+ const jobNodeKind = (engine: typeof jobEngine) => (engine === "dameng" ? "dameng" : engine ? "native" : "none");+ if (jobNodeKind(jobEngine) !== jobNodeKind(nextJobEngine)) {+ const connectionNode = findConnectionNode(connectionId);+ if (connectionNode) connectionNode.children = withConnectionUtilityNodes(connectionId, connectionNode.children ?? [], connectionNode);+ }if (tableListSourceChanged) {// ShardingSphere switches table enumeration from information_schema to SHOW FULL TABLES.// Discard physical-table metadata that may have loaded before background version detection completed.@@ -4633,16 +4742,18 @@ export const useConnectionStore = defineStore("connection", () => {// its loaded children after this background refresh completes.}- async function refreshConnectedDatabaseInfo(connectionId: string, config: ConnectionConfig): Promise<void> {- const expectedConfigFingerprint = connectionConfigFingerprint(config);+ async function refreshConnectedDatabaseInfo(connectionId: string, config: ConnectionConfig, expectedConfigFingerprint: string, isCurrent: () => boolean): Promise<void> {+ if (!isCurrent()) return;const current = getConfig(connectionId);- if (config.db_type === "kingbase" && current?.database_info && connectionConfigFingerprint(current) === expectedConfigFingerprint) {+ if (!current || connectionConfigFingerprint(current) !== expectedConfigFingerprint) return;+ if (config.db_type === "kingbase" && current.database_info) {current.database_info = { ...current.database_info, compatibilityMode: undefined };}try {const detected = await api.connectionDatabaseInfo(connectionId);+ if (!isCurrent()) return;const normalized = normalizeDatabaseConnectionInfo(detected, configuredDatabaseProductName(config), config.database);- if (normalized) await updateConnectionDatabaseInfo(connectionId, normalized, expectedConfigFingerprint);+ if (normalized) await updateConnectionDatabaseInfo(connectionId, normalized, expectedConfigFingerprint, isCurrent);} catch {// Database metadata is optional and must not turn a successful connection into a failure.}@@ -5044,7 +5155,7 @@ export const useConnectionStore = defineStore("connection", () => {}}- async function persistRememberedConnectionPassword(config: ConnectionConfig, rememberPassword: boolean, expectedConfigFingerprint: string, localAttempt: number): Promise<void> {+ async function persistRememberedConnectionPassword(config: ConnectionConfig, rememberPassword: boolean, expectedConfigFingerprint: string, localAttempt: number): Promise<string | undefined> {if (!rememberPassword || !isCurrentLocalConnectionAttempt(config.id, localAttempt)) return;const index = connections.value.findIndex((connection) => connection.id === config.id);if (index < 0) return;@@ -5059,6 +5170,7 @@ export const useConnectionStore = defineStore("connection", () => {}connections.value = nextConnections;rebuildTreeNodes();+ return connectionConfigFingerprint(nextConnections[index]!);}async function connectDbWithPasswordRetry(config: ConnectionConfig, localAttempt: number): Promise<{ config: ConnectionConfig; id: string; rememberPassword: boolean }> {@@ -5084,6 +5196,7 @@ export const useConnectionStore = defineStore("connection", () => {if (getBlockingDisconnectInFlight(config.id)) await waitForBlockingDisconnectInFlight(config.id);if (passwordChangeReconnectRequired.get(config.id) !== passwordChangeState) throw new Error(i18n.global.t("userAdmin.passwordChangedReconnect"));const localAttempt = beginLocalConnectionAttempt(config.id);+ const metadataRevision = connectionStateRevision(config.id);try {let rememberPassword = false;if (passwordChangeState === "ready") {@@ -5104,6 +5217,7 @@ export const useConnectionStore = defineStore("connection", () => {config = connection.config;rememberPassword ||= connection.rememberPassword;const id = connection.id;+ const isCurrentMetadata = () => isCurrentConnectionStateRevision(config.id, metadataRevision) && (isCurrentLocalConnectionAttempt(config.id, localAttempt) || (successfulLocalConnectionAttempts.get(config.id) === localAttempt && connectedIds.value.has(id)));await ensureLocalConnectionAttemptActiveAfterConnectResult(config.id, localAttempt, id);await syncMongoLegacyDriverFallback(id, config);await ensureLocalConnectionAttemptActiveAfterConnectResult(config.id, localAttempt, id);@@ -5111,7 +5225,7 @@ export const useConnectionStore = defineStore("connection", () => {if (config.db_type !== "plugin" && refreshMetadataBeforeReady) {// Kingbase parsing needs the live mode; DWS needs the current product version.// Metadata remains optional: refreshConnectedDatabaseInfo swallows failures.- await refreshConnectedDatabaseInfo(id, { ...config, id });+ await refreshConnectedDatabaseInfo(id, { ...config, id }, expectedConfigFingerprint, isCurrentMetadata);await ensureLocalConnectionAttemptActiveAfterConnectResult(config.id, localAttempt, id);}passwordChangeReconnectRequired.delete(config.id);@@ -5121,7 +5235,6 @@ export const useConnectionStore = defineStore("connection", () => {clearConnectionClosedByUser(config.id);clearConnectionClosedByUser(id);if (config.db_type !== "plugin") {- if (!refreshMetadataBeforeReady) void refreshConnectedDatabaseInfo(id, { ...config, id });await refreshConnectionIdentifierQuote(id, { ...config, id });ensureLocalConnectionAttemptActive(config.id, localAttempt);// Compatibility modes warm asynchronously; the QueryEditor watcher and the@@ -5154,12 +5267,14 @@ export const useConnectionStore = defineStore("connection", () => {comment: config.note || null,});}+ let metadataConfigFingerprint = expectedConfigFingerprint;try {- await persistRememberedConnectionPassword(config, rememberPassword, expectedConfigFingerprint, localAttempt);+ metadataConfigFingerprint = (await persistRememberedConnectionPassword(config, rememberPassword, expectedConfigFingerprint, localAttempt)) ?? expectedConfigFingerprint;} catch (error) {if (isCurrentLocalConnectionAttempt(config.id, localAttempt)) setConnectionError(id, i18n.global.t("connection.rememberPasswordSaveFailed", { message: connectionErrorMessage(error) }));}ensureLocalConnectionAttemptActive(config.id, localAttempt);+ if (config.db_type !== "plugin" && !refreshMetadataBeforeReady) void refreshConnectedDatabaseInfo(id, { ...config, id }, metadataConfigFingerprint, isCurrentMetadata);return id;} catch (e) {if (isCancelledLocalConnectionAttempt(config.id, localAttempt)) {@@ -5559,6 +5674,7 @@ export const useConnectionStore = defineStore("connection", () => {return;}const localAttempt = beginLocalConnectionAttempt(connectionId);+ const metadataRevision = connectionStateRevision(connectionId);const connectPromise = (async () => {let rememberPassword = false;// Fast-path the common case (password saved or no password needed) so the@@ -5579,20 +5695,20 @@ export const useConnectionStore = defineStore("connection", () => {config = connection.config;rememberPassword ||= connection.rememberPassword;const id = connection.id;+ const isCurrentMetadata = () => isCurrentConnectionStateRevision(connectionId, metadataRevision) && (isCurrentLocalConnectionAttempt(connectionId, localAttempt) || (successfulLocalConnectionAttempts.get(connectionId) === localAttempt && connectedIds.value.has(connectionId)));await ensureLocalConnectionAttemptActiveAfterConnectResult(connectionId, localAttempt, id);await syncMongoLegacyDriverFallback(connectionId, config);await ensureLocalConnectionAttemptActiveAfterConnectResult(connectionId, localAttempt, id);const refreshMetadataBeforeReady = config.db_type === "kingbase" || (config.db_type === "gaussdb" && gaussdbConnectionMode(config) === "dws");if (config.db_type !== "plugin" && refreshMetadataBeforeReady) {// Refresh mode/version before reconnect completion, never infer mode from version.- await refreshConnectedDatabaseInfo(connectionId, config);+ await refreshConnectedDatabaseInfo(connectionId, config, expectedConfigFingerprint, isCurrentMetadata);await ensureLocalConnectionAttemptActiveAfterConnectResult(connectionId, localAttempt, id);}markConnectionConnected(connectionId);// 任何路径真的连上之后,"用户已关闭"标记就不能再拦后续的被动唤醒。clearConnectionClosedByUser(connectionId);if (config.db_type !== "plugin") {- if (!refreshMetadataBeforeReady) void refreshConnectedDatabaseInfo(connectionId, config);await refreshConnectionIdentifierQuote(connectionId, config);ensureLocalConnectionAttemptActive(connectionId, localAttempt);void refreshConnectionDatabaseModes(connectionId, config);@@ -5600,12 +5716,14 @@ export const useConnectionStore = defineStore("connection", () => {markSuccessfulLocalConnectionAttempt(connectionId, localAttempt);markConnectionHealthChecked(connectionId);clearConnectionError(connectionId);+ let metadataConfigFingerprint = expectedConfigFingerprint;try {- await persistRememberedConnectionPassword(config, rememberPassword, expectedConfigFingerprint, localAttempt);+ metadataConfigFingerprint = (await persistRememberedConnectionPassword(config, rememberPassword, expectedConfigFingerprint, localAttempt)) ?? expectedConfigFingerprint;} catch (error) {if (isCurrentLocalConnectionAttempt(connectionId, localAttempt)) setConnectionError(connectionId, i18n.global.t("connection.rememberPasswordSaveFailed", { message: connectionErrorMessage(error) }));}ensureLocalConnectionAttemptActive(connectionId, localAttempt);+ if (config.db_type !== "plugin" && !refreshMetadataBeforeReady) void refreshConnectedDatabaseInfo(connectionId, config, metadataConfigFingerprint, isCurrentMetadata);})();connectInFlight.set(connectionId, connectPromise);try {@@ -7167,7 +7285,7 @@ export const useConnectionStore = defineStore("connection", () => {pagedSearch: isSidebarTableSearch,force: options?.force,});- const globalPageSearch = config?.db_type === "oceanbase-oracle" && !isSidebarTableSearch ? searchFilter : undefined;+ const globalPageSearch = (config?.db_type === "oceanbase-oracle" || triggerObjectReadOptions(connectionId, nonTableObjectTypes)) && !isSidebarTableSearch ? searchFilter : undefined;children = page.hasMore && (!searchFilter || isSidebarTableSearch || globalPageSearch !== undefined) ? appendTableTreeLoadMoreNode(page.children, buildLoadMoreNode(node, page.nextOffset, pageSize, page.nextAnchor, globalPageSearch), page.loadMoreParent) : page.children;nextObjectCount = page.objectCount;} else if (simpleObjectDisplay) {@@ -7216,7 +7334,7 @@ export const useConnectionStore = defineStore("connection", () => {database,querySchema,effectiveSchema,- objectTypes: config?.db_type === "oceanbase-oracle" && !tableNameFilter ? nonTableObjectTypes.filter((type) => type === "INDEX") : nonTableObjectTypes,+ objectTypes: (config?.db_type === "oceanbase-oracle" || triggerObjectReadOptions(connectionId, nonTableObjectTypes)) && !tableNameFilter ? nonTableObjectTypes.filter((type) => type === "INDEX") : nonTableObjectTypes,cacheKey,loadOptions: options,load,@@ -7309,7 +7427,7 @@ export const useConnectionStore = defineStore("connection", () => {catalog: node.catalog,});const isSidebarTableSearch = !!options?.sidebarTableSearchParentId;- const globalPageSearch = (config?.db_type === "oceanbase-oracle" || isSchemaIndexGroup(node)) && !isSidebarTableSearch ? searchFilter : undefined;+ const globalPageSearch = (config?.db_type === "oceanbase-oracle" || isSchemaIndexGroup(node) || triggerObjectReadOptions(node.connectionId, objectTypes, node.catalog)) && !isSidebarTableSearch ? searchFilter : undefined;if (!isSchemaIndexGroup(node) && !options?.force && !searchFilter && !tableNameFilter) {const cached = await loadPersistedTreeChildren(node, cacheKey, load);if (cached.hit) {@@ -8299,25 +8417,32 @@ export const useConnectionStore = defineStore("connection", () => {return;}const querySchema = metadataQuerySchema(connectionId, database, schema);- const triggers = await api.listTriggers(connectionId, database, querySchema, table, catalog);+ const readOptions = triggerObjectReadOptions(connectionId, undefined, catalog);+ const triggers = readOptions ? await api.listTriggers(connectionId, database, querySchema, table, catalog, readOptions) : await api.listTriggers(connectionId, database, querySchema, table, catalog);const targetNode = treeNodeLoadTarget(load);if (!targetNode) return;const isXugu = effectiveDatabaseTypeForConnection(getConfig(connectionId)) === "xugu";setLoadedTableMetadataChildren(targetNode,triggers.map((tr) => {+ const exact = exactOracleTriggerMetadata(tr);+ const parent = exact && (exact.scope === "TABLE" || exact.scope === "VIEW") ? exact.parent : undefined;const xuguDetails = isXugu ? [tr.timing, tr.event, tr.level, tr.enabled === false ? i18n.global.t("objects.disabled") : null, tr.valid === false ? i18n.global.t("objects.invalid") : null].filter(Boolean).join(" · ") : `${tr.timing} ${tr.event}`;return {- id: `${parentId}:${tr.name}`,+ id: `${parentId}:${exact ? oracleTriggerIdentityKey(exact, catalog) : tr.name}`,label: `${tr.name} (${xuguDetails})`,objectName: tr.name,type: "trigger" as const,connectionId,database,- schema,- tableName: table,+ schema: exact?.owner ?? schema,+ catalog,+ parentSchema: exact ? parent?.owner : undefined,+ parentName: exact ? parent?.name : undefined,+ parentType: parent?.objectType === "VIEW" ? "view" : parent?.objectType === "TABLE" ? "table" : undefined,+ tableName: exact ? parent?.name : table,comment: isXugu ? tr.comment : undefined,- valid: isXugu ? tr.valid : undefined,+ valid: isXugu || exact ? tr.valid : undefined,meta: tr,};}),@@ -8553,6 +8678,16 @@ export const useConnectionStore = defineStore("connection", () => {if (options?.sidebarSearch) {return withSidebarSearchLoad(node.connectionId, () => refreshTreeNode(node, { ...options, sidebarSearch: false }));}+ const exactTrigger = exactOracleTriggerNodeMetadata(node);+ if (exactTrigger && node.connectionId && node.database) {+ const parent = findParentNode(treeNodes.value, node.id);+ if (parent) {+ if (!options?.skipObjectCacheInvalidation) await invalidateOracleTriggerLists({ connectionId: node.connectionId, database: node.database, catalog: node.catalog, owner: exactTrigger.owner }, exactTrigger.parent ? [exactTrigger.parent] : []);+ if (parent.type === "group-triggers" && parent.tableName) await loadTriggers(parent.connectionId!, parent.database!, parent.tableName, parent.schema, parent.id, parent.catalog);+ else await loadTreeNodeChildren(parent, { force: true });+ return;+ }+ }invalidateCompletionCachesForNode(node);invalidateMetadataCachesForNode(node, options);if (node.type === "trigger") {@@ -11349,6 +11484,8 @@ export const useConnectionStore = defineStore("connection", () => {invalidateCompletionTableCache,completionCacheRevision,invalidateMetadataCache,+ invalidateOracleTriggerLists,+ syncOracleTriggerNodeState,exportConnectionsToFile,readImportFile,parseConnectionsImport,diff --git a/apps/desktop/src/stores/queryStore.ts b/apps/desktop/src/stores/queryStore.tsindex 41ce541fc1..a95011c728 100644--- a/apps/desktop/src/stores/queryStore.ts+++ b/apps/desktop/src/stores/queryStore.ts@@ -12,6 +12,7 @@ import { useI18n } from "vue-i18n";import { useToast } from "@/composables/useToast";import { savedSqlErrorMessage } from "@/lib/savedSql/savedSqlErrors";import { sanitizeTabPageUiState } from "@/lib/tabs/tabUiState";+import { nativeJobAdminEngine, nativeJobAdminSelection, nativeJobAdminSupported, type NativeJobAdminSelection } from "@/lib/database/nativeJobAdmin";import type { DeletedConnectionTabKeepMode } from "@/lib/tabs/deletedConnectionTabs";import type {BatchSqlExecution,@@ -156,9 +157,12 @@ import { isTauriRuntime } from "@/lib/backend/tauriRuntime";import { resolveSavedSqlExecutionTarget, savedSqlExecutionTargetFromFile, savedSqlExecutionTargetFromTab, type SavedSqlExecutionTarget, type SavedSqlOpenTargetMode } from "@/lib/savedSql/savedSqlExecutionTarget";import { safeLocalStorageGet, safeLocalStorageRemove } from "@/lib/backend/safeStorage";import { sqlTextFingerprint } from "@/lib/sql/sqlTextFingerprint";-import { loadEditableObjectSourceForEditor } from "@/lib/table/objectSourceLoad";+import { loadEditableObjectSourceForEditor, oracleTriggerErrorEditorOffset } from "@/lib/table/objectSourceLoad";import { assertSourceIdentity, captureSourceIdentity, renewSourceIdentity, type SourceIdentitySnapshot } from "@/lib/table/objectSourceIdentity";import { buildEditableObjectSource, prepareRoutineSourceRun, supportsRoutineSourceReplaceOnRun } from "@/lib/table/objectSourceEditor";+import { oracleTriggerReadOptions } from "@/lib/database/oracleTriggerIdentity";+import { readOracleTriggerSource, prepareOracleTriggerPlan, type OracleTriggerSnapshot, type OracleTriggerExecutionResult, type OracleTriggerAction } from "@/lib/database/oracleTriggerPlan";+import { confirmOracleTriggerPlan } from "@/lib/database/oracleTriggerActions";import { restoreOracleTypeManagementDraft, type OracleTypeManagementDraft } from "@/lib/table/oracleTypeManagement";import { typeManagementRecordsEqual } from "@/lib/table/oracleTypeManagementRecord";import { isOracleFamilyTypeSource } from "@/lib/database/databaseObjectCapabilities";@@ -1157,6 +1161,35 @@ export const useQueryStore = defineStore("query", () => {const t = getI18nT();const settingsStore = useSettingsStore();const tabs = ref<QueryTab[]>([]);+ /** Runtime authority is never restored from persisted tabs or cached SQL. */+ const oracleTriggerSources = reactive<Record<string, { baseline?: OracleTriggerSnapshot; profile?: ObjectSource["trigger"]; result?: OracleTriggerExecutionResult; error?: string; busy?: boolean; readVersion?: number }>>({});+ let triggerSourceReadVersion = 0;+ function oracleTriggerSourceState(id: string) {+ return oracleTriggerSources[id];+ }+ function revealOracleTriggerSourceError(id: string, location: { line: number; position: number }, expectedObjectId?: string): boolean {+ const tab = tabs.value.find((candidate) => candidate.id === id);+ const baseline = oracleTriggerSources[id]?.baseline;+ if (!tab || tab.objectSource?.objectType !== "TRIGGER" || !baseline || (expectedObjectId !== undefined && baseline.metadata.objectId !== expectedObjectId)) return false;+ const offset = oracleTriggerErrorEditorOffset(baseline.raw, tab.sql, location);+ if (offset === undefined) return false;+ const lines = tab.sql.replace(/\r\n?/g, "\n").slice(0, offset).split("\n");+ if (tab.objectDetails) tab.objectDetails.section = "source";+ tab.editorRevealRequest = { id: ++contentRevealSeq, line: lines.length, column: lines[lines.length - 1].length + 1 };+ return true;+ }+ function acceptOracleTriggerDiagnosticResult(id: string, result: OracleTriggerExecutionResult, before: OracleTriggerSnapshot, originRevision?: number): void {+ const tab = tabs.value.find((candidate) => candidate.id === id);+ const state = oracleTriggerSources[id];+ const source = tab?.objectSource;+ const baseline = state?.baseline;+ if (!tab || source?.objectType !== "TRIGGER" || !baseline || (originRevision !== undefined && state.readVersion !== originRevision) || JSON.stringify(baseline.target) !== JSON.stringify(before.target) || baseline.metadata.objectId !== before.metadata.objectId) return;+ state.result = result;+ if (!result.cancelled && result.steps.every((step) => step.state === "committed") && result.snapshot && result.snapshot.metadata.objectId === baseline.metadata.objectId && baseline.raw.source === before.raw.source) {+ state.baseline = result.snapshot;+ sourceIdentities.set(source, result.snapshot.identity);+ } else if (result.snapshot) state.error = t("oracleTrigger.reloadBaseline");+ }const sourceIdentities = new WeakMap<NonNullable<QueryTab["objectSource"]>, SourceIdentitySnapshot>();function getObjectSourceIdentitySnapshot(tab: QueryTab): SourceIdentitySnapshot | undefined {if (!tab.objectSource) return undefined;@@ -1188,6 +1221,15 @@ export const useQueryStore = defineStore("query", () => {});}watch(() => tabs.value.map((tab) => tab.id), ensureTabCreationTimes, { immediate: true, flush: "sync" });+ watch(+ () => tabs.value.map((tab) => tab.id),+ (ids) => {+ for (const id of Object.keys(oracleTriggerSources))+ if (!ids.includes(id)) {+ delete oracleTriggerSources[id];+ }+ },+ );// 重名标签的编号同样在这里集中分配:编号只在标签首次重名时发一次,关闭标签不会// 让幸存标签改名(#9938),新建的标签接着最大编号往后排。放在 store 的 watcher// 里而不是渲染函数里,是为了避免在 computed 求值过程中写标签状态;getter 只读@@ -3324,6 +3366,7 @@ export const useQueryStore = defineStore("query", () => {await connectionStore.ensureConnected(connectionId);const databaseType = effectiveDatabaseTypeForConnection(connectionStore.getConfig(connectionId));if (!databaseType) return;+ if (objectSource.objectType === "TRIGGER" && oracleTriggerReadOptions(databaseType)) return; // Only explicit reads may renew an exact trigger baseline.const {raw,editableSource,@@ -3371,6 +3414,9 @@ export const useQueryStore = defineStore("query", () => {if (tab.sourceLoad && !tab.sourceLoad.error) return true;const request = tab.sourceLoad?.request ? { ...tab.sourceLoad.request } : tab.objectSource ? { name: tab.objectSource.name, objectType: tab.objectSource.objectType, signature: tab.objectSource.signature } : null;if (!request) return false;+ if (request.objectType === "TRIGGER" && oracleTriggerSources[id]) {+ oracleTriggerSources[id].readVersion = ++triggerSourceReadVersion;+ }sourceRevalidateInFlight.delete(id);tab.sourceLoad = {startedAt: Date.now(),@@ -3385,6 +3431,59 @@ export const useQueryStore = defineStore("query", () => {tab.sourceLoad = undefined;}+ async function runOracleTriggerSourceAction(id: string, action: OracleTriggerAction = "replace", submittedSource?: string): Promise<boolean> {+ const tab = tabs.value.find((candidate) => candidate.id === id);+ const sourceObject = tab?.objectSource;+ if (!tab || sourceObject?.objectType !== "TRIGGER") return false;+ const state = oracleTriggerSources[id] ?? (oracleTriggerSources[id] = {});+ if (state.busy) return false;+ const baseline = state.baseline;+ if (!baseline) {+ state.error = t("oracleTrigger.reloadBaseline");+ return false;+ }+ if (action === "replace" && (submittedSource ?? tab.sql).trim() !== tab.sql.trim()) {+ state.error = t("oracleTrigger.runFullDefinition");+ return false;+ }+ const draft = tab.sql;+ const readVersion = state.readVersion;+ const current = () =>+ tabs.value.includes(tab) &&+ state.readVersion === readVersion &&+ activeTabId.value === id &&+ tab.objectSource === sourceObject &&+ tab.connectionId === baseline.target.connectionId &&+ tab.database === baseline.target.database &&+ tab.catalog === baseline.target.catalog &&+ (sourceObject.schema || tab.schema || tab.database) === baseline.target.owner &&+ (tab.schema || tab.database) === baseline.target.executionSchema &&+ (action !== "replace" || tab.sql === draft);+ state.busy = true;+ state.error = "";+ try {+ const plan = await prepareOracleTriggerPlan({ target: baseline.target, action, expectedObjectId: baseline.metadata.objectId ?? undefined, ...(action === "replace" ? { baseline, source: draft } : {}) });+ if (!current()) return false;+ const result = await confirmOracleTriggerPlan(plan, { isCurrent: current });+ const saved = !result.cancelled && result.steps.every((step) => step.state === "committed");+ if (oracleTriggerSources[id] !== state || state.readVersion !== readVersion || !tabs.value.includes(tab) || tab.objectSource !== sourceObject) return saved;+ // The result remains attached to the original tab; merely switching UI+ // does not discard the fixed target's already-dispatched readback.+ state.result = result;+ if (saved && result.snapshot && result.snapshot.metadata.objectId === baseline.metadata.objectId && (action === "replace" || baseline.raw.source === plan.before.raw.source)) {+ state.baseline = result.snapshot;+ sourceIdentities.set(sourceObject, result.snapshot.identity);+ } else if (result.snapshot) state.error = t("oracleTrigger.reloadBaseline");+ if (saved && action === "replace" && tab.sql === draft) markTabClean(tab);+ return saved;+ } catch (error) {+ state.error = formatError(error);+ return false;+ } finally {+ state.busy = false;+ }+ }+async function loadObjectSourceIntoTab(id: string) {const tab = tabs.value.find((candidate) => candidate.id === id);if (!tab?.sourceLoad || !tab.connectionId) return;@@ -3400,11 +3499,13 @@ export const useQueryStore = defineStore("query", () => {connectionStore.activeConnectionId = connectionId;const databaseType = effectiveDatabaseTypeForConnection(connectionStore.getConfig(connectionId));if (!databaseType) throw new Error("Connection type is unavailable.");+ const triggerOptions = request.objectType === "TRIGGER" ? oracleTriggerReadOptions(databaseType, tab.catalog) : undefined;+ const triggerLoaded = triggerOptions ? await readOracleTriggerSource({ connectionId, database, catalog: tab.catalog, owner: schema, name: request.name, executionSchema: tab.schema || database }) : undefined;const {raw,editableSource,objectType: resolvedType,- } = await loadEditableObjectSourceForEditor(api.getObjectSource, buildEditableObjectSource, {+ } = await loadEditableObjectSourceForEditor(triggerLoaded ? async () => triggerLoaded.raw : api.getObjectSource, buildEditableObjectSource, {connectionId,database,schema,@@ -3412,14 +3513,15 @@ export const useQueryStore = defineStore("query", () => {objectType: request.objectType,databaseType,signature: request.signature,+ metadataReadOptions: triggerOptions,});if (tabs.value.find((candidate) => candidate.id === id)?.sourceLoad !== sourceLoad) return;if (tab.connectionId !== connectionId || tab.database !== database || (tab.schema || tab.database) !== schema) throw new Error(i18n.global.t("objects.sourceIdentityChanged"));- const renewedIdentity = renewSourceIdentity(identity);+ const renewedIdentity = triggerLoaded?.snapshot?.identity ?? renewSourceIdentity(identity);// Fallback can resolve another kind; never activate a frozen resolved object.const resolvedIdentity = resolvedType === request.objectType ? renewedIdentity : captureSourceIdentity({ ...identity, objectType: resolvedType });assertSourceIdentity(resolvedIdentity);- applyLoadedObjectSource(id, { connectionId, database, schema, catalog: tab.catalog, title: tab.title, request, initialEditing, databaseType, editableSource, raw, resolvedType });+ applyLoadedObjectSource(id, { connectionId, database, schema, catalog: tab.catalog, title: tab.title, request, initialEditing, databaseType, editableSource, raw, resolvedType, triggerBaseline: triggerLoaded?.snapshot, triggerError: triggerLoaded?.identityError });const loadedTab = tabs.value.find((candidate) => candidate.id === id);if (loadedTab?.objectSource) sourceIdentities.set(loadedTab.objectSource, resolvedIdentity);} catch (e: any) {@@ -3443,15 +3545,22 @@ export const useQueryStore = defineStore("query", () => {editableSource: string;raw: ObjectSource;resolvedType: ObjectSourceKind;+ triggerBaseline?: OracleTriggerSnapshot;+ triggerError?: string;},) {// 加载期间 tab 被关掉(用户放弃)或连接被断开:静默丢弃,不重建、不写库const tab = tabs.value.find((candidate) => candidate.id === id);if (!tab?.sourceLoad) return;+ const keptTriggerDraft = loaded.resolvedType === "TRIGGER" && tab.objectSource?.objectType === "TRIGGER" && isTabDirty(tab) ? tab.sql : undefined;const details = sourceDetails(loaded, { ...loaded.request, objectType: loaded.resolvedType }, tab.objectDetails?.section);+ const exactTrigger = loaded.resolvedType === "TRIGGER" && loaded.triggerBaseline?.exists === true;const managedType = isOracleFamilyTypeSource(loaded.databaseType, loaded.resolvedType);const sourceIsEditable =- !isViewOnlySourceWithoutEditablePayload(loaded.initialEditing, loaded.resolvedType) && loaded.raw.editable !== false && (!OBJECT_SOURCE_READ_ONLY_TYPES.includes(loaded.resolvedType) || (loaded.databaseType === "oceanbase-oracle" && loaded.resolvedType === "SEQUENCE") || managedType);+ exactTrigger ||+ (!isViewOnlySourceWithoutEditablePayload(loaded.initialEditing, loaded.resolvedType) && loaded.raw.editable !== false && (!OBJECT_SOURCE_READ_ONLY_TYPES.includes(loaded.resolvedType) || (loaded.databaseType === "oceanbase-oracle" && loaded.resolvedType === "SEQUENCE") || managedType));+ if (loaded.resolvedType === "TRIGGER" && (loaded.triggerBaseline || loaded.triggerError))+ oracleTriggerSources[id] = { baseline: loaded.triggerBaseline, profile: loaded.triggerBaseline?.raw.trigger ?? oracleTriggerSources[id]?.profile, error: loaded.triggerError, readVersion: ++triggerSourceReadVersion };if (sourceIsEditable) {const options: OpenObjectSourceTabOptions = {connectionId: loaded.connectionId,@@ -3489,7 +3598,11 @@ export const useQueryStore = defineStore("query", () => {}tab.sourceView = true;tab.objectDetails = details;- markTabClean(tab);+ if (loaded.resolvedType === "TRIGGER" && oracleTriggerReadOptions(loaded.databaseType) && keptTriggerDraft !== undefined) {+ // Rebase authority, not the user's unfinished correction. Explicit refresh+ // after unknown/permission repair must not turn into a destructive reload.+ updateSql(id, keptTriggerDraft);+ } else markTabClean(tab);clearObjectSourceLoad(tab);}@@ -4075,6 +4188,23 @@ export const useQueryStore = defineStore("query", () => {return registerOpenTab(tab);}+ function openDatabaseJobAdmin(connectionId: string, selection?: NativeJobAdminSelection) {+ const config = useConnectionStore().getConfig(connectionId);+ if (!nativeJobAdminSupported(config)) return;+ const existing = tabs.value.find((tab) => (tab.mode === "database-jobs" || tab.mode === "dameng-jobs") && tab.connectionId === connectionId);+ if (existing) {+ if (selection) existing.nativeJobAdmin = nativeJobAdminSelection(selection);+ switchTab(existing.id);+ return existing.id;+ }+ if (nativeJobAdminEngine(config) === "dameng") {+ const id = openDamengJobAdmin(connectionId);+ if (selection) tabs.value.find((tab) => tab.id === id)!.nativeJobAdmin = nativeJobAdminSelection(selection);+ return id;+ }+ return registerOpenTab({ id: uuid(), title: t("nativeJobs.title"), connectionId, database: "", sql: "", isExecuting: false, isCancelling: false, isExplaining: false, mode: "database-jobs", ...(selection ? { nativeJobAdmin: nativeJobAdminSelection(selection) } : {}) });+ }+function openDamengUsers(connectionId: string) {const existing = tabs.value.find((tab) => tab.mode === "dameng-users" && tab.connectionId === connectionId);if (existing) {@@ -7933,6 +8063,11 @@ export const useQueryStore = defineStore("query", () => {assertUpdateAllowsInteraction();const tab = findExecutionTab(id);if (!tab || !sql.trim()) return;+ if (tab.objectSource?.objectType === "TRIGGER" && oracleTriggerReadOptions(effectiveDatabaseTypeForConnection(useConnectionStore().getConfig(tab.connectionId)))) {+ if (options?.executionTarget || options?.targetContext) throw new Error(t("oracleTrigger.runFullDefinition"));+ await runOracleTriggerSourceAction(id, "replace", sql);+ return false;+ }if (tab.typeManagementDraft || isOracleFamilyTypeSource(effectiveDatabaseTypeForConnection(useConnectionStore().getConfig(tab.connectionId)), tab.objectSource?.objectType)) throw new Error(t("objects.typeManagementUseSave"));if (pendingResultRunPreparations.has(tab)) return false;@@ -11185,6 +11320,7 @@ export const useQueryStore = defineStore("query", () => {openDamengUsers,openDamengRoles,openDamengJobAdmin,+ openDatabaseJobAdmin,openMqAdmin,openMqttAdmin,openNacosAdmin,@@ -11220,6 +11356,10 @@ export const useQueryStore = defineStore("query", () => {tableStructureRefreshVersion,setObjectSource,getObjectSourceIdentitySnapshot,+ oracleTriggerSourceState,+ revealOracleTriggerSourceError,+ acceptOracleTriggerDiagnosticResult,+ runOracleTriggerSourceAction,setExecuting,setExecutingWithId,setErrorResult,diff --git a/apps/desktop/src/types/database.ts b/apps/desktop/src/types/database.tsindex 51b2f205b0..24cf888e16 100644--- a/apps/desktop/src/types/database.ts+++ b/apps/desktop/src/types/database.ts@@ -1152,6 +1152,7 @@ export interface ObjectSource {editable?: boolean;/** Optional structured metadata exposed by generic JDBC sidecars. */routine_parameters?: RoutineParameterMetadata[];+ trigger?: TriggerInfo | null;}export interface MysqlEventInfo {@@ -1579,6 +1580,43 @@ export interface TriggerInfo {comment?: string | null;created_at?: string | null;statement?: string | null;+ oracle_metadata?: OracleTriggerMetadata | null;+}++/** Missing metadata means a provider has not established exact identity. */+export interface MetadataReadOptions {+ identityMode?: "exact";+ catalog?: string;+}++export interface OracleTriggerParent {+ owner: string;+ name: string;+ objectType: "TABLE" | "VIEW";+ objectId?: string | null;+}++export interface OracleTriggerReadState {+ state: "available" | "empty" | "denied" | "unavailable" | "unsupported" | "error" | "incomplete";+ message?: string | null;+}++export interface OracleTriggerMetadata {+ contractVersion: 1;+ identityMode: "exact";+ engine: "oracle" | "oceanbase-oracle" | "dm";+ engineVersion?: string | null;+ owner: string;+ name: string;+ scope: "TABLE" | "VIEW" | "SCHEMA" | "DATABASE" | "TIMER" | "OTHER" | "UNKNOWN";+ scopeType?: string | null;+ scopeOwner?: string | null;+ parent?: OracleTriggerParent | null;+ objectId?: string | null;+ lastDdlTime?: string | null;+ definition?: { origin: string; format: "ddl" | "declaration" | "body"; complete: boolean } | null;+ errors?: { sequence: number; line: number; position: number; text: string; severity?: string | null }[] | null;+ reads: Partial<Record<"identity" | "scope" | "parent" | "enabled" | "validity" | "definition" | "errors", OracleTriggerReadState>>;}export interface ConstraintInfo {@@ -2096,6 +2134,7 @@ export type TreeNodeType =| "dameng-users"| "dameng-roles"| "dameng-job-admin"+ | "database-job-admin"| "saved-sql-root"| "saved-sql-folder"| "saved-sql-file"@@ -2347,6 +2386,11 @@ export interface TableStructureEditorDraft {remaining: import("@/lib/table/tableStructureEditorSql").OracleForeignKeyDefinition[];uncertainSteps: string[];};+ oracleTriggerStructureRecovery?: {+ target: import("@/lib/database/oracleTriggerStructurePlan").OracleTriggerStructureTarget;+ steps: import("@/lib/database/oracleTriggerPlan").OracleTriggerStructureStepResult[];+ details: string;+ };constraintsLoaded?: boolean;triggers: import("@/lib/table/tableStructureEditorSql").EditableStructureTrigger[];triggersLoaded?: boolean;@@ -2652,6 +2696,7 @@ export interface QueryTab {| "dameng-users"| "dameng-roles"| "dameng-jobs"+ | "database-jobs"| "processlist"| "sqlserver-trace"| "mysql-dashboard"@@ -2678,6 +2723,8 @@ export interface QueryTab {};/** Ephemeral navigation intent; it is consumed by HBaseBrowser and is not persisted. */hbaseCreateTableOnOpen?: boolean;+ /** Connection-level native Job selection; bodies and backend context IDs are not persisted. */+ nativeJobAdmin?: { kind: "scheduler"; owner: string; name: string } | { kind: "legacy"; jobId: string } | { kind: "dameng-native"; jobId: string; name: string };mqTenant?: string;mqInitialTab?: "topics";mqttInitialTopic?: string;diff --git a/crates/dbx-core/src/connection/mod.rs b/crates/dbx-core/src/connection/mod.rsindex 558a618695..72c64c3266 100644--- a/crates/dbx-core/src/connection/mod.rs+++ b/crates/dbx-core/src/connection/mod.rs@@ -58,7 +58,7 @@ const SQLSERVER_LEGACY_DRIVER_INSTALL_HINT: &str ="Install the SQL Server legacy compatibility component from Driver Manager, or open the connection settings and enable SQL Server legacy compatibility mode again.";const DEFAULT_AGENT_CONNECT_TIMEOUT_SECS: u64 = 30;const ACCESS_AGENT_CONNECT_TIMEOUT_SECS: u64 = 30;-const POOL_CLOSE_TIMEOUT_SECS: u64 = 3;+pub(crate) const POOL_CLOSE_TIMEOUT_SECS: u64 = 3;const HEALTH_CHECK_POOL_ACQUIRE_TIMEOUT: Duration = Duration::from_millis(500);/// Upper bound for the "is this checked-out connection still alive" query that/// follows a successful health checkout. Windows keeps retransmitting on a@@ -461,6 +461,7 @@ pub struct AppState {pub session_credentials: SessionCredentialStore,/// In-memory, never-persisted 1/5 minute write overrides for read-only connections.pub write_unlock_windows: crate::write_unlock::WriteUnlockWindows,+ pub native_jobs: crate::schema::native_jobs::NativeJobRegistry,metadata_gates: Arc<Mutex<HashMap<String, Arc<Semaphore>>>>,/// Backend-confirmed liveness losses plus resync requests (#4339). The keepalive task/// publishes here once a connection has no pools left; each shell relays it to its own@@ -1952,6 +1953,7 @@ impl AppState {sqlserver_transaction_ends: Arc::new(std::sync::Mutex::new(Default::default())),session_credentials: SessionCredentialStore::new(),write_unlock_windows: crate::write_unlock::WriteUnlockWindows::default(),+ native_jobs: crate::schema::native_jobs::NativeJobRegistry::default(),metadata_gates: Arc::new(Mutex::new(HashMap::new())),// Bounded so a shell that stops draining cannot grow memory without bound. A// lagged receiver re-syncs from the read-only status check on its next use, sodiff --git a/crates/dbx-core/src/data/transfer.rs b/crates/dbx-core/src/data/transfer.rsindex 277485d850..495b9a91e8 100644--- a/crates/dbx-core/src/data/transfer.rs+++ b/crates/dbx-core/src/data/transfer.rs@@ -10598,6 +10598,7 @@ async fn get_postgres_schema_object_sources_for_transfer(source,editable: None,routine_parameters: None,+ trigger: None,});}for row in execute_on_pool(state, pool_key, &routines_sql).await?.rows {@@ -10618,6 +10619,7 @@ async fn get_postgres_schema_object_sources_for_transfer(source,editable: None,routine_parameters: None,+ trigger: None,});}@@ -17232,6 +17234,7 @@ CREATE TABLE "Other"."prefix""Source"."NAME" ("ID" INT);"#;source: "SELECT 1".into(),editable: None,routine_parameters: None,+ trigger: None,},db::ObjectSource {name: "v2".into(),@@ -17240,6 +17243,7 @@ CREATE TABLE "Other"."prefix""Source"."NAME" ("ID" INT);"#;source: "SELECT 2".into(),editable: None,routine_parameters: None,+ trigger: None,},];let selection =diff --git a/crates/dbx-core/src/lib.rs b/crates/dbx-core/src/lib.rsindex c63d4074bd..3aa5af14a2 100644--- a/crates/dbx-core/src/lib.rs+++ b/crates/dbx-core/src/lib.rs@@ -77,6 +77,7 @@ pub use dbx_sql::mysql_event_sql;pub use dbx_sql::object_source_sql;pub use dbx_sql::oracle_view_rename;pub use dbx_types::models;+pub use dbx_types::native_jobs;pub use host::external;pub use persistence::history;pub use query::document_ops;diff --git a/crates/dbx-core/src/query/mod.rs b/crates/dbx-core/src/query/mod.rsindex 87d910f67a..3b7dc5c019 100644--- a/crates/dbx-core/src/query/mod.rs+++ b/crates/dbx-core/src/query/mod.rs@@ -2762,7 +2762,7 @@ fn external_driver_preview_fallback_sql(sql: &str) -> Option<String> {Some(format!("{}{}{}", &sql[..select_end], rewritten_projection, &sql[from_start..]))}-fn is_external_driver_method_unsupported(error: &str, method: &str) -> bool {+pub(crate) fn is_external_driver_method_unsupported(error: &str, method: &str) -> bool {let normalized = error.to_ascii_lowercase();let method = method.to_ascii_lowercase();normalized.contains(&method)diff --git a/crates/dbx-core/src/schema/exact_metadata.rs b/crates/dbx-core/src/schema/exact_metadata.rsindex 392f1ee6aa..85a82d6c85 100644--- a/crates/dbx-core/src/schema/exact_metadata.rs+++ b/crates/dbx-core/src/schema/exact_metadata.rs@@ -527,6 +527,7 @@ for line in sys.stdin:None,None,Some("exact-test"),+ &MetadataReadOptions::default(),).await.unwrap();@@ -550,6 +551,7 @@ for line in sys.stdin:Some(&types),None,Some("exact-test"),+ &MetadataReadOptions::default(),).await.unwrap();@@ -583,6 +585,7 @@ for line in sys.stdin:Some(&["INDEX".into()]),None,Some("exact-test"),+ &MetadataReadOptions::default(),).await;if mode == "legacy-empty" {@@ -608,6 +611,7 @@ for line in sys.stdin:Some(&["INDEX".into()]),None,Some("exact-test"),+ &MetadataReadOptions::default(),).await.unwrap();diff --git a/crates/dbx-core/src/schema/mod.rs b/crates/dbx-core/src/schema/mod.rsindex ad4404e0cc..8c3671b8de 100644--- a/crates/dbx-core/src/schema/mod.rs+++ b/crates/dbx-core/src/schema/mod.rs@@ -1,4 +1,5 @@pub mod exact_metadata;+pub mod native_jobs;pub mod table_structure_sql;pub use dbx_drivers::metadata::sqlite_ddl;@@ -28,6 +29,7 @@ mod mongodb_columns;mod oracle_ddl_indexes;pub mod oracle_routines;mod oracle_table_triggers;+mod oracle_triggers;pub use oracle_ddl_indexes::{prepare_schema_sync_oracle_ddl_core, separate_table_ddl_indexes_core};mod oracle_type_data;mod oracle_type_details;@@ -40,6 +42,8 @@ pub mod plugin_metadata;mod plugin_metadata_tests;#[cfg(test)]mod sqlserver_temporal_ddl_tests;+#[cfg(all(test, unix))]+mod trigger_metadata_routing_tests;macro_rules! extract_pool {($pool:expr, $variant:ident) => {@@ -125,6 +129,7 @@ const TDENGINE_LIKE_PATTERN_MAX_BYTES: usize = 100;pub use dbx_types::metadata_filter::{sql_like_pattern_matches_case_insensitive, table_name_filter_matches, TableNameFilter,};+pub use dbx_types::oracle_trigger::{MetadataIdentityMode, MetadataReadOptions};fn clickhouse_metadata_database<'a>(database: &'a str, schema: &'a str) -> &'a str {if schema.trim().is_empty() {@@ -4693,6 +4698,7 @@ donesource: "CREATE EVENT event_daily_sync ON SCHEDULE EVERY 1 DAY DO SELECT 1".to_string(),editable: None,routine_parameters: None,+ trigger: None,},None,);@@ -4713,6 +4719,7 @@ donesource: "CREATE TYPE ...".to_string(),editable: Some(true),routine_parameters: None,+ trigger: None,},Some(&config),);@@ -4741,6 +4748,7 @@ donesource: "CREATE TYPE ...".into(),editable: Some(true),routine_parameters: None,+ trigger: None,},Some(&config),);@@ -7011,6 +7019,33 @@ pub async fn list_objects_core(offset: Option<usize>,object_types: Option<&[String]>,table_name_filter: Option<&TableNameFilter>,+) -> Result<Vec<db::ObjectInfo>, String> {+ list_objects_core_with_options(+ state,+ connection_id,+ database,+ schema,+ filter,+ limit,+ offset,+ object_types,+ table_name_filter,+ &Default::default(),+ )+ .await+}++pub async fn list_objects_core_with_options(+ state: &AppState,+ connection_id: &str,+ database: &str,+ schema: &str,+ filter: Option<&str>,+ limit: Option<usize>,+ offset: Option<usize>,+ object_types: Option<&[String]>,+ table_name_filter: Option<&TableNameFilter>,+ options: &MetadataReadOptions,) -> Result<Vec<db::ObjectInfo>, String> {let db_config = connection_config(state, connection_id).await;if db_config.as_ref().is_some_and(|config| config.db_type == DatabaseType::OceanbaseOracle) {@@ -7037,6 +7072,7 @@ pub async fn list_objects_core(object_types,table_name_filter,metadata_session.client_session_id(),+ options,).await.map(|outcome| {@@ -7665,6 +7701,7 @@ fn unpaged_object_list(objects: Vec<db::ObjectInfo>) -> ObjectListOutcome {ObjectListOutcome { objects, paging_applied: false }}+#[allow(clippy::too_many_arguments)]async fn list_objects_once(state: &AppState,connection_id: &str,@@ -7676,10 +7713,30 @@ async fn list_objects_once(object_types: Option<&[String]>,table_name_filter: Option<&TableNameFilter>,client_session_id: Option<&str>,+ options: &MetadataReadOptions,) -> Result<ObjectListOutcome, String> {let pool_key =state.get_or_create_metadata_pool_for_session(connection_id, Some(database), client_session_id).await?;let db_config = connection_config(state, connection_id).await;+ if options.is_exact() {+ if let Some(result) = oracle_triggers::list_objects(+ state,+ &pool_key,+ db_config.as_ref(),+ database,+ schema,+ filter,+ limit,+ offset,+ object_types,+ table_name_filter,+ options,+ )+ .await?+ {+ return Ok(result);+ }+ }let force_local_table_name_filter = table_name_filter.is_some_and(|filter| !filter.is_empty());let (mysql_limit, mysql_offset) = if filter.is_none_or(|value| value.trim().is_empty())&& table_name_filter.is_none_or(|filter| filter.is_empty())@@ -8093,8 +8150,20 @@ async fn list_completion_objects_once(db::postgres::list_objects(p, schema, true, true, false).await.map(filter_completion_objects)}PoolKind::SqlServer(_) => {- let outcome =- list_objects_once(state, connection_id, database, schema, None, None, None, None, None, None).await?;+ let outcome = list_objects_once(+ state,+ connection_id,+ database,+ schema,+ None,+ None,+ None,+ None,+ None,+ None,+ &Default::default(),+ )+ .await?;Ok(filter_completion_objects(outcome.objects))}_ => Ok(Vec::new()),@@ -9227,6 +9296,17 @@ pub async fn list_triggers_core(database: &str,schema: &str,table: &str,+) -> Result<Vec<db::TriggerInfo>, String> {+ list_triggers_core_with_options(state, connection_id, database, schema, table, &Default::default()).await+}++pub async fn list_triggers_core_with_options(+ state: &AppState,+ connection_id: &str,+ database: &str,+ schema: &str,+ table: &str,+ options: &MetadataReadOptions,) -> Result<Vec<db::TriggerInfo>, String> {if crate::sql_dialect::parse_sqlserver_linked_schema_ref(schema).is_some() {return Ok(vec![]);@@ -9237,13 +9317,35 @@ pub async fn list_triggers_core({let pool_handle = state.pool_handle(&pool_key).await;+ if let Some(PoolKind::ExternalDriver { config, session, .. }) = pool_handle.as_ref() {+ let mut params = serde_json::json!({ "connection": config.as_ref(), "database": database, "schema": schema, "table": table });+ options.apply_to(&mut params);+ return match session.invoke_with_timeout("listTriggers", params, agent_metadata_timeout(Some(config.as_ref()))).await {+ Err(error) if !options.is_exact() && crate::query::is_external_driver_method_unsupported(&error, "listTriggers") => Ok(Vec::new()),+ result => result,+ };+ }try_sqlserver!(pool_handle, list_triggers, schema, table);if let Some(client) = extract_pool!(pool_handle.as_ref(), Agent) {+ if options.is_exact() && db_config.as_ref().is_some_and(|config| config.db_type == DatabaseType::Oracle && !is_default_oracle_agent_config(config)) {+ let mut reader = oracle_triggers::agent_reader(client, database, schema, agent_metadata_timeout(db_config.as_ref())).await;+ return reader.list_triggers(schema, table).await;+ }let mut client = client.lock().await;- let triggers =- client.list_triggers(database, schema, table, agent_metadata_timeout(db_config.as_ref())).await?;+ let triggers = client+ .list_triggers_with_options(+ database,+ schema,+ table,+ options,+ agent_metadata_timeout(db_config.as_ref()),+ )+ .await?;drop(client);drop(pool_handle);+ if options.is_exact() {+ return Ok(triggers);+ }return oracle_table_triggers::enrich(state, connection_id, database, schema, table, triggers).await;}}@@ -9253,6 +9355,9 @@ pub async fn list_triggers_core(match &pool {PoolKind::Mysql(p, mode) => {if *mode == MysqlMode::OceanBaseOracle {+ if options.is_exact() {+ return oracle_triggers::pool_reader(p.clone()).await.list_triggers(schema, table).await;+ }db::ob_oracle::list_triggers(p, schema, table).await} else {db::mysql::list_triggers(p, mysql_table_metadata_catalog(database, schema), table).await@@ -12052,9 +12157,34 @@ pub async fn get_object_source_core(object_type: db::ObjectSourceKind,signature: Option<&str>,relation_name: Option<&str>,+) -> Result<db::ObjectSource, String> {+ get_object_source_core_with_options(+ state,+ connection_id,+ database,+ schema,+ name,+ object_type,+ signature,+ relation_name,+ &Default::default(),+ )+ .await+}++pub async fn get_object_source_core_with_options(+ state: &AppState,+ connection_id: &str,+ database: &str,+ schema: &str,+ name: &str,+ object_type: db::ObjectSourceKind,+ signature: Option<&str>,+ relation_name: Option<&str>,+ options: &MetadataReadOptions,) -> Result<db::ObjectSource, String> {let config = connection_config(state, connection_id).await;- let source = retry_metadata_connection(state, connection_id, Some(database), || {+ let mut source = retry_metadata_connection(state, connection_id, Some(database), || {get_object_source_once(state,connection_id,@@ -12064,9 +12194,13 @@ pub async fn get_object_source_core(object_type.clone(),signature,relation_name,+ options,)}).await?;+ if options.is_exact() {+ oracle_triggers::validate_source_definition(&mut source, schema, name);+ }Ok(finalize_object_source(source, config.as_ref()))}@@ -12145,37 +12279,26 @@ async fn managed_object_source<T: serde::de::DeserializeOwned + Send + 'static>(object_type: &db::ObjectSourceKind,signature: Option<&str>,relation_name: Option<&str>,+ options: &MetadataReadOptions,include_source_origin: bool,timeout: Option<Duration>,) -> Result<T, String> {match pool {PoolKind::Agent(client) => {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- }+ client+ .get_object_source_with_options(+ database,+ schema,+ name,+ object_type,+ signature,+ relation_name,+ options,+ include_source_origin,+ timeout,+ )+ .await}PoolKind::ExternalDriver { config, session, .. } => {let mut params = serde_json::json!({@@ -12185,6 +12308,7 @@ async fn managed_object_source<T: serde::de::DeserializeOwned + Send + 'static>("name": name,"object_type": object_type,});+ options.apply_to(&mut params);// An empty signature identifies the zero-argument overload; absence means unknown.if let Some(signature) = signature {params["signature"] = serde_json::Value::String(signature.to_string());@@ -12207,6 +12331,7 @@ async fn get_object_source_once(object_type: db::ObjectSourceKind,signature: Option<&str>,relation_name: Option<&str>,+ options: &MetadataReadOptions,) -> Result<db::ObjectSource, String> {let pool_key = state.get_or_create_metadata_pool_for_session(connection_id, Some(database), None).await?;let db_config = connection_config(state, connection_id).await;@@ -12237,6 +12362,7 @@ async fn get_object_source_once(source,editable: None,routine_parameters: None,+ trigger: None,});}let result: db::ObjectSource = managed_object_source(@@ -12247,6 +12373,7 @@ async fn get_object_source_once(&object_type,signature,None,+ options,false,agent_metadata_timeout(Some(config.as_ref())),)@@ -12265,6 +12392,17 @@ async fn get_object_source_once(}first_string_cell(result?)?} else if let Some(client) = extract_pool!(pool_handle.as_ref(), Agent) {+ if options.is_exact()+ && matches!(object_type, db::ObjectSourceKind::Trigger)+ && db_config.as_ref().is_some_and(|config| {+ config.db_type == DatabaseType::Oracle && !is_default_oracle_agent_config(config)+ })+ {+ let mut reader =+ oracle_triggers::agent_reader(client, database, schema, agent_metadata_timeout(db_config.as_ref()))+ .await;+ return reader.source(schema, name).await;+ }if uses_oracle_metadata_object_source(db_config.as_ref(), &object_type) {oracle_agent_object_source(client,@@ -12295,6 +12433,7 @@ async fn get_object_source_once(source,editable: None,routine_parameters: None,+ trigger: None,});}None => String::new(),@@ -12308,6 +12447,7 @@ async fn get_object_source_once(&object_type,signature,relation_name,+ options,false,agent_metadata_timeout(db_config.as_ref()),)@@ -12316,6 +12456,17 @@ async fn get_object_source_once(}} else {match pool_handle.as_ref().ok_or("Pool not found")? {+ PoolKind::Mysql(pool, MysqlMode::OceanBaseOracle)+ if matches!(object_type, db::ObjectSourceKind::Trigger) =>+ {+ if options.is_exact() {+ return oracle_triggers::pool_reader(pool.clone()).await.source(schema, name).await;+ }+ first_string_cell(+ db::mysql::execute_query(pool, &oracle_object_source_sql(schema, name, &object_type), true)+ .await?,+ )?+ }PoolKind::Mysql(pool, _) => {mysql_object_source(pool, mysql_table_metadata_catalog(database, schema), name, &object_type).await?@@ -12437,6 +12588,7 @@ async fn get_object_source_once(source,editable,routine_parameters: None,+ trigger: None,})}diff --git a/crates/dbx-core/src/schema/native_jobs/details.rs b/crates/dbx-core/src/schema/native_jobs/details.rsnew file mode 100644index 0000000000..09105610ca--- /dev/null+++ b/crates/dbx-core/src/schema/native_jobs/details.rs@@ -0,0 +1,475 @@+use super::*;+use dbx_types::native_jobs::{+ NativeJobArgument, NativeJobArgumentValue, NativeJobCatalogSource, NativeJobDetails, NativeJobEngine,+ NativeJobReferenceKind, NativeJobReferenceListRequest, NativeJobRow, NativeJobSnapshot,+};++pub(super) fn map_metadata<T, U>(data: NativeJobMetadata<T>, map: impl FnOnce(T) -> U) -> NativeJobMetadata<U> {+ match data {+ NativeJobMetadata::Available { value } => NativeJobMetadata::Available { value: map(value) },+ NativeJobMetadata::Truncated { value, limit } => NativeJobMetadata::Truncated { value: map(value), limit },+ NativeJobMetadata::Empty => NativeJobMetadata::Empty,+ NativeJobMetadata::Denied { reason } => NativeJobMetadata::Denied { reason },+ NativeJobMetadata::Unsupported { reason } => NativeJobMetadata::Unsupported { reason },+ NativeJobMetadata::Error { reason } => NativeJobMetadata::Error { reason },+ NativeJobMetadata::Unknown { reason } => NativeJobMetadata::Unknown { reason },+ }+}++pub(super) fn integer(value: Option<&Value>) -> Option<i64> {+ value.and_then(|value| value.as_i64().or_else(|| value.as_str()?.parse().ok()))+}++pub(super) fn boolean(value: Option<&Value>) -> Option<bool> {+ match value? {+ Value::Bool(value) => Some(*value),+ Value::Number(number) if number.as_i64() == Some(1) => Some(true),+ Value::Number(number) if number.as_i64() == Some(0) => Some(false),+ Value::String(value) if value.eq_ignore_ascii_case("true") || value == "1" => Some(true),+ Value::String(value) if value.eq_ignore_ascii_case("false") || value == "0" => Some(false),+ _ => None,+ }+}++/// Oracle documents these as generated observations, not user-owned Job definition inputs.+/// Keep their raw values in details; only semantic comparison excludes them.+pub(super) fn generated_definition_column(+ engine: NativeJobEngine,+ target: &NativeJobRef,+ row: &NativeJobRow,+ name: &str,+) -> bool {+ engine == NativeJobEngine::Oracle+ && matches!(target, NativeJobRef::Scheduler { .. })+ && (matches!(name, "FLAGS" | "EVENT_RULE" | "NUMBER_OF_DESTINATIONS")+ || (file_watcher_reference_present(row)+ && matches!(name, "EVENT_QUEUE_OWNER" | "EVENT_QUEUE_NAME" | "EVENT_QUEUE_AGENT")))+}++pub(super) fn file_watcher_reference_present(row: &NativeJobRow) -> bool {+ ["FILE_WATCHER_OWNER", "FILE_WATCHER_NAME"]+ .iter()+ .all(|name| row.get(*name).and_then(Value::as_str).is_some_and(|value| !value.is_empty()))+}++/// Keep raw partitions for lossless display. Referenced Program counts/defaults are independent+/// of inline job columns; an unreadable default or opaque ANYDATA never becomes an inferred NULL.+pub async fn read_native_job_details_with<Q, F>(+ dialect: NativeJobCatalogDialect,+ target: &NativeJobRef,+ mut query: Q,+) -> Result<NativeJobDetails, &'static str>+where+ Q: FnMut(NativeJobCatalogQuery) -> F,+ F: Future<Output = Result<Value, NativeJobCatalogFailure>>,+{+ target.validate()?;+ let before =+ read_native_job_catalog_part_with(dialect, target, NativeJobCatalogPart::Generation, &mut query).await?;+ let mut sources = BTreeMap::new();+ let mut partitions = BTreeMap::new();+ for (key, part) in [+ ("definition", NativeJobCatalogPart::Definition),+ ("arguments", NativeJobCatalogPart::Arguments),+ ("steps", NativeJobCatalogPart::Steps),+ ("schedules", NativeJobCatalogPart::Schedules),+ ("running", NativeJobCatalogPart::Running),+ ("history", NativeJobCatalogPart::History),+ ] {+ let section = read_native_job_catalog_part_with(dialect, target, part, &mut query).await?;+ sources.insert(+ key.into(),+ NativeJobCatalogSource { source: section.source.map(str::to_string), coverage: section.coverage },+ );+ partitions.insert(key, section.data);+ }+ let mut definition =+ map_metadata(partitions.remove("definition").unwrap(), |rows| rows.into_iter().next().unwrap_or_default());+ if dialect == NativeJobCatalogDialect::OceanbaseOracle && matches!(target, NativeJobRef::Scheduler { .. }) {+ let native =+ read_native_job_catalog_part_with(dialect, target, NativeJobCatalogPart::NativeAttributes, &mut query)+ .await?;+ sources.insert(+ "nativeDefinition".into(),+ NativeJobCatalogSource { source: native.source.map(str::to_string), coverage: native.coverage },+ );+ if let NativeJobMetadata::Available { value: definition } = &mut definition {+ // The public MAX_FAILURES column is a compatibility NULL, not the actual limit.+ definition.remove("MAX_FAILURES");+ if let (NativeJobMetadata::Available { value: native }, NativeJobMetadata::Available { value: identity }) =+ (&native.data, &before.data)+ {+ if let (Some(native), Some(identity)) = (native.first(), identity.first()) {+ if native.get("DBX_JOB_ID") == identity.get("DBX_JOB_ID")+ && native.get("DBX_CREATED_AT") == identity.get("DBX_CREATED_AT")+ && integer(native.get("MAX_FAILURES")).is_some_and(|value| value >= 0)+ {+ definition.insert("MAX_FAILURES".into(), native["MAX_FAILURES"].clone());+ }+ }+ }+ }+ }+ let legacy_definition =+ if dialect == NativeJobCatalogDialect::Dameng && matches!(target, NativeJobRef::Legacy { .. }) {+ let legacy =+ read_native_job_catalog_part_with(dialect, target, NativeJobCatalogPart::NativeAttributes, &mut query)+ .await?;+ sources.insert(+ "legacyDefinition".into(),+ NativeJobCatalogSource { source: legacy.source.map(str::to_string), coverage: legacy.coverage },+ );+ Some(map_metadata(legacy.data, |rows| rows.into_iter().next().unwrap_or_default()))+ } else {+ None+ };+ let (program, program_arguments) = if let NativeJobMetadata::Available { value } = &definition {+ if matches!(target, NativeJobRef::Scheduler { .. }) && has_program(value) {+ let name = value["PROGRAM_NAME"].as_str().unwrap();+ if let Some(owner) = value.get("PROGRAM_OWNER").and_then(Value::as_str).filter(|owner| !owner.is_empty()) {+ let mut request = NativeJobReferenceListRequest {+ scope: target.scope().clone(),+ kind: NativeJobReferenceKind::Program,+ schema: Some(owner.into()),+ name: Some(name.into()),+ filter: String::new(),+ offset: 0,+ limit: 1,+ };+ let program = super::references::read_references_with(dialect, &request, None, &mut query).await?;+ sources.insert("program".into(), program.source);+ request.kind = NativeJobReferenceKind::ProgramArguments;+ request.limit = 10_000;+ let arguments = super::references::read_references_with(dialect, &request, None, &mut query).await?;+ sources.insert("programArguments".into(), arguments.source);+ (+ Some(map_metadata(program.objects, |rows| rows.into_iter().next().unwrap_or_default())),+ Some(arguments.objects),+ )+ } else {+ let reason = "native_job_program_identity_unavailable".to_string();+ (+ Some(NativeJobMetadata::Unknown { reason: reason.clone() }),+ Some(NativeJobMetadata::Unknown { reason }),+ )+ }+ } else {+ (None, None)+ }+ } else {+ (None, None)+ };+ let after =+ read_native_job_catalog_part_with(dialect, target, NativeJobCatalogPart::Generation, &mut query).await?;+ sources.insert(+ "identity".into(),+ NativeJobCatalogSource { source: after.source.map(str::to_string), coverage: after.coverage },+ );+ let consistency = match (&before.data, &after.data) {+ (NativeJobMetadata::Available { value: before }, NativeJobMetadata::Available { value: after })+ if before == after =>+ {+ NativeJobMetadata::Available { value: () }+ }+ (NativeJobMetadata::Available { .. }, NativeJobMetadata::Available { .. }) => {+ NativeJobMetadata::Error { reason: "native_job_replaced_during_read".into() }+ }+ _ => NativeJobMetadata::Unknown { reason: "native_job_identity_unverified".into() },+ };+ let parameter_metadata = partitions.remove("arguments").unwrap();+ let arguments = parse_arguments(+ dialect,+ target,+ &definition,+ ¶meter_metadata,+ program.as_ref(),+ program_arguments.as_ref(),+ );+ Ok(NativeJobDetails {+ snapshot: NativeJobSnapshot { job_ref: target.clone(), revision: String::new(), definition, arguments },+ native_identity: map_metadata(after.data, |rows| rows.into_iter().next().unwrap_or_default()),+ consistency,+ parameter_metadata,+ program,+ program_arguments,+ legacy_definition,+ steps: partitions.remove("steps").unwrap(),+ schedules: partitions.remove("schedules").unwrap(),+ running: partitions.remove("running").unwrap(),+ history: partitions.remove("history").unwrap(),+ sources,+ })+}++fn has_program(definition: &NativeJobCatalogRow) -> bool {+ definition.get("PROGRAM_NAME").and_then(Value::as_str).is_some_and(|name| !name.is_empty())+}++fn argument_positions(+ rows: &[NativeJobCatalogRow],+ count: i64,+) -> Result<BTreeMap<i64, &NativeJobCatalogRow>, &'static str> {+ let mut result = BTreeMap::new();+ for row in rows {+ let position = integer(row.get("ARGUMENT_POSITION").or_else(|| row.get("ARG_POSITION")));+ let Some(position) = position.filter(|position| *position > 0 && *position <= count) else {+ return Err("native_job_arguments_invalid");+ };+ if result.insert(position, row).is_some() {+ return Err("native_job_arguments_ambiguous");+ }+ }+ Ok(result)+}++pub(super) fn program_default(+ engine: NativeJobEngine,+ row: Option<&NativeJobCatalogRow>,+ metadata: Option<&NativeJobMetadata<Vec<NativeJobCatalogRow>>>,+) -> NativeJobMetadata<NativeJobArgumentValue> {+ if let Some(row) = row {+ if engine == NativeJobEngine::Oracle {+ let storage = dbx_sql::native_job_arguments::decode_argument(row, true);+ if !matches!(storage, dbx_sql::native_job_arguments::ArgumentStorage::Opaque(_))+ || boolean(row.get("DBX_ANYDATA_PRESENT")) == Some(true)+ {+ return NativeJobMetadata::Available {+ value: dbx_sql::native_job_arguments::editable_argument(row, true),+ };+ }+ return NativeJobMetadata::Unknown { reason: "native_job_program_default_ambiguous".into() };+ }+ if let Some(value) = row.get("DEFAULT_VALUE").filter(|value| !value.is_null()) {+ return NativeJobMetadata::Available { value: NativeJobArgumentValue::Value { value: value.clone() } };+ }+ if let Some(value) = row.get("DEFAULT_ANYDATA_VALUE").filter(|value| !value.is_null()) {+ return NativeJobMetadata::Available { value: NativeJobArgumentValue::Opaque { value: value.clone() } };+ }+ // A nullable DEFAULT_VALUE does not distinguish no default from a string NULL default.+ return NativeJobMetadata::Unknown { reason: "native_job_program_default_ambiguous".into() };+ }+ match metadata {+ Some(NativeJobMetadata::Denied { reason }) => NativeJobMetadata::Denied { reason: reason.clone() },+ Some(NativeJobMetadata::Unsupported { reason }) => NativeJobMetadata::Unsupported { reason: reason.clone() },+ Some(NativeJobMetadata::Error { reason }) => NativeJobMetadata::Error { reason: reason.clone() },+ _ => NativeJobMetadata::Unknown { reason: "native_job_program_default_unavailable".into() },+ }+}++pub(super) type SchedulerArgumentInventory = BTreeMap<usize, NativeJobCatalogRow>;++/// Read all native overrides before considering the active Program's argument count. A conversion+/// can leave old positions behind; those rows must remain visible to reconciliation.+pub(super) fn parse_argument_inventory(+ parameters: &NativeJobMetadata<Vec<NativeJobCatalogRow>>,+) -> NativeJobMetadata<SchedulerArgumentInventory> {+ let rows = match parameters {+ NativeJobMetadata::Available { value } => value,+ NativeJobMetadata::Empty => return NativeJobMetadata::Available { value: BTreeMap::new() },+ NativeJobMetadata::Truncated { .. } => {+ return NativeJobMetadata::Unknown { reason: "native_job_arguments_truncated".into() };+ }+ other => return map_metadata(other.clone(), |_| unreachable!()),+ };+ let mut inventory = BTreeMap::new();+ for row in rows {+ let Some(position) = integer(row.get("ARGUMENT_POSITION").or_else(|| row.get("ARG_POSITION")))+ .filter(|position| *position > 0)+ .and_then(|position| usize::try_from(position).ok())+ else {+ return NativeJobMetadata::Error { reason: "native_job_arguments_invalid".into() };+ };+ if inventory.insert(position, row.clone()).is_some() {+ return NativeJobMetadata::Error { reason: "native_job_arguments_ambiguous".into() };+ }+ }+ NativeJobMetadata::Available { value: inventory }+}++pub(super) fn inventory_value(engine: NativeJobEngine, row: &NativeJobCatalogRow) -> NativeJobArgumentValue {+ if engine == NativeJobEngine::Oracle {+ return dbx_sql::native_job_arguments::editable_argument(row, false);+ }+ if row.get("OUT_ARGUMENT").is_none_or(|value| boolean(Some(value)) == Some(false)) {+ if matches!(+ row.get("DBX_ANYDATA_TYPE").and_then(Value::as_str),+ Some(+ "SYS.VARCHAR2"+ | "SYS.CHAR"+ | "SYS.NUMBER"+ | "SYS.DATE"+ | "SYS.TIMESTAMP"+ | "SYS.TIMESTAMP WITH TIME ZONE"+ )+ ) && boolean(row.get("DBX_ANYDATA_IS_NULL")) == Some(true)+ {+ return NativeJobArgumentValue::Null;+ }+ if let Some(value) = row.get("VALUE").filter(|value| !value.is_null()) {+ return NativeJobArgumentValue::Value { value: value.clone() };+ }+ }+ NativeJobArgumentValue::Opaque { value: serde_json::to_value(row).expect("JSON metadata") }+}++pub(super) fn parse_argument_layout(+ engine: NativeJobEngine,+ definition: &NativeJobMetadata<NativeJobCatalogRow>,+ program: Option<&NativeJobMetadata<NativeJobCatalogRow>>,+ program_parameters: Option<&NativeJobMetadata<Vec<NativeJobCatalogRow>>>,+) -> NativeJobMetadata<Vec<NativeJobArgument>> {+ let NativeJobMetadata::Available { value: definition } = definition else {+ return NativeJobMetadata::Unknown { reason: "native_job_argument_definition_unavailable".into() };+ };+ let program_reference = has_program(definition);+ let count_definition = if program_reference {+ match program {+ Some(NativeJobMetadata::Available { value }) => value,+ _ => return NativeJobMetadata::Unknown { reason: "native_job_program_argument_count_unavailable".into() },+ }+ } else {+ definition+ };+ let Some(count) =+ integer(count_definition.get("NUMBER_OF_ARGUMENTS")).filter(|count| *count >= 0 && *count <= 10_000)+ else {+ return NativeJobMetadata::Unknown { reason: "native_job_argument_count_unavailable".into() };+ };+ let program_rows = match program_parameters {+ Some(NativeJobMetadata::Available { value }) => match argument_positions(value, count) {+ Ok(rows) => rows,+ Err(reason) => return NativeJobMetadata::Error { reason: reason.into() },+ },+ _ => BTreeMap::new(),+ };+ let mut arguments = Vec::new();+ for position in 1..=count {+ let program_row = program_rows.get(&position).copied();+ let description = program_row;+ let name = description+ .and_then(|row| row.get("ARGUMENT_NAME").or_else(|| row.get("ARG_NAME")))+ .and_then(Value::as_str)+ .map(str::to_string);+ let data_type = description+ .and_then(|row| row.get("ARGUMENT_TYPE").or_else(|| row.get("ARG_TYPE")))+ .and_then(Value::as_str)+ .unwrap_or("UNKNOWN")+ .to_string();+ let (value, editable, reason) = if program_reference {+ (+ if program_row.is_some() {+ NativeJobArgumentValue::Inherit+ } else {+ NativeJobArgumentValue::Opaque { value: Value::Null }+ },+ program_row.is_some(),+ program_row.is_none().then(|| "native_job_program_defaults_unavailable".into()),+ )+ } else {+ (NativeJobArgumentValue::Unset, true, None)+ };+ let metadata_attribute = program_row+ .and_then(|row| row.get("METADATA_ATTRIBUTE"))+ .and_then(Value::as_str)+ .filter(|value| !value.is_empty())+ .map(str::to_string);+ let out_argument = program_row+ .and_then(|row| row.get("OUT_ARGUMENT"))+ .is_some_and(|value| !value.is_null() && boolean(Some(value)) != Some(false));+ let reason = if metadata_attribute.is_some() {+ Some("native_job_metadata_argument".into())+ } else if out_argument {+ Some("native_job_argument_opaque".into())+ } else {+ reason+ };+ let editable = editable && metadata_attribute.is_none() && !out_argument;+ let default_value = (program_reference && metadata_attribute.is_none())+ .then(|| program_default(engine, program_row, program_parameters));+ arguments.push(NativeJobArgument {+ position: position as usize,+ name,+ data_type,+ value,+ default_value,+ metadata_attribute,+ editable,+ reason,+ });+ }+ NativeJobMetadata::Available { value: arguments }+}++pub(super) fn project_arguments(+ engine: NativeJobEngine,+ layout: &[NativeJobArgument],+ inventory: &SchedulerArgumentInventory,+) -> NativeJobMetadata<Vec<NativeJobArgument>> {+ if inventory.keys().any(|position| *position > layout.len()) {+ return NativeJobMetadata::Error { reason: "native_job_arguments_invalid".into() };+ }+ let arguments = layout+ .iter()+ .cloned()+ .map(|mut argument| {+ if let Some(row) = inventory.get(&argument.position) {+ argument.value = inventory_value(engine, row);+ let out = row+ .get("OUT_ARGUMENT")+ .is_some_and(|value| !value.is_null() && boolean(Some(value)) != Some(false));+ let layout_out = argument.reason.as_deref() == Some("native_job_argument_opaque");+ argument.editable = argument.metadata_attribute.is_none()+ && !layout_out+ && !out+ && !matches!(argument.value, NativeJobArgumentValue::Opaque { .. });+ argument.reason = (!argument.editable).then(|| {+ if argument.metadata_attribute.is_some() {+ "native_job_metadata_argument"+ } else {+ "native_job_argument_opaque"+ }+ .into()+ });+ // Program metadata describes the new context even when a native engine retained an old+ // override row. Only an unknown description falls back to the native override metadata.+ if argument.data_type == "UNKNOWN" {+ argument.data_type = row+ .get("ARGUMENT_TYPE")+ .or_else(|| row.get("ARG_TYPE"))+ .and_then(Value::as_str)+ .unwrap_or("UNKNOWN")+ .into();+ argument.name = row+ .get("ARGUMENT_NAME")+ .or_else(|| row.get("ARG_NAME"))+ .and_then(Value::as_str)+ .map(str::to_string);+ }+ }+ argument+ })+ .collect();+ NativeJobMetadata::Available { value: arguments }+}++fn parse_arguments(+ engine: NativeJobEngine,+ target: &NativeJobRef,+ definition: &NativeJobMetadata<NativeJobCatalogRow>,+ parameters: &NativeJobMetadata<Vec<NativeJobCatalogRow>>,+ program: Option<&NativeJobMetadata<NativeJobCatalogRow>>,+ program_parameters: Option<&NativeJobMetadata<Vec<NativeJobCatalogRow>>>,+) -> NativeJobMetadata<Vec<NativeJobArgument>> {+ if !matches!(target, NativeJobRef::Scheduler { .. }) {+ return NativeJobMetadata::Available { value: Vec::new() };+ }+ let layout = parse_argument_layout(engine, definition, program, program_parameters);+ let inventory = parse_argument_inventory(parameters);+ match (layout, inventory) {+ (NativeJobMetadata::Available { value: layout }, NativeJobMetadata::Available { value: inventory }) => {+ project_arguments(engine, &layout, &inventory)+ }+ (NativeJobMetadata::Available { .. }, inventory) => map_metadata(inventory, |_| unreachable!()),+ (layout, _) => layout,+ }+}diff --git a/crates/dbx-core/src/schema/native_jobs/mod.rs b/crates/dbx-core/src/schema/native_jobs/mod.rsnew file mode 100644index 0000000000..1ffb5dd080--- /dev/null+++ b/crates/dbx-core/src/schema/native_jobs/mod.rs@@ -0,0 +1,413 @@+use crate::connection::PoolKind;+use crate::db::agent_driver::{AgentCallError, AgentErrorCategory, AgentSessionDisposition};+use crate::query::{agent_execute_query_params, QueryExecutionOptions};+use dbx_sql::native_jobs::{+ native_job_catalog_queries, NativeJobCatalogCoverage, NativeJobCatalogDialect, NativeJobCatalogPart,+ NativeJobCatalogQuery,+};+use dbx_types::native_jobs::{NativeJobMetadata, NativeJobRef};+use serde_json::Value;+use std::collections::{BTreeMap, HashSet};+use std::future::Future;+use std::time::Duration;++mod details;+mod operations;+mod references;+mod service;++pub use details::read_native_job_details_with;+pub use operations::{+ native_job_apply_core, native_job_apply_with, native_job_cancel, native_job_prepare_core,+ native_job_prepare_request_with, native_job_prepare_with, native_job_prepare_with_references, native_job_status,+ native_job_status_observed_core, NativeJobDispatchOutcome, NativeJobExecutionRead, NativeJobMutationSession,+ NativeJobStepReceipt,+};+pub use references::{native_job_references_core, native_job_references_with};+pub use service::{+ native_job_list_core, native_job_list_with, native_job_open_context_core, native_job_open_context_with,+ native_job_read_core, native_job_read_with, NativeJobRegistry, NativeJobRuntimeIdentity,+};++pub type NativeJobCatalogRow = BTreeMap<String, Value>;++// This backend-only token must never enter a page result or diagnostic Debug output.+#[derive(Clone)]+pub(super) struct NativeJobPhysicalSession {+ operation_id: String,+ token: String,+}++impl NativeJobPhysicalSession {+ fn bind(&self, params: &mut Value) {+ let params = params.as_object_mut().expect("native Job RPC parameters");+ params.insert("nativeJobOperationId".into(), Value::String(self.operation_id.clone()));+ params.insert("nativeJobSessionToken".into(), Value::String(self.token.clone()));+ }+}++// These contain SQL bodies and parameter values; do not derive Debug.+pub struct NativeJobCatalogSection {+ pub data: NativeJobMetadata<Vec<NativeJobCatalogRow>>,+ pub source: Option<&'static str>,+ pub coverage: Option<NativeJobCatalogCoverage>,+ pub failures: Vec<NativeJobCatalogAttemptFailure>,+}++#[derive(Debug, Clone, PartialEq, Eq)]+pub struct NativeJobCatalogAttemptFailure {+ pub source: &'static str,+ pub failure: NativeJobCatalogFailure,+}++/// Only diagnostics supplied by the driver, never text extracted from SQL or an error row.+#[derive(Debug, Clone, PartialEq, Eq)]+pub enum NativeJobCatalogFailure {+ Denied(Option<i32>),+ Unavailable(Option<i32>),+ Unsupported(Option<i32>),+ Query(Option<i32>),+ Transport,+ RouteUnavailable,+ Timeout,+ Canceled,+ InvalidResponse,+ IdentityMismatch,+ AmbiguousIdentity,+}++impl NativeJobCatalogFailure {+ pub fn sql(dialect: NativeJobCatalogDialect, vendor_code: Option<i32>, sql_state: Option<&str>) -> Self {+ let oracle_family = dialect != NativeJobCatalogDialect::Dameng;+ if sql_state == Some("42501")+ || oracle_family && vendor_code == Some(1031)+ || !oracle_family && vendor_code == Some(-5669)+ {+ Self::Denied(vendor_code)+ } else if matches!(sql_state, Some("42S02" | "42S22"))+ || oracle_family && matches!(vendor_code, Some(942 | 904))+ || !oracle_family && vendor_code == Some(-2106)+ {+ // A hidden view and a missing view can have the same native code.+ Self::Unavailable(vendor_code)+ } else if sql_state == Some("0A000") {+ Self::Unsupported(vendor_code)+ } else {+ Self::Query(vendor_code)+ }+ }++ fn from_agent(dialect: NativeJobCatalogDialect, error: AgentCallError) -> Self {+ match error {+ AgentCallError::Structured { context, .. }+ if context.category == AgentErrorCategory::Sql+ && context.session_disposition == AgentSessionDisposition::Keep =>+ {+ Self::sql(dialect, context.vendor_code, context.sql_state.as_deref())+ }+ AgentCallError::Timeout { .. } => Self::Timeout,+ AgentCallError::Canceled { .. } => Self::Canceled,+ AgentCallError::Structured { context, .. } if context.category == AgentErrorCategory::Timeout => {+ Self::Timeout+ }+ AgentCallError::Structured { context, .. } if context.category == AgentErrorCategory::Canceled => {+ Self::Canceled+ }+ AgentCallError::Structured { context, .. } if context.category == AgentErrorCategory::Sql => {+ Self::Query(context.vendor_code)+ }+ AgentCallError::Legacy { hints, .. } if hints.category == Some(AgentErrorCategory::Sql) => {+ Self::Query(None)+ }+ _ => Self::Transport,+ }+ }++ fn permits_fallback(&self) -> bool {+ matches!(self, Self::Denied(_) | Self::Unavailable(_) | Self::Unsupported(_))+ }++ fn metadata<T>(&self) -> NativeJobMetadata<T> {+ let (key, code) = match self {+ Self::Denied(code) => ("native_job_catalog_denied", *code),+ Self::Unavailable(code) => ("native_job_catalog_unavailable", *code),+ Self::Unsupported(code) => ("native_job_catalog_unsupported", *code),+ Self::Query(code) => ("native_job_catalog_query_failed", *code),+ Self::Transport => ("native_job_catalog_transport_failed", None),+ Self::RouteUnavailable => ("native_job_catalog_driver_route_missing", None),+ Self::Timeout => ("native_job_catalog_timeout", None),+ Self::Canceled => ("native_job_catalog_canceled", None),+ Self::InvalidResponse => ("native_job_catalog_invalid_response", None),+ Self::IdentityMismatch => ("native_job_catalog_identity_mismatch", None),+ Self::AmbiguousIdentity => ("native_job_catalog_identity_ambiguous", None),+ };+ let reason = code.map_or_else(|| key.to_string(), |code| format!("{key}:{code}"));+ match self {+ Self::Denied(_) => NativeJobMetadata::Denied { reason },+ Self::Unavailable(_) => NativeJobMetadata::Unknown { reason },+ Self::Unsupported(_) => NativeJobMetadata::Unsupported { reason },+ _ => NativeJobMetadata::Error { reason },+ }+ }+}++/// Read a single partition using the existing driver corridor without query history or body logging.+/// The caller owns the connection lifecycle and the selected target's context binding.+pub async fn read_native_job_catalog_part(+ dialect: NativeJobCatalogDialect,+ target: &NativeJobRef,+ part: NativeJobCatalogPart,+ pool: &PoolKind,+ timeout: Option<Duration>,+) -> Result<NativeJobCatalogSection, &'static str> {+ let database = &target.scope().database;+ read_native_job_catalog_part_with(dialect, target, part, |query| {+ execute_catalog_query(dialect, pool, database, query, timeout)+ })+ .await+}++pub(super) async fn execute_catalog_query(+ dialect: NativeJobCatalogDialect,+ pool: &PoolKind,+ database: &str,+ query: NativeJobCatalogQuery,+ timeout: Option<Duration>,+) -> Result<Value, NativeJobCatalogFailure> {+ execute_catalog_query_in_session(dialect, pool, database, query, timeout, None).await+}++pub(super) async fn execute_catalog_query_in_session(+ dialect: NativeJobCatalogDialect,+ pool: &PoolKind,+ database: &str,+ query: NativeJobCatalogQuery,+ timeout: Option<Duration>,+ physical: Option<&NativeJobPhysicalSession>,+) -> Result<Value, NativeJobCatalogFailure> {+ match pool {+ PoolKind::Agent(client) => {+ let mut client = tokio::time::timeout(crate::connection::METADATA_POOL_ACQUIRE_TIMEOUT, client.lock())+ .await+ .map_err(|_| NativeJobCatalogFailure::Timeout)?;+ let mut params = agent_execute_query_params(+ &query.sql,+ (!database.is_empty()).then_some(database),+ None,+ QueryExecutionOptions {+ max_rows: Some(query.limit + 1),+ fetch_size: Some(1_000),+ ..Default::default()+ },+ );+ if let Some(physical) = physical {+ physical.bind(&mut params);+ }+ client+ .execute_query_typed_with_timeout(params, timeout)+ .await+ .map_err(|error| NativeJobCatalogFailure::from_agent(dialect, error))+ }+ PoolKind::ExternalDriver { config, session, .. } => {+ let mut params = serde_json::json!({ "connection": config.as_ref(), "database": database, "sql": query.sql,+ "maxRows": query.limit + 1, "fetchSize": 1000, "deferLobs": false, "nativeDiagnostics": true });+ if let Some(physical) = physical {+ physical.bind(&mut params);+ }+ session+ .invoke_with_timeout("executeQuery", params, timeout)+ .await+ .map_err(|_| NativeJobCatalogFailure::Transport)+ }+ _ => Err(NativeJobCatalogFailure::RouteUnavailable),+ }+}++/// The callback is the database boundary. All source choice, result validation and identity checks+/// are shared by production reads and tests.+pub async fn read_native_job_catalog_part_with<Q, F>(+ dialect: NativeJobCatalogDialect,+ target: &NativeJobRef,+ part: NativeJobCatalogPart,+ mut query: Q,+) -> Result<NativeJobCatalogSection, &'static str>+where+ Q: FnMut(NativeJobCatalogQuery) -> F,+ F: Future<Output = Result<Value, NativeJobCatalogFailure>>,+{+ let queries = native_job_catalog_queries(dialect, target, part)?;+ read_catalog_candidates_with(+ queries,+ |raw, limit| decode_catalog_rows(dialect, target, part, raw, limit),+ &mut query,+ )+ .await+}++async fn read_catalog_candidates_with<Q, F, D>(+ queries: Vec<NativeJobCatalogQuery>,+ decode: D,+ query: &mut Q,+) -> Result<NativeJobCatalogSection, &'static str>+where+ Q: FnMut(NativeJobCatalogQuery) -> F,+ F: Future<Output = Result<Value, NativeJobCatalogFailure>>,+ D: Fn(Value, usize) -> Result<NativeJobMetadata<Vec<NativeJobCatalogRow>>, NativeJobCatalogFailure>,+{+ let mut failures = Vec::new();+ let mut source = None;+ let mut coverage = None;+ for candidate in queries {+ source = Some(candidate.source);+ coverage = Some(candidate.coverage);+ let limit = candidate.limit;+ let read = query(candidate).await.and_then(|raw| decode(raw, limit));+ match read {+ Ok(data) => return Ok(NativeJobCatalogSection { data, source, coverage, failures }),+ Err(failure) => {+ let retry = failure.permits_fallback();+ failures.push(NativeJobCatalogAttemptFailure { source: source.unwrap(), failure });+ if !retry {+ break;+ }+ }+ }+ }+ let data = failures.last().map_or_else(+ || NativeJobMetadata::Unsupported { reason: "native_job_catalog_section_not_applicable".into() },+ |attempt| attempt.failure.metadata(),+ );+ Ok(NativeJobCatalogSection { data, source, coverage, failures })+}++fn decode_catalog_rows(+ dialect: NativeJobCatalogDialect,+ target: &NativeJobRef,+ part: NativeJobCatalogPart,+ raw: Value,+ limit: usize,+) -> Result<NativeJobMetadata<Vec<NativeJobCatalogRow>>, NativeJobCatalogFailure> {+ let result = decode_query_result(dialect, raw)?;+ if matches!(+ part,+ NativeJobCatalogPart::Definition | NativeJobCatalogPart::Generation | NativeJobCatalogPart::NativeAttributes+ ) && result.rows.len() > 1+ {+ return Err(NativeJobCatalogFailure::AmbiguousIdentity);+ }+ rows_from_result(result, limit, |row| validate_catalog_identity(dialect, target, part, row))+}++fn decode_query_result(+ dialect: NativeJobCatalogDialect,+ raw: Value,+) -> Result<dbx_types::types::QueryResult, NativeJobCatalogFailure> {+ for flag in ["execution_error", "executionError"] {+ if raw.get(flag).is_some_and(|flag| flag != &Value::Bool(false) && !flag.is_null()) {+ return Err(query_response_failure(dialect, &raw));+ }+ }+ if raw.get("error").is_some_and(|error| !error.is_null()) {+ return Err(query_response_failure(dialect, &raw));+ }+ let result: dbx_types::types::QueryResult =+ serde_json::from_value(raw).map_err(|_| NativeJobCatalogFailure::InvalidResponse)?;+ Ok(result)+}++fn rows_from_result(+ result: dbx_types::types::QueryResult,+ limit: usize,+ validate: impl Fn(&NativeJobCatalogRow) -> Result<(), NativeJobCatalogFailure>,+) -> Result<NativeJobMetadata<Vec<NativeJobCatalogRow>>, NativeJobCatalogFailure> {+ let mut column_names = HashSet::new();+ let columns = result.columns.iter().map(|column| column.to_ascii_uppercase()).collect::<Vec<_>>();+ if columns.is_empty() || columns.iter().any(|column| column.is_empty() || !column_names.insert(column)) {+ return Err(NativeJobCatalogFailure::InvalidResponse);+ }+ if result.rows.iter().any(|row| row.len() != columns.len()) {+ return Err(NativeJobCatalogFailure::InvalidResponse);+ }+ let incomplete = result.truncated || result.has_more || result.rows.len() > limit;+ let mut rows = result+ .rows+ .into_iter()+ .take(limit)+ .map(|row| columns.iter().cloned().zip(row).collect::<NativeJobCatalogRow>())+ .collect::<Vec<_>>();+ for row in &mut rows {+ validate(row)?;+ for value in row.values_mut() {+ *value = dbx_types::json::json_value_for_js(value.take());+ }+ }+ Ok(if incomplete {+ NativeJobMetadata::Truncated { value: rows, limit }+ } else if rows.is_empty() {+ NativeJobMetadata::Empty+ } else {+ NativeJobMetadata::Available { value: rows }+ })+}++fn query_response_failure(dialect: NativeJobCatalogDialect, raw: &Value) -> NativeJobCatalogFailure {+ let diagnostics = &raw["error"]["diagnostics"];+ match diagnostics["category"].as_str() {+ Some("sql") => NativeJobCatalogFailure::sql(+ dialect,+ diagnostics["vendorCode"].as_i64().and_then(|code| i32::try_from(code).ok()),+ diagnostics["sqlState"].as_str(),+ ),+ Some("connection") => NativeJobCatalogFailure::Transport,+ Some("timeout") => NativeJobCatalogFailure::Timeout,+ Some("canceled") => NativeJobCatalogFailure::Canceled,+ _ => NativeJobCatalogFailure::Query(None),+ }+}++fn validate_catalog_identity(+ dialect: NativeJobCatalogDialect,+ target: &NativeJobRef,+ part: NativeJobCatalogPart,+ row: &NativeJobCatalogRow,+) -> Result<(), NativeJobCatalogFailure> {+ let mismatch = NativeJobCatalogFailure::IdentityMismatch;+ if matches!(part, NativeJobCatalogPart::Generation | NativeJobCatalogPart::NativeAttributes) {+ let id = row.get("DBX_JOB_ID").and_then(Value::as_str).ok_or(mismatch.clone())?;+ if id.is_empty() || id.starts_with('0') || !id.bytes().all(|byte| byte.is_ascii_digit()) {+ return Err(mismatch);+ }+ if matches!(target, NativeJobRef::Legacy { job_id, .. } | NativeJobRef::DamengNative { job_id, .. } if id != job_id)+ {+ return Err(mismatch);+ }+ if !matches!(target, NativeJobRef::Legacy { .. })+ && row.get("DBX_CREATED_AT").and_then(Value::as_str).is_none_or(str::is_empty)+ {+ return Err(mismatch);+ }+ }+ if matches!(part, NativeJobCatalogPart::Definition | NativeJobCatalogPart::NativeAttributes) {+ let valid = match target {+ NativeJobRef::Scheduler { owner, name, .. } => {+ row.get("DBX_OWNER").or_else(|| row.get("OWNER")).and_then(Value::as_str) == Some(owner)+ && row.get("JOB_NAME").and_then(Value::as_str) == Some(name)+ }+ NativeJobRef::Legacy { job_id, .. } => {+ row.get("DBX_JOB_ID").and_then(Value::as_str) == Some(job_id)+ && (dialect != NativeJobCatalogDialect::Dameng+ || part == NativeJobCatalogPart::NativeAttributes+ || matches!(row.get("SYS_FLAG"), Some(Value::Number(value)) if value.as_i64() == Some(2))+ || row.get("SYS_FLAG").and_then(Value::as_str) == Some("2"))+ }+ NativeJobRef::DamengNative { job_id, name, .. } => {+ row.get("DBX_JOB_ID").and_then(Value::as_str) == Some(job_id)+ && row.get("NAME").and_then(Value::as_str) == Some(name)+ }+ };+ if !valid {+ return Err(mismatch);+ }+ }+ Ok(())+}diff --git a/crates/dbx-core/src/schema/native_jobs/operations.rs b/crates/dbx-core/src/schema/native_jobs/operations.rsnew file mode 100644index 0000000000..71ca7958e1--- /dev/null+++ b/crates/dbx-core/src/schema/native_jobs/operations.rs@@ -0,0 +1,1582 @@+use super::*;+use crate::connection::{AppState, ClientSessionPoolCleanupGuard};+use crate::session_credentials::{current_credential_owner, with_credential_owner};+use dbx_sql::native_job_changes::{+ native_job_dameng_create_plan, native_job_legacy_create_preview, native_job_mutation_plan,+ native_job_scheduler_create_plan, native_job_scheduler_edit_plan, NativeJobDamengCreatePlan,+ NativeJobSchedulerSqlPlan, NativeJobSqlPlan, NativeJobSqlStep, NativeJobStepEffect,+};+use dbx_types::native_jobs::*;+use std::collections::{HashMap, VecDeque};+use std::sync::{Arc, Mutex, Weak};+use tokio_util::sync::CancellationToken;++const MAX_OPERATIONS: usize = 256;++mod arguments;+mod dameng;+mod legacy;+mod observation;+pub use observation::Snapshot as NativeJobExecutionRead;+mod scheduler;+mod values;++enum PreparedAction {+ Mutation { mutation: NativeJobMutation, plan: NativeJobSqlPlan },+ SchedulerTransition { mutation: NativeJobMutation, plan: Box<scheduler::transition::PreparedSchedulerTransition> },+ LegacyCreate { definition: NativeJobLegacyCreate, steps: Vec<NativeJobStepPreview> },+ SchedulerCreate { definition: Box<NativeJobSchedulerCreate>, plan: NativeJobSchedulerSqlPlan },+ DamengCreate { definition: NativeJobDamengCreate, plan: NativeJobDamengCreatePlan },+}++struct PreparedExecution {+ binding: super::service::BoundContext,+ action: PreparedAction,+ origin_key: String,+ lock_key: String,+}++type OperationClaim = (NativeJobOperationStatus, Option<(PreparedExecution, CancellationToken)>);++struct OperationRecord {+ plan_id: String,+ actor: Option<String>,+ status: NativeJobOperationStatus,+ pending: Option<PreparedExecution>,+ cancel: CancellationToken,+ observation: Option<Arc<tokio::sync::Mutex<observation::Tracker>>>,+ rename: Option<Arc<tokio::sync::Mutex<dameng::rename::Binding>>>,+ run_lease: Option<Weak<RunLease>>,+}++struct RunLease {+ _guards: Vec<tokio::sync::OwnedMutexGuard<()>>,+ binding: super::service::BoundContext,+ target: NativeJobRef,+ identity: NativeJobRow,+}++struct PublishedRun {+ operations: NativeJobOperations,+ id: String,+ _lease: Arc<RunLease>,+}++impl Drop for PublishedRun {+ fn drop(&mut self) {+ if let Some(record) = self+ .operations+ .0+ .lock()+ .unwrap_or_else(|error| error.into_inner())+ .records+ .iter_mut()+ .find(|record| record.status.operation_id == self.id)+ {+ record.run_lease = None;+ }+ }+}++#[derive(Default)]+struct Ledger {+ records: VecDeque<OperationRecord>,+ job_locks: HashMap<String, Weak<tokio::sync::Mutex<()>>>,+ pending_dm_configurations: HashSet<String>,+}++#[derive(Clone, Default)]+pub struct NativeJobOperations(Arc<Mutex<Ledger>>);++impl NativeJobOperations {+ fn register(&self, execution: PreparedExecution) -> Result<NativeJobPreparedPlan, &'static str> {+ let plan_id = uuid::Uuid::new_v4().to_string();+ let operation_id = uuid::Uuid::new_v4().to_string();+ let (target, steps) = match &execution.action {+ PreparedAction::Mutation { mutation, plan } => (+ Some(mutation.target.clone()),+ plan.steps+ .iter()+ .map(|step| NativeJobStepPreview {+ id: step.id.clone(),+ label: step.label.clone(),+ sql: step.sql.clone(),+ })+ .collect(),+ ),+ PreparedAction::SchedulerTransition { mutation, plan } => (+ Some(mutation.target.clone()),+ plan.edit+ .sql+ .steps+ .iter()+ .map(|step| NativeJobStepPreview {+ id: step.id.clone(),+ label: step.label.clone(),+ sql: step.sql.clone(),+ })+ .collect(),+ ),+ PreparedAction::LegacyCreate { steps, .. } => (None, steps.clone()),+ PreparedAction::DamengCreate { plan, .. } => (+ None,+ plan.steps+ .iter()+ .map(|step| NativeJobStepPreview {+ id: step.id.clone(),+ label: step.label.clone(),+ sql: step.sql.clone(),+ })+ .collect(),+ ),+ PreparedAction::SchedulerCreate { plan, .. } => (+ Some(plan.target.clone()),+ plan.steps+ .iter()+ .map(|step| NativeJobStepPreview {+ id: step.id.clone(),+ label: step.label.clone(),+ sql: step.sql.clone(),+ })+ .collect(),+ ),+ };+ let prepared = NativeJobPreparedPlan {+ plan_id: plan_id.clone(),+ operation_id: operation_id.clone(),+ scope: execution.binding.context.scope.clone(),+ target,+ steps,+ };+ let status = NativeJobOperationStatus {+ operation_id,+ target: prepared.target.clone(),+ observed_identity: None,+ created_children: Vec::new(),+ execution_observation: None,+ state: NativeJobOperationState::Prepared,+ outcome: NativeJobOperationOutcome::NotStarted,+ cancel_requested: false,+ steps: prepared+ .steps+ .iter()+ .map(|step| NativeJobStepStatus {+ id: step.id.clone(),+ state: NativeJobStepState::Pending,+ reason: None,+ vendor_code: None,+ })+ .collect(),+ reason: None,+ };+ let mut ledger = self.0.lock().unwrap_or_else(|error| error.into_inner());+ if ledger.records.len() >= MAX_OPERATIONS {+ let disposable = ledger+ .records+ .iter()+ .position(|record| {+ matches!(record.status.state, NativeJobOperationState::Prepared | NativeJobOperationState::Finished)+ })+ .ok_or("native_job_operations_busy")?;+ ledger.records.remove(disposable);+ }+ ledger.records.push_back(OperationRecord {+ plan_id,+ actor: current_credential_owner(),+ status,+ pending: Some(execution),+ cancel: CancellationToken::new(),+ observation: None,+ rename: None,+ run_lease: None,+ });+ Ok(prepared)+ }++ fn claim(&self, plan_id: &str) -> Result<OperationClaim, &'static str> {+ let actor = current_credential_owner();+ let mut ledger = self.0.lock().unwrap_or_else(|error| error.into_inner());+ let record = ledger+ .records+ .iter_mut()+ .find(|record| record.plan_id == plan_id && record.actor == actor)+ .ok_or("native_job_preview_stale")?;+ let execution = record.pending.take();+ if execution.is_some() {+ record.status.state = NativeJobOperationState::Queued;+ }+ Ok((record.status.clone(), execution.map(|execution| (execution, record.cancel.clone()))))+ }++ fn status(&self, operation_id: &str) -> NativeJobOperationStatus {+ let actor = current_credential_owner();+ self.0+ .lock()+ .unwrap_or_else(|error| error.into_inner())+ .records+ .iter()+ .find(|record| record.status.operation_id == operation_id && record.actor == actor)+ .map(|record| record.status.clone())+ .unwrap_or_else(|| missing_status(operation_id))+ }++ fn edit(&self, operation_id: &str, edit: impl FnOnce(&mut NativeJobOperationStatus)) {+ let actor = current_credential_owner();+ if let Some(record) = self+ .0+ .lock()+ .unwrap_or_else(|error| error.into_inner())+ .records+ .iter_mut()+ .find(|record| record.status.operation_id == operation_id && record.actor == actor)+ {+ edit(&mut record.status);+ }+ }++ fn job_lock(&self, key: &str) -> Arc<tokio::sync::Mutex<()>> {+ let mut ledger = self.0.lock().unwrap_or_else(|error| error.into_inner());+ ledger.job_locks.retain(|_, lock| lock.strong_count() > 0);+ if let Some(lock) = ledger.job_locks.get(key).and_then(Weak::upgrade) {+ return lock;+ }+ let lock = Arc::new(tokio::sync::Mutex::new(()));+ ledger.job_locks.insert(key.into(), Arc::downgrade(&lock));+ lock+ }++ fn configuration_pending(&self, key: &str) -> bool {+ self.0.lock().unwrap_or_else(|error| error.into_inner()).pending_dm_configurations.contains(key)+ }++ fn publish_run(+ &self,+ id: &str,+ execution: &PreparedExecution,+ target: &NativeJobRef,+ identity: NativeJobRow,+ guards: &mut Vec<tokio::sync::OwnedMutexGuard<()>>,+ step: usize,+ ) -> PublishedRun {+ let lease = Arc::new(RunLease {+ _guards: std::mem::take(guards),+ binding: execution.binding.clone(),+ target: target.clone(),+ identity,+ });+ let mut ledger = self.0.lock().unwrap_or_else(|error| error.into_inner());+ let record =+ ledger.records.iter_mut().find(|record| record.status.operation_id == id).expect("claimed Run record");+ record.run_lease = Some(Arc::downgrade(&lease));+ record.status.steps[step].state = NativeJobStepState::Dispatching;+ PublishedRun { operations: self.clone(), id: id.into(), _lease: lease }+ }++ fn borrow_run(&self, execution: &PreparedExecution, target: &NativeJobRef) -> Option<Arc<RunLease>> {+ let actor = current_credential_owner();+ let ledger = self.0.lock().unwrap_or_else(|error| error.into_inner());+ ledger+ .records+ .iter()+ .filter(|record| {+ record.actor == actor+ && record.status.state == NativeJobOperationState::Running+ && record+ .status+ .steps+ .iter()+ .any(|step| step.id == "run" && step.state == NativeJobStepState::Dispatching)+ })+ .find_map(|record| {+ let lease = record.run_lease.as_ref()?.upgrade()?;+ (&lease.target == target && lease.binding.context.scope == execution.binding.context.scope)+ .then_some(lease)+ })+ }++ fn configuration_dispatched(&self, key: &str) -> bool {+ self.0.lock().unwrap_or_else(|error| error.into_inner()).pending_dm_configurations.insert(key.into())+ }++ fn configuration_verified(&self, key: &str) {+ self.0.lock().unwrap_or_else(|error| error.into_inner()).pending_dm_configurations.remove(key);+ }+}++fn missing_status(operation_id: &str) -> NativeJobOperationStatus {+ NativeJobOperationStatus {+ operation_id: operation_id.into(),+ target: None,+ observed_identity: None,+ created_children: Vec::new(),+ execution_observation: None,+ state: NativeJobOperationState::Finished,+ outcome: NativeJobOperationOutcome::Unknown,+ cancel_requested: false,+ steps: Vec::new(),+ reason: Some("native_job_operation_record_unavailable".into()),+ }+}++pub fn native_job_status(state: &AppState, operation_id: &str) -> NativeJobOperationStatus {+ state.native_jobs.operations().status(operation_id)+}++pub async fn native_job_status_observed_core(+ state: &AppState,+ operation_id: &str,+ observe: bool,+) -> NativeJobOperationStatus {+ let operations = state.native_jobs.operations();+ let actor = current_credential_owner();+ let (tracker, rename) = if observe {+ operations+ .0+ .lock()+ .unwrap_or_else(|error| error.into_inner())+ .records+ .iter()+ .find(|record| {+ record.status.operation_id == operation_id+ && record.actor == actor+ && record.status.state == NativeJobOperationState::Finished+ })+ .map(|record| (record.observation.clone(), record.rename.clone()))+ .unwrap_or_default()+ } else {+ (None, None)+ };+ if let Some(tracker) = tracker {+ let mut tracker = tracker.lock().await;+ let result = observation::read_core(state, &tracker.binding, &tracker.target).await;+ let observed = match result {+ Ok(current) => tracker.record(current),+ Err(reason) => observation::unavailable(reason),+ };+ operations.edit(operation_id, |status| status.execution_observation = Some(observed));+ }+ if let Some(tracker) = rename {+ let tracker = tracker.lock().await;+ if let Ok((target, identity)) = dameng::rename::observe_core(state, &tracker).await {+ operations.edit(operation_id, |status| {+ status.target = Some(target);+ status.observed_identity = Some(identity);+ });+ }+ }+ operations.status(operation_id)+}++pub fn native_job_cancel(state: &AppState, operation_id: &str) -> NativeJobOperationStatus {+ let operations = state.native_jobs.operations();+ let actor = current_credential_owner();+ {+ let mut ledger = operations.0.lock().unwrap_or_else(|error| error.into_inner());+ if let Some(record) =+ ledger.records.iter_mut().find(|record| record.status.operation_id == operation_id && record.actor == actor)+ {+ if record.status.state != NativeJobOperationState::Finished {+ record.cancel.cancel();+ record.status.cancel_requested = true;+ if record.pending.take().is_some() {+ record.status.state = NativeJobOperationState::Finished;+ record.status.outcome = NativeJobOperationOutcome::NotApplied;+ record.status.reason = Some("native_job_canceled_before_dispatch".into());+ for step in &mut record.status.steps {+ step.state = NativeJobStepState::Skipped;+ }+ }+ }+ }+ }+ operations.status(operation_id)+}++pub async fn native_job_prepare_with<Q, F>(+ state: &AppState,+ mutation: NativeJobMutation,+ read: Q,+) -> Result<NativeJobPreparedPlan, &'static str>+where+ Q: FnOnce(NativeJobRef) -> F,+ F: Future<Output = Result<NativeJobDetails, &'static str>>,+{+ native_job_prepare_with_references(state, mutation, read, |request| async move {+ super::native_job_references_core(state, &request).await.map_err(|_| "native_job_reference_read_failed")+ })+ .await+}++pub async fn native_job_prepare_with_references<Q, F, R, RF>(+ state: &AppState,+ mutation: NativeJobMutation,+ read: Q,+ mut read_reference: R,+) -> Result<NativeJobPreparedPlan, &'static str>+where+ Q: FnOnce(NativeJobRef) -> F,+ F: Future<Output = Result<NativeJobDetails, &'static str>>,+ R: FnMut(NativeJobReferenceListRequest) -> RF,+ RF: Future<Output = Result<NativeJobReferenceCatalog, &'static str>>,+{+ mutation.target.validate()?;+ let binding = state.native_jobs.context(state, mutation.target.scope())?;+ let latest = read(mutation.target.clone()).await?;+ let scheduler_edit = if matches!(mutation.target, NativeJobRef::Scheduler { .. })+ && matches!(mutation.change, NativeJobChange::Update { .. })+ {+ Some(native_job_scheduler_edit_plan(binding.context.engine, &mutation, &latest)?)+ } else {+ None+ };+ let mut plan = scheduler_edit+ .as_ref()+ .map(|edit| Ok(edit.sql.clone()))+ .unwrap_or_else(|| native_job_mutation_plan(binding.context.engine, &mutation, &latest));+ let NativeJobMetadata::Available { value: identity } = &latest.native_identity else {+ return Err("native_job_identity_unverified");+ };+ let origin_key = native_origin_key(&binding, &mutation.target, identity);+ if binding.context.engine == NativeJobEngine::Dameng+ && !matches!(mutation.target, NativeJobRef::Scheduler { .. })+ && (matches!(mutation.change, NativeJobChange::Enable)+ || (plan.as_ref().err().copied() == Some("native_job_no_changes")+ && matches!(mutation.change, NativeJobChange::Update { .. } | NativeJobChange::ConfigureDameng { .. })))+ && (state.native_jobs.operations().configuration_pending(&origin_key)+ || row(&latest).is_some_and(|row| row.get("VALID").and_then(Value::as_str) == Some("N")))+ {+ // A fresh preview explicitly shows the new configuration cycle. It neither replays the+ // previous fields nor sends an old COMMIT to a replacement physical session.+ let enabled = if matches!(mutation.change, NativeJobChange::Enable) {+ true+ } else {+ row(&latest)+ .and_then(|row| super::details::boolean(row.get("ENABLE")))+ .ok_or("native_job_metadata_incomplete")?+ };+ let recovery = NativeJobMutation {+ target: mutation.target.clone(),+ baseline: mutation.baseline.clone(),+ change: NativeJobChange::Update {+ final_enabled: None,+ argument_target: None,+ attributes: vec![NativeJobAttributeChange {+ name: "ENABLE".into(),+ change: NativeJobFieldChange::Set { value: Value::Bool(enabled) },+ }],+ arguments: Vec::new(),+ },+ };+ plan = native_job_mutation_plan(binding.context.engine, &recovery, &latest);+ }+ let mut plan = plan?;+ let transition = if let Some(edit) = scheduler_edit.filter(|edit| edit.transition) {+ let prepared = scheduler::transition::prepare(&binding, &mutation, &latest, edit, &mut read_reference).await?;+ plan = prepared.edit.sql.clone();+ Some(prepared)+ } else {+ None+ };+ if binding.context.engine == NativeJobEngine::Dameng+ && matches!(mutation.target, NativeJobRef::Legacy { .. })+ && matches!(+ mutation.change,+ NativeJobChange::Run+ | NativeJobChange::Enable+ | NativeJobChange::Disable+ | NativeJobChange::Drop { .. }+ | NativeJobChange::ClearHistory+ )+ && state.native_jobs.legacy_definition_recorded(state, &mutation.target, &mutation.baseline)?+ {+ plan.required_partitions.push("legacyDefinition".into());+ }+ state.native_jobs.compare_baseline(+ state,+ &mutation.target,+ &mutation.baseline,+ &latest.snapshot.revision,+ &plan.required_partitions.iter().map(String::as_str).collect::<Vec<_>>(),+ plan.compare_next_date,+ )?;+ state.native_jobs.context(state, mutation.target.scope())?;+ let lock_key = if binding.context.engine == NativeJobEngine::Dameng+ && !matches!(mutation.target, NativeJobRef::Scheduler { .. })+ {+ let name = match &mutation.target {+ NativeJobRef::DamengNative { name, .. } => name.as_str(),+ _ => row(&latest)+ .and_then(|row| row.get("NAME"))+ .and_then(Value::as_str)+ .ok_or("native_job_metadata_incomplete")?,+ };+ dameng_name_key(&binding, name)+ } else {+ origin_key.clone()+ };+ state.native_jobs.operations().register(PreparedExecution {+ binding,+ action: match transition {+ Some(plan) => PreparedAction::SchedulerTransition { mutation, plan: Box::new(plan) },+ None => PreparedAction::Mutation { mutation, plan },+ },+ origin_key,+ lock_key,+ })+}++fn native_origin_key(binding: &super::service::BoundContext, target: &NativeJobRef, identity: &NativeJobRow) -> String {+ if let NativeJobRef::Scheduler { owner, name, .. } = target {+ // Name-scoped serialization also covers the absent -> created transition. A generation+ // check still rejects an old preview after same-name replacement.+ return serde_json::to_string(&serde_json::json!([+ target.scope().connection_id,+ target.scope().database,+ binding.context.actual_database,+ binding.context.engine,+ "scheduler",+ owner,+ name,+ ]))+ .expect("JSON identity");+ }+ let family =+ if binding.context.engine == NativeJobEngine::Dameng && !matches!(target, NativeJobRef::Scheduler { .. }) {+ "dameng-native"+ } else if matches!(target, NativeJobRef::Scheduler { .. }) {+ "scheduler"+ } else {+ "legacy"+ };+ serde_json::to_string(&serde_json::json!([+ target.scope().connection_id,+ target.scope().database,+ binding.context.actual_database,+ binding.context.engine,+ family,+ identity.get("DBX_JOB_ID"),+ identity.get("DBX_CREATED_AT")+ ]))+ .expect("JSON identity")+}++fn dameng_name_key(binding: &super::service::BoundContext, name: &str) -> String {+ serde_json::to_string(&serde_json::json!([+ binding.context.scope.connection_id,+ binding.context.scope.database,+ binding.context.actual_database,+ "dameng-native-name",+ name.to_ascii_uppercase(),+ ]))+ .expect("JSON identity")+}++pub async fn native_job_prepare_request_with<Q, F>(+ state: &AppState,+ request: NativeJobRequest,+ read: Q,+) -> Result<NativeJobPreparedPlan, &'static str>+where+ Q: FnOnce(NativeJobRef) -> F,+ F: Future<Output = Result<NativeJobDetails, &'static str>>,+{+ match request {+ NativeJobRequest::Mutation(mutation) => native_job_prepare_with(state, mutation, read).await,+ NativeJobRequest::Create { scope, definition: NativeJobCreateDefinition::DamengNative(definition) } => {+ scope.validate()?;+ let binding = state.native_jobs.context(state, &scope)?;+ if binding.context.engine != NativeJobEngine::Dameng {+ return Err("native_job_action_not_applicable");+ }+ let plan = native_job_dameng_create_plan(&definition)?;+ let origin_key = dameng_name_key(&binding, &definition.name);+ state.native_jobs.operations().register(PreparedExecution {+ binding,+ action: PreparedAction::DamengCreate { definition, plan },+ lock_key: origin_key.clone(),+ origin_key,+ })+ }+ NativeJobRequest::Create { scope, definition: NativeJobCreateDefinition::Scheduler(mut definition) } => {+ scope.validate()?;+ let binding = state.native_jobs.context(state, &scope)?;+ if definition.owner.is_empty() {+ definition.owner = binding.context.session_user.clone();+ }+ scheduler::validate_namespace(&binding, &definition)?;+ let plan = native_job_scheduler_create_plan(binding.context.engine, &scope, &definition, None)?;+ let latest = read(plan.target.clone()).await?;+ scheduler::require_absent(&latest, &binding.context.session_user)?;+ state.native_jobs.context(state, &scope)?;+ let origin_key = native_origin_key(&binding, &plan.target, &NativeJobRow::new());+ state.native_jobs.operations().register(PreparedExecution {+ binding,+ action: PreparedAction::SchedulerCreate { definition, plan },+ lock_key: origin_key.clone(),+ origin_key,+ })+ }+ NativeJobRequest::Create { scope, definition: NativeJobCreateDefinition::Legacy(mut definition) } => {+ scope.validate()?;+ let binding = state.native_jobs.context(state, &scope)?;+ if !matches!(binding.context.engine, NativeJobEngine::Oracle | NativeJobEngine::OceanbaseOracle) {+ return Err("native_job_legacy_protocol_unavailable");+ }+ let parsed = chrono::NaiveDateTime::parse_from_str(&definition.next_date, "%Y-%m-%d %H:%M:%S")+ .map_err(|_| "native_job_date_invalid")?;+ if chrono::Datelike::year(&parsed) < 1+ || parsed.format("%Y-%m-%d %H:%M:%S").to_string() != definition.next_date+ {+ return Err("native_job_date_invalid");+ }+ if definition.schema.is_empty() {+ definition.schema = binding.context.session_user.clone();+ }+ let steps = native_job_legacy_create_preview(binding.context.engine, &definition)?;+ let origin_key = serde_json::to_string(&serde_json::json!([+ scope.connection_id,+ scope.database,+ binding.context.actual_database,+ binding.context.engine,+ "legacy-create",+ binding.context.session_user,+ ]))+ .expect("JSON identity");+ state.native_jobs.operations().register(PreparedExecution {+ binding,+ action: PreparedAction::LegacyCreate { definition, steps },+ lock_key: origin_key.clone(),+ origin_key,+ })+ }+ }+}++pub async fn native_job_prepare_core(+ state: &AppState,+ mut request: NativeJobRequest,+) -> Result<NativeJobPreparedPlan, String> {+ arguments::normalize_core(state, &mut request).await.map_err(str::to_string)?;+ native_job_prepare_request_with(state, request, |target| async move {+ super::native_job_read_core(state, &target).await.map_err(|_| "native_job_readback_failed")+ })+ .await+ .map_err(str::to_string)+}++#[derive(Clone, Copy, PartialEq, Eq)]+pub enum NativeJobDispatchOutcome {+ NotStarted,+ Applied,+ Unknown,+}++pub struct NativeJobStepReceipt {+ pub outcome: NativeJobDispatchOutcome,+ pub reason: Option<String>,+ pub vendor_code: Option<i32>,+}++#[async_trait::async_trait]+pub trait NativeJobMutationSession: Send {+ async fn read(&mut self, target: &NativeJobRef) -> Result<NativeJobDetails, &'static str>;+ async fn read_execution(&mut self, _target: &NativeJobRef) -> Result<NativeJobExecutionRead, &'static str> {+ Err("native_job_execution_reader_unavailable")+ }+ async fn execute(&mut self, step: &NativeJobSqlStep) -> NativeJobStepReceipt;+ async fn read_reference(+ &mut self,+ _request: NativeJobReferenceListRequest,+ ) -> Result<NativeJobReferenceCatalog, &'static str> {+ Err("native_job_reference_reader_unavailable")+ }+ async fn begin_configure(&mut self, _operation_id: &str) -> Result<(), &'static str> {+ Err("native_job_configuration_protocol_unavailable")+ }+ async fn query(&mut self, _query: NativeJobCatalogQuery) -> Result<Value, NativeJobCatalogFailure> {+ Err(NativeJobCatalogFailure::RouteUnavailable)+ }+ async fn prepare_legacy(+ &mut self,+ operation_id: &str,+ _definition: &NativeJobLegacyCreate,+ ) -> NativeJobLegacyReceipt {+ legacy::receipt(operation_id, NativeJobLegacyPhase::NotStarted, "native_job_legacy_protocol_unavailable")+ }+ async fn finish_legacy(+ &mut self,+ operation_id: &str,+ _job_id: Option<&str>,+ _commit: bool,+ ) -> NativeJobLegacyReceipt {+ legacy::receipt(operation_id, NativeJobLegacyPhase::Unknown, "native_job_legacy_session_unavailable")+ }+ /// Close this operation's own scope. Never commit or activate during cleanup.+ async fn finish(&mut self) -> Result<(), &'static str>;+}++pub async fn native_job_apply_with(+ state: &AppState,+ plan_id: &str,+ session: &mut impl NativeJobMutationSession,+) -> Result<NativeJobOperationStatus, &'static str> {+ let operations = state.native_jobs.operations().clone();+ let (status, claimed) = operations.claim(plan_id)?;+ if let Some((execution, cancel)) = claimed {+ run_claimed(state, &operations, &status.operation_id, execution, cancel, session).await;+ }+ Ok(operations.status(&status.operation_id))+}++struct UnknownOnDrop {+ operations: NativeJobOperations,+ id: String,+ armed: bool,+}+impl Drop for UnknownOnDrop {+ fn drop(&mut self) {+ if self.armed {+ finish_status(+ &self.operations,+ &self.id,+ NativeJobOperationOutcome::Unknown,+ Some("native_job_worker_interrupted"),+ );+ }+ }+}++fn finish_status(operations: &NativeJobOperations, id: &str, outcome: NativeJobOperationOutcome, reason: Option<&str>) {+ operations.edit(id, |status| {+ status.state = NativeJobOperationState::Finished;+ status.outcome = outcome;+ status.reason = reason.map(str::to_string);+ for step in &mut status.steps {+ if step.state == NativeJobStepState::Pending {+ step.state = NativeJobStepState::Skipped;+ } else if step.state == NativeJobStepState::Dispatching {+ step.state = NativeJobStepState::Unknown;+ }+ }+ });+}++async fn require_write(state: &AppState, binding: &super::service::BoundContext) -> Result<(), &'static str> {+ if !state.connection_lifecycle_is_current(&binding.context.scope.connection_id, &binding.lifecycle) {+ return Err("native_job_context_changed");+ }+ if !state.configs.read().await.contains_key(&binding.context.scope.connection_id) {+ return Err("native_job_connection_missing");+ }+ if crate::query::connection_readonly_name(state, &binding.context.scope.connection_id).await.is_some() {+ return Err("native_job_connection_read_only");+ }+ Ok(())+}++async fn run_claimed(+ state: &AppState,+ operations: &NativeJobOperations,+ id: &str,+ execution: PreparedExecution,+ cancel: CancellationToken,+ session: &mut impl NativeJobMutationSession,+) {+ let mut guard = UnknownOnDrop { operations: operations.clone(), id: id.into(), armed: true };+ let mut lock_keys = vec![execution.lock_key.clone()];+ if let PreparedAction::Mutation { plan, .. } = &execution.action {+ for step in &plan.steps {+ if let NativeJobStepEffect::DamengRenamed { old_name, new_name } = &step.effect {+ lock_keys.extend([+ dameng_name_key(&execution.binding, old_name),+ dameng_name_key(&execution.binding, new_name),+ ]);+ }+ }+ }+ lock_keys.sort();+ lock_keys.dedup();+ let locks = lock_keys.iter().map(|key| operations.job_lock(key)).collect::<Vec<_>>();+ let mut job_guards = Vec::new();+ let mut shared_run = None;+ let mut published_run = None;+ let mut stop_guard = None;+ let mut created_job_guard = None;+ let scope = &execution.binding.context.scope;+ let mut dispatched = false;+ let result: Result<NativeJobOperationOutcome, (&'static str, NativeJobOperationOutcome)> = async {+ if let PreparedAction::Mutation { mutation, .. } = &execution.action {+ if matches!(mutation.change, NativeJobChange::Stop { .. }) {+ let serial = operations.job_lock(&format!("native-stop:{}", execution.lock_key));+ stop_guard = Some(tokio::select! {+ biased;+ _ = cancel.cancelled() => return Err(("native_job_canceled_before_dispatch", NativeJobOperationOutcome::NotApplied)),+ _ = execution.binding.lifecycle.cancellation().cancelled() => return Err(("native_job_context_changed", NativeJobOperationOutcome::NotApplied)),+ guard = serial.lock_owned() => guard,+ });+ shared_run = operations.borrow_run(&execution, &mutation.target);+ }+ }+ if shared_run.is_none() { for lock in &locks { job_guards.push(tokio::select! {+ biased;+ _ = cancel.cancelled() => return Err(("native_job_canceled_before_dispatch", NativeJobOperationOutcome::NotApplied)),+ _ = execution.binding.lifecycle.cancellation().cancelled() => return Err(("native_job_context_changed", NativeJobOperationOutcome::NotApplied)),+ guard = lock.clone().lock_owned() => guard,+ }); } }+ require_write(state, &execution.binding).await.map_err(|reason| (reason, NativeJobOperationOutcome::NotApplied))?;+ if matches!(&execution.action, PreparedAction::LegacyCreate { .. }) {+ return legacy::run_create(state, &execution, id, &cancel, session, &mut created_job_guard, &mut dispatched).await;+ }+ if matches!(&execution.action, PreparedAction::SchedulerCreate { .. }) {+ return scheduler::run_create(state, &execution, id, &cancel, session, &mut dispatched).await;+ }+ if matches!(&execution.action, PreparedAction::DamengCreate { .. }) {+ return dameng::run_create(state, &execution, id, &cancel, session, &mut dispatched).await;+ }+ if matches!(&execution.action, PreparedAction::SchedulerTransition { .. }) {+ return scheduler::transition::run(state, &execution, id, &cancel, session, &mut dispatched).await;+ }+ let PreparedAction::Mutation { mutation, plan } = &execution.action else { unreachable!() };+ if plan.dameng_configuration.is_some() {+ return dameng::run_configure(state, &execution, id, &cancel, session, &mut dispatched).await;+ }+ if execution.binding.context.engine == NativeJobEngine::Dameng+ && !matches!(mutation.target, NativeJobRef::Scheduler { .. })+ && matches!(mutation.change, NativeJobChange::Enable | NativeJobChange::Run)+ && operations.configuration_pending(&execution.origin_key)+ {+ return Err(("native_job_configuration_preview_required", NativeJobOperationOutcome::NotApplied));+ }+ let mut before = session.read(&mutation.target).await.map_err(|reason| (reason, NativeJobOperationOutcome::NotApplied))?;+ state.native_jobs.compare_baseline(state, &mutation.target, &mutation.baseline,+ &before.snapshot.revision, &plan.required_partitions.iter().map(String::as_str).collect::<Vec<_>>(),+ plan.compare_next_date).map_err(|reason| (reason, NativeJobOperationOutcome::NotApplied))?;+ if let Some(lease) = &shared_run {+ require_write(state, &lease.binding).await.map_err(|reason| (reason, NativeJobOperationOutcome::NotApplied))?;+ if !matches!(&before.native_identity, NativeJobMetadata::Available { value } if value == &lease.identity) {+ return Err(("native_job_replaced", NativeJobOperationOutcome::NotApplied));+ }+ }+ operations.edit(id, |status| status.state = NativeJobOperationState::Running);+ let mut outcome = NativeJobOperationOutcome::Verified;+ for (index, step) in plan.steps.iter().enumerate() {+ let stopped = if cancel.is_cancelled() { Some("native_job_canceled_after_dispatch") }+ else { require_write(state, &execution.binding).await.err() };+ if let Some(reason) = stopped { return Err((reason, if dispatched { NativeJobOperationOutcome::Partial } else { NativeJobOperationOutcome::NotApplied })); }+ if plan.steps.len() == 1 && matches!(mutation.change, NativeJobChange::Run)+ && (matches!(mutation.target, NativeJobRef::Scheduler { .. }) || execution.binding.context.engine == NativeJobEngine::Dameng)+ {+ let NativeJobMetadata::Available { value: identity } = &before.native_identity else { unreachable!("baseline identity verified") };+ published_run = Some(operations.publish_run(id, &execution, &mutation.target, identity.clone(), &mut job_guards, index));+ } else {+ operations.edit(id, |status| status.steps[index].state = NativeJobStepState::Dispatching);+ }+ dispatched = true;+ // Do not drop an in-flight mutation because a page canceled its remaining steps.+ let receipt = session.execute(step).await;+ operations.edit(id, |status| {+ status.steps[index].vendor_code = receipt.vendor_code;+ status.steps[index].reason = receipt.reason.clone();+ status.steps[index].state = match receipt.outcome {+ NativeJobDispatchOutcome::NotStarted => NativeJobStepState::Failed,+ NativeJobDispatchOutcome::Applied => NativeJobStepState::Applied,+ NativeJobDispatchOutcome::Unknown => NativeJobStepState::Unknown,+ };+ });+ if receipt.outcome == NativeJobDispatchOutcome::NotStarted {+ return Err(("native_job_step_not_applied", if index == 0 { NativeJobOperationOutcome::NotApplied } else { NativeJobOperationOutcome::Partial }));+ }+ if matches!(step.effect, NativeJobStepEffect::Accepted | NativeJobStepEffect::Completed) {+ if matches!(step.effect, NativeJobStepEffect::Accepted)+ && matches!(mutation.change, NativeJobChange::Run | NativeJobChange::Stop { .. })+ {+ let tracker = Arc::new(tokio::sync::Mutex::new(observation::Tracker {+ binding: execution.binding.clone(), target: mutation.target.clone(),+ stop: matches!(mutation.change, NativeJobChange::Stop { .. }),+ baseline: NativeJobExecutionRead::from_details(&before),+ running_keys: HashSet::new(),+ }));+ if let Some(record) = operations.0.lock().unwrap_or_else(|error| error.into_inner()).records.iter_mut()+ .find(|record| record.status.operation_id == id && record.actor == current_credential_owner())+ {+ record.observation = Some(tracker.clone());+ }+ let mut tracker = tracker.lock().await;+ let observed = if !state.connection_lifecycle_is_current(&scope.connection_id, &execution.binding.lifecycle) {+ observation::unavailable("native_job_context_changed")+ } else {+ match session.read_execution(&mutation.target).await {+ Ok(current) if state.connection_lifecycle_is_current(&scope.connection_id, &execution.binding.lifecycle) => tracker.record(current),+ Ok(_) => observation::unavailable("native_job_context_changed"),+ Err(reason) => observation::unavailable(reason),+ }+ };+ operations.edit(id, |status| status.execution_observation = Some(observed));+ }+ if receipt.outcome == NativeJobDispatchOutcome::Unknown { return Err(("native_job_execution_outcome_unknown", NativeJobOperationOutcome::Unknown)); }+ outcome = if matches!(step.effect, NativeJobStepEffect::Completed) { NativeJobOperationOutcome::Verified } else { NativeJobOperationOutcome::Accepted };+ operations.edit(id, |status| status.steps[index].state = if outcome == NativeJobOperationOutcome::Accepted { NativeJobStepState::Accepted } else { NativeJobStepState::Applied });+ continue;+ }+ if !state.connection_lifecycle_is_current(&scope.connection_id, &execution.binding.lifecycle) {+ return Err(("native_job_context_changed", NativeJobOperationOutcome::Unknown));+ }+ let after = session.read(&mutation.target).await.map_err(|reason| (reason,+ if receipt.outcome == NativeJobDispatchOutcome::Unknown { NativeJobOperationOutcome::Unknown } else { NativeJobOperationOutcome::Partial }))?;+ if !verify_effect(&before, &after, &step.effect, &execution.binding.context.session_user, execution.binding.context.engine) {+ return Err(("native_job_readback_not_verified", if receipt.outcome == NativeJobDispatchOutcome::Unknown { NativeJobOperationOutcome::Unknown } else { NativeJobOperationOutcome::Partial }));+ }+ operations.edit(id, |status| status.steps[index].state = NativeJobStepState::Applied);+ if matches!(step.effect, NativeJobStepEffect::Deleted) {+ operations.configuration_verified(&execution.origin_key);+ }+ before = after;+ }+ Ok(outcome)+ }.await;+ let (outcome, reason) = match result {+ Ok(outcome) => (+ outcome,+ if outcome == NativeJobOperationOutcome::Accepted+ && matches!(&execution.action, PreparedAction::Mutation { plan, .. } if plan.steps.iter().any(|step| matches!(step.effect, NativeJobStepEffect::DamengLegacyInterval { expected_seconds: None })))+ {+ Some("native_job_legacy_interval_expression_not_readable")+ } else {+ None+ },+ ),+ Err((reason, outcome)) => (outcome, Some(reason)),+ };+ let (outcome, reason) = if session.finish().await.is_err() {+ (+ if dispatched { NativeJobOperationOutcome::Unknown } else { NativeJobOperationOutcome::NotApplied },+ Some("native_job_session_cleanup_unknown"),+ )+ } else {+ (outcome, reason)+ };+ finish_status(operations, id, outcome, reason);+ guard.armed = false;+ drop(published_run);+ drop(shared_run);+ drop(stop_guard);+ drop(created_job_guard);+ drop(job_guards);+}++fn row(details: &NativeJobDetails) -> Option<&NativeJobRow> {+ match &details.snapshot.definition {+ NativeJobMetadata::Available { value } => Some(value),+ _ => None,+ }+}++fn verify_effect(+ before: &NativeJobDetails,+ after: &NativeJobDetails,+ effect: &NativeJobStepEffect,+ session_user: &str,+ engine: NativeJobEngine,+) -> bool {+ verify_effect_with_extra(before, after, effect, session_user, engine, &[])+}++fn verify_effect_with_extra(+ before: &NativeJobDetails,+ after: &NativeJobDetails,+ effect: &NativeJobStepEffect,+ session_user: &str,+ engine: NativeJobEngine,+ extra: &[&str],+) -> bool {+ if matches!(effect, NativeJobStepEffect::Deleted) {+ let source = after.sources.get("definition");+ let own = matches!(&after.snapshot.job_ref, NativeJobRef::Scheduler { owner, .. } if owner == session_user)+ || row(before).is_some_and(|row| {+ row.get("LOG_USER").or_else(|| row.get("USERNAME")).and_then(Value::as_str) == Some(session_user)+ });+ return matches!(after.snapshot.definition, NativeJobMetadata::Empty)+ && matches!(after.native_identity, NativeJobMetadata::Empty)+ && (own || source.is_some_and(|source| source.coverage == Some(NativeJobCatalogCoverage::Database)));+ }+ if !matches!(after.consistency, NativeJobMetadata::Available { .. })+ || before.native_identity != after.native_identity+ {+ return false;+ }+ if !preserved_definition_with_extra(before, after, effect, extra, engine) {+ return false;+ }+ match effect {+ NativeJobStepEffect::Enabled(expected) => {+ let Some(row) = row(after) else {+ return false;+ };+ super::details::boolean(row.get("ENABLED").or_else(|| row.get("ENABLE"))) == Some(*expected)+ || row.get("BROKEN").and_then(Value::as_str) == Some(if *expected { "N" } else { "Y" })+ }+ NativeJobStepEffect::SchedulerDefinition(effect) => row(after).is_some_and(|row| {+ effect.columns.iter().all(|change| match &change.change {+ NativeJobFieldChange::Set { value } => {+ values::field_matches(&change.name, row.get(&change.name), value)+ }+ NativeJobFieldChange::Clear => row.get(&change.name) == Some(&Value::Null),+ NativeJobFieldChange::Keep => true,+ }) && scheduler::transition::reference_projections_match(row, &effect.references)+ }),+ NativeJobStepEffect::Fields(changes) => row(after).is_some_and(|row| {+ changes.iter().all(|change| match &change.change {+ NativeJobFieldChange::Set { value } => {+ values::field_matches(&change.name, row.get(&change.name), value)+ }+ NativeJobFieldChange::Clear => row.get(&change.name) == Some(&Value::Null),+ NativeJobFieldChange::Keep => true,+ })+ }),+ NativeJobStepEffect::Argument(change, expected) if engine == NativeJobEngine::Oracle => {+ match super::details::parse_argument_inventory(&after.parameter_metadata) {+ NativeJobMetadata::Available { value } => match &change.value {+ NativeJobArgumentValue::Inherit | NativeJobArgumentValue::Unset => {+ !value.contains_key(&change.position)+ }+ _ => value.get(&change.position).is_some_and(|row| match expected {+ Some(expected) => expected.matches(&dbx_sql::native_job_arguments::decode_argument(row, false)),+ None => dbx_sql::native_job_arguments::oracle_argument_matches(row, &change.value, "UNKNOWN"),+ }),+ },+ _ => false,+ }+ }+ NativeJobStepEffect::Argument(change, _) => match &after.snapshot.arguments {+ NativeJobMetadata::Available { value } => {+ value.iter().any(|argument| argument.position == change.position && argument.value == change.value)+ }+ _ => false,+ },+ NativeJobStepEffect::HistoryCleared => {+ matches!(after.history, NativeJobMetadata::Empty)+ || matches!(&after.history, NativeJobMetadata::Available { value } if value.is_empty())+ }+ _ => false,+ }+}++fn preserved_definition(+ before: &NativeJobDetails,+ after: &NativeJobDetails,+ effect: &NativeJobStepEffect,+ engine: NativeJobEngine,+) -> bool {+ preserved_definition_with_extra(before, after, effect, &[], engine)+}++fn preserved_definition_with_extra(+ before: &NativeJobDetails,+ after: &NativeJobDetails,+ effect: &NativeJobStepEffect,+ extra: &[&str],+ engine: NativeJobEngine,+) -> bool {+ let target = &before.snapshot.job_ref;+ let (Some(before), Some(after)) = (row(before), row(after)) else {+ return false;+ };+ let changed = |key: &str| match effect {+ NativeJobStepEffect::Fields(changes) | NativeJobStepEffect::DamengDefinition(changes) => {+ changes.iter().any(|change| change.name == key)+ }+ NativeJobStepEffect::SchedulerDefinition(effect) => effect.columns.iter().any(|change| change.name == key),+ NativeJobStepEffect::Enabled(_) => matches!(key, "ENABLED" | "ENABLE" | "BROKEN"),+ _ => false,+ };+ let ignored = |key: &str| {+ extra.contains(&key)+ || super::details::generated_definition_column(engine, target, before, key)+ || changed(key)+ || matches!(+ key,+ "STATE"+ | "RUN_COUNT"+ | "FAILURE_COUNT"+ | "RETRY_COUNT"+ | "LAST_START_DATE"+ | "LAST_RUN_DATE"+ | "LAST_RUN_DURATION"+ | "NEXT_RUN_DATE"+ | "LAST_DATE"+ | "LAST_SEC"+ | "THIS_DATE"+ | "THIS_SEC"+ | "NEXT_DATE"+ | "NEXT_SEC"+ | "TOTAL_TIME"+ | "FAILURES"+ | "GMT_MODIFIED"+ | "MODIFYTIME"+ )+ };+ before.iter().all(|(key, value)| ignored(key) || after.get(key) == Some(value))+ && after.keys().all(|key| ignored(key) || before.contains_key(key))+}++struct OwnedPoolSession {+ state: Arc<AppState>,+ binding: super::service::BoundContext,+ client_session_id: String,+ cleanup: Option<ClientSessionPoolCleanupGuard>,+ pool: Option<PoolKind>,+ operation_timeout: Option<Duration>,+ configuration_operation: Option<String>,+ physical_session: Option<NativeJobPhysicalSession>,+ legacy_operation: Option<String>,+ legacy_disposal: Option<bool>,+}++#[derive(serde::Deserialize)]+#[serde(rename_all = "camelCase")]+struct PhysicalSessionReceipt {+ operation_id: String,+ phase: String,+ #[serde(default)]+ session_token: Option<String>,+}++impl OwnedPoolSession {+ async fn open(&mut self) -> Result<(), &'static str> {+ if self.pool.is_some() {+ return Ok(());+ }+ let scope = &self.binding.context.scope;+ let database = (!scope.database.is_empty()).then_some(scope.database.as_str());+ self.cleanup = self+ .state+ .metadata_session_pool_cleanup_guard(&scope.connection_id, database, &self.client_session_id)+ .await;+ if self.cleanup.is_none() {+ return Err("native_job_isolated_session_required");+ }+ let key = self+ .state+ .get_or_create_metadata_pool_for_session(&scope.connection_id, database, Some(&self.client_session_id))+ .await+ .map_err(|_| "native_job_session_open_failed")?;+ let pool = self.state.pool_handle(&key).await.ok_or("native_job_session_open_failed")?;+ super::service::validate_runtime_context(&self.state, &self.binding, &pool).await?;+ self.pool = Some(pool);+ Ok(())+ }++ async fn legacy_call(&mut self, id: &str, method: &str, mut params: Value) -> NativeJobLegacyReceipt {+ let Some(pool) = &self.pool else {+ return legacy::receipt(id, NativeJobLegacyPhase::Unknown, "native_job_legacy_session_unavailable");+ };+ let result = match pool {+ PoolKind::Agent(client) => {+ let mut client = client.lock().await;+ client.call_typed_with_timeout(method, params, self.operation_timeout).await.map_err(|error| {+ let mut failure =+ legacy::receipt(id, NativeJobLegacyPhase::Unknown, "native_job_legacy_rpc_failed");+ if let AgentCallError::Structured { context, .. } = error {+ failure.vendor_code = context.vendor_code;+ }+ failure+ })+ }+ PoolKind::ExternalDriver { config, session, .. } => {+ params+ .as_object_mut()+ .expect("owned native parameters")+ .insert("connection".into(), serde_json::json!(config.as_ref()));+ let method = match method {+ "prepare_legacy_job" => "prepareLegacyJob",+ "commit_legacy_job" => "commitLegacyJob",+ "rollback_legacy_job" => "rollbackLegacyJob",+ "legacy_job_status" => "legacyJobStatus",+ _ => unreachable!(),+ };+ session+ .invoke_with_timeout(method, params, self.operation_timeout)+ .await+ .map_err(|_| legacy::receipt(id, NativeJobLegacyPhase::Unknown, "native_job_legacy_rpc_failed"))+ }+ _ => Err(legacy::receipt(id, NativeJobLegacyPhase::NotStarted, "native_job_legacy_protocol_unavailable")),+ };+ let receipt = result.unwrap_or_else(|failure| failure);+ if self.binding.context.engine == NativeJobEngine::OceanbaseOracle && receipt.operation_id == id {+ if receipt.phase != NativeJobLegacyPhase::NotStarted || receipt.disposal_confirmed.is_some() {+ self.legacy_operation = Some(id.into());+ }+ if receipt.disposal_confirmed == Some(false) {+ self.legacy_disposal = Some(false);+ } else if self.legacy_disposal != Some(false)+ && receipt.disposal_confirmed == Some(true)+ && matches!(+ receipt.phase,+ NativeJobLegacyPhase::Committed+ | NativeJobLegacyPhase::RolledBack+ | NativeJobLegacyPhase::NotStarted+ | NativeJobLegacyPhase::Unknown+ )+ {+ self.legacy_disposal = Some(true);+ }+ }+ receipt+ }++ async fn close_legacy(&mut self) -> Result<(), &'static str> {+ let Some(operation) = self.legacy_operation.clone() else { return Ok(()) };+ if self.legacy_disposal.is_none() {+ // Terminal acknowledgement loss allows a status read, never another native finish.+ let _ = tokio::time::timeout(+ Duration::from_secs(crate::connection::POOL_CLOSE_TIMEOUT_SECS),+ self.legacy_call(&operation, "legacy_job_status", serde_json::json!({"operationId":operation})),+ )+ .await;+ }+ if self.legacy_disposal == Some(true) {+ Ok(())+ } else {+ Err("native_job_legacy_dispose_unknown")+ }+ }++ async fn supports_protocol(&self, capability: &str) -> bool {+ match self.pool.as_ref().expect("opened pool") {+ PoolKind::Agent(client) => client+ .lock()+ .await+ .handshake()+ .is_some_and(|handshake| handshake.capabilities.iter().any(|value| value == capability)),+ PoolKind::ExternalDriver { config, session, .. } => session+ .invoke_with_timeout::<Value>(+ "jdbcSessionProtocol",+ serde_json::json!({"connection":config.as_ref()}),+ self.operation_timeout,+ )+ .await+ .ok()+ .is_some_and(|protocol| {+ protocol["capabilities"]+ .as_array()+ .is_some_and(|values| values.iter().any(|value| value.as_str() == Some(capability)))+ }),+ _ => false,+ }+ }++ async fn physical_session_call(+ &self,+ open: bool,+ mut params: Value,+ ) -> Result<PhysicalSessionReceipt, &'static str> {+ let timeout = if open {+ self.operation_timeout+ } else {+ Some(Duration::from_secs(crate::connection::POOL_CLOSE_TIMEOUT_SECS))+ };+ let raw: Value = match self.pool.as_ref() {+ Some(PoolKind::Agent(client)) => {+ let mut client = tokio::time::timeout(crate::connection::METADATA_POOL_ACQUIRE_TIMEOUT, client.lock())+ .await+ .map_err(|_| "native_job_configuration_session_unavailable")?;+ client+ .call_typed_with_timeout(+ if open { "open_native_job_session" } else { "close_native_job_session" },+ params,+ timeout,+ )+ .await+ .map_err(|_| "native_job_configuration_session_rpc_failed")?+ }+ Some(PoolKind::ExternalDriver { config, session, .. }) => {+ params["connection"] = serde_json::json!(config.as_ref());+ session+ .invoke_with_timeout(+ if open { "openNativeJobSession" } else { "closeNativeJobSession" },+ params,+ timeout,+ )+ .await+ .map_err(|_| "native_job_configuration_session_rpc_failed")?+ }+ _ => return Err("native_job_configuration_session_unavailable"),+ };+ serde_json::from_value(raw).map_err(|_| "native_job_configuration_session_receipt_invalid")+ }++ async fn close_configuration(&self) -> Result<(), &'static str> {+ let Some(operation_id) = &self.configuration_operation else { return Ok(()) };+ let mut params = serde_json::json!({"operationId":operation_id});+ if let Some(physical) = &self.physical_session {+ params["sessionToken"] = Value::String(physical.token.clone());+ }+ // No reopening or replacement connection: only the original physical owner can confirm+ // disposal, including an open whose receipt was lost before its token reached Core.+ let receipt = self.physical_session_call(false, params).await?;+ if receipt.operation_id != *operation_id+ || receipt.phase != "closed"+ || self+ .physical_session+ .as_ref()+ .is_some_and(|physical| receipt.session_token.as_ref() != Some(&physical.token))+ {+ return Err("native_job_configuration_session_dispose_unknown");+ }+ Ok(())+ }+}++#[async_trait::async_trait]+impl NativeJobMutationSession for OwnedPoolSession {+ async fn read_execution(&mut self, target: &NativeJobRef) -> Result<NativeJobExecutionRead, &'static str> {+ observation::read_core(&self.state, &self.binding, target).await+ }+ async fn read_reference(+ &mut self,+ request: NativeJobReferenceListRequest,+ ) -> Result<NativeJobReferenceCatalog, &'static str> {+ super::native_job_references_core(&self.state, &request).await.map_err(|_| "native_job_reference_read_failed")+ }+ async fn read(&mut self, target: &NativeJobRef) -> Result<NativeJobDetails, &'static str> {+ self.open().await?;+ if let Some(physical) = &self.physical_session {+ let timeout = super::super::agent_metadata_timeout(+ self.state.configs.read().await.get(&self.binding.context.scope.connection_id),+ );+ return super::native_job_read_with(&self.state, target, |query| {+ execute_catalog_query_in_session(+ self.binding.context.engine,+ self.pool.as_ref().expect("opened pool"),+ &self.binding.context.scope.database,+ query,+ timeout,+ Some(physical),+ )+ })+ .await;+ }+ // A separate read scope proves visibility after commit; do not verify using an operation's+ // potentially uncommitted connection after an unknown response.+ super::native_job_read_core(&self.state, target).await.map_err(|_| "native_job_readback_failed")+ }+ async fn execute(&mut self, step: &NativeJobSqlStep) -> NativeJobStepReceipt {+ if let Err(reason) = require_write(&self.state, &self.binding).await {+ return NativeJobStepReceipt {+ outcome: NativeJobDispatchOutcome::NotStarted,+ reason: Some(reason.into()),+ vendor_code: None,+ };+ }+ let config = self.state.configs.read().await.get(&self.binding.context.scope.connection_id).cloned();+ let timeout = config.as_ref().and_then(|config| match config.effective_query_timeout_secs() {+ 0 => None,+ secs => Some(Duration::from_secs(secs)),+ });+ let query = NativeJobCatalogQuery {+ source: "native-job-operation",+ coverage: NativeJobCatalogCoverage::CurrentUser,+ sql: step.sql.clone(),+ limit: 1,+ };+ let raw = execute_catalog_query_in_session(+ self.binding.context.engine,+ self.pool.as_ref().expect("opened pool"),+ &self.binding.context.scope.database,+ query,+ timeout,+ self.physical_session.as_ref(),+ )+ .await;+ let result = raw.and_then(|raw| decode_query_result(self.binding.context.engine, raw));+ match result {+ Ok(_) => {+ NativeJobStepReceipt { outcome: NativeJobDispatchOutcome::Applied, reason: None, vendor_code: None }+ }+ Err(error) => {+ let vendor_code = match error {+ NativeJobCatalogFailure::Denied(code)+ | NativeJobCatalogFailure::Unavailable(code)+ | NativeJobCatalogFailure::Unsupported(code)+ | NativeJobCatalogFailure::Query(code) => code,+ _ => None,+ };+ NativeJobStepReceipt {+ outcome: NativeJobDispatchOutcome::Unknown,+ reason: Some("native_job_native_call_failed".into()),+ vendor_code,+ }+ }+ }+ }+ async fn begin_configure(&mut self, operation_id: &str) -> Result<(), &'static str> {+ self.open().await?;+ require_write(&self.state, &self.binding).await?;+ let seconds = self+ .state+ .configs+ .read()+ .await+ .get(&self.binding.context.scope.connection_id)+ .map(|config| config.effective_query_timeout_secs())+ .ok_or("native_job_connection_missing")?;+ self.operation_timeout = (seconds != 0).then(|| Duration::from_secs(seconds));+ if !self.supports_protocol("native_job_session_v1").await {+ return Err("native_job_configuration_protocol_unavailable");+ }+ self.configuration_operation = Some(operation_id.into());+ let receipt = self.physical_session_call(true, serde_json::json!({"operationId":operation_id})).await?;+ if receipt.operation_id != operation_id || receipt.phase != "opened" {+ return Err("native_job_configuration_session_open_unverified");+ }+ let token = receipt+ .session_token+ .filter(|token| !token.is_empty() && token.len() <= 512 && !token.contains('\0'))+ .ok_or("native_job_configuration_session_receipt_invalid")?;+ self.physical_session = Some(NativeJobPhysicalSession { operation_id: operation_id.into(), token });+ super::service::validate_runtime_context_in_session(+ &self.state,+ &self.binding,+ self.pool.as_ref().expect("opened pool"),+ self.physical_session.as_ref(),+ )+ .await+ }+ async fn query(&mut self, query: NativeJobCatalogQuery) -> Result<Value, NativeJobCatalogFailure> {+ let Some(physical) = &self.physical_session else { return Err(NativeJobCatalogFailure::RouteUnavailable) };+ let timeout = super::super::agent_metadata_timeout(+ self.state.configs.read().await.get(&self.binding.context.scope.connection_id),+ );+ execute_catalog_query_in_session(+ self.binding.context.engine,+ self.pool.as_ref().expect("opened pool"),+ &self.binding.context.scope.database,+ query,+ timeout,+ Some(physical),+ )+ .await+ }+ async fn prepare_legacy(+ &mut self,+ operation_id: &str,+ definition: &NativeJobLegacyCreate,+ ) -> NativeJobLegacyReceipt {+ if let Err(reason) = self.open().await {+ return legacy::receipt(operation_id, NativeJobLegacyPhase::NotStarted, reason);+ }+ if let Err(reason) = require_write(&self.state, &self.binding).await {+ return legacy::receipt(operation_id, NativeJobLegacyPhase::NotStarted, reason);+ }+ let seconds = self+ .state+ .configs+ .read()+ .await+ .get(&self.binding.context.scope.connection_id)+ .map(|config| config.effective_query_timeout_secs());+ let Some(seconds) = seconds.filter(|seconds| *seconds <= i32::MAX as u64) else {+ return legacy::receipt(operation_id, NativeJobLegacyPhase::NotStarted, "native_job_timeout_invalid");+ };+ self.operation_timeout = (seconds != 0).then(|| Duration::from_secs(seconds));+ let oceanbase = self.binding.context.engine == NativeJobEngine::OceanbaseOracle;+ let available =+ self.supports_protocol(if oceanbase { "native_job_legacy_ob_v1" } else { "native_job_legacy_v1" }).await;+ if !available {+ return legacy::receipt(+ operation_id,+ NativeJobLegacyPhase::NotStarted,+ if oceanbase {+ "native_job_legacy_runtime_update_required"+ } else {+ "native_job_legacy_protocol_unavailable"+ },+ );+ }+ let mut params = serde_json::json!({+ "operationId":operation_id, "what":definition.what, "nextDate":definition.next_date,+ "interval":definition.interval, "enabled":definition.enabled, "instance":definition.instance,+ "schema":definition.schema, "timeoutSecs":seconds,+ });+ if oceanbase {+ params["dialect"] = Value::String("oceanbase-oracle".into());+ params["zone"] = serde_json::json!(definition.zone);+ }+ self.legacy_call(operation_id, "prepare_legacy_job", params).await+ }+ async fn finish_legacy(+ &mut self,+ operation_id: &str,+ job_id: Option<&str>,+ commit: bool,+ ) -> NativeJobLegacyReceipt {+ let mut params = serde_json::json!({"operationId":operation_id});+ if let Some(job_id) = job_id {+ params["jobId"] = Value::String(job_id.into());+ }+ // Deliberately do not reopen a lost session or reevaluate connection configuration here.+ self.legacy_call(operation_id, if commit { "commit_legacy_job" } else { "rollback_legacy_job" }, params).await+ }+ async fn finish(&mut self) -> Result<(), &'static str> {+ let legacy = self.close_legacy().await;+ let native = self.close_configuration().await;+ let physical = tokio::time::timeout(Duration::from_secs(crate::connection::POOL_CLOSE_TIMEOUT_SECS), async {+ match self.pool.as_ref() {+ Some(PoolKind::Agent(client)) => {+ client.lock().await.disconnect().await.map(|_| ()).map_err(|_| "native_job_session_cleanup_unknown")+ }+ Some(PoolKind::ExternalDriver { session, .. }) => {+ session.shutdown_confirmed().await.map_err(|_| "native_job_session_cleanup_unknown")+ }+ _ => Ok(()),+ }+ })+ .await+ .map_err(|_| "native_job_session_cleanup_unknown")+ .and_then(|result| result);+ let scope = &self.binding.context.scope;+ let closed = self+ .state+ .close_metadata_session_pool(+ &scope.connection_id,+ (!scope.database.is_empty()).then_some(scope.database.as_str()),+ &self.client_session_id,+ )+ .await;+ if matches!(closed, Ok(true)) {+ if let Some(cleanup) = &mut self.cleanup {+ cleanup.disarm();+ }+ }+ self.pool = None;+ legacy.and(native).and(physical).and(closed.map(|_| ()).map_err(|_| "native_job_session_cleanup_unknown"))+ }+}++pub fn native_job_apply_core(state: Arc<AppState>, plan_id: &str) -> Result<NativeJobOperationStatus, String> {+ let operations = state.native_jobs.operations().clone();+ let (status, claimed) = operations.claim(plan_id).map_err(str::to_string)?;+ if let Some((execution, cancel)) = claimed {+ let actor = current_credential_owner();+ let id = status.operation_id.clone();+ tokio::spawn(async move {+ with_credential_owner(actor, async {+ let mut session = OwnedPoolSession {+ state: state.clone(),+ binding: execution.binding.clone(),+ client_session_id: crate::connection::task_client_session_id("native-job-operation", &id),+ cleanup: None,+ pool: None,+ operation_timeout: None,+ configuration_operation: None,+ physical_session: None,+ legacy_operation: None,+ legacy_disposal: None,+ };+ run_claimed(&state, &operations, &id, execution, cancel, &mut session).await;+ })+ .await;+ });+ }+ Ok(status)+}diff --git a/crates/dbx-core/src/schema/native_jobs/operations/arguments.rs b/crates/dbx-core/src/schema/native_jobs/operations/arguments.rsnew file mode 100644index 0000000000..2950d5fe9a--- /dev/null+++ b/crates/dbx-core/src/schema/native_jobs/operations/arguments.rs@@ -0,0 +1,145 @@+use super::*;+use dbx_sql::native_job_arguments::{civil_date_query, normalize_civil_date};++fn values(request: &mut NativeJobRequest) -> Vec<&mut Value> {+ match request {+ NativeJobRequest::Create { definition: NativeJobCreateDefinition::Scheduler(definition), .. } => definition+ .arguments+ .iter_mut()+ .filter_map(|argument| match &mut argument.value {+ NativeJobArgumentValue::Value { value } => Some(value),+ _ => None,+ })+ .collect(),+ NativeJobRequest::Mutation(NativeJobMutation {+ change: NativeJobChange::Update { arguments, argument_target, .. },+ ..+ }) => {+ let mut result = arguments+ .iter_mut()+ .filter_map(|argument| match &mut argument.value {+ NativeJobArgumentValue::Value { value } => Some(value),+ _ => None,+ })+ .collect::<Vec<_>>();+ if let Some(target) = argument_target {+ result.extend(target.arguments.iter_mut().filter_map(|argument| match &mut argument.value {+ NativeJobArgumentValue::Value { value } => Some(value),+ _ => None,+ }));+ }+ result+ }+ _ => Vec::new(),+ }+}++async fn normalize_with<Q, F>(pending: Vec<(&mut Value, String)>, mut query: Q) -> Result<(), &'static str>+where+ Q: FnMut(String) -> F,+ F: Future<Output = Result<NativeJobRow, &'static str>>,+{+ for (value, sql) in pending {+ let row = query(sql).await?;+ *value = normalize_civil_date(value, &row)?;+ }+ Ok(())+}++pub(super) async fn normalize_core(state: &AppState, request: &mut NativeJobRequest) -> Result<(), &'static str> {+ let scope = match &*request {+ NativeJobRequest::Create { scope, .. } => scope.clone(),+ NativeJobRequest::Mutation(mutation) => mutation.target.scope().clone(),+ };+ let mut pending = Vec::new();+ for value in values(request) {+ if let Some(sql) = civil_date_query(value)? {+ pending.push((value, sql));+ }+ }+ if pending.is_empty() {+ return Ok(());+ }+ let bound = state.native_jobs.context(state, &scope)?;+ if bound.context.engine != NativeJobEngine::Oracle {+ return Err("native_job_argument_value_invalid");+ }+ let timeout = super::super::super::agent_metadata_timeout(state.configs.read().await.get(&scope.connection_id));+ let (session, pool) = super::super::service::open_pool(state, &scope).await?;+ let result = async {+ super::super::service::validate_runtime_context(state, &bound, &pool).await?;+ let pool = &pool;+ let database = scope.database.as_str();+ let engine = bound.context.engine;+ tokio::select! {+ biased;+ _ = bound.lifecycle.cancellation().cancelled() => Err("native_job_context_changed"),+ result = normalize_with(pending, |sql| async move {+ let raw = execute_catalog_query(engine, pool, database, NativeJobCatalogQuery {+ source: "oracle-native-job-civil-date", coverage: NativeJobCatalogCoverage::CurrentUser, sql, limit: 1,+ }, timeout).await.map_err(|_| "native_job_argument_date_conversion_failed")?;+ let rows = rows_from_result(decode_query_result(engine, raw).map_err(|_| "native_job_argument_date_read_failed")?, 1, |_| Ok(())).map_err(|_| "native_job_argument_date_read_failed")?;+ match rows {+ NativeJobMetadata::Available { mut value } if value.len() == 1 => Ok(value.remove(0)),+ _ => Err("native_job_argument_date_read_failed"),+ }+ }) => result,+ }?;+ state.native_jobs.context(state, &scope)?;+ Ok(())+ }.await;+ session.finish(state, &scope.connection_id, (!scope.database.is_empty()).then_some(scope.database.as_str())).await;+ result+}++#[cfg(test)]+mod tests {+ use super::*;+ use serde_json::json;++ #[tokio::test]+ async fn normalizes_only_new_civil_inputs_before_the_request_can_be_prepared() {+ let typed = json!({"$dbx":"oracle-anydata-v1","scalarType":"timestamp","value":{"civilDate":"-0001-12-31","seconds":"1.123456789"}});+ let mut request: NativeJobRequest = serde_json::from_value(json!({"target":{"kind":"scheduler","owner":"Owner","name":"Job","scope":{"connectionId":"c","database":"","contextId":"ctx"}},"baseline":"read","action":"update","attributes":[],"arguments":[{"position":1,"value":{"kind":"value","value":"literal text"}},{"position":2,"value":{"kind":"value","value":typed}}]})).unwrap();+ let mut pending = Vec::new();+ for value in values(&mut request) {+ if let Some(sql) = civil_date_query(value).unwrap() {+ pending.push((value, sql));+ }+ }+ assert_eq!(pending.len(), 1);+ let mut calls = 0;+ normalize_with(pending, |sql| {+ calls += 1;+ assert!(sql.contains("NLS_CALENDAR=GREGORIAN"));+ std::future::ready(Ok(serde_json::from_value(+ json!({"DBX_DAY":"1234567","DBX_CIVIL":"-0001-12-31","DBX_REBUILT":"-0001-12-31"}),+ )+ .unwrap()))+ })+ .await+ .unwrap();+ assert_eq!(calls, 1);+ let payload = serde_json::to_value(&request).unwrap();+ assert_eq!(payload["arguments"][0]["value"]["value"], "literal text");+ assert_eq!(+ payload["arguments"][1]["value"]["value"]["value"],+ json!({"day":"1234567","seconds":"1.123456789"})+ );+ for value in values(&mut request) {+ assert!(civil_date_query(value).unwrap().is_none());+ }+ }++ #[tokio::test]+ async fn conversion_failure_is_returned_instead_of_producing_an_executable_value() {+ let mut value =+ json!({"$dbx":"oracle-anydata-v1","scalarType":"date","value":{"civilDate":"1582-10-05","seconds":"0"}});+ let original = value.clone();+ let sql = civil_date_query(&value).unwrap().unwrap();+ let error =+ normalize_with(vec![(&mut value, sql)], |_| std::future::ready(Err("native_job_context_changed"))).await;+ assert_eq!(error, Err("native_job_context_changed"));+ assert_eq!(value, original);+ }+}diff --git a/crates/dbx-core/src/schema/native_jobs/operations/dameng.rs b/crates/dbx-core/src/schema/native_jobs/operations/dameng.rsnew file mode 100644index 0000000000..0fbc8c662a--- /dev/null+++ b/crates/dbx-core/src/schema/native_jobs/operations/dameng.rs@@ -0,0 +1,656 @@+use super::*;+use dbx_sql::native_job_changes::{+ native_job_dameng_child_key, resolve_native_job_dameng_child_step, NativeJobDamengChildAction,+ NativeJobDamengConfigPlan, NativeJobDamengOperatorSelector, NativeJobDamengPart,+};++mod creation;+mod parts;+pub(super) mod rename;+pub(super) use creation::run_create;++type Failure = (&'static str, NativeJobOperationOutcome);++fn legacy_coverage(details: &NativeJobDetails, user: &str) -> bool {+ let own = row(details).and_then(|row| row.get("USERNAME")).and_then(Value::as_str) == Some(user);+ ["legacyDefinition", "steps", "schedules"].into_iter().all(|part| {+ match details.sources.get(part).and_then(|source| source.coverage) {+ Some(NativeJobCatalogCoverage::Database | NativeJobCatalogCoverage::Accessible) => true,+ Some(NativeJobCatalogCoverage::CurrentUser) => own,+ _ => false,+ }+ })+}++fn legacy_preserved(+ before: &NativeJobDetails,+ after: &NativeJobDetails,+ interval: bool,+ next_date: bool,+ what: bool,+) -> bool {+ let (Some(NativeJobMetadata::Available { value: before }), Some(NativeJobMetadata::Available { value: after })) =+ (&before.legacy_definition, &after.legacy_definition)+ else {+ return false;+ };+ let ignored = |key: &str| {+ matches!(key, "LAST_DATE" | "LAST_SEC" | "THIS_DATE" | "THIS_SEC" | "TOTAL_TIME" | "FAILURES")+ || (interval && key == "INTERVAL")+ || (next_date && matches!(key, "NEXT_DATE" | "NEXT_SEC"))+ || (what && key == "WHAT")+ };+ before.iter().all(|(key, value)| ignored(key) || after.get(key) == Some(value))+ && after.keys().all(|key| ignored(key) || before.contains_key(key))+}++fn interval_matches(after: &NativeJobDetails, expected: &str) -> bool {+ let Some(NativeJobMetadata::Available { value }) = &after.legacy_definition else {+ return false;+ };+ let Some(Value::String(value)) = value.get("INTERVAL") else {+ return false;+ };+ let (integer, fraction) = value.split_once('.').map_or((value.as_str(), ""), |parts| parts);+ !integer.is_empty()+ && integer.bytes().all(|byte| byte.is_ascii_digit())+ && fraction.bytes().all(|byte| byte == b'0')+ && integer.trim_start_matches('0') == expected+}++async fn resolve_operators(+ session: &mut impl NativeJobMutationSession,+ plan: &NativeJobDamengConfigPlan,+) -> Result<BTreeMap<&'static str, Option<i64>>, &'static str> {+ let rows = if let Some(query) = plan.operator_query() {+ let limit = query.limit;+ let raw = session.query(query).await.map_err(|_| "native_job_notification_operator_unverified")?;+ let result = decode_query_result(NativeJobEngine::Dameng, raw)+ .and_then(|result| rows_from_result(result, limit, |_| Ok(())))+ .map_err(|_| "native_job_notification_operator_unverified")?;+ match result {+ NativeJobMetadata::Available { value } => value,+ NativeJobMetadata::Empty => Vec::new(),+ _ => return Err("native_job_notification_operator_unverified"),+ }+ } else {+ Vec::new()+ };+ let mut expected = BTreeMap::new();+ for operator in &plan.operators {+ let id = if matches!(operator.selector, NativeJobDamengOperatorSelector::Unassigned) {+ None+ } else {+ // The database supplies the match bit using its own name/case semantics. Do not+ // approximate a database name comparison with a client-side case conversion.+ let key = format!("DBX_MATCH_{}", operator.column);+ if rows.iter().any(|row| super::super::details::boolean(row.get(&key)).is_none()) {+ return Err("native_job_notification_operator_unverified");+ }+ let matching = rows+ .iter()+ .filter(|row| super::super::details::boolean(row.get(&key)) == Some(true))+ .collect::<Vec<_>>();+ if matching.len() != 1 || matching[0].get("NAME").and_then(Value::as_str).is_none() {+ return Err("native_job_notification_operator_unverified");+ }+ let id = matching[0]+ .get("DBX_OPERATOR_ID")+ .and_then(Value::as_str)+ .and_then(|value| value.parse::<i64>().ok())+ .filter(|id| *id > 0)+ .ok_or("native_job_notification_operator_unverified")?;+ if matches!(operator.selector, NativeJobDamengOperatorSelector::Id(expected) if expected != id) {+ return Err("native_job_notification_operator_unverified");+ }+ Some(id)+ };+ expected.insert(operator.column, id);+ }+ Ok(expected)+}++fn fields_match(after: &NativeJobDetails, changes: &[NativeJobAttributeChange]) -> bool {+ row(after).is_some_and(|row| {+ changes.iter().all(|change| match &change.change {+ NativeJobFieldChange::Set { value } => values::field_matches(&change.name, row.get(&change.name), value),+ NativeJobFieldChange::Clear => row.get(&change.name) == Some(&Value::Null),+ NativeJobFieldChange::Keep => true,+ })+ })+}++fn preserved_partition(+ before: &NativeJobMetadata<Vec<NativeJobRow>>,+ after: &NativeJobMetadata<Vec<NativeJobRow>>,+ generated: &[&str],+) -> bool {+ let empty = Vec::new();+ let before = match before {+ NativeJobMetadata::Available { value } => value,+ NativeJobMetadata::Empty => &empty,+ // Unrelated unreadable partitions are not new privileges required for a metadata edit.+ _ => return true,+ };+ let after = match after {+ NativeJobMetadata::Available { value } => value,+ NativeJobMetadata::Empty => &empty,+ _ => return false,+ };+ before.len() == after.len()+ && before.iter().zip(after).all(|(before, after)| {+ before.iter().all(|(key, value)| generated.contains(&key.as_str()) || after.get(key) == Some(value))+ && after.keys().all(|key| generated.contains(&key.as_str()) || before.contains_key(key))+ })+}++fn unchanged(before: &NativeJobDetails, current: &NativeJobDetails) -> bool {+ matches!(current.consistency, NativeJobMetadata::Available { .. })+ && current.native_identity == before.native_identity+ && preserved_definition(before, current, &NativeJobStepEffect::Completed, NativeJobEngine::Dameng)+ && preserved_partition(&before.steps, ¤t.steps, &[])+ && preserved_partition(&before.schedules, ¤t.schedules, &[])+}++fn verify_step(+ before: &NativeJobDetails,+ after: &NativeJobDetails,+ effect: &NativeJobStepEffect,+ operators: &BTreeMap<&'static str, Option<i64>>,+ user: &str,+) -> bool {+ if !matches!(after.consistency, NativeJobMetadata::Available { .. })+ || before.native_identity != after.native_identity+ {+ return false;+ }+ let extra: &[&str] = match effect {+ NativeJobStepEffect::DamengRenamed { .. } => &["NAME"],+ NativeJobStepEffect::DamengDefinition(_) => &["VALID", "EMAIL_OPERID", "NETSEND_OPERID"],+ NativeJobStepEffect::DamengConfigurationStarted+ | NativeJobStepEffect::DamengConfigurationCommitted+ | NativeJobStepEffect::Fields(_)+ | NativeJobStepEffect::DamengChild(_) => &["VALID"],+ _ => &[],+ };+ let child = if let NativeJobStepEffect::DamengChild(child) = effect { Some(child) } else { None };+ let steps_preserved = child.is_some_and(|child| child.part == NativeJobDamengPart::Steps)+ || preserved_partition(&before.steps, &after.steps, &[]);+ let schedules_preserved = child.is_some_and(|child| child.part == NativeJobDamengPart::Schedules)+ || preserved_partition(+ &before.schedules,+ &after.schedules,+ if matches!(effect, NativeJobStepEffect::DamengConfigurationCommitted) {+ &["VALID", "SCHNAME", "TRIGNAME"]+ } else {+ &[]+ },+ );+ if !preserved_definition_with_extra(before, after, effect, extra, NativeJobEngine::Dameng)+ || !steps_preserved+ || !schedules_preserved+ || child.is_some_and(|child| !parts::verify(before, after, child, user))+ {+ return false;+ }+ let Some(after_row) = row(after) else { return false };+ let enabled = super::super::details::boolean(after_row.get("ENABLE"));+ let expected_enabled = if matches!(effect, NativeJobStepEffect::DamengRenamed { .. }) {+ row(before).and_then(|row| super::super::details::boolean(row.get("ENABLE")))+ } else {+ Some(matches!(effect, NativeJobStepEffect::Enabled(true)))+ };+ if expected_enabled.is_none() || enabled != expected_enabled {+ return false;+ }+ match effect {+ NativeJobStepEffect::DamengRenamed { new_name, .. } => {+ after_row.get("NAME").and_then(Value::as_str) == Some(new_name)+ && (!matches!(before.legacy_definition, Some(NativeJobMetadata::Available { .. }))+ || legacy_preserved(before, after, false, expected_enabled == Some(true), false))+ }+ NativeJobStepEffect::Enabled(_)+ | NativeJobStepEffect::DamengConfigurationStarted+ | NativeJobStepEffect::DamengChild(_) => true,+ NativeJobStepEffect::DamengConfigurationCommitted => {+ after_row.get("VALID").and_then(Value::as_str) == Some("Y")+ }+ NativeJobStepEffect::Fields(changes) => fields_match(after, changes),+ NativeJobStepEffect::DamengDefinition(changes) => {+ fields_match(after, changes)+ && operators.iter().all(|(column, expected)| match expected {+ Some(id) => values::field_matches(column, after_row.get(*column), &serde_json::json!(id)),+ None => after_row.get(*column).is_some_and(|value| {+ value.is_null() || super::super::details::integer(Some(value)).is_some_and(|value| value <= 0)+ }),+ })+ }+ NativeJobStepEffect::DamengLegacyInterval { expected_seconds } => {+ legacy_preserved(before, after, true, false, false)+ && matches!(&after.legacy_definition, Some(NativeJobMetadata::Available { value }) if value.contains_key("INTERVAL"))+ && expected_seconds.as_ref().is_none_or(|expected| interval_matches(after, expected))+ }+ NativeJobStepEffect::DamengLegacyWhat { expected } => {+ legacy_preserved(before, after, false, false, true)+ && matches!(&after.legacy_definition, Some(NativeJobMetadata::Available { value }) if value.get("WHAT").and_then(Value::as_str) == Some(expected))+ }+ NativeJobStepEffect::DamengLegacyNextDate { expected } => {+ legacy_preserved(before, after, false, true, false) && legacy_time_matches(after, expected)+ }+ _ => false,+ }+}++fn legacy_time_matches(details: &NativeJobDetails, expected: &str) -> bool {+ matches!(&details.legacy_definition, Some(NativeJobMetadata::Available { value })+ if dbx_sql::native_job_changes::native_job_dameng_legacy_time(value).as_deref() == Ok(expected))+}++async fn check_dispatch(+ state: &AppState,+ execution: &PreparedExecution,+ cancel: &CancellationToken,+ dispatched: bool,+) -> Result<(), Failure> {+ let reason = if cancel.is_cancelled() {+ Some("native_job_canceled_after_dispatch")+ } else {+ require_write(state, &execution.binding).await.err()+ };+ match reason {+ Some(reason) => Err((+ reason,+ if dispatched { NativeJobOperationOutcome::Partial } else { NativeJobOperationOutcome::NotApplied },+ )),+ None => Ok(()),+ }+}++pub(super) async fn run_configure(+ state: &AppState,+ execution: &PreparedExecution,+ id: &str,+ cancel: &CancellationToken,+ session: &mut impl NativeJobMutationSession,+ dispatched: &mut bool,+) -> Result<NativeJobOperationOutcome, Failure> {+ let PreparedAction::Mutation { mutation, plan } = &execution.action else { unreachable!() };+ if plan.steps.iter().any(|step| {+ matches!(+ step.effect,+ NativeJobStepEffect::DamengLegacyInterval { .. }+ | NativeJobStepEffect::DamengLegacyWhat { .. }+ | NativeJobStepEffect::DamengLegacyNextDate { .. }+ | NativeJobStepEffect::DamengRenamed { .. }+ )+ }) && !plan.steps.iter().any(|step| matches!(step.effect, NativeJobStepEffect::DamengConfigurationCommitted))+ && state.native_jobs.operations().configuration_pending(&execution.origin_key)+ {+ return Err(("native_job_configuration_preview_required", NativeJobOperationOutcome::NotApplied));+ }+ session.begin_configure(id).await.map_err(|reason| (reason, NativeJobOperationOutcome::NotApplied))?;+ check_dispatch(state, execution, cancel, false).await?;+ let before =+ session.read(&mutation.target).await.map_err(|reason| (reason, NativeJobOperationOutcome::NotApplied))?;+ if plan.steps.iter().any(|step| {+ matches!(+ step.effect,+ NativeJobStepEffect::DamengLegacyInterval { .. }+ | NativeJobStepEffect::DamengLegacyWhat { .. }+ | NativeJobStepEffect::DamengLegacyNextDate { .. }+ )+ }) && !legacy_coverage(&before, &execution.binding.context.session_user)+ {+ return Err(("native_job_legacy_coverage_incomplete", NativeJobOperationOutcome::NotApplied));+ }+ if plan.steps.iter().any(|step| {+ matches!(+ step.effect,+ NativeJobStepEffect::DamengLegacyInterval { .. }+ | NativeJobStepEffect::DamengLegacyWhat { .. }+ | NativeJobStepEffect::DamengLegacyNextDate { .. }+ | NativeJobStepEffect::DamengRenamed { .. }+ )+ }) && !plan.steps.iter().any(|step| matches!(step.effect, NativeJobStepEffect::DamengConfigurationCommitted))+ && row(&before).is_some_and(|row| row.get("VALID").and_then(Value::as_str) == Some("N"))+ {+ return Err(("native_job_configuration_preview_required", NativeJobOperationOutcome::NotApplied));+ }+ state+ .native_jobs+ .compare_baseline(+ state,+ &mutation.target,+ &mutation.baseline,+ &before.snapshot.revision,+ &plan.required_partitions.iter().map(String::as_str).collect::<Vec<_>>(),+ plan.compare_next_date,+ )+ .map_err(|reason| (reason, NativeJobOperationOutcome::NotApplied))?;+ check_dispatch(state, execution, cancel, false).await?;+ for step in &plan.steps {+ if let NativeJobStepEffect::DamengLegacyWhat { expected } = &step.effect {+ let query = dbx_sql::native_job_changes::native_job_dameng_what_query(expected);+ let raw = session+ .query(query)+ .await+ .map_err(|_| ("native_job_attribute_value_invalid", NativeJobOperationOutcome::NotApplied))?;+ let result = decode_query_result(NativeJobEngine::Dameng, raw)+ .and_then(|result| rows_from_result(result, 1, |_| Ok(())))+ .map_err(|_| ("native_job_attribute_value_invalid", NativeJobOperationOutcome::NotApplied))?;+ if !matches!(result, NativeJobMetadata::Available { value } if value.len() == 1 && value[0].get("DBX_WHAT").and_then(Value::as_str) == Some(expected))+ {+ return Err(("native_job_attribute_value_invalid", NativeJobOperationOutcome::NotApplied));+ }+ }+ if let NativeJobStepEffect::DamengLegacyNextDate { expected } = &step.effect {+ let query = dbx_sql::native_job_changes::native_job_dameng_date_query(expected);+ let raw = session+ .query(query)+ .await+ .map_err(|_| ("native_job_attribute_value_invalid", NativeJobOperationOutcome::NotApplied))?;+ let result = decode_query_result(NativeJobEngine::Dameng, raw)+ .and_then(|result| rows_from_result(result, 1, |_| Ok(())))+ .map_err(|_| ("native_job_attribute_value_invalid", NativeJobOperationOutcome::NotApplied))?;+ let NativeJobMetadata::Available { value } = result else {+ return Err(("native_job_attribute_value_invalid", NativeJobOperationOutcome::NotApplied));+ };+ if value.len() != 1+ || !value[0].get("DBX_NEXT_DATE").and_then(Value::as_str).is_some_and(|date| {+ let date = date.trim_start_matches(' ').strip_prefix('+').unwrap_or(date.trim_start_matches(' '));+ dbx_sql::native_job_changes::native_job_dameng_civil_time(date).as_deref() == Ok(expected.as_str())+ })+ {+ return Err(("native_job_attribute_value_invalid", NativeJobOperationOutcome::NotApplied));+ }+ }+ }+ run_steps(+ state,+ execution,+ id,+ cancel,+ session,+ dispatched,+ ConfigurationExecution { target: &mutation.target, plan, origin_key: &execution.origin_key, offset: 0, before },+ )+ .await+}++struct ConfigurationExecution<'a> {+ target: &'a NativeJobRef,+ plan: &'a NativeJobSqlPlan,+ origin_key: &'a str,+ offset: usize,+ before: NativeJobDetails,+}++async fn run_steps(+ state: &AppState,+ execution: &PreparedExecution,+ id: &str,+ cancel: &CancellationToken,+ session: &mut impl NativeJobMutationSession,+ dispatched: &mut bool,+ configuration: ConfigurationExecution<'_>,+) -> Result<NativeJobOperationOutcome, Failure> {+ let ConfigurationExecution { target, plan, origin_key, offset, mut before } = configuration;+ let mut effective_target = target.clone();+ let mut renamed = false;+ let rename = if let Some((old_name, new_name)) = plan.steps.iter().find_map(|step| match &step.effect {+ NativeJobStepEffect::DamengRenamed { old_name, new_name } => Some((old_name.clone(), new_name.clone())),+ _ => None,+ }) {+ let NativeJobMetadata::Available { value: identity } = &before.native_identity else {+ return Err(("native_job_identity_unverified", NativeJobOperationOutcome::NotApplied));+ };+ if let Some(existing) = creation::lookup(session, &new_name)+ .await+ .map_err(|reason| (reason, NativeJobOperationOutcome::NotApplied))?+ {+ if existing.get("DBX_JOB_ID") != identity.get("DBX_JOB_ID") {+ return Err(("native_job_name_conflict", NativeJobOperationOutcome::NotApplied));+ }+ }+ Some(Arc::new(tokio::sync::Mutex::new(rename::Binding {+ binding: execution.binding.clone(),+ target: target.clone(),+ identity: identity.clone(),+ old_name,+ new_name,+ })))+ } else {+ None+ };+ let operators = resolve_operators(session, plan.dameng_configuration.as_ref().expect("DM configuration plan"))+ .await+ .map_err(|reason| {+ (+ reason,+ if *dispatched { NativeJobOperationOutcome::Partial } else { NativeJobOperationOutcome::NotApplied },+ )+ })?;+ let operations = state.native_jobs.operations();+ if let Some(rename) = &rename {+ if let Some(record) = operations+ .0+ .lock()+ .unwrap_or_else(|error| error.into_inner())+ .records+ .iter_mut()+ .find(|record| record.status.operation_id == id && record.actor == current_credential_owner())+ {+ record.rename = Some(rename.clone());+ }+ }+ operations.edit(id, |status| status.state = NativeJobOperationState::Running);+ let mut configuration_written = false;+ let mut created_children = BTreeMap::new();+ let legacy_interval = plan.steps.iter().any(|step| {+ matches!(+ step.effect,+ NativeJobStepEffect::DamengLegacyInterval { .. }+ | NativeJobStepEffect::DamengLegacyWhat { .. }+ | NativeJobStepEffect::DamengLegacyNextDate { .. }+ )+ });+ let mut accepted_seen = false;+ let mut requested_date: Option<String> = None;+ for (index, step) in plan.steps.iter().enumerate() {+ let status_index = index + offset;+ check_dispatch(state, execution, cancel, *dispatched).await?;+ let current = session.read(&effective_target).await.map_err(|reason| {+ (+ reason,+ if *dispatched { NativeJobOperationOutcome::Partial } else { NativeJobOperationOutcome::NotApplied },+ )+ })?;+ if !*dispatched && plan.compare_next_date {+ state+ .native_jobs+ .compare_baseline(+ state,+ &effective_target,+ &before.snapshot.revision,+ ¤t.snapshot.revision,+ &[],+ true,+ )+ .map_err(|reason| (reason, NativeJobOperationOutcome::NotApplied))?;+ }+ if !unchanged(&before, ¤t)+ || requested_date.as_deref().is_some_and(|expected| !legacy_time_matches(¤t, expected))+ || (legacy_interval && !legacy_coverage(¤t, &execution.binding.context.session_user))+ || (legacy_interval+ && !legacy_preserved(+ &before,+ ¤t,+ false,+ row(&before).and_then(|row| super::super::details::boolean(row.get("ENABLE"))) == Some(true),+ false,+ ))+ {+ return Err((+ "native_job_definition_changed",+ if *dispatched { NativeJobOperationOutcome::Partial } else { NativeJobOperationOutcome::NotApplied },+ ));+ }+ before = current;+ let resolved = if renamed && matches!(step.effect, NativeJobStepEffect::Enabled(_)) {+ let NativeJobStepEffect::Enabled(enabled) = step.effect else { unreachable!() };+ let request = NativeJobMutation {+ target: effective_target.clone(),+ baseline: before.snapshot.revision.clone(),+ change: if enabled { NativeJobChange::Enable } else { NativeJobChange::Disable },+ };+ Some(+ dbx_sql::native_job_changes::native_job_mutation_plan(NativeJobEngine::Dameng, &request, &before)+ .map_err(|reason| (reason, NativeJobOperationOutcome::Partial))?+ .steps+ .into_iter()+ .next()+ .ok_or(("native_job_step_missing", NativeJobOperationOutcome::Partial))?,+ )+ } else if matches!(step.effect, NativeJobStepEffect::DamengChild(_)) {+ Some(resolve_native_job_dameng_child_step(step, target, &before, &created_children).map_err(|reason| {+ (+ reason,+ if *dispatched {+ NativeJobOperationOutcome::Partial+ } else {+ NativeJobOperationOutcome::NotApplied+ },+ )+ })?)+ } else {+ None+ };+ let step = resolved.as_ref().unwrap_or(step);+ // Reads can take long enough for cancellation or the existing write lock to change.+ check_dispatch(state, execution, cancel, *dispatched).await?;+ let first_configuration = !configuration_written+ && matches!(+ step.effect,+ NativeJobStepEffect::DamengDefinition(_) | NativeJobStepEffect::DamengConfigurationStarted+ );+ let newly_pending = first_configuration && operations.configuration_dispatched(origin_key);+ operations.edit(id, |status| status.steps[status_index].state = NativeJobStepState::Dispatching);+ *dispatched = true;+ let receipt = session.execute(step).await;+ scheduler::mark(operations, id, status_index, &receipt);+ if receipt.outcome == NativeJobDispatchOutcome::NotStarted {+ if newly_pending {+ operations.configuration_verified(origin_key);+ }+ return Err((+ "native_job_step_not_applied",+ if status_index == 0 {+ NativeJobOperationOutcome::NotApplied+ } else {+ NativeJobOperationOutcome::Partial+ },+ ));+ }+ configuration_written |= first_configuration;+ let unknown = receipt.outcome == NativeJobDispatchOutcome::Unknown;+ if unknown && matches!(step.effect, NativeJobStepEffect::DamengLegacyInterval { .. }) {+ return Err(("native_job_legacy_interval_commit_unknown", NativeJobOperationOutcome::Unknown));+ }+ if unknown+ && matches!(+ step.effect,+ NativeJobStepEffect::DamengLegacyWhat { .. } | NativeJobStepEffect::DamengLegacyNextDate { .. }+ )+ {+ return Err(("native_job_step_outcome_unknown", NativeJobOperationOutcome::Unknown));+ }+ if unknown && matches!(step.effect, NativeJobStepEffect::DamengRenamed { .. }) {+ return Err(("native_job_rename_commit_unknown", NativeJobOperationOutcome::Unknown));+ }+ if unknown+ && (matches!(+ step.effect,+ NativeJobStepEffect::DamengConfigurationStarted | NativeJobStepEffect::DamengConfigurationCommitted+ ) || matches!(&step.effect, NativeJobStepEffect::DamengChild(child) if child.requires_acknowledgement))+ {+ return Err(("native_job_configuration_protocol_outcome_unknown", NativeJobOperationOutcome::Unknown));+ }+ let after_target = if matches!(step.effect, NativeJobStepEffect::DamengRenamed { .. }) {+ let rename = rename.as_ref().expect("rename binding").lock().await;+ rename.locate_session(session).await.map_err(|reason| (reason, NativeJobOperationOutcome::Partial))?+ } else {+ effective_target.clone()+ };+ let after = session.read(&after_target).await.map_err(|reason| {+ (reason, if unknown { NativeJobOperationOutcome::Unknown } else { NativeJobOperationOutcome::Partial })+ })?;+ if matches!(step.effect, NativeJobStepEffect::DamengRenamed { .. }) {+ let rename = rename.as_ref().expect("rename binding").lock().await;+ let identity = rename+ .verified(&after_target, &after)+ .map_err(|reason| (reason, NativeJobOperationOutcome::Partial))?;+ if let NativeJobStepEffect::DamengRenamed { new_name, .. } = &step.effect {+ if identity.get("NAME").and_then(Value::as_str) != Some(new_name) {+ return Err(("native_job_rename_not_observed", NativeJobOperationOutcome::Partial));+ }+ }+ effective_target = after_target;+ renamed = true;+ operations.edit(id, |status| {+ status.target = Some(effective_target.clone());+ status.observed_identity = Some(identity);+ });+ }+ if !verify_step(&before, &after, &step.effect, &operators, &execution.binding.context.session_user)+ || (legacy_interval && !legacy_coverage(&after, &execution.binding.context.session_user))+ || (legacy_interval+ && !legacy_preserved(+ &before,+ &after,+ matches!(step.effect, NativeJobStepEffect::DamengLegacyInterval { .. }),+ matches!(step.effect, NativeJobStepEffect::DamengLegacyNextDate { .. })+ || (!plan.compare_next_date && matches!(step.effect, NativeJobStepEffect::Enabled(_))),+ matches!(step.effect, NativeJobStepEffect::DamengLegacyWhat { .. }),+ ))+ {+ return Err((+ "native_job_readback_not_verified",+ if unknown { NativeJobOperationOutcome::Unknown } else { NativeJobOperationOutcome::Partial },+ ));+ }+ if let NativeJobStepEffect::DamengLegacyNextDate { expected } = &step.effect {+ requested_date = Some(expected.clone());+ }+ if requested_date.as_deref().is_some_and(|expected| !legacy_time_matches(&after, expected)) {+ return Err(("native_job_readback_not_verified", NativeJobOperationOutcome::Partial));+ }+ let accepted = matches!(step.effect, NativeJobStepEffect::DamengLegacyInterval { expected_seconds: None });+ accepted_seen |= accepted;+ operations.edit(id, |status| {+ status.steps[status_index].state =+ if accepted { NativeJobStepState::Accepted } else { NativeJobStepState::Applied };+ if accepted {+ status.steps[status_index].reason = Some("native_job_legacy_interval_expression_not_readable".into());+ }+ });+ if let NativeJobStepEffect::DamengChild(child) = &step.effect {+ if child.action == NativeJobDamengChildAction::Added {+ let native_id = parts::created_id(&after, child)+ .ok_or(("native_job_child_identity_unverified", NativeJobOperationOutcome::Partial))?;+ operations.edit(id, |status| {+ status.created_children.push(NativeJobDamengCreatedChild {+ partition: child.part.key().into(),+ name: child.name.clone(),+ id: native_id.clone(),+ })+ });+ created_children.insert(native_job_dameng_child_key(child.part, &child.name), native_id);+ }+ }+ if matches!(step.effect, NativeJobStepEffect::DamengConfigurationCommitted) {+ operations.configuration_verified(origin_key);+ }+ before = after;+ }+ Ok(if accepted_seen { NativeJobOperationOutcome::Accepted } else { NativeJobOperationOutcome::Verified })+}diff --git a/crates/dbx-core/src/schema/native_jobs/operations/dameng/creation.rs b/crates/dbx-core/src/schema/native_jobs/operations/dameng/creation.rsnew file mode 100644index 0000000000..e2d5e9810d--- /dev/null+++ b/crates/dbx-core/src/schema/native_jobs/operations/dameng/creation.rs@@ -0,0 +1,141 @@+use super::*;+use dbx_sql::native_job_changes::{native_job_dameng_catalog_id, native_job_dameng_name_queries};++pub(super) async fn lookup(+ session: &mut impl NativeJobMutationSession,+ name: &str,+) -> Result<Option<NativeJobRow>, &'static str> {+ for query in native_job_dameng_name_queries(name)? {+ let read = session.query(query).await.and_then(|raw| {+ decode_query_result(NativeJobEngine::Dameng, raw).and_then(|result| rows_from_result(result, 1, |_| Ok(())))+ });+ match read {+ Ok(NativeJobMetadata::Empty) => return Ok(None),+ Ok(NativeJobMetadata::Available { mut value }) if value.len() == 1 => {+ let row = value.pop().expect("one job");+ if !row.get("NAME").and_then(Value::as_str).is_some_and(|actual| actual.eq_ignore_ascii_case(name))+ || row.get("DBX_JOB_ID").and_then(native_job_dameng_catalog_id).is_none()+ || row.get("USERNAME").and_then(Value::as_str).is_none()+ {+ return Err("native_job_identity_unverified");+ }+ return Ok(Some(row));+ }+ Err(error) if error.permits_fallback() => continue,+ _ => return Err("native_job_creation_visibility_unverified"),+ }+ }+ Err("native_job_creation_visibility_unverified")+}++fn initial_matches(+ details: &NativeJobDetails,+ plan: &NativeJobDamengCreatePlan,+ operators: &BTreeMap<&'static str, Option<i64>>,+ user: &str,+) -> bool {+ let Some(row) = row(details) else { return false };+ matches!(details.consistency, NativeJobMetadata::Available { .. })+ && matches!(details.native_identity, NativeJobMetadata::Available { .. })+ && row.get("USERNAME").and_then(Value::as_str) == Some(user)+ && super::super::super::details::boolean(row.get("ENABLE")) == Some(false)+ && fields_match(details, &plan.definition_fields)+ && operators.iter().all(|(column, expected)| match expected {+ Some(id) => values::field_matches(column, row.get(*column), &serde_json::json!(id)),+ None => row.get(*column).is_some_and(|value| {+ value.is_null() || super::super::super::details::integer(Some(value)).is_some_and(|id| id <= 0)+ }),+ })+ && [&details.steps, &details.schedules].into_iter().all(|part| {+ matches!(part, NativeJobMetadata::Empty)+ || matches!(part, NativeJobMetadata::Available {value} if value.is_empty())+ })+}++pub(in super::super) async fn run_create(+ state: &AppState,+ execution: &PreparedExecution,+ id: &str,+ cancel: &CancellationToken,+ session: &mut impl NativeJobMutationSession,+ dispatched: &mut bool,+) -> Result<NativeJobOperationOutcome, Failure> {+ let PreparedAction::DamengCreate { definition, plan } = &execution.action else { unreachable!() };+ session.begin_configure(id).await.map_err(|reason| (reason, NativeJobOperationOutcome::NotApplied))?;+ check_dispatch(state, execution, cancel, false).await?;+ if lookup(session, &definition.name)+ .await+ .map_err(|reason| (reason, NativeJobOperationOutcome::NotApplied))?+ .is_some()+ {+ return Err(("native_job_creation_target_not_absent", NativeJobOperationOutcome::NotApplied));+ }+ let operators = resolve_operators(session, &plan.configuration)+ .await+ .map_err(|reason| (reason, NativeJobOperationOutcome::NotApplied))?;+ check_dispatch(state, execution, cancel, false).await?;+ let operations = state.native_jobs.operations();+ operations.edit(id, |status| {+ status.state = NativeJobOperationState::Running;+ status.steps[0].state = NativeJobStepState::Dispatching;+ });+ *dispatched = true;+ let receipt = session.execute(&plan.steps[0]).await;+ scheduler::mark(operations, id, 0, &receipt);+ match receipt.outcome {+ NativeJobDispatchOutcome::NotStarted => {+ return Err(("native_job_step_not_applied", NativeJobOperationOutcome::NotApplied))+ }+ // Never adopt a same-name job after a lost CREATE receipt or send CONFIG/ENABLE to it.+ NativeJobDispatchOutcome::Unknown => {+ return Err(("native_job_creation_outcome_unknown", NativeJobOperationOutcome::Unknown))+ }+ NativeJobDispatchOutcome::Applied => {}+ }+ let created = lookup(session, &definition.name)+ .await+ .map_err(|reason| (reason, NativeJobOperationOutcome::Partial))?+ .ok_or(("native_job_created_definition_unverified", NativeJobOperationOutcome::Partial))?;+ let target = NativeJobRef::DamengNative {+ scope: execution.binding.context.scope.clone(),+ job_id: created["DBX_JOB_ID"]+ .as_str()+ .ok_or(("native_job_identity_unverified", NativeJobOperationOutcome::Partial))?+ .into(),+ name: created["NAME"].as_str().expect("validated native name").into(),+ };+ if created["USERNAME"].as_str() != Some(execution.binding.context.session_user.as_str()) {+ return Err(("native_job_created_definition_unverified", NativeJobOperationOutcome::Partial));+ }+ operations.edit(id, |status| status.target = Some(target.clone()));+ let before = session.read(&target).await.map_err(|reason| (reason, NativeJobOperationOutcome::Partial))?;+ let NativeJobMetadata::Available { value: identity } = &before.native_identity else {+ return Err(("native_job_created_definition_unverified", NativeJobOperationOutcome::Partial));+ };+ if !matches!(before.consistency, NativeJobMetadata::Available { .. }) {+ return Err(("native_job_created_definition_unverified", NativeJobOperationOutcome::Partial));+ }+ let origin_key = native_origin_key(&execution.binding, &target, identity);+ operations.edit(id, |status| status.observed_identity = Some(identity.clone()));+ operations.configuration_dispatched(&origin_key);+ if !initial_matches(&before, plan, &operators, &execution.binding.context.session_user) {+ return Err(("native_job_created_definition_unverified", NativeJobOperationOutcome::Partial));+ }+ let mutation = NativeJobMutation {+ target: target.clone(),+ baseline: before.snapshot.revision.clone(),+ change: NativeJobChange::ConfigureDameng { configuration: plan.remaining.clone() },+ };+ let configured = native_job_mutation_plan(NativeJobEngine::Dameng, &mutation, &before)+ .map_err(|reason| (reason, NativeJobOperationOutcome::Partial))?;+ run_steps(+ state,+ execution,+ id,+ cancel,+ session,+ dispatched,+ ConfigurationExecution { target: &target, plan: &configured, origin_key: &origin_key, offset: 1, before },+ )+ .await+}diff --git a/crates/dbx-core/src/schema/native_jobs/operations/dameng/parts.rs b/crates/dbx-core/src/schema/native_jobs/operations/dameng/parts.rsnew file mode 100644index 0000000000..8d05bbd2ba--- /dev/null+++ b/crates/dbx-core/src/schema/native_jobs/operations/dameng/parts.rs@@ -0,0 +1,196 @@+use super::*;+use dbx_sql::native_job_changes::{+ native_job_dameng_catalog_id, native_job_dameng_child_id, NativeJobDamengChildAction, NativeJobDamengChildEffect,+ NativeJobDamengPart,+};++fn same_name(left: &str, right: &str) -> bool {+ left == right || (left.is_ascii() && right.is_ascii() && left.eq_ignore_ascii_case(right))+}++fn rows(details: &NativeJobDetails, part: NativeJobDamengPart) -> Option<&[NativeJobRow]> {+ match if part == NativeJobDamengPart::Steps { &details.steps } else { &details.schedules } {+ NativeJobMetadata::Available { value } => Some(value),+ NativeJobMetadata::Empty => Some(&[]),+ _ => None,+ }+}++fn job_id(details: &NativeJobDetails) -> Option<&str> {+ match &details.snapshot.job_ref {+ NativeJobRef::DamengNative { job_id, .. } | NativeJobRef::Legacy { job_id, .. } => Some(job_id),+ _ => None,+ }+}++fn indexed<'a>(rows: &'a [NativeJobRow], job: &str) -> Option<(Vec<String>, BTreeMap<String, &'a NativeJobRow>)> {+ let mut order = Vec::new();+ let mut result = BTreeMap::new();+ let mut names = HashSet::new();+ for row in rows {+ let id = native_job_dameng_child_id(row)?;+ let name = row.get("NAME")?.as_str()?;+ let parent = row.get("JOBID")?;+ if native_job_dameng_catalog_id(parent).as_deref() != Some(job)+ || !names.insert(name.to_ascii_uppercase())+ || result.insert(id.clone(), row).is_some()+ {+ return None;+ }+ order.push(id);+ }+ Some((order, result))+}++fn no_target(value: &Value) -> bool {+ value.is_null() || value.as_str() == Some("")+}++fn field_matches(key: &str, actual: Option<&Value>, expected: &Value) -> bool {+ if matches!(key, "SUCC_NEXT_STEP" | "FAIL_NEXT_STEP") {+ return actual.is_some_and(|actual| {+ (no_target(actual) && no_target(expected))+ || actual.as_str().zip(expected.as_str()).is_some_and(|(actual, expected)| same_name(actual, expected))+ });+ }+ values::field_matches(key, actual, expected)+}++fn readable_native_value(key: &str, value: Option<&Value>) -> bool {+ let Some(value) = value.and_then(Value::as_str).filter(|value| !value.is_empty()) else { return false };+ match key {+ "STARTTIME" | "ENDTIME" => chrono::NaiveTime::parse_from_str(value, "%H:%M:%S%.f").is_ok(),+ "DURING_START_DATE" | "DURING_END_DATE" => {+ chrono::NaiveDate::parse_from_str(value, "%Y-%m-%d").is_ok()+ || chrono::NaiveDateTime::parse_from_str(value, "%Y-%m-%d %H:%M:%S%.f").is_ok()+ }+ "COMMAND" => true,+ _ => false,+ }+}++fn row_preserved(+ before: &NativeJobRow,+ after: &NativeJobRow,+ effect: &NativeJobDamengChildEffect,+ selected: bool,+) -> bool {+ let ignored = |key: &str| {+ (selected+ && (effect.fields.contains_key(key)+ || effect.acknowledged_fields.iter().any(|field| field == key)+ || (key == "NAME" && matches!(effect.action, NativeJobDamengChildAction::Renamed(_)))))+ || (effect.part == NativeJobDamengPart::Schedules && matches!(key, "VALID" | "SCHNAME" | "TRIGNAME"))+ || (effect.part == NativeJobDamengPart::Steps+ && key == "SEQNO"+ && matches!(effect.action, NativeJobDamengChildAction::Added | NativeJobDamengChildAction::Dropped))+ };+ let allowed_rename = |key: &str, old: &Value, new: &Value| {+ if effect.part != NativeJobDamengPart::Steps || !matches!(key, "SUCC_NEXT_STEP" | "FAIL_NEXT_STEP") {+ return false;+ }+ let NativeJobDamengChildAction::Renamed(name) = &effect.action else { return false };+ old.as_str().is_some_and(|old| same_name(old, &effect.name))+ && new.as_str().is_some_and(|new| same_name(new, name))+ };+ before.iter().all(|(key, value)| {+ ignored(key) || after.get(key).is_some_and(|actual| actual == value || allowed_rename(key, value, actual))+ }) && after.keys().all(|key| ignored(key) || before.contains_key(key))+}++pub(super) fn verify(+ before: &NativeJobDetails,+ after: &NativeJobDetails,+ effect: &NativeJobDamengChildEffect,+ user: &str,+) -> bool {+ let (Some(before_rows), Some(after_rows), Some(job)) =+ (rows(before, effect.part), rows(after, effect.part), job_id(before))+ else {+ return false;+ };+ let (Some((before_order, before_rows)), Some((after_order, after_rows))) =+ (indexed(before_rows, job), indexed(after_rows, job))+ else {+ return false;+ };+ let added = effect.action == NativeJobDamengChildAction::Added;+ let dropped = effect.action == NativeJobDamengChildAction::Dropped;+ let selected_before = effect.native_id.as_ref().and_then(|id| before_rows.get(id).copied());+ if !added+ && !selected_before.is_some_and(|row| {+ row.get("NAME").and_then(Value::as_str).is_some_and(|name| same_name(name, &effect.name))+ })+ {+ return false;+ }+ if added+ && before_rows+ .values()+ .any(|row| row.get("NAME").and_then(Value::as_str).is_some_and(|name| same_name(name, &effect.name)))+ {+ return false;+ }+ let selected_after = if added {+ let found = after_rows+ .iter()+ .filter(|(_, row)| {+ row.get("NAME").and_then(Value::as_str).is_some_and(|name| same_name(name, &effect.name))+ })+ .collect::<Vec<_>>();+ if found.len() != 1 || before_rows.contains_key(found[0].0) {+ return false;+ }+ Some((found[0].0, *found[0].1))+ } else {+ effect.native_id.as_ref().and_then(|id| after_rows.get_key_value(id).map(|(id, row)| (id, *row)))+ };+ if dropped {+ let own = super::row(before).is_some_and(|row| row.get("USERNAME").and_then(Value::as_str) == Some(user));+ let visible = after.sources.get(effect.part.key()).is_some_and(|source| {+ source.coverage == Some(NativeJobCatalogCoverage::Database)+ || (own && source.coverage == Some(NativeJobCatalogCoverage::CurrentUser))+ });+ if !visible || selected_after.is_some() || after_rows.len() + 1 != before_rows.len() {+ return false;+ }+ } else {+ let Some((_, selected)) = selected_after else { return false };+ let name = match &effect.action {+ NativeJobDamengChildAction::Renamed(name) => name,+ _ => &effect.name,+ };+ if !selected.get("NAME").and_then(Value::as_str).is_some_and(|actual| same_name(actual, name))+ || !effect.fields.iter().all(|(key, expected)| field_matches(key, selected.get(key), expected))+ || !effect.acknowledged_fields.iter().all(|key| readable_native_value(key, selected.get(key)))+ {+ return false;+ }+ if added && after_rows.len() != before_rows.len() + 1 {+ return false;+ }+ if !added && after_rows.len() != before_rows.len() {+ return false;+ }+ }+ if !before_rows.iter().all(|(id, row)| {+ if dropped && effect.native_id.as_ref() == Some(id) {+ return true;+ }+ after_rows.get(id).is_some_and(|after| row_preserved(row, after, effect, effect.native_id.as_ref() == Some(id)))+ }) {+ return false;+ }+ let kept_before =+ before_order.iter().filter(|id| !dropped || effect.native_id.as_ref() != Some(*id)).collect::<Vec<_>>();+ let kept_after = after_order.iter().filter(|id| before_rows.contains_key(*id)).collect::<Vec<_>>();+ // Native step deletion may renumber SEQNO; the surviving execution order must not change.+ effect.part != NativeJobDamengPart::Steps || kept_before == kept_after+}++pub(super) fn created_id(after: &NativeJobDetails, effect: &NativeJobDamengChildEffect) -> Option<String> {+ rows(after, effect.part)?+ .iter()+ .find(|row| row.get("NAME").and_then(Value::as_str).is_some_and(|name| same_name(name, &effect.name)))+ .and_then(native_job_dameng_child_id)+}diff --git a/crates/dbx-core/src/schema/native_jobs/operations/dameng/rename.rs b/crates/dbx-core/src/schema/native_jobs/operations/dameng/rename.rsnew file mode 100644index 0000000000..bc0c1ee7b4--- /dev/null+++ b/crates/dbx-core/src/schema/native_jobs/operations/dameng/rename.rs@@ -0,0 +1,215 @@+use super::*;+use crate::schema::native_jobs::{details, service};+use dbx_sql::native_job_changes::native_job_dameng_identity_queries;++pub(in crate::schema::native_jobs::operations) struct Binding {+ pub binding: service::BoundContext,+ pub target: NativeJobRef,+ pub identity: NativeJobRow,+ pub old_name: String,+ pub new_name: String,+}++impl Binding {+ pub(in crate::schema::native_jobs::operations) async fn locate_session(+ &self,+ session: &mut impl NativeJobMutationSession,+ ) -> Result<NativeJobRef, &'static str> {+ for query in native_job_dameng_identity_queries(&self.target)? {+ let limit = query.limit;+ match session.query(query).await.and_then(|raw| {+ decode_catalog_rows(NativeJobEngine::Dameng, &self.target, NativeJobCatalogPart::Generation, raw, limit)+ }) {+ Ok(data) => return self.located(data),+ Err(error) if error.permits_fallback() => continue,+ _ => return Err("native_job_rename_identity_unavailable"),+ }+ }+ Err("native_job_rename_identity_unavailable")+ }+ pub(in crate::schema::native_jobs::operations) async fn locate<Q, F>(+ &self,+ mut query: Q,+ ) -> Result<NativeJobRef, &'static str>+ where+ Q: FnMut(NativeJobCatalogQuery) -> F,+ F: Future<Output = Result<Value, NativeJobCatalogFailure>>,+ {+ let section = read_catalog_candidates_with(+ native_job_dameng_identity_queries(&self.target)?,+ |raw, limit| {+ decode_catalog_rows(NativeJobEngine::Dameng, &self.target, NativeJobCatalogPart::Generation, raw, limit)+ },+ &mut query,+ )+ .await?;+ self.located(section.data)+ }++ fn located(&self, data: NativeJobMetadata<Vec<NativeJobRow>>) -> Result<NativeJobRef, &'static str> {+ let NativeJobMetadata::Available { value } = data else {+ return Err("native_job_rename_identity_unavailable");+ };+ let [row] = value.as_slice() else {+ return Err("native_job_rename_identity_unavailable");+ };+ if row.get("DBX_JOB_ID") != self.identity.get("DBX_JOB_ID")+ || row.get("DBX_CREATED_AT") != self.identity.get("DBX_CREATED_AT")+ {+ return Err("native_job_replaced");+ }+ let Some(name) =+ row.get("NAME").and_then(Value::as_str).filter(|name| *name == self.old_name || *name == self.new_name)+ else {+ return Err("native_job_rename_name_changed");+ };+ if matches!(self.target, NativeJobRef::Legacy { .. }) && details::integer(row.get("SYS_FLAG")) != Some(2) {+ return Err("native_job_identity_mismatch");+ }+ Ok(match &self.target {+ NativeJobRef::DamengNative { scope, job_id, .. } => {+ NativeJobRef::DamengNative { scope: scope.clone(), job_id: job_id.clone(), name: name.into() }+ }+ NativeJobRef::Legacy { .. } => self.target.clone(),+ _ => return Err("native_job_kind_invalid"),+ })+ }++ pub(in crate::schema::native_jobs::operations) fn verified(+ &self,+ target: &NativeJobRef,+ details: &NativeJobDetails,+ ) -> Result<NativeJobRow, &'static str> {+ let NativeJobMetadata::Available { value } = &details.native_identity else {+ return Err("native_job_identity_unverified");+ };+ if details.snapshot.job_ref != *target+ || !matches!(details.consistency, NativeJobMetadata::Available { .. })+ || value.get("DBX_JOB_ID") != self.identity.get("DBX_JOB_ID")+ || value.get("DBX_CREATED_AT") != self.identity.get("DBX_CREATED_AT")+ {+ return Err("native_job_replaced");+ }+ let definition = row(details).ok_or("native_job_definition_unavailable")?;+ let name = definition+ .get("NAME")+ .and_then(Value::as_str)+ .filter(|name| *name == self.old_name || *name == self.new_name)+ .ok_or("native_job_rename_name_changed")?;+ if matches!(target, NativeJobRef::DamengNative { name: target_name, .. } if name != target_name) {+ return Err("native_job_identity_mismatch");+ }+ let mut identity = value.clone();+ identity.insert("NAME".into(), Value::String(name.into()));+ Ok(identity)+ }+}++pub(in crate::schema::native_jobs::operations) async fn observe_core(+ state: &AppState,+ tracker: &Binding,+) -> Result<(NativeJobRef, NativeJobRow), &'static str> {+ let binding = &tracker.binding;+ let scope = tracker.target.scope();+ if !state.connection_lifecycle_is_current(&scope.connection_id, &binding.lifecycle) {+ return Err("native_job_context_changed");+ }+ let timeout = crate::schema::agent_metadata_timeout(state.configs.read().await.get(&scope.connection_id));+ let (session, pool) = service::open_pool(state, scope).await?;+ let result = async {+ service::validate_runtime_context(state, binding, &pool).await?;+ let observed = tokio::select! {+ biased;+ _ = binding.lifecycle.cancellation().cancelled() => return Err("native_job_context_changed"),+ observed = async {+ let target = tracker.locate(|query| execute_catalog_query(NativeJobEngine::Dameng, &pool, &scope.database, query, timeout)).await?;+ let details = read_native_job_details_with(NativeJobEngine::Dameng, &target, |query| execute_catalog_query(NativeJobEngine::Dameng, &pool, &scope.database, query, timeout)).await?;+ Ok::<_, &'static str>((target.clone(), tracker.verified(&target, &details)?))+ } => observed?,+ };+ service::validate_runtime_context(state, binding, &pool).await?;+ Ok(observed)+ }.await;+ session.finish(state, &scope.connection_id, (!scope.database.is_empty()).then_some(scope.database.as_str())).await;+ result+}++#[cfg(test)]+mod tests {+ use super::*;+ use serde_json::json;++ async fn tracker() -> (tempfile::TempDir, AppState, Binding) {+ let dir = tempfile::tempdir().unwrap();+ let storage = crate::persistence::test_storage::open(&dir.path().join("state.db")).await.unwrap();+ let state = AppState::new_with_plugin_and_agent_dir_and_app_version(+ storage,+ dir.path().join("plugins"),+ dir.path().join("agents"),+ "0.0.0",+ );+ state.configs.write().await.insert("c".into(), serde_json::from_value(json!({"id":"c","name":"test","db_type":"dameng","host":"127.0.0.1","port":1,"username":"Owner","password":""})).unwrap());+ let context = crate::schema::native_jobs::native_job_open_context_with(&state, "c", "", |_| {+ std::future::ready(Ok(crate::schema::native_jobs::NativeJobRuntimeIdentity {+ database_info: None,+ session_user: "Owner".into(),+ }))+ })+ .await+ .unwrap();+ let binding = state.native_jobs.context(&state, &context.scope).unwrap();+ let tracker = Binding {+ binding,+ target: NativeJobRef::DamengNative {+ scope: context.scope,+ job_id: "900719925474099312345".into(),+ name: "Old Job".into(),+ },+ identity: serde_json::from_value(json!({"DBX_JOB_ID":"900719925474099312345","DBX_CREATED_AT":"creation"}))+ .unwrap(),+ old_name: "Old Job".into(),+ new_name: "New Job".into(),+ };+ (dir, state, tracker)+ }++ fn rows(name: &str, created: &str, flag: i64) -> Value {+ json!({"columns":["DBX_JOB_ID","DBX_CREATED_AT","NAME","USERNAME","SYS_FLAG"],"rows":[["900719925474099312345",created,name,"Owner",flag]],"affected_rows":0,"execution_time_ms":0})+ }++ #[tokio::test]+ async fn identity_observation_follows_only_the_frozen_generation_and_old_or_new_name() {+ let (_dir, _state, tracker) = tracker().await;+ for name in ["Old Job", "New Job", "Third Job"] {+ let observed = tracker.locate(|_| std::future::ready(Ok(rows(name, "creation", 0)))).await;+ if name == "Third Job" {+ assert_eq!(observed.err(), Some("native_job_rename_name_changed"));+ } else {+ assert!(matches!(observed.unwrap(), NativeJobRef::DamengNative { name: actual, .. } if actual == name));+ }+ }+ assert_eq!(+ tracker.locate(|_| std::future::ready(Ok(rows("New Job", "replacement", 0)))).await.err(),+ Some("native_job_replaced")+ );+ }++ #[tokio::test]+ async fn identity_observation_preserves_legacy_classification_and_requires_full_readback() {+ let (_dir, _state, mut tracker) = tracker().await;+ tracker.target =+ NativeJobRef::Legacy { scope: tracker.target.scope().clone(), job_id: "900719925474099312345".into() };+ assert_eq!(+ tracker.locate(|_| std::future::ready(Ok(rows("New Job", "creation", 0)))).await.err(),+ Some("native_job_identity_mismatch")+ );+ assert!(matches!(+ tracker.locate(|_| std::future::ready(Ok(rows("New Job", "creation", 2)))).await.unwrap(),+ NativeJobRef::Legacy { .. }+ ));+ let mut details: NativeJobDetails = serde_json::from_value(json!({"snapshot":{"ref":tracker.target,"revision":"read","definition":{"status":"available","value":{"NAME":"New Job","ENABLE":1}},"arguments":{"status":"empty"}},"nativeIdentity":{"status":"available","value":tracker.identity},"consistency":{"status":"available","value":null},"parameterMetadata":{"status":"empty"},"steps":{"status":"empty"},"schedules":{"status":"empty"},"running":{"status":"empty"},"history":{"status":"empty"},"sources":{}})).unwrap();+ assert_eq!(tracker.verified(&tracker.target, &details).unwrap()["NAME"], json!("New Job"));+ details.consistency = NativeJobMetadata::Unknown { reason: "changed".into() };+ assert_eq!(tracker.verified(&tracker.target, &details).err(), Some("native_job_replaced"));+ }+}diff --git a/crates/dbx-core/src/schema/native_jobs/operations/legacy.rs b/crates/dbx-core/src/schema/native_jobs/operations/legacy.rsnew file mode 100644index 0000000000..1685ba9462--- /dev/null+++ b/crates/dbx-core/src/schema/native_jobs/operations/legacy.rs@@ -0,0 +1,217 @@+use super::*;++pub(super) fn receipt(id: &str, phase: NativeJobLegacyPhase, reason: &'static str) -> NativeJobLegacyReceipt {+ NativeJobLegacyReceipt {+ operation_id: id.into(),+ phase,+ job_id: None,+ reason: Some(reason.into()),+ vendor_code: None,+ disposal_confirmed: None,+ }+}++fn safe_reason(reason: &Option<String>) -> Option<String> {+ reason.as_ref().map(|reason| {+ if reason.len() <= 96+ && reason.starts_with("native_job_")+ && reason.bytes().all(|byte| byte.is_ascii_alphanumeric() || byte == b'_')+ {+ reason.clone()+ } else {+ "native_job_legacy_protocol_error".into()+ }+ })+}++fn mark(state: &AppState, id: &str, index: usize, phase: NativeJobStepState, native: &NativeJobLegacyReceipt) {+ state.native_jobs.operations().edit(id, |status| {+ status.steps[index].state = phase;+ status.steps[index].reason = safe_reason(&native.reason);+ status.steps[index].vendor_code = native.vendor_code;+ });+}++async fn rollback_before_commit(+ state: &AppState,+ id: &str,+ job_id: Option<&str>,+ session: &mut impl NativeJobMutationSession,+ reason: &'static str,+) -> Result<NativeJobOperationOutcome, (&'static str, NativeJobOperationOutcome)> {+ let native = session.finish_legacy(id, job_id, false).await;+ let confirmed = native.operation_id == id+ && native.phase == NativeJobLegacyPhase::RolledBack+ && native.job_id.as_deref().is_none_or(|actual| job_id.is_none_or(|expected| actual == expected));+ mark(state, id, 0, if confirmed { NativeJobStepState::Failed } else { NativeJobStepState::Unknown }, &native);+ Err(if confirmed {+ (reason, NativeJobOperationOutcome::NotApplied)+ } else {+ ("native_job_rollback_unknown", NativeJobOperationOutcome::Unknown)+ })+}++pub(super) async fn run_create(+ state: &AppState,+ execution: &PreparedExecution,+ id: &str,+ cancel: &CancellationToken,+ session: &mut impl NativeJobMutationSession,+ created_guard: &mut Option<tokio::sync::OwnedMutexGuard<()>>,+ dispatched: &mut bool,+) -> Result<NativeJobOperationOutcome, (&'static str, NativeJobOperationOutcome)> {+ let PreparedAction::LegacyCreate { definition, .. } = &execution.action else { unreachable!() };+ let operations = state.native_jobs.operations();+ if cancel.is_cancelled() {+ return Err(("native_job_canceled_before_dispatch", NativeJobOperationOutcome::NotApplied));+ }+ operations.edit(id, |status| {+ status.state = NativeJobOperationState::Running;+ status.steps[0].state = NativeJobStepState::Dispatching;+ });+ *dispatched = true;+ // Await the receipt even when the page cancels: only the owner can dispose this transaction.+ let prepared = session.prepare_legacy(id, definition).await;+ let target = prepared.job_id.as_ref().and_then(|job_id| {+ let target = NativeJobRef::Legacy { scope: execution.binding.context.scope.clone(), job_id: job_id.clone() };+ target.validate().ok().map(|_| target)+ });+ if prepared.operation_id != id {+ return rollback_before_commit(state, id, None, session, "native_job_legacy_protocol_error").await;+ }+ if prepared.phase != NativeJobLegacyPhase::NotStarted {+ if let Some(target) = &target {+ // Persist the real OUT identity before authorizing the first COMMIT.+ operations.edit(id, |status| status.target = Some(target.clone()));+ }+ }+ if matches!(prepared.phase, NativeJobLegacyPhase::NotStarted | NativeJobLegacyPhase::RolledBack) {+ mark(state, id, 0, NativeJobStepState::Failed, &prepared);+ let reason = if prepared.reason.as_deref() == Some("native_job_legacy_runtime_update_required") {+ "native_job_legacy_runtime_update_required"+ } else {+ "native_job_legacy_not_applied"+ };+ return Err((reason, NativeJobOperationOutcome::NotApplied));+ }+ let Some(NativeJobRef::Legacy { job_id, .. }) = target.as_ref() else {+ return rollback_before_commit(state, id, None, session, "native_job_out_id_unverified").await;+ };+ if prepared.phase != NativeJobLegacyPhase::Prepared {+ return rollback_before_commit(state, id, Some(job_id), session, "native_job_prepare_unknown").await;+ }+ mark(state, id, 0, NativeJobStepState::Applied, &prepared);+ let target = target.as_ref().expect("validated OUT target");+ let identity = NativeJobRow::from([("DBX_JOB_ID".into(), Value::String(job_id.clone()))]);+ let lock = operations.job_lock(&native_origin_key(&execution.binding, target, &identity));+ *created_guard = Some(tokio::select! {+ biased;+ _ = cancel.cancelled() => return rollback_before_commit(state, id, Some(job_id), session, "native_job_canceled_before_commit").await,+ _ = execution.binding.lifecycle.cancellation().cancelled() => return rollback_before_commit(state, id, Some(job_id), session, "native_job_context_changed").await,+ guard = lock.lock_owned() => guard,+ });+ let stopped = if cancel.is_cancelled() {+ Some("native_job_canceled_before_commit")+ } else {+ require_write(state, &execution.binding).await.err()+ };+ if let Some(reason) = stopped {+ return rollback_before_commit(state, id, Some(job_id), session, reason).await;+ }+ operations.edit(id, |status| status.steps[1].state = NativeJobStepState::Dispatching);+ let commit = session.finish_legacy(id, Some(job_id), true).await;+ // No SUBMIT, COMMIT, BROKEN, or ROLLBACK is resent after this call.+ let matching = commit.operation_id == id && commit.job_id.as_deref().is_none_or(|actual| actual == job_id);+ if matching && commit.phase == NativeJobLegacyPhase::RolledBack {+ mark(state, id, 1, NativeJobStepState::Failed, &commit);+ return Err(("native_job_legacy_not_applied", NativeJobOperationOutcome::NotApplied));+ }+ let committed =+ matching && commit.phase == NativeJobLegacyPhase::Committed && commit.job_id.as_deref() == Some(job_id);+ mark(state, id, 1, if committed { NativeJobStepState::Applied } else { NativeJobStepState::Unknown }, &commit);+ if !matching+ || !matches!(+ commit.phase,+ NativeJobLegacyPhase::Committed | NativeJobLegacyPhase::CommitSent | NativeJobLegacyPhase::Unknown+ )+ {+ return Err(("native_job_legacy_commit_unknown", NativeJobOperationOutcome::Unknown));+ }+ if !state.connection_lifecycle_is_current(&target.scope().connection_id, &execution.binding.lifecycle) {+ return Err((+ "native_job_context_changed",+ if committed { NativeJobOperationOutcome::Partial } else { NativeJobOperationOutcome::Unknown },+ ));+ }+ operations.edit(id, |status| status.steps[2].state = NativeJobStepState::Dispatching);+ let after = session.read(target).await;+ let verified = after.as_ref().is_ok_and(|details| {+ verify_created(+ details,+ target,+ definition,+ &execution.binding.context.session_user,+ execution.binding.context.engine,+ )+ });+ if !verified {+ operations.edit(id, |status| {+ status.steps[2].state = NativeJobStepState::Unknown;+ status.steps[2].reason = Some("native_job_readback_not_verified".into());+ });+ return Err((+ "native_job_readback_not_verified",+ if committed { NativeJobOperationOutcome::Partial } else { NativeJobOperationOutcome::Unknown },+ ));+ }+ operations.edit(id, |status| {+ status.steps[1].state = NativeJobStepState::Applied;+ status.steps[2].state = NativeJobStepState::Applied;+ });+ Ok(NativeJobOperationOutcome::Verified)+}++pub(super) fn same_date(actual: Option<&Value>, expected: &str) -> bool {+ let Some(actual) = actual.and_then(Value::as_str) else { return false };+ let parsed = ["%Y-%m-%d %H:%M:%S%.f", "%Y-%m-%dT%H:%M:%S%.f"]+ .into_iter()+ .find_map(|format| chrono::NaiveDateTime::parse_from_str(actual, format).ok());+ parsed+ .is_some_and(|parsed| chrono::NaiveDateTime::parse_from_str(expected, "%Y-%m-%d %H:%M:%S").ok() == Some(parsed))+}++fn verify_created(+ details: &NativeJobDetails,+ target: &NativeJobRef,+ expected: &NativeJobLegacyCreate,+ user: &str,+ engine: NativeJobEngine,+) -> bool {+ if &details.snapshot.job_ref != target || !matches!(details.consistency, NativeJobMetadata::Available { .. }) {+ return false;+ }+ let NativeJobRef::Legacy { job_id, .. } = target else { return false };+ let NativeJobMetadata::Available { value: identity } = &details.native_identity else { return false };+ if identity.get("DBX_JOB_ID").and_then(Value::as_str) != Some(job_id) {+ return false;+ }+ let Some(row) = row(details) else { return false };+ let instance = row.get("INSTANCE").and_then(|value| value.as_i64().or_else(|| value.as_str()?.parse().ok()));+ let placement_matches = if engine == NativeJobEngine::OceanbaseOracle {+ row.get("INSTANCE").is_some_and(|actual| match &expected.zone {+ Some(zone) => actual.as_str() == Some(zone),+ None => actual.is_null(),+ })+ } else {+ instance == Some(expected.instance)+ };+ row.get("WHAT").and_then(Value::as_str) == Some(expected.what.as_str())+ && row.get("INTERVAL").and_then(Value::as_str).unwrap_or("") == expected.interval+ && row.get("BROKEN").and_then(Value::as_str) == Some(if expected.enabled { "N" } else { "Y" })+ && placement_matches+ && row.get("LOG_USER").and_then(Value::as_str) == Some(user)+ && row.get("PRIV_USER").and_then(Value::as_str) == Some(user)+ && row.get("SCHEMA_USER").and_then(Value::as_str) == Some(expected.schema.as_str())+ // Initial NEXT_DATE was checked on the uncommitted connection. Enabled jobs may advance it.+ && (expected.enabled || same_date(row.get("NEXT_DATE"), &expected.next_date))+}diff --git a/crates/dbx-core/src/schema/native_jobs/operations/observation.rs b/crates/dbx-core/src/schema/native_jobs/operations/observation.rsnew file mode 100644index 0000000000..315b21c6e0--- /dev/null+++ b/crates/dbx-core/src/schema/native_jobs/operations/observation.rs@@ -0,0 +1,642 @@+use super::*;++#[derive(Clone)]+pub struct Snapshot {+ identity: NativeJobMetadata<NativeJobRow>,+ consistent: bool,+ running: NativeJobMetadata<Vec<NativeJobRow>>,+ history: NativeJobMetadata<Vec<NativeJobRow>>,+ sources: BTreeMap<String, NativeJobCatalogSource>,+ owner: Option<String>,+}++impl Snapshot {+ pub fn from_details(details: &NativeJobDetails) -> Self {+ Self {+ identity: details.native_identity.clone(),+ consistent: matches!(details.consistency, NativeJobMetadata::Available { .. }),+ running: details.running.clone(),+ history: details.history.clone(),+ sources: details+ .sources+ .iter()+ .filter(|(key, _)| matches!(key.as_str(), "running" | "history" | "identity"))+ .map(|(key, value)| (key.clone(), value.clone()))+ .collect(),+ owner: row(details)+ .and_then(|row| row.get("OWNER").or_else(|| row.get("LOG_USER")).or_else(|| row.get("USERNAME")))+ .and_then(Value::as_str)+ .map(str::to_string),+ }+ }+}++pub(super) struct Tracker {+ pub binding: super::super::service::BoundContext,+ pub target: NativeJobRef,+ pub stop: bool,+ pub baseline: Snapshot,+ pub running_keys: HashSet<String>,+}++impl Tracker {+ pub(super) fn record(&mut self, current: Snapshot) -> NativeJobExecutionObservation {+ if self.binding.context.engine == NativeJobEngine::Oracle+ && matches!(self.target, NativeJobRef::Scheduler { .. })+ && current.consistent+ && self.baseline.identity == current.identity+ {+ if let Ok(running) = keyed(¤t.running, "LOG_ID") {+ self.running_keys.extend(running.into_keys());+ }+ }+ compare(+ self.binding.context.engine,+ &self.target,+ &self.binding.context.session_user,+ self.stop,+ &self.baseline,+ &self.running_keys,+ current,+ )+ }+}++pub(super) async fn read_core(+ state: &AppState,+ binding: &super::super::service::BoundContext,+ target: &NativeJobRef,+) -> Result<Snapshot, &'static str> {+ let scope = target.scope();+ if !state.connection_lifecycle_is_current(&scope.connection_id, &binding.lifecycle) {+ return Err("native_job_context_changed");+ }+ let timeout = super::super::super::agent_metadata_timeout(state.configs.read().await.get(&scope.connection_id));+ let (session, pool) = super::super::service::open_pool(state, scope).await?;+ let result = async {+ super::super::service::validate_runtime_context(state, binding, &pool).await?;+ let observed = tokio::select! {+ biased;+ _ = binding.lifecycle.cancellation().cancelled() => return Err("native_job_context_changed"),+ observed = read(binding.context.engine, target, |query| execute_catalog_query(binding.context.engine, &pool, &scope.database, query, timeout)) => observed?,+ };+ super::super::service::validate_runtime_context(state, binding, &pool).await?;+ Ok(observed)+ }.await;+ session.finish(state, &scope.connection_id, (!scope.database.is_empty()).then_some(scope.database.as_str())).await;+ result+}++pub(super) async fn read<Q, F>(+ engine: NativeJobEngine,+ target: &NativeJobRef,+ mut query: Q,+) -> Result<Snapshot, &'static str>+where+ Q: FnMut(NativeJobCatalogQuery) -> F,+ F: Future<Output = Result<Value, NativeJobCatalogFailure>>,+{+ let before =+ read_native_job_catalog_part_with(engine, target, NativeJobCatalogPart::Generation, &mut query).await?;+ let running = read_native_job_catalog_part_with(engine, target, NativeJobCatalogPart::Running, &mut query).await?;+ let history = read_native_job_catalog_part_with(engine, target, NativeJobCatalogPart::History, &mut query).await?;+ let after = read_native_job_catalog_part_with(engine, target, NativeJobCatalogPart::Generation, &mut query).await?;+ let consistent = matches!((&before.data, &after.data),+ (NativeJobMetadata::Available { value: before }, NativeJobMetadata::Available { value: after })+ if before.len() == 1 && before == after);+ let mut sources = BTreeMap::new();+ for (name, section) in [("running", &running), ("history", &history), ("identity", &after)] {+ sources.insert(+ name.into(),+ NativeJobCatalogSource { source: section.source.map(str::to_string), coverage: section.coverage },+ );+ }+ Ok(Snapshot {+ identity: super::super::details::map_metadata(after.data, |rows| rows.into_iter().next().unwrap_or_default()),+ consistent,+ running: running.data,+ history: history.data,+ sources,+ owner: None,+ })+}++fn rows(metadata: &NativeJobMetadata<Vec<NativeJobRow>>) -> Option<&[NativeJobRow]> {+ match metadata {+ NativeJobMetadata::Available { value } => Some(value),+ NativeJobMetadata::Empty => Some(&[]),+ _ => None,+ }+}++fn key(row: &NativeJobRow, column: &str) -> Option<String> {+ let value = row.get(column)?;+ let number = match value {+ Value::String(value) => value.clone(),+ Value::Number(value) => {+ value.as_i64().map(|value| value.to_string()).or_else(|| value.as_u64().map(|value| value.to_string()))?+ }+ _ => return None,+ };+ let digits = number.strip_prefix('-').unwrap_or(&number);+ if digits.is_empty() || !digits.bytes().all(|byte| byte.is_ascii_digit()) {+ return None;+ }+ let normalized = digits.trim_start_matches('0');+ Some(if normalized.is_empty() {+ "0".into()+ } else if number.starts_with('-') {+ format!("-{normalized}")+ } else {+ normalized.into()+ })+}++fn keyed(+ metadata: &NativeJobMetadata<Vec<NativeJobRow>>,+ column: &str,+) -> Result<BTreeMap<String, NativeJobRow>, &'static str> {+ let mut result = BTreeMap::new();+ for row in rows(metadata).ok_or("native_job_observation_incomplete")? {+ let key = key(row, column).ok_or("native_job_observation_key_unavailable")?;+ if result.insert(key, row.clone()).is_some() {+ return Err("native_job_observation_key_ambiguous");+ }+ }+ Ok(result)+}++fn wire_ids(row: &mut NativeJobRow) {+ for column in ["LOG_ID", "EXEC_ID", "JOBID", "JOB", "SID", "SESSION_ID", "INSTANCE_ID", "DEST_ID"] {+ if let Some(id) = key(row, column) {+ row.insert(column.into(), Value::String(id));+ }+ }+}++fn wire_partition(metadata: &mut NativeJobMetadata<Vec<NativeJobRow>>) {+ if let NativeJobMetadata::Available { value } | NativeJobMetadata::Truncated { value, .. } = metadata {+ for row in value {+ wire_ids(row);+ }+ }+}++pub(super) fn unavailable(reason: &str) -> NativeJobExecutionObservation {+ NativeJobExecutionObservation {+ observed_at: chrono::Utc::now().to_rfc3339(),+ association: "unavailable".into(),+ reason: reason.into(),+ running: NativeJobMetadata::Unknown { reason: reason.into() },+ history: NativeJobMetadata::Unknown { reason: reason.into() },+ sources: BTreeMap::new(),+ candidates: Vec::new(),+ }+}++fn compare(+ engine: NativeJobEngine,+ target: &NativeJobRef,+ session_user: &str,+ stop: bool,+ baseline: &Snapshot,+ seen_running: &HashSet<String>,+ current: Snapshot,+) -> NativeJobExecutionObservation {+ if !baseline.consistent+ || !current.consistent+ || !matches!(baseline.identity, NativeJobMetadata::Available { .. })+ || baseline.identity != current.identity+ {+ return unavailable("native_job_observation_generation_changed");+ }+ let mut result = NativeJobExecutionObservation {+ observed_at: chrono::Utc::now().to_rfc3339(),+ association: "uncertain".into(),+ reason: "native_job_observation_request_uncertain".into(),+ running: current.running.clone(),+ history: current.history.clone(),+ sources: current.sources.clone(),+ candidates: Vec::new(),+ };+ let mut partial = None;+ let candidates = (|| -> Result<Vec<NativeJobExecutionCandidate>, &'static str> {+ let coverage = |snapshot: &Snapshot, partition: &str| -> Result<(), &'static str> {+ let owner = match target {+ NativeJobRef::Scheduler { owner, .. } => Some(owner.as_str()),+ _ => baseline.owner.as_deref(),+ };+ match snapshot.sources.get(partition).and_then(|source| source.coverage) {+ Some(NativeJobCatalogCoverage::Database | NativeJobCatalogCoverage::Accessible) => {}+ Some(NativeJobCatalogCoverage::CurrentUser) if owner == Some(session_user) => {}+ _ => return Err("native_job_observation_coverage_incomplete"),+ }+ Ok(())+ };+ if engine == NativeJobEngine::Oracle && matches!(target, NativeJobRef::Scheduler { .. }) {+ let old_running = coverage(baseline, "running").and_then(|_| keyed(&baseline.running, "LOG_ID"));+ if stop {+ old_running.as_ref().map_err(|reason| *reason)?;+ }+ let old_history = if stop {+ Ok(BTreeMap::new())+ } else {+ coverage(baseline, "history").and_then(|_| keyed(&baseline.history, "LOG_ID"))+ };+ let baseline_complete = old_running.is_ok() && old_history.is_ok();+ let running = coverage(¤t, "running").and_then(|_| keyed(¤t.running, "LOG_ID"));+ let history = coverage(¤t, "history").and_then(|_| keyed(¤t.history, "LOG_ID"));+ let current_complete = running.is_ok() && history.is_ok();+ let mut available = |value: Result<BTreeMap<String, NativeJobRow>, &'static str>| match value {+ Ok(value) => value,+ Err(reason) => {+ partial = Some(reason);+ BTreeMap::new()+ }+ };+ let old_running = available(old_running);+ let old_history = available(old_history);+ let running = available(running);+ let history = available(history);+ let mut selected = BTreeMap::new();+ for (id, row) in &running {+ if (stop && old_running.contains_key(id))+ || (!stop+ && !old_running.contains_key(id)+ && !old_history.contains_key(id)+ && (baseline_complete || seen_running.contains(id)))+ {+ selected.insert(+ id.clone(),+ NativeJobExecutionCandidate {+ native_key: id.clone(),+ phase: "running".into(),+ evidence: "running-log-id".into(),+ row: row.clone(),+ },+ );+ }+ }+ for (id, row) in &history {+ if (stop && old_running.contains_key(id))+ || (!stop+ && !old_running.contains_key(id)+ && !old_history.contains_key(id)+ && (baseline_complete || seen_running.contains(id)))+ {+ selected.insert(+ id.clone(),+ NativeJobExecutionCandidate {+ native_key: id.clone(),+ phase: "history".into(),+ evidence: if old_running.contains_key(id)+ || running.contains_key(id)+ || seen_running.contains(id)+ {+ "running-log-id"+ } else {+ "new-history"+ }+ .into(),+ row: row.clone(),+ },+ );+ }+ }+ if current_complete && stop {+ for id in old_running.keys().filter(|id| !running.contains_key(*id) && !history.contains_key(*id)) {+ selected.insert(+ id.clone(),+ NativeJobExecutionCandidate {+ native_key: id.clone(),+ phase: "not-observed".into(),+ evidence: "running-log-id".into(),+ row: NativeJobRow::new(),+ },+ );+ }+ } else if current_complete {+ for id in seen_running.iter().filter(|id| {+ !old_running.contains_key(*id)+ && !old_history.contains_key(*id)+ && !running.contains_key(*id)+ && !history.contains_key(*id)+ }) {+ selected.insert(+ id.clone(),+ NativeJobExecutionCandidate {+ native_key: id.clone(),+ phase: "not-observed".into(),+ evidence: "running-log-id".into(),+ row: NativeJobRow::new(),+ },+ );+ }+ }+ return Ok(selected.into_values().collect());+ }+ if engine == NativeJobEngine::Dameng && !stop {+ coverage(baseline, "history")?;+ coverage(¤t, "history")?;+ let column = if matches!(target, NativeJobRef::Scheduler { .. }) { "LOG_ID" } else { "EXEC_ID" };+ let baseline = keyed(&baseline.history, column)?;+ return Ok(keyed(¤t.history, column)?+ .into_iter()+ .filter(|(id, _)| !baseline.contains_key(id))+ .map(|(id, row)| NativeJobExecutionCandidate {+ native_key: id,+ phase: "history".into(),+ evidence: "new-history".into(),+ row,+ })+ .collect());+ }+ Err("native_job_observation_mapping_unverified")+ })();+ match candidates {+ Ok(candidates) => {+ result.candidates = candidates;+ if let Some(reason) = partial {+ result.reason = reason.into();+ if result.candidates.is_empty() {+ result.association = "unavailable".into();+ }+ }+ }+ Err(reason) => {+ result.reason = reason.into();+ result.association = "unavailable".into();+ }+ }+ wire_partition(&mut result.running);+ wire_partition(&mut result.history);+ for candidate in &mut result.candidates {+ wire_ids(&mut candidate.row);+ }+ result+}++#[cfg(test)]+mod tests {+ use super::*;+ use serde_json::json;++ fn target() -> NativeJobRef {+ NativeJobRef::Scheduler {+ scope: NativeJobScope { connection_id: "c".into(), database: "".into(), context_id: "ctx".into() },+ owner: "Owner".into(),+ name: "Job".into(),+ }+ }+ fn snapshot() -> Snapshot {+ Snapshot {+ identity: NativeJobMetadata::Available {+ value: serde_json::from_value(json!({"DBX_JOB_ID":"42","DBX_CREATED_AT":"creation"})).unwrap(),+ },+ consistent: true,+ running: NativeJobMetadata::Empty,+ history: NativeJobMetadata::Empty,+ sources: ["running", "history"]+ .into_iter()+ .map(|part| {+ (+ part.into(),+ NativeJobCatalogSource {+ source: Some("fixture".into()),+ coverage: Some(NativeJobCatalogCoverage::Database),+ },+ )+ })+ .collect(),+ owner: Some("Owner".into()),+ }+ }+ fn data(value: Value) -> NativeJobMetadata<Vec<NativeJobRow>> {+ NativeJobMetadata::Available { value: serde_json::from_value(value).unwrap() }+ }+ fn oracle(stop: bool, before: &Snapshot, after: Snapshot) -> NativeJobExecutionObservation {+ compare(NativeJobEngine::Oracle, &target(), "Owner", stop, before, &HashSet::new(), after)+ }++ #[test]+ fn one_fast_history_failure_is_only_a_newly_observed_candidate() {+ let before = snapshot();+ let mut after = before.clone();+ after.history = data(json!([{"LOG_ID":"900719925474099312345","STATUS":"FAILED","ERROR#":20001}]));+ let result = oracle(false, &before, after);+ assert_eq!(result.association, "uncertain");+ assert_eq!(result.candidates.len(), 1);+ assert_eq!(result.candidates[0].native_key, "900719925474099312345");+ assert_eq!(result.candidates[0].row["STATUS"], "FAILED");+ assert_eq!(result.candidates[0].evidence, "new-history");+ }++ #[test]+ fn oracle_baseline_running_and_history_share_one_instance_key_space() {+ let mut before = snapshot();+ before.running = data(json!([{"LOG_ID":9007199254740993_u64}]));+ before.history = data(json!([{"LOG_ID":"8"}]));+ let mut after = snapshot();+ after.history = data(json!([{"LOG_ID":"09007199254740993","STATUS":"SUCCEEDED"},{"LOG_ID":8}]));+ assert!(oracle(false, &before, after).candidates.is_empty());+ }++ #[test]+ fn a_previously_observed_running_key_can_be_followed_into_history_without_a_request_claim() {+ let before = snapshot();+ let seen = HashSet::from(["9007199254740993".into()]);+ let mut after = snapshot();+ after.history = data(json!([{"LOG_ID":9007199254740993_u64,"STATUS":"SUCCEEDED"}]));+ let result = compare(NativeJobEngine::Oracle, &target(), "Owner", false, &before, &seen, after);+ assert_eq!(result.association, "uncertain");+ assert_eq!(result.candidates[0].evidence, "running-log-id");+ assert_eq!(result.candidates[0].row["LOG_ID"], "9007199254740993");+ let NativeJobMetadata::Available { value } = result.history else { panic!("history retained") };+ assert_eq!(value[0]["LOG_ID"], "9007199254740993");+ let absent = compare(NativeJobEngine::Oracle, &target(), "Owner", false, &before, &seen, snapshot());+ assert_eq!(absent.candidates[0].phase, "not-observed");+ }++ #[test]+ fn newly_observed_keys_are_not_assumed_to_be_monotonically_increasing() {+ let mut before = snapshot();+ before.history = data(json!([{"LOG_ID":99}]));+ let mut after = snapshot();+ after.history = data(json!([{"LOG_ID":99},{"LOG_ID":1}]));+ assert_eq!(oracle(false, &before, after).candidates[0].native_key, "1");+ }++ #[test]+ fn stop_tracks_its_baseline_instance_without_attributing_the_terminal_state() {+ let mut before = snapshot();+ before.running = data(json!([{"LOG_ID":"7"}]));+ let mut after = snapshot();+ after.history = data(json!([{"LOG_ID":7,"STATUS":"STOPPED"},{"LOG_ID":8,"STATUS":"SUCCEEDED"}]));+ let result = oracle(true, &before, after);+ assert_eq!(result.association, "uncertain");+ assert_eq!(result.candidates.len(), 1);+ assert_eq!(result.candidates[0].native_key, "7");+ assert_eq!(result.candidates[0].phase, "history");+ assert_eq!(result.candidates[0].evidence, "running-log-id");+ let gone = oracle(true, &before, snapshot());+ assert_eq!(gone.candidates[0].phase, "not-observed");+ assert_eq!(gone.association, "uncertain");+ }++ #[test]+ fn stop_does_not_require_baseline_history_or_an_unrelated_current_partition() {+ let mut before = snapshot();+ before.running = data(json!([{"LOG_ID":7}]));+ before.history = NativeJobMetadata::Denied { reason: "baseline history denied".into() };+ before.sources.remove("history");+ for readable in ["history", "running", "neither"] {+ let mut after = snapshot();+ after.running = if readable == "running" {+ data(json!([{"LOG_ID":7}]))+ } else {+ NativeJobMetadata::Denied { reason: "running denied".into() }+ };+ after.history = if readable == "history" {+ data(json!([{"LOG_ID":7,"STATUS":"STOPPED"}]))+ } else {+ NativeJobMetadata::Denied { reason: "history denied".into() }+ };+ let result = oracle(true, &before, after);+ if readable == "neither" {+ assert_eq!(result.association, "unavailable");+ assert!(result.candidates.is_empty());+ } else {+ assert_eq!(result.association, "uncertain");+ assert_eq!(result.candidates.len(), 1);+ assert_eq!(result.candidates[0].phase, readable);+ assert_eq!(result.candidates[0].native_key, "7");+ }+ }+ }++ #[test]+ fn a_captured_oracle_instance_remains_observable_when_the_request_baseline_was_incomplete() {+ let mut before = snapshot();+ before.history = NativeJobMetadata::Denied { reason: "baseline history denied".into() };+ let mut after = snapshot();+ after.running = NativeJobMetadata::Denied { reason: "running denied".into() };+ after.history = data(json!([{"LOG_ID":7,"STATUS":"FAILED"},{"LOG_ID":8,"STATUS":"SUCCEEDED"}]));+ let result =+ compare(NativeJobEngine::Oracle, &target(), "Owner", false, &before, &HashSet::from(["7".into()]), after);+ assert_eq!(result.association, "uncertain");+ assert_eq!(result.candidates.len(), 1);+ assert_eq!(result.candidates[0].native_key, "7");+ assert_eq!(result.candidates[0].evidence, "running-log-id");+ }++ #[test]+ fn multiple_new_instances_are_retained_without_choosing_the_latest() {+ let before = snapshot();+ let mut after = snapshot();+ after.running = data(json!([{"LOG_ID":2,"JOB_SUBNAME":"child"}]));+ after.history = data(json!([{"LOG_ID":1,"STATUS":"SUCCEEDED","DESTINATION":"remote"}]));+ let result = oracle(false, &before, after);+ assert_eq!(result.candidates.len(), 2);+ assert_eq!(result.association, "uncertain");+ assert_eq!(result.candidates[0].row["DESTINATION"], "remote");+ assert_eq!(result.candidates[1].row["JOB_SUBNAME"], "child");+ }++ #[test]+ fn ambiguous_missing_fractional_or_truncated_keys_do_not_create_candidates() {+ for history in [+ data(json!([{"LOG_ID":1},{"LOG_ID":"1"}])),+ data(json!([{"LOG_ID":1.5}])),+ data(json!([{"SESSION_ID":1}])),+ NativeJobMetadata::Truncated { value: vec![], limit: 200 },+ NativeJobMetadata::Denied { reason: "denied".into() },+ ] {+ let before = snapshot();+ let mut after = snapshot();+ after.history = history;+ let result = oracle(false, &before, after);+ assert_eq!(result.association, "unavailable");+ assert!(result.candidates.is_empty());+ }+ }++ #[test]+ fn user_only_coverage_does_not_prove_a_different_owners_history() {+ let mut before = snapshot();+ before.sources.get_mut("history").unwrap().coverage = Some(NativeJobCatalogCoverage::CurrentUser);+ let result = compare(NativeJobEngine::Oracle, &target(), "Other", false, &before, &HashSet::new(), snapshot());+ assert_eq!(result.reason, "native_job_observation_coverage_incomplete");+ assert!(result.candidates.is_empty());+ }++ #[test]+ fn generation_change_or_inconsistent_read_never_attaches_a_rebuilt_job() {+ for inconsistent in [false, true] {+ let before = snapshot();+ let mut after = snapshot();+ if inconsistent {+ after.consistent = false;+ } else {+ after.identity = NativeJobMetadata::Empty;+ }+ after.history = data(json!([{"LOG_ID":1,"STATUS":"SUCCEEDED"}]));+ let result = oracle(false, &before, after);+ assert_eq!(result.reason, "native_job_observation_generation_changed");+ assert!(result.candidates.is_empty());+ }+ }++ #[test]+ fn dm_running_compatibility_log_id_is_not_used_to_join_history() {+ let mut before = snapshot();+ before.running = data(json!([{"LOG_ID":1,"SESSION_ID":3}]));+ let mut after = snapshot();+ after.history = data(json!([{"LOG_ID":1,"STATUS":"FAILED","SESSION_ID":3}]));+ let result = compare(NativeJobEngine::Dameng, &target(), "Owner", false, &before, &HashSet::new(), after);+ assert_eq!(result.candidates.len(), 1);+ assert_eq!(result.candidates[0].evidence, "new-history");+ assert_eq!(result.association, "uncertain");+ assert!(compare(NativeJobEngine::Dameng, &target(), "Owner", true, &before, &HashSet::new(), snapshot())+ .candidates+ .is_empty());+ }++ #[test]+ fn dm_native_execution_ids_are_lossless_and_ob_does_not_borrow_them() {+ let before = snapshot();+ let mut after = snapshot();+ after.history = data(json!([{"EXEC_ID":"9223372036854775807","STATUS":"FAILED"}]));+ let target =+ NativeJobRef::DamengNative { scope: target().scope().clone(), job_id: "42".into(), name: "Job".into() };+ let result = compare(NativeJobEngine::Dameng, &target, "Owner", false, &before, &HashSet::new(), after.clone());+ assert_eq!(result.candidates[0].native_key, "9223372036854775807");+ assert_eq!(+ compare(NativeJobEngine::OceanbaseOracle, &target, "Owner", false, &before, &HashSet::new(), after).reason,+ "native_job_observation_mapping_unverified"+ );+ }++ #[tokio::test]+ async fn narrow_reader_queries_history_even_when_running_is_empty() {+ let mut queries = Vec::new();+ let observed = read(NativeJobEngine::Oracle, &target(), |query| {+ queries.push(query.source);+ let (columns, rows) = if query.source.ends_with("_OBJECTS") {+ (json!(["DBX_JOB_ID", "DBX_CREATED_AT"]), json!([["42", "creation"]]))+ } else if query.source.ends_with("_RUN_DETAILS") {+ (json!(["LOG_ID", "STATUS"]), json!([["99", "FAILED"]]))+ } else {+ (json!(["LOG_ID"]), json!([]))+ };+ std::future::ready(Ok(json!({"columns":columns,"rows":rows,"affected_rows":0,"execution_time_ms":0})))+ })+ .await+ .unwrap();+ assert!(observed.consistent);+ assert_eq!(queries.len(), 4);+ assert!(queries[0].ends_with("_OBJECTS") && queries[3].ends_with("_OBJECTS"));+ assert!(queries[1].ends_with("_RUNNING_JOBS"));+ assert!(queries[2].ends_with("_RUN_DETAILS"));+ assert_eq!(rows(&observed.history).unwrap()[0]["STATUS"], "FAILED");+ }+}diff --git a/crates/dbx-core/src/schema/native_jobs/operations/scheduler.rs b/crates/dbx-core/src/schema/native_jobs/operations/scheduler.rsnew file mode 100644index 0000000000..a160247fb9--- /dev/null+++ b/crates/dbx-core/src/schema/native_jobs/operations/scheduler.rs@@ -0,0 +1,359 @@+use super::*;++pub(super) mod transition;++pub(super) fn validate_namespace(+ binding: &super::super::service::BoundContext,+ definition: &NativeJobSchedulerCreate,+) -> Result<(), &'static str> {+ if binding.context.engine == NativeJobEngine::OceanbaseOracle {+ // BP7 treats a qualified CREATE_JOB argument as a literal name, not another owner's job.+ if definition.owner != binding.context.session_user {+ return Err("native_job_create_owner_mapping_unverified");+ }+ for reference in [&definition.program, &definition.schedule].into_iter().flatten() {+ if reference.owner != binding.context.session_user {+ return Err("native_job_reference_owner_mapping_unverified");+ }+ }+ }+ Ok(())+}++pub(super) fn require_absent(details: &NativeJobDetails, user: &str) -> Result<(), &'static str> {+ if !matches!(details.snapshot.definition, NativeJobMetadata::Empty)+ || !matches!(details.native_identity, NativeJobMetadata::Empty)+ {+ return Err("native_job_creation_target_not_absent");+ }+ let own = matches!(&details.snapshot.job_ref, NativeJobRef::Scheduler { owner, .. } if owner == user);+ if !details.sources.get("definition").is_some_and(|source| {+ source.coverage == Some(NativeJobCatalogCoverage::Database)+ || (own+ && matches!(+ source.coverage,+ Some(NativeJobCatalogCoverage::CurrentUser | NativeJobCatalogCoverage::Accessible)+ ))+ }) {+ return Err("native_job_creation_visibility_unverified");+ }+ Ok(())+}++fn nullable_text(actual: Option<&Value>, expected: &str) -> bool {+ actual.and_then(Value::as_str) == Some(expected) || (expected.is_empty() && actual == Some(&Value::Null))+}++pub(super) fn same_timestamp(actual: Option<&Value>, expected: &str) -> bool {+ let Some(actual) = actual.and_then(Value::as_str) else { return false };+ let parse = |value: &str| {+ let normalized = value.trim().replacen(' ', "T", 1).replace(" +", "+").replace(" -", "-");+ let offset = regex::Regex::new(r"([+-])(\d):(\d{2})$").unwrap();+ let normalized = offset.replace(&normalized, "${1}0${2}:${3}");+ chrono::DateTime::parse_from_rfc3339(&normalized).ok()+ };+ match (parse(actual), parse(expected)) {+ (Some(actual), Some(expected)) => actual == expected,+ _ => false,+ }+}++fn reference_matches(row: &NativeJobRow, prefix: &str, reference: &NativeJobObjectReference) -> bool {+ row.get(&format!("{prefix}_OWNER")).and_then(Value::as_str) == Some(reference.owner.as_str())+ && row.get(&format!("{prefix}_NAME")).and_then(Value::as_str) == Some(reference.name.as_str())+}++fn verify_initial(details: &NativeJobDetails, target: &NativeJobRef, definition: &NativeJobSchedulerCreate) -> bool {+ if &details.snapshot.job_ref != target+ || !matches!(details.consistency, NativeJobMetadata::Available { .. })+ || !matches!(details.native_identity, NativeJobMetadata::Available { .. })+ {+ return false;+ }+ let Some(row) = row(details) else { return false };+ if super::super::details::boolean(row.get("ENABLED")) != Some(false)+ || super::super::details::boolean(row.get("AUTO_DROP")) != Some(definition.auto_drop)+ {+ return false;+ }+ if let Some(program) = &definition.program {+ if !reference_matches(row, "PROGRAM", program) {+ return false;+ }+ } else if row+ .get("JOB_TYPE")+ .and_then(Value::as_str)+ .zip(definition.job_type.as_deref())+ .is_none_or(|(actual, expected)| !actual.eq_ignore_ascii_case(expected))+ || !definition.job_action.as_deref().is_some_and(|expected| nullable_text(row.get("JOB_ACTION"), expected))+ || super::super::details::integer(row.get("NUMBER_OF_ARGUMENTS")) != Some(definition.number_of_arguments as i64)+ {+ return false;+ }+ if let Some(schedule) = &definition.schedule {+ if !reference_matches(row, "SCHEDULE", schedule) {+ return false;+ }+ } else {+ if definition.start_date.as_deref().is_some_and(|expected| !same_timestamp(row.get("START_DATE"), expected))+ || definition.end_date.as_deref().is_some_and(|expected| !same_timestamp(row.get("END_DATE"), expected))+ || definition+ .repeat_interval+ .as_deref()+ .is_some_and(|expected| !nullable_text(row.get("REPEAT_INTERVAL"), expected))+ || definition+ .event_condition+ .as_deref()+ .is_some_and(|expected| !nullable_text(row.get("EVENT_CONDITION"), expected))+ {+ return false;+ }+ match &definition.event_source {+ Some(NativeJobEventSource::Queue { owner, name, agent }) => {+ if row.get("EVENT_QUEUE_OWNER").and_then(Value::as_str) != Some(owner.as_str())+ || row.get("EVENT_QUEUE_NAME").and_then(Value::as_str) != Some(name.as_str())+ || agent.as_deref().is_some_and(|agent| !nullable_text(row.get("EVENT_QUEUE_AGENT"), agent))+ {+ return false;+ }+ }+ Some(NativeJobEventSource::FileWatcher { reference })+ if !reference_matches(row, "FILE_WATCHER", reference) =>+ {+ return false;+ }+ _ => {}+ }+ }+ for (key, expected) in [+ ("COMMENTS", &definition.comments),+ ("JOB_CLASS", &definition.job_class),+ ("JOB_STYLE", &definition.job_style),+ ("CREDENTIAL_NAME", &definition.credential_name),+ ("DESTINATION", &definition.destination_name),+ ] {+ if expected.as_deref().is_some_and(|expected| !nullable_text(row.get(key), expected)) {+ return false;+ }+ }+ true+}++pub(super) fn mark(operations: &NativeJobOperations, id: &str, index: usize, receipt: &NativeJobStepReceipt) {+ operations.edit(id, |status| {+ status.steps[index].state = match receipt.outcome {+ NativeJobDispatchOutcome::NotStarted => NativeJobStepState::Failed,+ NativeJobDispatchOutcome::Applied => NativeJobStepState::Applied,+ NativeJobDispatchOutcome::Unknown => NativeJobStepState::Unknown,+ };+ status.steps[index].reason = receipt.reason.clone();+ status.steps[index].vendor_code = receipt.vendor_code;+ });+}++async fn run_validations(+ state: &AppState,+ execution: &PreparedExecution,+ id: &str,+ cancel: &CancellationToken,+ session: &mut impl NativeJobMutationSession,+ steps: &[NativeJobSqlStep],+) -> Result<usize, (&'static str, NativeJobOperationOutcome)> {+ let operations = state.native_jobs.operations();+ let mut count = 0;+ for (index, step) in+ steps.iter().enumerate().take_while(|(_, step)| matches!(step.effect, NativeJobStepEffect::ArgumentValidated))+ {+ require_write(state, &execution.binding)+ .await+ .map_err(|reason| (reason, NativeJobOperationOutcome::NotApplied))?;+ if cancel.is_cancelled() {+ return Err(("native_job_canceled_before_dispatch", NativeJobOperationOutcome::NotApplied));+ }+ operations.edit(id, |status| {+ status.state = NativeJobOperationState::Running;+ status.steps[index].state = NativeJobStepState::Dispatching;+ });+ let receipt = session.execute(step).await;+ mark(operations, id, index, &receipt);+ if receipt.outcome != NativeJobDispatchOutcome::Applied {+ return Err(("native_job_argument_validation_failed", NativeJobOperationOutcome::NotApplied));+ }+ count += 1;+ }+ Ok(count)+}++pub(super) async fn run_create(+ state: &AppState,+ execution: &PreparedExecution,+ id: &str,+ cancel: &CancellationToken,+ session: &mut impl NativeJobMutationSession,+ dispatched: &mut bool,+) -> Result<NativeJobOperationOutcome, (&'static str, NativeJobOperationOutcome)> {+ let PreparedAction::SchedulerCreate { definition, plan } = &execution.action else { unreachable!() };+ let projection = (execution.binding.context.engine == NativeJobEngine::Oracle)+ .then(|| transition::projection::OracleSchedulerProjection::for_create(definition))+ .flatten();+ let operations = state.native_jobs.operations();+ let existing =+ session.read(&plan.target).await.map_err(|reason| (reason, NativeJobOperationOutcome::NotApplied))?;+ require_absent(&existing, &execution.binding.context.session_user)+ .map_err(|reason| (reason, NativeJobOperationOutcome::NotApplied))?;+ let create_index = run_validations(state, execution, id, cancel, session, &plan.steps).await?;+ if create_index != 0 {+ let existing =+ session.read(&plan.target).await.map_err(|reason| (reason, NativeJobOperationOutcome::NotApplied))?;+ require_absent(&existing, &execution.binding.context.session_user)+ .map_err(|reason| (reason, NativeJobOperationOutcome::NotApplied))?;+ }+ require_write(state, &execution.binding).await.map_err(|reason| (reason, NativeJobOperationOutcome::NotApplied))?;+ if cancel.is_cancelled() {+ return Err(("native_job_canceled_before_dispatch", NativeJobOperationOutcome::NotApplied));+ }+ operations.edit(id, |status| {+ status.state = NativeJobOperationState::Running;+ status.steps[create_index].state = NativeJobStepState::Dispatching;+ });+ *dispatched = true;+ let receipt = session.execute(&plan.steps[create_index]).await;+ mark(operations, id, create_index, &receipt);+ if receipt.outcome == NativeJobDispatchOutcome::NotStarted {+ return Err(("native_job_step_not_applied", NativeJobOperationOutcome::NotApplied));+ }+ let created = session.read(&plan.target).await;+ if let Ok(created) = &created {+ if let NativeJobMetadata::Available { value } = &created.native_identity {+ operations.edit(id, |status| status.observed_identity = Some(value.clone()));+ }+ }+ // A same-name object appearing after a lost CREATE receipt is not proof that this call created+ // it. Keep it available for inspection, but do not configure, enable, remove or create again.+ if receipt.outcome == NativeJobDispatchOutcome::Unknown {+ return Err(("native_job_creation_outcome_unknown", NativeJobOperationOutcome::Unknown));+ }+ let mut before = created.map_err(|reason| (reason, NativeJobOperationOutcome::Partial))?;+ if !verify_initial(&before, &plan.target, definition) {+ return Err(("native_job_created_definition_unverified", NativeJobOperationOutcome::Partial));+ }+ if let Some(projection) = &projection {+ if !projection+ .preserved(&before, &before, true)+ .map_err(|reason| (reason, NativeJobOperationOutcome::Partial))?+ {+ return Err(("native_job_created_definition_unverified", NativeJobOperationOutcome::Partial));+ }+ }+ let NativeJobMetadata::Available { value: identity } = &before.native_identity else { unreachable!() };+ let resolved = native_job_scheduler_create_plan(+ execution.binding.context.engine,+ &execution.binding.context.scope,+ definition,+ Some(identity),+ )+ .map_err(|reason| (reason, NativeJobOperationOutcome::Partial))?;+ for (index, step) in resolved.steps.iter().enumerate().skip(create_index + 1) {+ let stopped = if cancel.is_cancelled() {+ Some("native_job_canceled_after_dispatch")+ } else {+ require_write(state, &execution.binding).await.err()+ };+ if let Some(reason) = stopped {+ return Err((reason, NativeJobOperationOutcome::Partial));+ }+ let current =+ session.read(&plan.target).await.map_err(|reason| (reason, NativeJobOperationOutcome::Partial))?;+ let definition_preserved = if let Some(projection) = &projection {+ projection+ .preserved(&before, ¤t, true)+ .map_err(|reason| (reason, NativeJobOperationOutcome::Partial))?+ } else {+ preserved_definition(&before, ¤t, &NativeJobStepEffect::Completed, execution.binding.context.engine)+ };+ let storage_preserved = if execution.binding.context.engine == NativeJobEngine::Oracle {+ match (+ super::super::details::parse_argument_inventory(&before.parameter_metadata),+ super::super::details::parse_argument_inventory(¤t.parameter_metadata),+ ) {+ (NativeJobMetadata::Available { value: before }, NativeJobMetadata::Available { value: current }) => {+ transition::same_inventory(NativeJobEngine::Oracle, &before, ¤t)+ }+ _ => true,+ }+ } else {+ true+ };+ if !matches!(current.consistency, NativeJobMetadata::Available { .. })+ || current.native_identity != before.native_identity+ || !definition_preserved+ || current.snapshot.arguments != before.snapshot.arguments+ || !storage_preserved+ {+ return Err(("native_job_created_target_changed", NativeJobOperationOutcome::Partial));+ }+ before = current;+ // A cancellation or write-lock change may arrive while the preflight read is in flight.+ require_write(state, &execution.binding)+ .await+ .map_err(|reason| (reason, NativeJobOperationOutcome::Partial))?;+ if cancel.is_cancelled() {+ return Err(("native_job_canceled_after_dispatch", NativeJobOperationOutcome::Partial));+ }+ operations.edit(id, |status| status.steps[index].state = NativeJobStepState::Dispatching);+ let receipt = session.execute(step).await;+ mark(operations, id, index, &receipt);+ if receipt.outcome == NativeJobDispatchOutcome::NotStarted {+ return Err(("native_job_step_not_applied", NativeJobOperationOutcome::Partial));+ }+ let unknown = receipt.outcome == NativeJobDispatchOutcome::Unknown;+ let after = session.read(&plan.target).await.map_err(|reason| {+ (reason, if unknown { NativeJobOperationOutcome::Unknown } else { NativeJobOperationOutcome::Partial })+ })?;+ let failed_read = if unknown { NativeJobOperationOutcome::Unknown } else { NativeJobOperationOutcome::Partial };+ let verified = if let Some(projection) = &projection {+ projection+ .verify(&before, &after, &step.effect, true, &execution.binding.context.session_user)+ .map_err(|reason| (reason, failed_read))?+ } else {+ verify_effect(+ &before,+ &after,+ &step.effect,+ &execution.binding.context.session_user,+ execution.binding.context.engine,+ )+ };+ if !verified {+ return Err(("native_job_readback_not_verified", failed_read));+ }+ operations.edit(id, |status| status.steps[index].state = NativeJobStepState::Applied);+ before = after;+ }+ Ok(NativeJobOperationOutcome::Verified)+}++#[cfg(test)]+mod tests {+ use super::same_timestamp;+ use serde_json::json;++ #[test]+ fn native_short_offsets_preserve_instant_and_nanoseconds() {+ for (actual, expected) in [+ ("2026-10-22 00:54:25.656000001 +8:00", "2026-10-21T16:54:25.656000001Z"),+ ("2026-10-21 22:24:25.656 +5:30", "2026-10-21T16:54:25.656Z"),+ ("2026-10-21 13:24:25.656 -3:30", "2026-10-21T16:54:25.656Z"),+ ] {+ assert!(same_timestamp(Some(&json!(actual)), expected));+ }+ for actual in [+ "2026-10-21 16:54:25.656 +8:00",+ "2026-10-22 00:54:25.656000001 +8:00",+ "2026-10-22 00:54:25.656 +8:60",+ "2026-10-22 00:54:25.656",+ ] {+ assert!(!same_timestamp(Some(&json!(actual)), "2026-10-21T16:54:25.656Z"), "{actual}");+ }+ }+}diff --git a/crates/dbx-core/src/schema/native_jobs/operations/scheduler/transition.rs b/crates/dbx-core/src/schema/native_jobs/operations/scheduler/transition.rsnew file mode 100644index 0000000000..ac3c247cc7--- /dev/null+++ b/crates/dbx-core/src/schema/native_jobs/operations/scheduler/transition.rs@@ -0,0 +1,773 @@+use super::*;+use crate::schema::native_jobs::details::{+ inventory_value, parse_argument_inventory, parse_argument_layout, SchedulerArgumentInventory,+};+use dbx_sql::native_job_changes::{+ scheduler_argument_step, NativeJobSchedulerDefinitionEffect, NativeJobSchedulerEditPlan,+ NativeJobSchedulerReferenceBinding,+};++mod dameng;+pub(super) mod projection;++struct BoundReference {+ request: NativeJobReferenceListRequest,+ rows: Vec<NativeJobRow>,+}++pub(in crate::schema::native_jobs::operations) struct PreparedSchedulerTransition {+ pub edit: NativeJobSchedulerEditPlan,+ dependencies: Vec<BoundReference>,+ original: NativeJobDetails,+ inventory: Option<SchedulerArgumentInventory>,+ layout: Option<Vec<NativeJobArgument>>,+ retired: HashSet<usize>,+ oracle: Option<projection::OracleSchedulerProjection>,+ dameng: Option<dameng::DamengNamedProjection>,+}++fn reference_request(+ scope: &NativeJobScope,+ binding: &NativeJobSchedulerReferenceBinding,+) -> NativeJobReferenceListRequest {+ NativeJobReferenceListRequest {+ scope: scope.clone(),+ kind: binding.target.kind,+ schema: Some(binding.target.reference.owner.clone()),+ name: Some(binding.target.reference.name.clone()),+ filter: String::new(),+ offset: 0,+ limit: 1,+ }+}++fn checked_rows(+ request: &NativeJobReferenceListRequest,+ catalog: &NativeJobReferenceCatalog,+) -> Result<Vec<NativeJobRow>, &'static str> {+ let rows = match &catalog.objects {+ NativeJobMetadata::Available { value } => value.clone(),+ NativeJobMetadata::Empty+ if matches!(+ request.kind,+ NativeJobReferenceKind::ProgramArguments | NativeJobReferenceKind::DestinationGroupMembers+ ) =>+ {+ Vec::new()+ }+ NativeJobMetadata::Denied { .. } => return Err("native_job_reference_denied"),+ NativeJobMetadata::Unsupported { .. } => return Err("native_job_reference_unsupported"),+ NativeJobMetadata::Truncated { .. } => return Err("native_job_reference_truncated"),+ NativeJobMetadata::Empty => return Err("native_job_reference_missing"),+ NativeJobMetadata::Error { .. } => return Err("native_job_reference_read_failed"),+ _ => return Err("native_job_reference_unavailable"),+ };+ if !matches!(+ request.kind,+ NativeJobReferenceKind::ProgramArguments | NativeJobReferenceKind::DestinationGroupMembers+ ) && rows.len() != 1+ {+ return Err("native_job_reference_identity_unavailable");+ }+ let mut positions = HashSet::new();+ let mut members = HashSet::new();+ for row in &rows {+ if row.get("DBX_OWNER").and_then(Value::as_str) != request.schema.as_deref()+ || row.get("DBX_NAME").and_then(Value::as_str) != request.name.as_deref()+ {+ return Err("native_job_reference_identity_unavailable");+ }+ if request.kind == NativeJobReferenceKind::ProgramArguments {+ let position = crate::schema::native_jobs::details::integer(row.get("ARGUMENT_POSITION"))+ .filter(|position| *position > 0)+ .ok_or("native_job_arguments_invalid")?;+ if !positions.insert(position) {+ return Err("native_job_arguments_ambiguous");+ }+ } else if request.kind == NativeJobReferenceKind::DestinationGroupMembers {+ let member = row+ .get("MEMBER_NAME")+ .and_then(Value::as_str)+ .filter(|member| !member.is_empty() && !member.contains('\0'))+ .ok_or("native_job_reference_identity_unavailable")?;+ if !members.insert(member) {+ return Err("native_job_reference_identity_unavailable");+ }+ }+ }+ Ok(rows)+}++fn stable_rows(engine: NativeJobEngine, kind: NativeJobReferenceKind, rows: &[NativeJobRow]) -> Vec<NativeJobRow> {+ let mut rows = rows.to_vec();+ for row in &mut rows {+ if engine == NativeJobEngine::Oracle && kind == NativeJobReferenceKind::ProgramArguments {+ *row = dbx_sql::native_job_arguments::canonical_argument_row(row, true);+ }+ row.remove("DBX_ROW_NUM");+ if kind == NativeJobReferenceKind::Window {+ for field in ["ACTIVE", "NEXT_START_DATE", "LAST_START_DATE"] {+ row.remove(field);+ }+ }+ }+ if kind == NativeJobReferenceKind::DestinationGroupMembers {+ rows.sort_by(|left, right| {+ left.get("MEMBER_NAME").and_then(Value::as_str).cmp(&right.get("MEMBER_NAME").and_then(Value::as_str))+ });+ } else {+ rows.sort_by_key(|row| crate::schema::native_jobs::details::integer(row.get("ARGUMENT_POSITION")).unwrap_or(0));+ }+ rows+}++fn program_ref(row: &NativeJobRow) -> Option<NativeJobObjectReference> {+ Some(NativeJobObjectReference {+ owner: row.get("PROGRAM_OWNER")?.as_str()?.into(),+ name: row.get("PROGRAM_NAME")?.as_str()?.into(),+ })+}++fn cached_program(+ details: &NativeJobDetails,+ request: &NativeJobReferenceListRequest,+) -> Option<NativeJobReferenceCatalog> {+ let reference = row(details).and_then(program_ref)?;+ if request.schema.as_deref() != Some(&reference.owner) || request.name.as_deref() != Some(&reference.name) {+ return None;+ }+ let (objects, source) = if request.kind == NativeJobReferenceKind::Program {+ (crate::schema::native_jobs::details::map_metadata(details.program.clone()?, |row| vec![row]), "program")+ } else if request.kind == NativeJobReferenceKind::ProgramArguments {+ (details.program_arguments.clone()?, "programArguments")+ } else {+ return None;+ };+ Some(NativeJobReferenceCatalog {+ objects,+ source: details.sources.get(source)?.clone(),+ offset: 0,+ limit: request.limit,+ })+}++pub(in crate::schema::native_jobs::operations) async fn prepare<Q, F>(+ binding: &crate::schema::native_jobs::service::BoundContext,+ mutation: &NativeJobMutation,+ original: &NativeJobDetails,+ mut edit: NativeJobSchedulerEditPlan,+ read_reference: &mut Q,+) -> Result<PreparedSchedulerTransition, &'static str>+where+ Q: FnMut(NativeJobReferenceListRequest) -> F,+ F: Future<Output = Result<NativeJobReferenceCatalog, &'static str>>,+{+ let mut dependencies: Vec<BoundReference> = Vec::new();+ let mut program = None;+ let mut program_arguments = None;+ let mut requests = edit+ .references+ .iter()+ .map(|reference| reference_request(&binding.context.scope, reference))+ .collect::<Vec<_>>();+ let destination_group =+ edit.references.iter().any(|reference| reference.target.kind == NativeJobReferenceKind::DestinationGroup);+ for reference in+ edit.references.iter().filter(|reference| reference.target.kind == NativeJobReferenceKind::DestinationGroup)+ {+ let mut request = reference_request(&binding.context.scope, reference);+ request.kind = NativeJobReferenceKind::DestinationGroupMembers;+ request.limit = 10_000;+ requests.push(request);+ }+ if destination_group && edit.definition.get("JOB_TYPE").is_none_or(Value::is_null) {+ let reference = program_ref(&edit.definition).ok_or("native_job_reference_compatibility_unavailable")?;+ requests.push(NativeJobReferenceListRequest {+ scope: binding.context.scope.clone(),+ kind: NativeJobReferenceKind::Program,+ schema: Some(reference.owner),+ name: Some(reference.name),+ filter: String::new(),+ offset: 0,+ limit: 1,+ });+ }+ if edit.argument_target.is_some() && program_ref(&edit.definition).is_some() {+ let reference = program_ref(&edit.definition).unwrap();+ requests.push(NativeJobReferenceListRequest {+ scope: binding.context.scope.clone(),+ kind: NativeJobReferenceKind::ProgramArguments,+ schema: Some(reference.owner),+ name: Some(reference.name),+ filter: String::new(),+ offset: 0,+ limit: 10_000,+ });+ }+ for request in requests {+ if dependencies.iter().any(|bound| {+ bound.request.kind == request.kind+ && bound.request.schema == request.schema+ && bound.request.name == request.name+ }) {+ continue;+ }+ let catalog = if let Some(cached) = cached_program(original, &request) {+ cached+ } else {+ read_reference(request.clone()).await?+ };+ let rows = checked_rows(&request, &catalog)?;+ if request.kind == NativeJobReferenceKind::Program {+ program = Some(NativeJobMetadata::Available { value: rows[0].clone() });+ }+ if request.kind == NativeJobReferenceKind::ProgramArguments {+ program_arguments = Some(NativeJobMetadata::Available { value: rows.clone() });+ }+ dependencies.push(BoundReference { rows: stable_rows(binding.context.engine, request.kind, &rows), request });+ }+ let style = edit.definition.get("JOB_STYLE").and_then(Value::as_str);+ if destination_group && style.is_none() {+ return Err("native_job_reference_compatibility_unavailable");+ }+ let job_type = program+ .as_ref()+ .and_then(|program| match program {+ NativeJobMetadata::Available { value } => value.get("PROGRAM_TYPE").and_then(Value::as_str),+ _ => None,+ })+ .or_else(|| edit.definition.get("JOB_TYPE").and_then(Value::as_str));+ for reference in &edit.references {+ if reference.target.kind == NativeJobReferenceKind::DestinationGroup+ && (job_type == Some("CHAIN")+ || matches!(style, Some("LIGHTWEIGHT" | "IN_MEMORY_RUNTIME" | "IN_MEMORY_FULL")))+ {+ return Err("native_job_reference_not_applicable");+ }+ if reference.attribute == "JOB_ACTION" && !matches!(style, Some("REGULAR" | "IN_MEMORY_FULL")) {+ return Err("native_job_reference_not_applicable");+ }+ }+ let (inventory, layout, retired) = if let Some(target) = &edit.argument_target {+ let NativeJobMetadata::Available { value: inventory } = parse_argument_inventory(&original.parameter_metadata)+ else {+ return Err("native_job_arguments_unavailable");+ };+ let NativeJobMetadata::Available { value: layout } = parse_argument_layout(+ binding.context.engine,+ &NativeJobMetadata::Available { value: edit.definition.clone() },+ program.as_ref(),+ program_arguments.as_ref(),+ ) else {+ return Err("native_job_argument_target_unavailable");+ };+ if target.arguments.len() != layout.len() {+ return Err("native_job_argument_target_incomplete");+ }+ if target.program.is_some() {+ let Some(NativeJobMetadata::Available { value: program_arguments }) = &program_arguments else {+ return Err("native_job_argument_target_unavailable");+ };+ if program_arguments.len() != layout.len() {+ return Err("native_job_argument_target_unavailable");+ }+ }+ let mut resolved = target.clone();+ for argument in &mut resolved.arguments {+ let description = layout+ .iter()+ .find(|description| description.position == argument.position)+ .ok_or("native_job_argument_target_incomplete")?;+ if !description.editable+ && !matches!(argument.value, NativeJobArgumentValue::Unset | NativeJobArgumentValue::Inherit)+ {+ return Err("native_job_argument_not_editable");+ }+ if target.program.is_some() {+ argument.data_type = description.data_type.clone();+ }+ }+ // Recompile using the bound target types, never a stale caller-supplied Program type.+ let mut resolved_mutation = mutation.clone();+ let NativeJobChange::Update { argument_target, .. } = &mut resolved_mutation.change else { unreachable!() };+ *argument_target = Some(resolved);+ edit = native_job_scheduler_edit_plan(binding.context.engine, &resolved_mutation, original)?;+ let retired: HashSet<_> = inventory+ .keys()+ .copied()+ .filter(|position| {+ *position > layout.len()+ || layout+ .iter()+ .find(|argument| argument.position == *position)+ .is_some_and(|argument| !argument.editable)+ })+ .collect();+ if !retired.is_empty() {+ let NativeJobMetadata::Available { value: old_layout } = parse_argument_layout(+ binding.context.engine,+ &original.snapshot.definition,+ original.program.as_ref(),+ original.program_arguments.as_ref(),+ ) else {+ return Err("native_job_argument_retirement_context_unavailable");+ };+ if retired+ .iter()+ .any(|position| !old_layout.iter().any(|argument| argument.position == *position && argument.editable))+ {+ return Err("native_job_argument_retirement_requires_original_context");+ }+ let NativeJobMetadata::Available { value: identity } = &original.native_identity else {+ return Err("native_job_identity_unverified");+ };+ let mut retiring = Vec::new();+ for position in retired.iter().copied().collect::<std::collections::BTreeSet<_>>() {+ let mut step = scheduler_argument_step(+ binding.context.engine,+ &mutation.target,+ Some(identity),+ &NativeJobArgumentChange { position, value: NativeJobArgumentValue::Unset },+ "UNKNOWN",+ )?;+ step.id = format!("retire-argument:{position}");+ step.label = "native_job_step_retire_argument".into();+ retiring.push(step);+ }+ let after_pause =+ edit.sql.steps.iter().position(|step| step.id == "pause").ok_or("native_job_transition_not_paused")?+ + 1;+ edit.sql.steps.splice(after_pause..after_pause, retiring);+ }+ (Some(inventory), Some(layout), retired)+ } else {+ (None, None, HashSet::new())+ };+ let oracle = if binding.context.engine == NativeJobEngine::Oracle {+ Some(projection::OracleSchedulerProjection::bind(&edit, original, &dependencies)?)+ } else {+ None+ };+ let dameng = if binding.context.engine == NativeJobEngine::Dameng {+ Some(dameng::DamengNamedProjection::bind(&edit, original, &dependencies)?)+ } else {+ None+ };+ Ok(PreparedSchedulerTransition {+ edit,+ dependencies,+ original: original.clone(),+ inventory,+ layout,+ retired,+ oracle,+ dameng,+ })+}++pub(in crate::schema::native_jobs::operations) fn reference_projections_match(+ row: &NativeJobRow,+ references: &[NativeJobSchedulerReferenceBinding],+) -> bool {+ references.iter().all(|binding| {+ if binding.attribute == "JOB_ACTION" {+ let owner = row.get("OWNER").and_then(Value::as_str).unwrap_or("");+ return dbx_sql::native_job_changes::native_job_scheduler_reference_target(+ "JOB_ACTION",+ row.get("JOB_ACTION").unwrap_or(&Value::Null),+ owner,+ "CHAIN",+ )+ .ok()+ .flatten()+ .is_some_and(|target| target == binding.target);+ }+ // Other references are checked as exact, separate owner/name columns by the effect.+ true+ })+}++fn inventory(details: &NativeJobDetails) -> Result<SchedulerArgumentInventory, &'static str> {+ match parse_argument_inventory(&details.parameter_metadata) {+ NativeJobMetadata::Available { value } => Ok(value),+ _ => Err("native_job_arguments_unavailable"),+ }+}++fn same_override(engine: NativeJobEngine, a: &NativeJobRow, b: &NativeJobRow) -> bool {+ if engine == NativeJobEngine::Oracle {+ return dbx_sql::native_job_arguments::decode_argument(a, false)+ == dbx_sql::native_job_arguments::decode_argument(b, false);+ }+ inventory_value(engine, a) == inventory_value(engine, b)+}++pub(in crate::schema::native_jobs::operations) fn same_inventory(+ engine: NativeJobEngine,+ a: &SchedulerArgumentInventory,+ b: &SchedulerArgumentInventory,+) -> bool {+ a.len() == b.len()+ && a.iter().all(|(position, row)| b.get(position).is_some_and(|other| same_override(engine, row, other)))+}++fn desired_value_matches(+ engine: NativeJobEngine,+ actual: Option<&NativeJobRow>,+ desired: &NativeJobArgumentValue,+ data_type: &str,+) -> bool {+ match desired {+ NativeJobArgumentValue::Inherit | NativeJobArgumentValue::Unset => actual.is_none(),+ _ if engine == NativeJobEngine::Oracle => {+ actual.is_some_and(|row| dbx_sql::native_job_arguments::oracle_argument_matches(row, desired, data_type))+ }+ _ => actual.is_some_and(|row| inventory_value(engine, row) == *desired),+ }+}++fn allowed_inventory(+ engine: NativeJobEngine,+ plan: &PreparedSchedulerTransition,+ current: &SchedulerArgumentInventory,+) -> bool {+ let Some(original) = &plan.inventory else { return true };+ let Some(target) = &plan.edit.argument_target else { return false };+ current.iter().all(|(position, row)| {+ original.get(position).is_some_and(|old| same_override(engine, row, old))+ || target+ .arguments+ .iter()+ .find(|argument| argument.position == *position)+ .is_some_and(|argument| desired_value_matches(engine, Some(row), &argument.value, &argument.data_type))+ })+}++fn complete_arguments(+ engine: NativeJobEngine,+ plan: &PreparedSchedulerTransition,+ current: &SchedulerArgumentInventory,+) -> bool {+ let Some(target) = &plan.edit.argument_target else { return true };+ let Some(layout) = &plan.layout else { return false };+ current.keys().all(|position| *position <= layout.len())+ && target.arguments.iter().all(|argument| {+ desired_value_matches(engine, current.get(&argument.position), &argument.value, &argument.data_type)+ })+}++fn argument_type(plan: &PreparedSchedulerTransition, position: usize) -> &str {+ plan.edit+ .argument_target+ .as_ref()+ .and_then(|target| {+ target+ .arguments+ .iter()+ .find(|argument| argument.position == position)+ .map(|argument| argument.data_type.as_str())+ })+ .or_else(|| match &plan.original.snapshot.arguments {+ NativeJobMetadata::Available { value } => {+ value.iter().find(|argument| argument.position == position).map(|argument| argument.data_type.as_str())+ }+ _ => None,+ })+ .unwrap_or("UNKNOWN")+}++async fn check_dependencies(+ engine: NativeJobEngine,+ plan: &PreparedSchedulerTransition,+ session: &mut impl NativeJobMutationSession,+) -> Result<(), &'static str> {+ for bound in &plan.dependencies {+ let current = session.read_reference(bound.request.clone()).await?;+ let rows = checked_rows(&bound.request, ¤t)?;+ if stable_rows(engine, bound.request.kind, &rows) != bound.rows {+ return Err("native_job_reference_changed");+ }+ }+ Ok(())+}++fn target_definition_matches(+ plan: &PreparedSchedulerTransition,+ current: &NativeJobDetails,+ user: &str,+ engine: NativeJobEngine,+ dameng_active: &HashSet<String>,+) -> Result<bool, &'static str> {+ let mut columns = Vec::new();+ for step in &plan.edit.sql.steps {+ if let NativeJobStepEffect::SchedulerDefinition(effect) = &step.effect {+ for column in &effect.columns {+ columns.retain(|previous: &NativeJobAttributeChange| previous.name != column.name);+ columns.push(column.clone());+ }+ }+ }+ columns.push(NativeJobAttributeChange {+ name: "ENABLED".into(),+ change: NativeJobFieldChange::Set { value: Value::Bool(false) },+ });+ let effect = NativeJobStepEffect::SchedulerDefinition(NativeJobSchedulerDefinitionEffect {+ columns,+ references: plan.edit.references.clone(),+ });+ if let Some(projection) = &plan.oracle {+ projection.verify(&plan.original, current, &effect, true, user)+ } else if let Some(projection) = &plan.dameng {+ Ok(projection.complete(dameng_active)+ && projection.verify(&plan.original, current, &effect, dameng_active, user))+ } else {+ Ok(verify_effect(&plan.original, current, &effect, user, engine))+ }+}++fn mark_skipped(operations: &NativeJobOperations, id: &str, index: usize) {+ operations.edit(id, |status| {+ status.steps[index].state = NativeJobStepState::Skipped;+ status.steps[index].reason = Some("native_job_already_satisfied".into());+ });+}++pub(in crate::schema::native_jobs::operations) async fn run(+ state: &AppState,+ execution: &PreparedExecution,+ id: &str,+ cancel: &CancellationToken,+ session: &mut impl NativeJobMutationSession,+ dispatched: &mut bool,+) -> Result<NativeJobOperationOutcome, (&'static str, NativeJobOperationOutcome)> {+ let PreparedAction::SchedulerTransition { mutation, plan } = &execution.action else { unreachable!() };+ let operations = state.native_jobs.operations();+ let engine = execution.binding.context.engine;+ let user = &execution.binding.context.session_user;+ let mut before =+ session.read(&mutation.target).await.map_err(|reason| (reason, NativeJobOperationOutcome::NotApplied))?;+ if let Some(projection) = &plan.oracle {+ projection.validate(&before).map_err(|reason| (reason, NativeJobOperationOutcome::NotApplied))?;+ }+ state+ .native_jobs+ .compare_baseline(+ state,+ &mutation.target,+ &mutation.baseline,+ &before.snapshot.revision,+ &plan.edit.sql.required_partitions.iter().map(String::as_str).collect::<Vec<_>>(),+ false,+ )+ .map_err(|reason| (reason, NativeJobOperationOutcome::NotApplied))?;+ check_dependencies(engine, plan, session)+ .await+ .map_err(|reason| (reason, NativeJobOperationOutcome::NotApplied))?;+ let mut observed = if plan.inventory.is_some() {+ Some(inventory(&before).map_err(|reason| (reason, NativeJobOperationOutcome::NotApplied))?)+ } else {+ None+ };+ if let (Some(original), Some(current)) = (&plan.inventory, &observed) {+ if !same_inventory(engine, original, current) {+ return Err(("native_job_argument_inventory_changed", NativeJobOperationOutcome::NotApplied));+ }+ }+ operations.edit(id, |status| status.state = NativeJobOperationState::Running);+ let validated = super::run_validations(state, execution, id, cancel, session, &plan.edit.sql.steps).await?;+ if validated != 0 {+ before =+ session.read(&mutation.target).await.map_err(|reason| (reason, NativeJobOperationOutcome::NotApplied))?;+ if let Some(projection) = &plan.oracle {+ projection.validate(&before).map_err(|reason| (reason, NativeJobOperationOutcome::NotApplied))?;+ }+ state+ .native_jobs+ .compare_baseline(+ state,+ &mutation.target,+ &mutation.baseline,+ &before.snapshot.revision,+ &plan.edit.sql.required_partitions.iter().map(String::as_str).collect::<Vec<_>>(),+ false,+ )+ .map_err(|reason| (reason, NativeJobOperationOutcome::NotApplied))?;+ check_dependencies(engine, plan, session)+ .await+ .map_err(|reason| (reason, NativeJobOperationOutcome::NotApplied))?;+ if plan.inventory.is_some() {+ let current = inventory(&before).map_err(|reason| (reason, NativeJobOperationOutcome::NotApplied))?;+ if observed.as_ref().is_some_and(|previous| !same_inventory(engine, previous, ¤t)) {+ return Err(("native_job_argument_inventory_changed", NativeJobOperationOutcome::NotApplied));+ }+ observed = Some(current);+ }+ }+ let mut event_applied = !plan.edit.event_changed;+ let mut dameng_active = HashSet::new();+ for (index, step) in plan.edit.sql.steps.iter().enumerate().skip(validated) {+ let failure =+ if *dispatched { NativeJobOperationOutcome::Partial } else { NativeJobOperationOutcome::NotApplied };+ require_write(state, &execution.binding).await.map_err(|reason| (reason, failure))?;+ if cancel.is_cancelled() {+ return Err(("native_job_canceled_after_dispatch", failure));+ }+ if step.id == "enable"+ && (!target_definition_matches(plan, &before, user, engine, &dameng_active)+ .map_err(|reason| (reason, failure))?+ || observed.as_ref().is_some_and(|current| !complete_arguments(engine, plan, current)))+ {+ return Err(("native_job_transition_incomplete", failure));+ }+ if step.id == "enable" || matches!(step.effect, NativeJobStepEffect::SchedulerDefinition(_)) {+ check_dependencies(engine, plan, session).await.map_err(|reason| (reason, failure))?;+ require_write(state, &execution.binding).await.map_err(|reason| (reason, failure))?;+ if cancel.is_cancelled() {+ return Err(("native_job_canceled_after_dispatch", failure));+ }+ }+ if step.id == "pause" {+ match row(&before).and_then(|row| crate::schema::native_jobs::details::boolean(row.get("ENABLED"))) {+ Some(false) => {+ mark_skipped(operations, id, index);+ continue;+ }+ Some(true) => {}+ _ => return Err(("native_job_enabled_state_unavailable", failure)),+ }+ } else if row(&before).and_then(|row| crate::schema::native_jobs::details::boolean(row.get("ENABLED")))+ != Some(false)+ {+ return Err(("native_job_transition_not_paused", failure));+ }+ if let (NativeJobStepEffect::Argument(change, _), Some(current)) = (&step.effect, &observed) {+ let desired =+ if step.id.starts_with("retire-argument:") { &NativeJobArgumentValue::Unset } else { &change.value };+ if desired_value_matches(+ engine,+ current.get(&change.position),+ desired,+ argument_type(plan, change.position),+ ) {+ mark_skipped(operations, id, index);+ continue;+ }+ if current.get(&change.position).is_some_and(|actual| {+ !plan+ .inventory+ .as_ref()+ .and_then(|old| old.get(&change.position))+ .is_some_and(|old| same_override(engine, actual, old))+ }) {+ return Err(("native_job_argument_inventory_changed", failure));+ }+ }+ operations.edit(id, |status| status.steps[index].state = NativeJobStepState::Dispatching);+ *dispatched = true;+ let receipt = session.execute(step).await;+ super::mark(operations, id, index, &receipt);+ if receipt.outcome == NativeJobDispatchOutcome::NotStarted {+ return Err(("native_job_step_not_applied", failure));+ }+ let unknown = receipt.outcome == NativeJobDispatchOutcome::Unknown;+ let failed_read = if unknown { NativeJobOperationOutcome::Unknown } else { NativeJobOperationOutcome::Partial };+ let after = session.read(&mutation.target).await.map_err(|reason| (reason, failed_read))?;+ let next_inventory =+ if observed.is_some() { Some(inventory(&after).map_err(|reason| (reason, failed_read))?) } else { None };+ let next_dameng_active = if let Some(projection) = &plan.dameng {+ check_dependencies(engine, plan, session).await.map_err(|reason| (reason, failed_read))?;+ projection.advance(&dameng_active, &step.effect)+ } else {+ HashSet::new()+ };+ let next_event_applied = event_applied+ || matches!(&step.effect, NativeJobStepEffect::SchedulerDefinition(effect) if effect.columns.iter().any(|column| matches!(column.name.as_str(), "SCHEDULE_NAME" | "SCHEDULE_TYPE" | "EVENT_CONDITION")));+ let verified = match (&step.effect, &observed, &next_inventory) {+ (NativeJobStepEffect::Argument(change, _), Some(old), Some(current)) => {+ let desired = if step.id.starts_with("retire-argument:") {+ &NativeJobArgumentValue::Unset+ } else {+ &change.value+ };+ desired_value_matches(+ engine,+ current.get(&change.position),+ desired,+ argument_type(plan, change.position),+ ) && old.iter().all(|(position, value)| {+ *position == change.position+ || current.get(position).is_some_and(|other| same_override(engine, value, other))+ }) && current.keys().all(|position| *position == change.position || old.contains_key(position))+ && after.native_identity == before.native_identity+ && matches!(after.consistency, NativeJobMetadata::Available { .. })+ && if let Some(projection) = &plan.oracle {+ projection.preserved(&before, &after, event_applied).map_err(|reason| (reason, failed_read))?+ } else if let Some(projection) = &plan.dameng {+ projection.preserved(&before, &after, &next_dameng_active)+ } else {+ preserved_definition(&before, &after, &NativeJobStepEffect::Completed, engine)+ }+ }+ _ => {+ if let Some(projection) = &plan.oracle {+ projection+ .verify(&before, &after, &step.effect, next_event_applied, user)+ .map_err(|reason| (reason, failed_read))?+ } else if let Some(projection) = &plan.dameng {+ projection.verify(&before, &after, &step.effect, &next_dameng_active, user)+ } else {+ verify_effect(&before, &after, &step.effect, user, engine)+ }+ }+ };+ if !verified || next_inventory.as_ref().is_some_and(|current| !allowed_inventory(engine, plan, current)) {+ return Err(("native_job_readback_not_verified", failed_read));+ }+ if engine == NativeJobEngine::Dameng+ && !dameng_active.contains("PROGRAM_NAME")+ && next_dameng_active.contains("PROGRAM_NAME")+ && next_inventory.as_ref().is_some_and(|current| {+ plan.edit.argument_target.as_ref().is_some_and(|target| {+ target.arguments.iter().any(|argument| {+ matches!(argument.value, NativeJobArgumentValue::Unset | NativeJobArgumentValue::Inherit)+ && current.contains_key(&argument.position)+ })+ })+ })+ {+ return Err(("native_job_argument_reset_mapping_unverified", failed_read));+ }+ if matches!(step.effect, NativeJobStepEffect::SchedulerDefinition(_)) {+ if next_inventory+ .as_ref()+ .is_some_and(|current| plan.retired.iter().any(|position| current.contains_key(position)))+ {+ return Err(("native_job_argument_inventory_changed", NativeJobOperationOutcome::Partial));+ }+ } else if !matches!(step.effect, NativeJobStepEffect::Argument(..)) {+ if let (Some(old), Some(current)) = (&observed, &next_inventory) {+ if !same_inventory(engine, old, current) {+ return Err(("native_job_argument_inventory_changed", failed_read));+ }+ }+ }+ operations.edit(id, |status| status.steps[index].state = NativeJobStepState::Applied);+ before = after;+ observed = next_inventory;+ event_applied = next_event_applied;+ dameng_active = next_dameng_active;+ }+ if !plan.edit.final_enabled+ && (!target_definition_matches(plan, &before, user, engine, &dameng_active)+ .map_err(|reason| (reason, NativeJobOperationOutcome::Partial))?+ || observed.as_ref().is_some_and(|current| !complete_arguments(engine, plan, current)))+ {+ return Err(("native_job_transition_incomplete", NativeJobOperationOutcome::Partial));+ }+ if !plan.edit.final_enabled {+ check_dependencies(engine, plan, session)+ .await+ .map_err(|reason| (reason, NativeJobOperationOutcome::Partial))?;+ }+ Ok(NativeJobOperationOutcome::Verified)+}diff --git a/crates/dbx-core/src/schema/native_jobs/operations/scheduler/transition/dameng.rs b/crates/dbx-core/src/schema/native_jobs/operations/scheduler/transition/dameng.rsnew file mode 100644index 0000000000..bfdb0325f3--- /dev/null+++ b/crates/dbx-core/src/schema/native_jobs/operations/scheduler/transition/dameng.rs@@ -0,0 +1,134 @@+use super::*;++pub(super) struct DamengNamedProjection {+ slots: Vec<NativeJobSchedulerReferenceBinding>,+}++impl DamengNamedProjection {+ pub(super) fn bind(+ edit: &NativeJobSchedulerEditPlan,+ original: &NativeJobDetails,+ dependencies: &[BoundReference],+ ) -> Result<Self, &'static str> {+ let before = row(original).ok_or("native_job_definition_unavailable")?;+ let mut slots = Vec::new();+ for binding in &edit.references {+ let (owner, name, fields) = match binding.attribute.as_str() {+ "PROGRAM_NAME" => {+ ("PROGRAM_OWNER", "PROGRAM_NAME", &["PROGRAM_TYPE", "PROGRAM_ACTION", "NUMBER_OF_ARGUMENTS"][..])+ }+ "SCHEDULE_NAME" => (+ "SCHEDULE_OWNER",+ "SCHEDULE_NAME",+ &["SCHEDULE_TYPE", "START_DATE", "REPEAT_INTERVAL", "END_DATE"][..],+ ),+ _ => continue,+ };+ if before.get(owner).and_then(Value::as_str) == Some(&binding.target.reference.owner)+ && before.get(name).and_then(Value::as_str) == Some(&binding.target.reference.name)+ {+ continue;+ }+ if ![owner, name]+ .iter()+ .all(|key| before.get(*key).and_then(Value::as_str).is_some_and(|value| !value.is_empty()))+ {+ return Err("native_job_reference_attach_mapping_unverified");+ }+ let definition = dependencies+ .iter()+ .find(|bound| {+ bound.request.kind == binding.target.kind+ && bound.request.schema.as_deref() == Some(&binding.target.reference.owner)+ && bound.request.name.as_deref() == Some(&binding.target.reference.name)+ })+ .and_then(|bound| bound.rows.first())+ .ok_or("native_job_reference_unavailable")?;+ if fields.iter().any(|field| !definition.contains_key(*field)) {+ return Err("native_job_reference_definition_unavailable");+ }+ if binding.attribute == "PROGRAM_NAME" {+ if definition.get("PROGRAM_TYPE").and_then(Value::as_str).is_none()+ || definition.get("PROGRAM_ACTION").and_then(Value::as_str).is_none()+ || crate::schema::native_jobs::details::integer(definition.get("NUMBER_OF_ARGUMENTS"))+ .is_none_or(|count| count < 0)+ {+ return Err("native_job_reference_definition_unavailable");+ }+ } else if !matches!(definition.get("SCHEDULE_TYPE").and_then(Value::as_str), Some("ONCE" | "CALENDAR"))+ || ["START_DATE", "REPEAT_INTERVAL", "END_DATE"]+ .iter()+ .any(|field| definition.get(*field).is_none_or(|value| !value.is_null() && !value.is_string()))+ {+ return Err("native_job_reference_definition_unavailable");+ }+ slots.push(binding.clone());+ }+ Ok(Self { slots })+ }++ pub(super) fn advance(&self, active: &HashSet<String>, effect: &NativeJobStepEffect) -> HashSet<String> {+ let mut next = active.clone();+ if let NativeJobStepEffect::SchedulerDefinition(effect) = effect {+ for binding in &effect.references {+ if self.slots.iter().any(|slot| slot.attribute == binding.attribute && slot.target == binding.target) {+ next.insert(binding.attribute.clone());+ }+ }+ }+ next+ }++ fn columns(&self, active: &HashSet<String>, details: &NativeJobDetails) -> Option<Vec<&'static str>> {+ let row = row(details)?;+ let mut columns = Vec::new();+ for slot in self.slots.iter().filter(|slot| active.contains(&slot.attribute)) {+ let owner = if slot.attribute == "PROGRAM_NAME" { "PROGRAM_OWNER" } else { "SCHEDULE_OWNER" };+ if row.get(owner).and_then(Value::as_str) != Some(&slot.target.reference.owner)+ || row.get(&slot.attribute).and_then(Value::as_str) != Some(&slot.target.reference.name)+ {+ return None;+ }+ columns.extend(if slot.attribute == "PROGRAM_NAME" {+ &["JOB_TYPE", "JOB_ACTION", "NUMBER_OF_ARGUMENTS"][..]+ } else {+ &["SCHEDULE_TYPE", "START_DATE", "REPEAT_INTERVAL", "END_DATE"][..]+ });+ }+ Some(columns)+ }++ pub(super) fn complete(&self, active: &HashSet<String>) -> bool {+ self.slots.iter().all(|slot| active.contains(&slot.attribute))+ }++ pub(super) fn verify(+ &self,+ before: &NativeJobDetails,+ after: &NativeJobDetails,+ effect: &NativeJobStepEffect,+ active: &HashSet<String>,+ user: &str,+ ) -> bool {+ self.columns(active, after).is_some_and(|columns| {+ verify_effect_with_extra(before, after, effect, user, NativeJobEngine::Dameng, &columns)+ })+ }++ pub(super) fn preserved(+ &self,+ before: &NativeJobDetails,+ after: &NativeJobDetails,+ active: &HashSet<String>,+ ) -> bool {+ self.columns(active, after).is_some_and(|columns| {+ preserved_definition_with_extra(+ before,+ after,+ &NativeJobStepEffect::Completed,+ &columns,+ NativeJobEngine::Dameng,+ )+ })+ }+}diff --git a/crates/dbx-core/src/schema/native_jobs/operations/scheduler/transition/projection.rs b/crates/dbx-core/src/schema/native_jobs/operations/scheduler/transition/projection.rsnew file mode 100644index 0000000000..c744f13f82--- /dev/null+++ b/crates/dbx-core/src/schema/native_jobs/operations/scheduler/transition/projection.rs@@ -0,0 +1,203 @@+use super::*;+use crate::schema::native_jobs::details::file_watcher_reference_present as watcher;++const EVENT_COLUMNS: &[&str] = &[+ "EVENT_CONDITION",+ "EVENT_QUEUE_OWNER",+ "EVENT_QUEUE_NAME",+ "EVENT_QUEUE_AGENT",+ "FILE_WATCHER_OWNER",+ "FILE_WATCHER_NAME",+];+const QUEUE_COLUMNS: &[&str] = &["EVENT_QUEUE_OWNER", "EVENT_QUEUE_NAME", "EVENT_QUEUE_AGENT"];++#[derive(Clone)]+enum EventProjection {+ Preserve,+ None,+ Queue(NativeJobRow),+ Watcher(NativeJobRow),+ Named { fields: NativeJobRow, watcher: bool },+}++pub(in crate::schema::native_jobs::operations::scheduler) struct OracleSchedulerProjection {+ before: EventProjection,+ target: EventProjection,+}++fn event_fields(row: &NativeJobRow) -> Result<NativeJobRow, &'static str> {+ EVENT_COLUMNS+ .iter()+ .map(|name| {+ let value = row.get(*name).ok_or("native_job_event_projection_unavailable")?;+ if !value.is_null() && !value.is_string() {+ return Err("native_job_event_projection_invalid");+ }+ Ok(((*name).to_string(), value.clone()))+ })+ .collect()+}++fn observations(row: &NativeJobRow) -> Result<(), &'static str> {+ match row.get("NUMBER_OF_DESTINATIONS") {+ None => return Err("native_job_destination_observation_unavailable"),+ Some(Value::Null) => {}+ Some(value) if values::integral(value).is_some_and(|count| count >= 0) => {}+ _ => return Err("native_job_destination_observation_invalid"),+ }+ if row.get("EVENT_RULE").is_some_and(|value| !value.is_null() && !value.is_string()) {+ return Err("native_job_event_projection_invalid");+ }+ Ok(())+}++impl EventProjection {+ fn generated(&self) -> &[&str] {+ match self {+ Self::Watcher(_) => QUEUE_COLUMNS,+ Self::Named { .. } => EVENT_COLUMNS,+ _ => &[],+ }+ }++ fn matches(&self, row: &NativeJobRow) -> Result<bool, &'static str> {+ if matches!(self, Self::Preserve) {+ return Ok(true);+ }+ let actual = event_fields(row)?;+ Ok(match self {+ Self::None => actual.values().all(Value::is_null),+ Self::Queue(expected) => actual == *expected,+ Self::Watcher(expected) => EVENT_COLUMNS+ .iter()+ .filter(|name| !QUEUE_COLUMNS.contains(name))+ .all(|name| actual.get(*name) == expected.get(*name)),+ Self::Named { fields, watcher } => EVENT_COLUMNS+ .iter()+ .filter(|name| !*watcher || !QUEUE_COLUMNS.contains(name))+ .all(|name| actual.get(*name).is_some_and(|value| value.is_null() || Some(value) == fields.get(*name))),+ Self::Preserve => unreachable!(),+ })+ }+}++impl OracleSchedulerProjection {+ pub(in crate::schema::native_jobs::operations::scheduler) fn for_create(+ definition: &NativeJobSchedulerCreate,+ ) -> Option<Self> {+ let mut fields = EVENT_COLUMNS.iter().map(|name| ((*name).to_string(), Value::Null)).collect::<NativeJobRow>();+ fields.insert("EVENT_CONDITION".into(), definition.event_condition.clone().map_or(Value::Null, Value::String));+ let target = match definition.event_source.as_ref()? {+ NativeJobEventSource::Queue { owner, name, agent } => {+ fields.insert("EVENT_QUEUE_OWNER".into(), Value::String(owner.clone()));+ fields.insert("EVENT_QUEUE_NAME".into(), Value::String(name.clone()));+ fields.insert("EVENT_QUEUE_AGENT".into(), agent.clone().map_or(Value::Null, Value::String));+ EventProjection::Queue(fields)+ }+ NativeJobEventSource::FileWatcher { reference } => {+ fields.insert("FILE_WATCHER_OWNER".into(), Value::String(reference.owner.clone()));+ fields.insert("FILE_WATCHER_NAME".into(), Value::String(reference.name.clone()));+ EventProjection::Watcher(fields)+ }+ };+ Some(Self { before: target.clone(), target })+ }++ pub(super) fn bind(+ edit: &NativeJobSchedulerEditPlan,+ original: &NativeJobDetails,+ dependencies: &[BoundReference],+ ) -> Result<Self, &'static str> {+ let original = row(original).ok_or("native_job_definition_unavailable")?;+ observations(original)?;+ let before = if watcher(original) {+ EventProjection::Watcher(event_fields(original)?)+ } else {+ EventProjection::Preserve+ };+ let target = if !edit.event_changed {+ if watcher(original) {+ EventProjection::Watcher(event_fields(original)?)+ } else {+ EventProjection::Preserve+ }+ } else if let Some(reference) = edit.references.iter().find(|binding| binding.attribute == "SCHEDULE_NAME") {+ if reference.target.kind == NativeJobReferenceKind::Schedule {+ let source = dependencies+ .iter()+ .find(|bound| {+ bound.request.kind == NativeJobReferenceKind::Schedule+ && bound.request.schema.as_deref() == Some(&reference.target.reference.owner)+ && bound.request.name.as_deref() == Some(&reference.target.reference.name)+ })+ .and_then(|bound| bound.rows.first())+ .ok_or("native_job_event_projection_unavailable")?;+ let fields = event_fields(source)?;+ let kind = source+ .get("SCHEDULE_TYPE")+ .and_then(Value::as_str)+ .ok_or("native_job_event_projection_unavailable")?;+ if kind != "EVENT" && fields.values().any(|value| !value.is_null()) {+ return Err("native_job_event_projection_invalid");+ }+ EventProjection::Named { watcher: watcher(source), fields }+ } else {+ EventProjection::None+ }+ } else if watcher(&edit.definition) {+ EventProjection::Watcher(event_fields(&edit.definition)?)+ } else if edit.definition.get("SCHEDULE_TYPE").and_then(Value::as_str) == Some("EVENT") {+ EventProjection::Queue(event_fields(&edit.definition)?)+ } else {+ EventProjection::None+ };+ Ok(Self { before, target })+ }++ fn source(&self, target_applied: bool) -> &EventProjection {+ if target_applied {+ &self.target+ } else {+ &self.before+ }+ }++ pub(super) fn validate(&self, details: &NativeJobDetails) -> Result<(), &'static str> {+ observations(row(details).ok_or("native_job_definition_unavailable")?)+ }++ pub(in crate::schema::native_jobs::operations::scheduler) fn verify(+ &self,+ before: &NativeJobDetails,+ after: &NativeJobDetails,+ effect: &NativeJobStepEffect,+ target_applied: bool,+ user: &str,+ ) -> Result<bool, &'static str> {+ self.validate(after)?;+ let source = self.source(target_applied);+ let mut effect = effect.clone();+ if let NativeJobStepEffect::SchedulerDefinition(effect) = &mut effect {+ effect.columns.retain(|column| !source.generated().contains(&column.name.as_str()));+ }+ Ok(verify_effect_with_extra(before, after, &effect, user, NativeJobEngine::Oracle, source.generated())+ && source.matches(row(after).ok_or("native_job_definition_unavailable")?)?)+ }++ pub(in crate::schema::native_jobs::operations::scheduler) fn preserved(+ &self,+ before: &NativeJobDetails,+ after: &NativeJobDetails,+ target_applied: bool,+ ) -> Result<bool, &'static str> {+ self.validate(after)?;+ let source = self.source(target_applied);+ Ok(preserved_definition_with_extra(+ before,+ after,+ &NativeJobStepEffect::Completed,+ source.generated(),+ NativeJobEngine::Oracle,+ ) && source.matches(row(after).ok_or("native_job_definition_unavailable")?)?)+ }+}diff --git a/crates/dbx-core/src/schema/native_jobs/operations/values.rs b/crates/dbx-core/src/schema/native_jobs/operations/values.rsnew file mode 100644index 0000000000..2bc0f97610--- /dev/null+++ b/crates/dbx-core/src/schema/native_jobs/operations/values.rs@@ -0,0 +1,101 @@+use serde_json::Value;+use std::sync::LazyLock;++pub(super) fn field_matches(name: &str, actual: Option<&Value>, expected: &Value) -> bool {+ let Some(actual) = actual else { return false };+ if actual == expected {+ return true;+ }+ if let Value::Bool(expected) = expected {+ return super::super::details::boolean(Some(actual)) == Some(*expected);+ }+ if actual.is_null() && expected.as_str() == Some("") {+ return true;+ }+ match name {+ "NUMBER_OF_ARGUMENTS"+ | "JOB_PRIORITY"+ | "MAX_RUNS"+ | "MAX_FAILURES"+ | "RAISE_EVENTS"+ | "INSTANCE_ID"+ | "JOB_WEIGHT"+ | "EMAIL_TYPE"+ | "NETSEND_TYPE"+ | "EMAIL_OPERID"+ | "NETSEND_OPERID"+ | "EP_SEQNO"+ | "TYPE"+ | "JOBID"+ | "SUCC_ACTION"+ | "FAIL_ACTION"+ | "RETRY_ATTEMPTS"+ | "RETRY_INTERVAL"+ | "FREQ_INTERVAL"+ | "FREQ_SUB_INTERVAL"+ | "FREQ_MINUTE_INTERVAL"+ | "INSTANCE" => {+ let expected = expected.as_u64().map(i128::from);+ expected.is_some() && integral(actual) == expected+ }+ "START_DATE" | "END_DATE" => {+ expected.as_str().is_some_and(|expected| super::scheduler::same_timestamp(Some(actual), expected))+ }+ "NEXT_DATE" => expected.as_str().is_some_and(|expected| super::legacy::same_date(Some(actual), expected)),+ "SCHEDULE_LIMIT" | "MAX_RUN_DURATION" => {+ let expected = expected.as_str().and_then(interval_nanos);+ expected.is_some() && actual.as_str().and_then(interval_nanos) == expected+ }+ _ => false,+ }+}++// NUMBER columns may be returned as decimal strings. Never round through a floating-point value.+pub(super) fn integral(value: &Value) -> Option<i128> {+ let text = match value {+ Value::String(value) => value.clone(),+ Value::Number(value) => value.to_string(),+ _ => return None,+ };+ let text = text.trim();+ let whole = if let Some((whole, fraction)) = text.split_once('.') {+ if fraction.is_empty() || !fraction.bytes().all(|byte| byte == b'0') {+ return None;+ }+ whole+ } else {+ text+ };+ whole.parse().ok()+}++fn interval_nanos(value: &str) -> Option<i128> {+ static SQL: LazyLock<regex::Regex> =+ LazyLock::new(|| regex::Regex::new(r"^([+-]?)(\d+) (\d{1,2}):(\d{2}):(\d{2})(?:\.(\d{1,9}))?$").unwrap());+ static ISO: LazyLock<regex::Regex> = LazyLock::new(|| {+ regex::Regex::new(r"^([+-]?)P(?:(\d+)D)?(?:T(?:(\d+)H)?(?:(\d+)M)?(?:(\d+)(?:\.(\d{1,9}))?S)?)?$").unwrap()+ });+ let value = value.trim();+ let captures = SQL.captures(value).or_else(|| ISO.captures(value))?;+ if (2..=5).all(|index| captures.get(index).is_none()) {+ return None;+ }+ let component =+ |index| -> Option<i128> { captures.get(index).map_or(Some(0), |value| value.as_str().parse().ok()) };+ let fraction = captures.get(6).map_or(Some(0), |value| {+ value.as_str().parse::<i128>().ok()?.checked_mul(10_i128.pow(9 - value.len() as u32))+ })?;+ let seconds = component(2)?+ .checked_mul(24)?+ .checked_add(component(3)?)?+ .checked_mul(60)?+ .checked_add(component(4)?)?+ .checked_mul(60)?+ .checked_add(component(5)?)?;+ let nanos = seconds.checked_mul(1_000_000_000)?.checked_add(fraction)?;+ if &captures[1] == "-" {+ nanos.checked_neg()+ } else {+ Some(nanos)+ }+}diff --git a/crates/dbx-core/src/schema/native_jobs/references.rs b/crates/dbx-core/src/schema/native_jobs/references.rsnew file mode 100644index 0000000000..fce7ac82b6--- /dev/null+++ b/crates/dbx-core/src/schema/native_jobs/references.rs@@ -0,0 +1,138 @@+use super::*;+use crate::connection::AppState;+use dbx_sql::native_jobs::native_job_reference_queries;+use dbx_types::native_jobs::{+ NativeJobCatalogSource, NativeJobReferenceCatalog, NativeJobReferenceKind, NativeJobReferenceListRequest,+};++pub(super) async fn read_references_with<Q, F>(+ engine: NativeJobCatalogDialect,+ request: &NativeJobReferenceListRequest,+ session_user: Option<&str>,+ query: &mut Q,+) -> Result<NativeJobReferenceCatalog, &'static str>+where+ Q: FnMut(NativeJobCatalogQuery) -> F,+ F: Future<Output = Result<Value, NativeJobCatalogFailure>>,+{+ let mut queries = native_job_reference_queries(engine, request)?;+ if request.schema.as_deref().zip(session_user).is_some_and(|(owner, user)| owner != user) {+ // A USER view cannot establish another owner's inventory, including a genuinely empty one.+ queries.retain(|query| query.coverage != NativeJobCatalogCoverage::CurrentUser);+ }+ let section = read_catalog_candidates_with(+ queries,+ |raw, limit| {+ let mut rows = rows_from_result(decode_query_result(engine, raw)?, limit, |row| {+ let owner = row.get("DBX_OWNER").and_then(Value::as_str).filter(|value| !value.is_empty());+ let name = row.get("DBX_NAME").and_then(Value::as_str).filter(|value| !value.is_empty());+ if owner.is_none()+ || name.is_none()+ || request.schema.as_deref().is_some_and(|expected| Some(expected) != owner)+ || request.name.as_deref().is_some_and(|expected| Some(expected) != name)+ {+ return Err(NativeJobCatalogFailure::IdentityMismatch);+ }+ let group_type = row.get("GROUP_TYPE").and_then(Value::as_str);+ if match request.kind {+ NativeJobReferenceKind::WindowGroup => group_type != Some("WINDOW"),+ NativeJobReferenceKind::DestinationGroup => {+ !matches!(group_type, Some("DB_DEST" | "EXTERNAL_DEST"))+ }+ _ => false,+ } {+ return Err(NativeJobCatalogFailure::InvalidResponse);+ }+ Ok(())+ })?;+ if let NativeJobMetadata::Available { value } | NativeJobMetadata::Truncated { value, .. } = &rows {+ let mut seen = HashSet::new();+ for row in value {+ let discriminator = if request.kind == NativeJobReferenceKind::ProgramArguments {+ super::details::integer(row.get("ARGUMENT_POSITION"))+ .filter(|value| *value > 0)+ .ok_or(NativeJobCatalogFailure::InvalidResponse)?+ .to_string()+ } else if request.kind == NativeJobReferenceKind::DestinationGroupMembers {+ row.get("MEMBER_NAME")+ .and_then(Value::as_str)+ .filter(|value| !value.is_empty() && !value.contains('\0'))+ .ok_or(NativeJobCatalogFailure::InvalidResponse)?+ .to_string()+ } else {+ String::new()+ };+ if !seen.insert((+ row["DBX_OWNER"].as_str().unwrap(),+ row["DBX_NAME"].as_str().unwrap(),+ discriminator,+ )) {+ return Err(NativeJobCatalogFailure::AmbiguousIdentity);+ }+ }+ }+ if request.kind == NativeJobReferenceKind::ProgramArguments {+ if let NativeJobMetadata::Available { value } | NativeJobMetadata::Truncated { value, .. } = &mut rows {+ for row in value {+ let default = super::details::program_default(engine, Some(row), None);+ row.insert(+ "DBX_ARGUMENT_DEFAULT".into(),+ serde_json::to_value(default).expect("JSON metadata"),+ );+ }+ }+ }+ Ok(rows)+ },+ query,+ )+ .await?;+ Ok(NativeJobReferenceCatalog {+ objects: section.data,+ source: NativeJobCatalogSource { source: section.source.map(str::to_string), coverage: section.coverage },+ offset: request.offset,+ limit: request.limit,+ })+}++pub async fn native_job_references_with<Q, F>(+ state: &AppState,+ request: &NativeJobReferenceListRequest,+ mut query: Q,+) -> Result<NativeJobReferenceCatalog, &'static str>+where+ Q: FnMut(NativeJobCatalogQuery) -> F,+ F: Future<Output = Result<Value, NativeJobCatalogFailure>>,+{+ request.scope.validate()?;+ let bound = state.native_jobs.context(state, &request.scope)?;+ let result = tokio::select! {+ biased;+ _=bound.lifecycle.cancellation().cancelled()=>return Err("native_job_context_changed"),+ result=read_references_with(bound.context.engine,request,Some(&bound.context.session_user),&mut query)=>result?,+ };+ state.native_jobs.context(state, &request.scope)?;+ Ok(result)+}++pub async fn native_job_references_core(+ state: &AppState,+ request: &NativeJobReferenceListRequest,+) -> Result<NativeJobReferenceCatalog, String> {+ let scope = &request.scope;+ scope.validate().map_err(str::to_string)?;+ let bound = state.native_jobs.context(state, scope).map_err(str::to_string)?;+ let timeout = super::super::agent_metadata_timeout(state.configs.read().await.get(&scope.connection_id));+ let (session, pool) = super::service::open_pool(state, scope).await.map_err(str::to_string)?;+ let result = async {+ super::service::validate_runtime_context(state, &bound, &pool).await?;+ native_job_references_with(state, request, |query| {+ execute_catalog_query(bound.context.engine, &pool, &scope.database, query, timeout)+ })+ .await+ }+ .await+ .map_err(str::to_string);+ session.finish(state, &scope.connection_id, (!scope.database.is_empty()).then_some(scope.database.as_str())).await;+ result+}diff --git a/crates/dbx-core/src/schema/native_jobs/service.rs b/crates/dbx-core/src/schema/native_jobs/service.rsnew file mode 100644index 0000000000..45534a7573--- /dev/null+++ b/crates/dbx-core/src/schema/native_jobs/service.rs@@ -0,0 +1,710 @@+use super::*;+use crate::connection::{AppState, ConnectionLifecycleSnapshot};+use crate::models::connection::{+ database_info_from_protocol_value, ConnectionConfig, DatabaseConnectionInfo, DatabaseType,+};+use crate::session_credentials::current_credential_owner;+use dbx_sql::native_jobs::native_job_list_queries;+use dbx_types::native_jobs::{+ NativeJobCatalogSource, NativeJobContext, NativeJobEngine, NativeJobKind, NativeJobList, NativeJobListRequest,+ NativeJobScope, NativeJobSummary,+};+use sha2::{Digest, Sha256};+use std::collections::VecDeque;++const MAX_CONTEXTS: usize = 256;+const MAX_BASELINES: usize = 512;++// Authentication owners can be session tokens. Neither these records nor definitions are Debug.+#[derive(Clone)]+pub(super) struct BoundContext {+ pub(super) context: NativeJobContext,+ actor: Option<String>,+ pub(super) lifecycle: ConnectionLifecycleSnapshot,+}++#[derive(Clone)]+struct Baseline {+ revision: String,+ target: NativeJobRef,+ identity: Option<NativeJobCatalogRow>,+ partitions: BTreeMap<String, String>,+ legacy_next_date: Option<Value>,+}++#[derive(Default)]+struct Registry {+ contexts: VecDeque<BoundContext>,+ baselines: VecDeque<Baseline>,+}++#[derive(Default)]+pub struct NativeJobRegistry(std::sync::Mutex<Registry>, super::operations::NativeJobOperations);++pub struct NativeJobRuntimeIdentity {+ pub database_info: Option<DatabaseConnectionInfo>,+ pub session_user: String,+}++impl NativeJobRegistry {+ pub(super) fn operations(&self) -> &super::operations::NativeJobOperations {+ &self.1+ }+ fn bind(+ &self,+ state: &AppState,+ context: NativeJobContext,+ lifecycle: ConnectionLifecycleSnapshot,+ ) -> NativeJobContext {+ let actor = current_credential_owner();+ let mut registry = self.0.lock().unwrap_or_else(|error| error.into_inner());+ if let Some(existing) = registry.contexts.iter().find(|bound| {+ bound.actor == actor+ && bound.context.scope.connection_id == context.scope.connection_id+ && bound.context.scope.database == context.scope.database+ && bound.context.engine == context.engine+ && bound.context.session_user == context.session_user+ && bound.context.actual_database == context.actual_database+ && bound.context.product_version == context.product_version+ && state.connection_lifecycle_is_current(&context.scope.connection_id, &bound.lifecycle)+ }) {+ return existing.context.clone();+ }+ registry.contexts.retain(|bound| {+ !(bound.actor == actor+ && bound.context.scope.connection_id == context.scope.connection_id+ && bound.context.scope.database == context.scope.database)+ });+ registry.contexts.push_back(BoundContext { context: context.clone(), actor, lifecycle });+ if registry.contexts.len() > MAX_CONTEXTS {+ registry.contexts.pop_front();+ }+ context+ }++ pub(super) fn context(&self, state: &AppState, scope: &NativeJobScope) -> Result<BoundContext, &'static str> {+ let actor = current_credential_owner();+ let bound = self+ .0+ .lock()+ .unwrap_or_else(|error| error.into_inner())+ .contexts+ .iter()+ .find(|bound| &bound.context.scope == scope && bound.actor == actor)+ .cloned()+ .ok_or("native_job_context_expired")?;+ if !state.connection_lifecycle_is_current(&scope.connection_id, &bound.lifecycle) {+ return Err("native_job_context_changed");+ }+ Ok(bound)+ }++ pub(super) fn remember(&self, engine: NativeJobEngine, details: &mut dbx_types::native_jobs::NativeJobDetails) {+ let identity = match (&details.native_identity, &details.consistency) {+ (NativeJobMetadata::Available { value }, NativeJobMetadata::Available { .. }) => Some(value.clone()),+ _ => None,+ };+ let mut partitions = BTreeMap::new();+ if let NativeJobMetadata::Available { value } = &details.snapshot.definition {+ let mut stable = value.clone();+ stable.retain(|name, _| {+ !super::details::generated_definition_column(engine, &details.snapshot.job_ref, value, name)+ });+ for volatile in [+ "STATE",+ "RUN_COUNT",+ "FAILURE_COUNT",+ "RETRY_COUNT",+ "LAST_START_DATE",+ "LAST_RUN_DATE",+ "LAST_RUN_DURATION",+ "NEXT_RUN_DATE",+ "LAST_DATE",+ "LAST_SEC",+ "THIS_DATE",+ "THIS_SEC",+ "NEXT_DATE",+ "NEXT_SEC",+ "TOTAL_TIME",+ "FAILURES",+ "GMT_MODIFIED",+ ] {+ stable.remove(volatile);+ }+ partitions.insert("definition".into(), fingerprint(&stable));+ }+ for (name, data) in [+ ("steps", &details.steps),+ ("schedules", &details.schedules),+ ("argument-inventory", &details.parameter_metadata),+ ] {+ match data {+ NativeJobMetadata::Available { value } => {+ if name == "argument-inventory" && engine == NativeJobEngine::Oracle {+ let canonical: Vec<_> = value+ .iter()+ .map(|row| dbx_sql::native_job_arguments::canonical_argument_row(row, false))+ .collect();+ partitions.insert(name.into(), fingerprint(&canonical));+ } else {+ partitions.insert(name.into(), fingerprint(value));+ }+ }+ NativeJobMetadata::Empty => {+ partitions.insert(name.into(), fingerprint(&Vec::<NativeJobCatalogRow>::new()));+ }+ _ => {}+ }+ }+ if let Some(NativeJobMetadata::Available { value }) = &details.legacy_definition {+ let mut stable = value.clone();+ for volatile in+ ["LAST_DATE", "LAST_SEC", "THIS_DATE", "THIS_SEC", "NEXT_DATE", "NEXT_SEC", "TOTAL_TIME", "FAILURES"]+ {+ stable.remove(volatile);+ }+ partitions.insert("legacyDefinition".into(), fingerprint(&stable));+ }+ if let NativeJobMetadata::Available { value } = &details.snapshot.arguments {+ let canonical = |argument: &dbx_types::native_jobs::NativeJobArgument| {+ let mut argument = argument.clone();+ if engine == NativeJobEngine::Oracle {+ if let NativeJobMetadata::Available { value } = &details.parameter_metadata {+ if let Some(row) = value.iter().find(|row| {+ super::details::integer(row.get("ARGUMENT_POSITION")) == Some(argument.position as i64)+ }) {+ argument.value =+ dbx_sql::native_job_arguments::decode_argument(row, false).editable_value();+ }+ }+ if matches!(argument.default_value, Some(NativeJobMetadata::Available { .. })) {+ if let Some(NativeJobMetadata::Available { value }) = &details.program_arguments {+ if let Some(row) = value.iter().find(|row| {+ super::details::integer(row.get("ARGUMENT_POSITION")) == Some(argument.position as i64)+ }) {+ argument.default_value = Some(NativeJobMetadata::Available {+ value: dbx_sql::native_job_arguments::decode_argument(row, true).editable_value(),+ });+ }+ }+ }+ }+ let native = |metadata: &NativeJobMetadata<Vec<NativeJobCatalogRow>>, default_value| match metadata {+ NativeJobMetadata::Available { value } if engine == NativeJobEngine::Oracle => value+ .iter()+ .find(|row| {+ super::details::integer(row.get("ARGUMENT_POSITION")) == Some(argument.position as i64)+ })+ .map(|row| {+ dbx_sql::native_job_arguments::decode_argument(row, default_value).canonical_value()+ }),+ _ => None,+ };+ serde_json::json!([+ argument,+ native(&details.parameter_metadata, false),+ details.program_arguments.as_ref().and_then(|rows| native(rows, true))+ ])+ };+ for argument in value.iter().filter(|argument| argument.editable) {+ partitions.insert(format!("argument:{}", argument.position), fingerprint(&canonical(argument)));+ }+ if value.iter().all(|argument| argument.editable) {+ partitions.insert("arguments".into(), fingerprint(&value.iter().map(canonical).collect::<Vec<_>>()));+ }+ }+ let revision = uuid::Uuid::new_v4().to_string();+ let legacy_next_date = if matches!(details.snapshot.job_ref, NativeJobRef::Legacy { .. }) {+ if engine == NativeJobEngine::Dameng {+ match &details.legacy_definition {+ Some(NativeJobMetadata::Available { value }) => value+ .get("NEXT_DATE")+ .zip(value.get("NEXT_SEC"))+ .map(|(date, seconds)| serde_json::json!([date, seconds])),+ _ => None,+ }+ } else {+ match &details.snapshot.definition {+ NativeJobMetadata::Available { value } => value.get("NEXT_DATE").cloned(),+ _ => None,+ }+ }+ } else {+ None+ };+ let baseline = Baseline {+ revision: revision.clone(),+ target: details.snapshot.job_ref.clone(),+ identity,+ partitions,+ legacy_next_date,+ };+ let mut registry = self.0.lock().unwrap_or_else(|error| error.into_inner());+ registry.baselines.push_back(baseline);+ if registry.baselines.len() > MAX_BASELINES {+ registry.baselines.pop_front();+ }+ details.snapshot.revision = revision;+ }++ pub(super) fn legacy_definition_recorded(+ &self,+ state: &AppState,+ target: &NativeJobRef,+ revision: &str,+ ) -> Result<bool, &'static str> {+ self.context(state, target.scope())?;+ let registry = self.0.lock().unwrap_or_else(|error| error.into_inner());+ let baseline = registry+ .baselines+ .iter()+ .find(|baseline| baseline.revision == revision && &baseline.target == target)+ .ok_or("native_job_preview_stale")?;+ Ok(baseline.partitions.contains_key("legacyDefinition"))+ }++ /// Validate only the partitions the pending change needs. Runtime/history availability is unrelated.+ pub fn compare_baseline(+ &self,+ state: &AppState,+ target: &NativeJobRef,+ previous: &str,+ current: &str,+ required_partitions: &[&str],+ compare_legacy_next_date: bool,+ ) -> Result<(), &'static str> {+ self.context(state, target.scope())?;+ let registry = self.0.lock().unwrap_or_else(|error| error.into_inner());+ let find = |revision: &str| {+ registry.baselines.iter().find(|baseline| baseline.revision == revision && &baseline.target == target)+ };+ let before = find(previous).ok_or("native_job_preview_stale")?;+ let after = find(current).ok_or("native_job_preview_stale")?;+ if before.identity.is_none() || after.identity.is_none() {+ return Err("native_job_identity_unverified");+ }+ if before.identity != after.identity {+ return Err("native_job_replaced");+ }+ for part in required_partitions {+ let initial = before.partitions.get(*part).ok_or("native_job_metadata_incomplete")?;+ let latest = after.partitions.get(*part).ok_or("native_job_metadata_incomplete")?;+ if initial != latest {+ return Err("native_job_definition_changed");+ }+ }+ if compare_legacy_next_date {+ if before.legacy_next_date.is_none() || after.legacy_next_date.is_none() {+ return Err("native_job_metadata_incomplete");+ }+ if before.legacy_next_date != after.legacy_next_date {+ return Err("native_job_definition_changed");+ }+ }+ Ok(())+ }+}++fn fingerprint(value: &impl serde::Serialize) -> String {+ // This fingerprint is for optimistic database conflict detection, not file-integrity bookkeeping.+ let bytes = serde_json::to_vec(value).expect("native Job metadata is JSON");+ format!("{:x}", Sha256::digest(bytes))+}++fn resolve_engine(+ config: &ConnectionConfig,+ info: Option<&DatabaseConnectionInfo>,+) -> Result<NativeJobEngine, &'static str> {+ let product = info.and_then(|info| info.product_name.as_deref()).unwrap_or("").to_ascii_lowercase();+ let mode = info.and_then(|info| info.compatibility_mode.as_deref()).unwrap_or("");+ if product.contains("oceanbase") {+ return if mode.eq_ignore_ascii_case("oracle") || config.db_type == DatabaseType::OceanbaseOracle {+ Ok(NativeJobEngine::OceanbaseOracle)+ } else {+ Err("native_job_engine_unresolved")+ };+ }+ match config.db_type {+ DatabaseType::Oracle => Ok(NativeJobEngine::Oracle),+ DatabaseType::OceanbaseOracle => Ok(NativeJobEngine::OceanbaseOracle),+ DatabaseType::Dameng => Ok(NativeJobEngine::Dameng),+ DatabaseType::Jdbc if product == "oracle" || product.starts_with("oracle database") => {+ Ok(NativeJobEngine::Oracle)+ }+ DatabaseType::Jdbc if product == "dm dbms" || product == "dameng" => Ok(NativeJobEngine::Dameng),+ _ => Err("native_job_engine_unresolved"),+ }+}++pub async fn native_job_open_context_with<Q, F>(+ state: &AppState,+ connection_id: &str,+ database: &str,+ read_identity: Q,+) -> Result<NativeJobContext, &'static str>+where+ Q: FnOnce(ConnectionConfig) -> F,+ F: Future<Output = Result<NativeJobRuntimeIdentity, &'static str>>,+{+ if connection_id.is_empty() || connection_id.contains('\0') || database.contains('\0') {+ return Err("native_job_identity_invalid");+ }+ let lifecycle = state.connection_lifecycle_snapshot(connection_id);+ let config = state.configs.read().await.get(connection_id).cloned().ok_or("native_job_connection_missing")?;+ let identity = read_identity(config.clone()).await?;+ if identity.session_user.is_empty() || identity.session_user.contains('\0') {+ return Err("native_job_runtime_identity_invalid");+ }+ if !state.connection_lifecycle_is_current(connection_id, &lifecycle) {+ return Err("native_job_context_changed");+ }+ let context = NativeJobContext {+ scope: NativeJobScope {+ connection_id: connection_id.into(),+ database: database.into(),+ context_id: uuid::Uuid::new_v4().to_string(),+ },+ engine: resolve_engine(&config, identity.database_info.as_ref())?,+ session_user: identity.session_user,+ actual_database: identity.database_info.as_ref().and_then(|info| info.current_database.clone()),+ product_version: identity.database_info.and_then(|info| info.product_version),+ };+ Ok(state.native_jobs.bind(state, context, lifecycle))+}++pub(super) async fn open_pool(+ state: &AppState,+ scope: &NativeJobScope,+) -> Result<(super::super::EphemeralAgentMetadataSession, PoolKind), &'static str> {+ let database = (!scope.database.is_empty()).then_some(scope.database.as_str());+ let session =+ super::super::EphemeralAgentMetadataSession::open(state, &scope.connection_id, database, "native-jobs").await;+ let key = state+ .get_or_create_metadata_pool_for_session(&scope.connection_id, database, session.client_session_id())+ .await+ .map_err(|_| "native_job_connection_failed")?;+ let pool = state.pool_handle(&key).await.ok_or("native_job_connection_failed")?;+ Ok((session, pool))+}++async fn runtime_identity(+ config: &ConnectionConfig,+ pool: &PoolKind,+ database: &str,+) -> Result<NativeJobRuntimeIdentity, &'static str> {+ runtime_identity_in_session(config, pool, database, None).await+}++async fn runtime_identity_in_session(+ config: &ConnectionConfig,+ pool: &PoolKind,+ database: &str,+ physical: Option<&NativeJobPhysicalSession>,+) -> Result<NativeJobRuntimeIdentity, &'static str> {+ let timeout = super::super::agent_metadata_timeout(Some(config));+ let info = match pool {+ PoolKind::Agent(client) => {+ if let Some(physical) = physical {+ let mut params = serde_json::json!({});+ physical.bind(&mut params);+ let value: Value = client+ .lock()+ .await+ .call_typed_with_timeout("connection_info", params, timeout)+ .await+ .map_err(|_| "native_job_runtime_identity_failed")?;+ database_info_from_protocol_value(&value)+ } else {+ client+ .lock()+ .await+ .connection_info(timeout)+ .await+ .map_err(|_| "native_job_runtime_identity_failed")?+ .database_info+ }+ }+ PoolKind::ExternalDriver { config, session, .. } => {+ let mut params = serde_json::json!({ "connection": config.as_ref() });+ if let Some(physical) = physical {+ physical.bind(&mut params);+ }+ let value: Value = session+ .invoke_with_timeout("connectionInfo", params, timeout)+ .await+ .map_err(|_| "native_job_runtime_identity_failed")?;+ database_info_from_protocol_value(&value)+ }+ _ => return Err("native_job_driver_route_missing"),+ };+ let engine = resolve_engine(config, info.as_ref())?;+ let query = NativeJobCatalogQuery {+ source: "session-user",+ coverage: NativeJobCatalogCoverage::CurrentUser,+ sql: "SELECT USER AS DBX_SESSION_USER FROM DUAL".into(),+ limit: 1,+ };+ let raw = execute_catalog_query_in_session(engine, pool, database, query, timeout, physical)+ .await+ .map_err(|_| "native_job_runtime_identity_failed")?;+ let rows = rows_from_result(+ decode_query_result(engine, raw).map_err(|_| "native_job_runtime_identity_failed")?,+ 2,+ |_| Ok(()),+ )+ .map_err(|_| "native_job_runtime_identity_failed")?;+ let NativeJobMetadata::Available { value } = rows else {+ return Err("native_job_runtime_identity_invalid");+ };+ if value.len() != 1 {+ return Err("native_job_runtime_identity_invalid");+ }+ let session_user = value[0]+ .get("DBX_SESSION_USER")+ .and_then(Value::as_str)+ .ok_or("native_job_runtime_identity_invalid")?+ .to_string();+ Ok(NativeJobRuntimeIdentity { database_info: info, session_user })+}++pub async fn native_job_open_context_core(+ state: &AppState,+ connection_id: &str,+ database: &str,+) -> Result<NativeJobContext, String> {+ let scope =+ NativeJobScope { connection_id: connection_id.into(), database: database.into(), context_id: "opening".into() };+ native_job_open_context_with(state, connection_id, database, |config| async move {+ let (session, pool) = open_pool(state, &scope).await?;+ let result = runtime_identity(&config, &pool, database).await;+ session.finish(state, connection_id, (!database.is_empty()).then_some(database)).await;+ result+ })+ .await+ .map_err(str::to_string)+}++pub async fn native_job_list_with<Q, F>(+ state: &AppState,+ request: &NativeJobListRequest,+ mut query: Q,+) -> Result<NativeJobList, &'static str>+where+ Q: FnMut(NativeJobCatalogQuery) -> F,+ F: Future<Output = Result<Value, NativeJobCatalogFailure>>,+{+ let (scope, kind, offset, limit) = (&request.scope, request.kind, request.offset, request.limit);+ let bound = state.native_jobs.context(state, scope)?;+ let candidates =+ native_job_list_queries(bound.context.engine, kind, request.schema.as_deref(), &request.filter, offset, limit)?;+ let section = tokio::select! {+ biased;+ _ = bound.lifecycle.cancellation().cancelled() => return Err("native_job_context_changed"),+ read = read_catalog_candidates_with(candidates, |raw, limit| {+ rows_from_result(decode_query_result(bound.context.engine, raw)?, limit, |row| {+ if kind != NativeJobKind::Scheduler && row.get("DBX_JOB_ID").and_then(Value::as_str).is_none() {+ return Err(NativeJobCatalogFailure::IdentityMismatch);+ }+ Ok(())+ })+ }, &mut query) => read?,+ };+ state.native_jobs.context(state, scope)?;+ let jobs = summaries(scope, bound.context.engine, kind, section.data);+ Ok(NativeJobList {+ jobs,+ source: NativeJobCatalogSource { source: section.source.map(str::to_string), coverage: section.coverage },+ offset,+ limit,+ })+}++fn summaries(+ scope: &NativeJobScope,+ engine: NativeJobEngine,+ kind: NativeJobKind,+ rows: NativeJobMetadata<Vec<NativeJobCatalogRow>>,+) -> NativeJobMetadata<Vec<NativeJobSummary>> {+ let parsed = match rows {+ NativeJobMetadata::Available { value } => (value, None),+ NativeJobMetadata::Truncated { value, limit } => (value, Some(limit)),+ other => return super::details::map_metadata(other, |_| unreachable!()),+ };+ let mut summaries = Vec::new();+ for row in parsed.0 {+ let text = |key: &str| row.get(key).and_then(Value::as_str).map(str::to_string);+ let mut aliases = Vec::new();+ let job_ref = match kind {+ NativeJobKind::Scheduler => NativeJobRef::Scheduler {+ scope: scope.clone(),+ owner: text("DBX_OWNER").unwrap_or_default(),+ name: text("JOB_NAME").unwrap_or_default(),+ },+ _ if engine == NativeJobEngine::Dameng => {+ let native = NativeJobRef::DamengNative {+ scope: scope.clone(),+ job_id: text("DBX_JOB_ID").unwrap_or_default(),+ name: text("NAME").unwrap_or_default(),+ };+ if native.validate().is_err() {+ return NativeJobCatalogFailure::IdentityMismatch.metadata();+ }+ if super::details::integer(row.get("SYS_FLAG")) == Some(2) {+ aliases.push(native);+ NativeJobRef::Legacy { scope: scope.clone(), job_id: text("DBX_JOB_ID").unwrap_or_default() }+ } else {+ native+ }+ }+ _ => NativeJobRef::Legacy { scope: scope.clone(), job_id: text("DBX_JOB_ID").unwrap_or_default() },+ };+ if job_ref.validate().is_err() {+ return NativeJobCatalogFailure::IdentityMismatch.metadata();+ }+ let legacy = matches!(job_ref, NativeJobRef::Legacy { .. });+ let scheduler = matches!(job_ref, NativeJobRef::Scheduler { .. });+ let name = text(if scheduler {+ "JOB_NAME"+ } else if engine == NativeJobEngine::Dameng {+ "NAME"+ } else {+ "DBX_JOB_ID"+ })+ .unwrap_or_default();+ let enabled = if legacy && engine != NativeJobEngine::Dameng {+ match text("BROKEN").as_deref() {+ Some("N") => Some(true),+ Some("Y") => Some(false),+ _ => None,+ }+ } else {+ super::details::boolean(row.get(if scheduler { "ENABLED" } else { "ENABLE" }))+ };+ summaries.push(NativeJobSummary {+ job_ref,+ name,+ owner: if scheduler {+ text("DBX_OWNER")+ } else if engine == NativeJobEngine::Dameng {+ text("USERNAME")+ } else {+ None+ },+ enabled,+ job_type: text("JOB_TYPE"),+ state: text("STATE"),+ next_run: row.get(if scheduler { "NEXT_RUN_DATE" } else { "NEXT_DATE" }).cloned(),+ comments: text(if engine == NativeJobEngine::Dameng && !scheduler { "DESCRIBE" } else { "COMMENTS" }),+ aliases,+ log_user: text("LOG_USER"),+ priv_user: text("PRIV_USER"),+ schema_user: text("SCHEMA_USER"),+ });+ }+ match parsed.1 {+ Some(limit) => NativeJobMetadata::Truncated { value: summaries, limit },+ None => NativeJobMetadata::Available { value: summaries },+ }+}++pub async fn native_job_list_core(state: &AppState, request: &NativeJobListRequest) -> Result<NativeJobList, String> {+ let scope = &request.scope;+ let bound = state.native_jobs.context(state, scope).map_err(str::to_string)?;+ let timeout = super::super::agent_metadata_timeout(state.configs.read().await.get(&scope.connection_id));+ let (session, pool) = open_pool(state, scope).await.map_err(str::to_string)?;+ let result = async {+ validate_runtime_context(state, &bound, &pool).await?;+ native_job_list_with(state, request, |query| {+ execute_catalog_query(bound.context.engine, &pool, &scope.database, query, timeout)+ })+ .await+ }+ .await+ .map_err(str::to_string);+ session.finish(state, &scope.connection_id, (!scope.database.is_empty()).then_some(scope.database.as_str())).await;+ result+}++pub async fn native_job_read_core(+ state: &AppState,+ target: &NativeJobRef,+) -> Result<dbx_types::native_jobs::NativeJobDetails, String> {+ target.validate().map_err(str::to_string)?;+ let bound = state.native_jobs.context(state, target.scope()).map_err(str::to_string)?;+ let timeout = super::super::agent_metadata_timeout(state.configs.read().await.get(&target.scope().connection_id));+ let (session, pool) = open_pool(state, target.scope()).await.map_err(str::to_string)?;+ let result = async {+ validate_runtime_context(state, &bound, &pool).await?;+ native_job_read_with(state, target, |query| {+ execute_catalog_query(bound.context.engine, &pool, &target.scope().database, query, timeout)+ })+ .await+ }+ .await+ .map_err(str::to_string);+ session+ .finish(+ state,+ &target.scope().connection_id,+ (!target.scope().database.is_empty()).then_some(target.scope().database.as_str()),+ )+ .await;+ result+}++pub(super) async fn validate_runtime_context(+ state: &AppState,+ bound: &BoundContext,+ pool: &PoolKind,+) -> Result<(), &'static str> {+ validate_runtime_context_in_session(state, bound, pool, None).await+}++pub(super) async fn validate_runtime_context_in_session(+ state: &AppState,+ bound: &BoundContext,+ pool: &PoolKind,+ physical: Option<&NativeJobPhysicalSession>,+) -> Result<(), &'static str> {+ let scope = &bound.context.scope;+ state.native_jobs.context(state, scope)?;+ let config =+ state.configs.read().await.get(&scope.connection_id).cloned().ok_or("native_job_connection_missing")?;+ let identity = tokio::select! {+ biased;+ _ = bound.lifecycle.cancellation().cancelled() => return Err("native_job_context_changed"),+ identity = runtime_identity_in_session(&config, pool, &scope.database, physical) => identity?,+ };+ let actual_database = identity.database_info.as_ref().and_then(|info| info.current_database.as_ref());+ if identity.session_user != bound.context.session_user+ || actual_database != bound.context.actual_database.as_ref()+ || identity.database_info.as_ref().and_then(|info| info.product_version.as_ref())+ != bound.context.product_version.as_ref()+ || resolve_engine(&config, identity.database_info.as_ref())? != bound.context.engine+ {+ return Err("native_job_runtime_context_changed");+ }+ state.native_jobs.context(state, scope)?;+ Ok(())+}++pub async fn native_job_read_with<Q, F>(+ state: &AppState,+ target: &NativeJobRef,+ query: Q,+) -> Result<dbx_types::native_jobs::NativeJobDetails, &'static str>+where+ Q: FnMut(NativeJobCatalogQuery) -> F,+ F: Future<Output = Result<Value, NativeJobCatalogFailure>>,+{+ target.validate()?;+ let bound = state.native_jobs.context(state, target.scope())?;+ let mut result = tokio::select! {+ biased;+ _ = bound.lifecycle.cancellation().cancelled() => return Err("native_job_context_changed"),+ result = super::details::read_native_job_details_with(bound.context.engine, target, query) => result?,+ };+ state.native_jobs.context(state, target.scope())?;+ state.native_jobs.remember(bound.context.engine, &mut result);+ Ok(result)+}diff --git a/crates/dbx-core/src/schema/oracle_routines.rs b/crates/dbx-core/src/schema/oracle_routines.rsindex b9459d989c..1f26798bc2 100644--- a/crates/dbx-core/src/schema/oracle_routines.rs+++ b/crates/dbx-core/src/schema/oracle_routines.rs@@ -334,6 +334,7 @@ impl RoutineCatalog for LiveCatalog<'_> {&identity.kind,None,None,+ &dbx_types::oracle_trigger::MetadataReadOptions::default(),true,agent_metadata_timeout(Some(self.config)),)diff --git a/crates/dbx-core/src/schema/oracle_table_triggers.rs b/crates/dbx-core/src/schema/oracle_table_triggers.rsindex 80176a0707..e5667d94c6 100644--- a/crates/dbx-core/src/schema/oracle_table_triggers.rs+++ b/crates/dbx-core/src/schema/oracle_table_triggers.rs@@ -93,6 +93,7 @@ pub(super) async fn enrich(source: trigger.statement.clone().unwrap(),editable: None,routine_parameters: None,+ trigger: None,}};if source.name != trigger.namediff --git a/crates/dbx-core/src/schema/oracle_triggers.rs b/crates/dbx-core/src/schema/oracle_triggers.rsnew file mode 100644index 0000000000..3299199b5e--- /dev/null+++ b/crates/dbx-core/src/schema/oracle_triggers.rs@@ -0,0 +1,700 @@+//! Exact reads for the two legacy Oracle-family SQL transports. Modern Agents+//! and JDBC keep their native metadata methods; only the legacy paths share+//! this bounded dictionary adapter.++use super::*;+use dbx_types::oracle_trigger::{+ OracleTriggerDefinition, OracleTriggerError, OracleTriggerMetadata, OracleTriggerParent, OracleTriggerReadState,+};+use serde_json::{json, Value};+use std::pin::Pin;++#[cfg(test)]+#[path = "oracle_triggers_tests.rs"]+mod tests;++type ReadFuture = Pin<Box<dyn Future<Output = Result<db::QueryResult, String>> + Send>>;+type ReadQuery = Box<dyn FnMut(String) -> ReadFuture + Send>;++/// Full transport text alone does not prove a complete, same-target definition.+/// Keep the original export/partial source, but clamp the optional exact proof.+pub(super) fn validate_source_definition(source: &mut db::ObjectSource, owner: &str, name: &str) {+ use crate::object_source_sql::{+ prepare_oracle_trigger_sql, OracleTriggerSqlBinding, OracleTriggerSqlInput, OracleTriggerSqlPurpose,+ };+ if source.object_type != db::ObjectSourceKind::Trigger {+ return;+ }+ let Some(trigger) = source.trigger.as_mut() else {+ return;+ };+ let Some(metadata) = trigger.oracle_metadata.as_mut() else {+ return;+ };+ let identity_matches = metadata.contract_version == 1+ && metadata.owner == owner+ && metadata.name == name+ && trigger.name == name+ && source.name == name+ && source.schema.as_deref() == Some(owner);+ if !identity_matches {+ metadata+ .reads+ .insert("identity".into(), state("incomplete", "The source does not match the requested exact trigger"));+ }+ if !metadata.definition.as_ref().is_some_and(|definition| definition.complete) {+ return;+ }+ let result = (|| {+ if !identity_matches {+ return Err("Reload the exact trigger identity".to_string());+ }+ if !metadata.reads.get("definition").is_some_and(|read| read.state == "available") {+ return Err("The complete source read was not verified".to_string());+ }+ let database_type = match metadata.engine.as_str() {+ "oracle" => DatabaseType::Oracle,+ "oceanbase-oracle" => DatabaseType::OceanbaseOracle,+ "dm" => DatabaseType::Dameng,+ _ => return Err("The trigger engine profile was not verified".to_string()),+ };+ let binding = match metadata.scope.as_str() {+ "TABLE" | "VIEW" => {+ metadata.parent.as_ref().filter(|parent| parent.object_type == metadata.scope).map(|parent| {+ OracleTriggerSqlBinding {+ scope: metadata.scope.clone(),+ owner: Some(parent.owner.clone()),+ name: Some(parent.name.clone()),+ pluggable: false,+ }+ })+ }+ "SCHEMA" => metadata.scope_owner.as_ref().map(|owner| OracleTriggerSqlBinding {+ scope: "SCHEMA".into(),+ owner: Some(owner.clone()),+ name: None,+ pluggable: false,+ }),+ _ => None, // The plan verifies actual database/container context.+ };+ let definition = metadata.definition.as_ref().unwrap();+ prepare_oracle_trigger_sql(OracleTriggerSqlInput {+ database_type,+ owner: owner.to_string(),+ name: name.to_string(),+ source: source.source.clone(),+ purpose: OracleTriggerSqlPurpose::Inspect,+ binding,+ enabled: None,+ allow_export_appendix: definition.origin == "DBMS_METADATA" && definition.format == "ddl",+ })+ .and_then(|prepared| {+ let matches = match metadata.scope.as_str() {+ "TABLE" | "VIEW" => {+ prepared.header.scope == "RELATION" && (!prepared.header.view_only || metadata.scope == "VIEW")+ }+ "SCHEMA" | "DATABASE" | "TIMER" => prepared.header.scope == metadata.scope,+ _ => true,+ };+ if matches {+ Ok(())+ } else {+ Err("The source ON scope does not match the trigger dictionary; reload".to_string())+ }+ })+ })();+ if let Err(error) = result {+ metadata.definition.as_mut().unwrap().complete = false;+ metadata.reads.insert("definition".into(), state("incomplete", &error));+ }+}++pub(super) async fn agent_reader(+ client: Arc<db::agent_driver::PooledAgentClient>,+ database: &str,+ schema: &str,+ timeout: Option<Duration>,+) -> LegacyReader {+ let version = client+ .lock()+ .await+ .connection_info(timeout)+ .await+ .ok()+ .and_then(|info| info.database_info)+ .and_then(|info| info.product_version);+ let database = database.to_string();+ let schema = schema.to_string();+ LegacyReader::new(+ "oracle",+ version,+ Box::new(move |sql| {+ let client = client.clone();+ let params = agent_execute_query_params(+ &sql,+ Some(&database),+ Some(&schema),+ QueryExecutionOptions { max_rows: Some(i32::MAX as usize), ..Default::default() },+ );+ Box::pin(async move { client.lock().await.execute_query_with_timeout(params, timeout).await })+ }),+ )+}++pub(super) async fn pool_reader(pool: db::mysql::MySqlPool) -> LegacyReader {+ let version =+ db::mysql::database_connection_info(&pool, "OceanBase").await.ok().and_then(|info| info.product_version);+ LegacyReader::new(+ "oceanbase-oracle",+ version,+ Box::new(move |sql| {+ let pool = pool.clone();+ Box::pin(async move {+ db::mysql::execute_query_with_max_rows(+ &pool,+ &sql,+ true,+ Some(i32::MAX as usize),+ db::mysql::MySqlQueryDialect::for_connection(DatabaseType::OceanbaseOracle, None),+ )+ .await+ })+ }),+ )+}++#[allow(clippy::too_many_arguments)]+pub(super) async fn list_objects(+ state: &AppState,+ pool_key: &str,+ config: Option<&ConnectionConfig>,+ database: &str,+ schema: &str,+ filter: Option<&str>,+ limit: Option<usize>,+ offset: Option<usize>,+ object_types: Option<&[String]>,+ table_name_filter: Option<&TableNameFilter>,+ options: &MetadataReadOptions,+) -> Result<Option<ObjectListOutcome>, String> {+ let local_filter = table_name_filter.is_some_and(|filter| !filter.is_empty());+ let (page_limit, page_offset) = if local_filter { (None, None) } else { (limit, offset) };+ match state.pool_handle(pool_key).await {+ Some(PoolKind::ExternalDriver { config, session, .. }) => {+ let mut params = json!({"connection": config.as_ref(), "database": database, "schema": schema});+ options.apply_to(&mut params);+ if let Some(filter) = filter {+ params["filter"] = json!(filter);+ }+ if let Some(types) = object_types {+ params["object_types"] = json!(types);+ }+ if let Some(limit) = page_limit {+ params["limit"] = json!(limit);+ }+ if let Some(offset) = page_offset {+ params["offset"] = json!(offset);+ }+ let objects =+ session.invoke_with_timeout("listObjects", params, agent_metadata_timeout(Some(&config))).await?;+ Ok(Some(ObjectListOutcome { objects, paging_applied: !local_filter }))+ }+ Some(PoolKind::Agent(client))+ if config.is_some_and(|config| {+ matches!(config.db_type, DatabaseType::Oracle | DatabaseType::OceanbaseOracle | DatabaseType::Dameng)+ }) =>+ {+ let timeout = agent_metadata_timeout(config);+ let objects = if config+ .is_some_and(|config| config.db_type == DatabaseType::Oracle && !is_default_oracle_agent_config(config))+ {+ agent_reader(client, database, schema, timeout)+ .await+ .list_objects(schema, filter, page_limit, page_offset, object_types)+ .await?+ } else {+ client+ .lock()+ .await+ .list_objects_with_options(+ database,+ schema,+ filter,+ page_limit,+ page_offset,+ object_types,+ options,+ timeout,+ )+ .await?+ };+ let paging_applied = !local_filter;+ Ok(Some(ObjectListOutcome { objects, paging_applied }))+ }+ Some(PoolKind::Mysql(pool, MysqlMode::OceanBaseOracle)) => {+ let objects =+ pool_reader(pool).await.list_objects(schema, filter, page_limit, page_offset, object_types).await?;+ Ok(Some(ObjectListOutcome { objects, paging_applied: !local_filter }))+ }+ _ => Ok(None),+ }+}++pub(super) struct LegacyReader {+ engine: String,+ version: Option<String>,+ query: ReadQuery,+}++impl LegacyReader {+ fn new(engine: &str, version: Option<String>, query: ReadQuery) -> Self {+ Self { engine: engine.to_string(), version, query }+ }++ async fn read(&mut self, sql: String) -> Result<db::QueryResult, String> {+ let result = (self.query)(sql).await?;+ if result.truncated || result.has_more {+ return Err("Trigger dictionary read is incomplete; reload".to_string());+ }+ Ok(result)+ }++ async fn list_objects(+ &mut self,+ owner: &str,+ filter: Option<&str>,+ limit: Option<usize>,+ offset: Option<usize>,+ requested_types: Option<&[String]>,+ ) -> Result<Vec<db::ObjectInfo>, String> {+ require_identity(owner)?;+ if limit == Some(0) {+ return Ok(Vec::new());+ }+ const TYPES: &[&str] = &[+ "TABLE",+ "VIEW",+ "MATERIALIZED_VIEW",+ "PROCEDURE",+ "FUNCTION",+ "PACKAGE",+ "PACKAGE_BODY",+ "SEQUENCE",+ "SYNONYM",+ "INDEX",+ "TRIGGER",+ "TYPE",+ "TYPE_BODY",+ ];+ let types: Vec<String> = match requested_types.filter(|types| !types.is_empty()) {+ Some(types) => types+ .iter()+ .map(|value| value.to_ascii_uppercase().replace(' ', "_"))+ .filter(|value| TYPES.contains(&value.as_str()))+ .collect(),+ None => TYPES.iter().map(|value| value.to_string()).collect(),+ };+ if types.is_empty() {+ return Ok(Vec::new());+ }+ let types = types.iter().map(|value| sql_string(&value.replace('_', " "))).collect::<Vec<_>>().join(",");+ let predicate = filter.filter(|value| !value.trim().is_empty()).map(|filter| {+ let mut pattern = "%".to_string();+ for ch in filter.trim().to_uppercase().chars() {+ if matches!(ch, '~' | '%' | '_') { pattern.push('~'); }+ pattern.push(ch);+ pattern.push('%');+ }+ let pattern = sql_string(&pattern);+ format!(" AND (UPPER(o.OBJECT_NAME) LIKE {pattern} ESCAPE '~' OR UPPER(c.COMMENTS) LIKE {pattern} ESCAPE '~')")+ }).unwrap_or_default();+ let mut sql = format!("SELECT o.OBJECT_NAME, REPLACE(o.OBJECT_TYPE,' ','_') AS OBJECT_TYPE, o.OWNER, c.COMMENTS, i.TABLE_OWNER AS PARENT_SCHEMA, i.TABLE_NAME AS PARENT_NAME FROM ALL_OBJECTS o LEFT JOIN ALL_TAB_COMMENTS c ON c.OWNER=o.OWNER AND c.TABLE_NAME=o.OBJECT_NAME AND o.OBJECT_TYPE IN ('TABLE','VIEW') LEFT JOIN ALL_INDEXES i ON o.OBJECT_TYPE='INDEX' AND i.OWNER=o.OWNER AND i.INDEX_NAME=o.OBJECT_NAME WHERE o.OWNER={} AND o.OBJECT_TYPE IN ({types}) AND (o.OBJECT_TYPE<>'INDEX' OR i.GENERATED='N' OR i.GENERATED IS NULL){predicate} ORDER BY CASE o.OBJECT_TYPE WHEN 'TABLE' THEN 0 WHEN 'VIEW' THEN 1 WHEN 'MATERIALIZED VIEW' THEN 2 WHEN 'PROCEDURE' THEN 3 WHEN 'FUNCTION' THEN 4 WHEN 'SEQUENCE' THEN 5 WHEN 'SYNONYM' THEN 6 WHEN 'PACKAGE' THEN 7 ELSE 8 END,o.OBJECT_NAME,o.OWNER,o.OBJECT_ID", sql_string(owner));+ if limit.is_some() || offset.is_some_and(|offset| offset > 0) {+ let offset = offset.unwrap_or(0);+ let bound = match limit {+ Some(limit) => {+ format!(" WHERE ROWNUM <= {}", offset.checked_add(limit).ok_or("Metadata page overflow")?)+ }+ None => String::new(),+ };+ sql = format!("SELECT OBJECT_NAME,OBJECT_TYPE,OWNER,COMMENTS,PARENT_SCHEMA,PARENT_NAME FROM (SELECT dbx_page.*,ROWNUM DBX_RN FROM ({sql}) dbx_page{bound}) WHERE DBX_RN > {offset}");+ }+ let result = self.read(sql).await?;+ let mut objects = result+ .rows+ .iter()+ .map(|row| {+ Ok(db::ObjectInfo {+ name: required(&result, row, "OBJECT_NAME")?,+ object_type: required(&result, row, "OBJECT_TYPE")?,+ schema: Some(required(&result, row, "OWNER")?),+ comment: cell(&result, row, "COMMENTS"),+ valid: None,+ signature: None,+ custom_type_kind: None,+ has_members: None,+ created_at: None,+ updated_at: None,+ parent_schema: cell(&result, row, "PARENT_SCHEMA"),+ parent_name: cell(&result, row, "PARENT_NAME"),+ trigger: None,+ xugu_type_members_expandable: None,+ })+ })+ .collect::<Result<Vec<_>, String>>()?;+ let names = objects+ .iter()+ .filter(|object| object.object_type == "TRIGGER")+ .map(|object| object.name.clone())+ .collect::<Vec<_>>();+ for names in names.chunks(500) {+ let predicate = format!(+ "t.OWNER={} AND t.TRIGGER_NAME IN ({})",+ sql_string(owner),+ names.iter().map(|name| sql_string(name)).collect::<Vec<_>>().join(",")+ );+ let summaries = self.summaries(&predicate, false).await;+ for object in+ objects.iter_mut().filter(|object| object.object_type == "TRIGGER" && names.contains(&object.name))+ {+ let trigger = match &summaries {+ Ok(summaries) => summaries+ .iter()+ .find(|trigger| {+ trigger.name == object.name+ && trigger.oracle_metadata.as_ref().is_some_and(|meta| meta.owner == owner)+ })+ .cloned()+ .unwrap_or_else(|| {+ self.unknown(+ owner,+ &object.name,+ state("incomplete", "Trigger changed or is no longer visible; reload"),+ )+ }),+ Err(error) => self.unknown(owner, &object.name, failure(error)),+ };+ object.valid = trigger.valid;+ if let Some(parent) = trigger.oracle_metadata.as_ref().and_then(|meta| meta.parent.as_ref()) {+ object.parent_schema = Some(parent.owner.clone());+ object.parent_name = Some(parent.name.clone());+ }+ object.trigger = Some(trigger);+ }+ }+ Ok(objects)+ }++ pub(super) async fn list_triggers(&mut self, owner: &str, parent: &str) -> Result<Vec<db::TriggerInfo>, String> {+ require_identity(owner)?;+ require_identity(parent)?;+ self.summaries(&format!("t.TABLE_OWNER={} AND t.TABLE_NAME={}", sql_string(owner), sql_string(parent)), true)+ .await+ }++ async fn summaries(&mut self, predicate: &str, body: bool) -> Result<Vec<db::TriggerInfo>, String> {+ let body_column = if body { ",t.TRIGGER_BODY AS BODY" } else { "" };+ let result = self.read(format!("SELECT t.OWNER,t.TRIGGER_NAME,t.TRIGGERING_EVENT,t.TRIGGER_TYPE,t.STATUS AS ENABLED_STATUS,t.TABLE_OWNER,t.TABLE_NAME,t.BASE_OBJECT_TYPE,t.WHEN_CLAUSE,TO_CHAR(o.OBJECT_ID) AS OBJECT_ID,TO_CHAR(o.LAST_DDL_TIME,'YYYY-MM-DD HH24:MI:SS') AS LAST_DDL_TIME,o.STATUS AS VALIDITY{body_column} FROM ALL_TRIGGERS t LEFT JOIN ALL_OBJECTS o ON o.OWNER=t.OWNER AND o.OBJECT_NAME=t.TRIGGER_NAME AND o.OBJECT_TYPE='TRIGGER' WHERE {predicate} ORDER BY t.TRIGGER_NAME,t.OWNER,o.OBJECT_ID")).await?;+ let mut identities = HashSet::new();+ result+ .rows+ .iter()+ .map(|row| {+ let owner = required(&result, row, "OWNER")?;+ let name = required(&result, row, "TRIGGER_NAME")?;+ if !identities.insert((owner.clone(), name.clone())) {+ return Err("Trigger identity is not unique".to_string());+ }+ let enabled = match cell(&result, row, "ENABLED_STATUS").as_deref() {+ Some("ENABLED") => Some(true),+ Some("DISABLED") => Some(false),+ _ => None,+ };+ let valid = match cell(&result, row, "VALIDITY").as_deref() {+ Some("VALID") => Some(true),+ Some("INVALID") => Some(false),+ _ => None,+ };+ let mut metadata = self.metadata(&owner, &name);+ metadata.scope_type = cell(&result, row, "BASE_OBJECT_TYPE");+ metadata.scope = match metadata.scope_type.as_deref() {+ Some(scope @ ("TABLE" | "VIEW" | "SCHEMA" | "DATABASE")) => scope.to_string(),+ None => "UNKNOWN".to_string(),+ _ => "OTHER".to_string(),+ };+ let parent_owner = cell(&result, row, "TABLE_OWNER");+ let parent_name = cell(&result, row, "TABLE_NAME");+ if matches!(metadata.scope.as_str(), "TABLE" | "VIEW") {+ if let (Some(owner), Some(name)) = (parent_owner.clone(), parent_name) {+ metadata.parent = Some(OracleTriggerParent {+ owner,+ name,+ object_type: metadata.scope.clone(),+ object_id: None,+ });+ }+ } else if metadata.scope == "SCHEMA" {+ metadata.scope_owner = parent_owner;+ }+ metadata.object_id = cell(&result, row, "OBJECT_ID");+ metadata.last_ddl_time = cell(&result, row, "LAST_DDL_TIME");+ metadata.reads.insert("identity".into(), availability(metadata.object_id.is_some(), "Object ID"));+ metadata.reads.insert(+ "scope".into(),+ availability(+ metadata.scope != "UNKNOWN" && (metadata.scope != "SCHEMA" || metadata.scope_owner.is_some()),+ "Trigger scope",+ ),+ );+ metadata.reads.insert(+ "parent".into(),+ availability(+ match metadata.scope.as_str() {+ "TABLE" | "VIEW" => metadata.parent.is_some(),+ "UNKNOWN" | "OTHER" => false,+ _ => true,+ },+ "Owning object",+ ),+ );+ metadata.reads.insert("enabled".into(), availability(enabled.is_some(), "Enabled state"));+ metadata.reads.insert("validity".into(), availability(valid.is_some(), "Object validity"));+ Ok(db::TriggerInfo {+ name,+ event: cell(&result, row, "TRIGGERING_EVENT").unwrap_or_default(),+ timing: cell(&result, row, "TRIGGER_TYPE").unwrap_or_default(),+ level: None,+ language: None,+ comment: None,+ created_at: None,+ condition: cell(&result, row, "WHEN_CLAUSE"),+ statement: cell(&result, row, "BODY"),+ enabled,+ valid,+ oracle_metadata: Some(metadata),+ })+ })+ .collect()+ }++ pub(super) async fn source(&mut self, owner: &str, name: &str) -> Result<db::ObjectSource, String> {+ require_identity(owner)?;+ require_identity(name)?;+ let predicate = format!("t.OWNER={} AND t.TRIGGER_NAME={}", sql_string(owner), sql_string(name));+ let before = self.summaries(&predicate, true).await?;+ let mut source = db::ObjectSource {+ name: name.to_string(),+ object_type: db::ObjectSourceKind::Trigger,+ schema: Some(owner.to_string()),+ source: String::new(),+ editable: None,+ routine_parameters: None,+ trigger: None,+ };+ let Some(first) = before.first() else {+ source.editable = Some(false);+ let mut trigger = self.unknown(owner, name, availability(false, "Visible trigger"));+ trigger+ .oracle_metadata+ .as_mut()+ .unwrap()+ .reads+ .insert("identity".into(), state("empty", "No visible trigger with this exact owner/name"));+ source.trigger = Some(trigger);+ return Ok(source);+ };+ if first.name != name || first.oracle_metadata.as_ref().is_none_or(|meta| meta.owner != owner) {+ return Err("Trigger identity does not match the exact request".to_string());+ }+ let mut origin = "catalog-body";+ let mut format = "body";+ let mut definition_state = availability(false, "Complete trigger definition");+ let queries = [+ (+ format!(+ "SELECT LINE,TEXT FROM ALL_SOURCE WHERE OWNER={} AND NAME={} AND TYPE='TRIGGER' ORDER BY LINE",+ sql_string(owner),+ sql_string(name)+ ),+ "ALL_SOURCE",+ "declaration",+ ),+ (+ format!(+ "SELECT DBMS_METADATA.GET_DDL('TRIGGER',{}, {}) FROM DUAL",+ sql_string(name),+ sql_string(owner)+ ),+ "DBMS_METADATA",+ "ddl",+ ),+ ];+ for (sql, next_origin, next_format) in queries {+ match self.read(sql).await.and_then(|result| {+ let mut text = String::new();+ for (index, row) in result.rows.iter().enumerate() {+ if next_origin == "ALL_SOURCE" && cell(&result, row, "LINE") != Some((index + 1).to_string()) {+ return Err("Trigger source lines are incomplete".to_string());+ }+ let value = if next_origin == "ALL_SOURCE" {+ cell(&result, row, "TEXT")+ } else {+ row.first().and_then(Value::as_str).map(str::to_string)+ };+ text.push_str(&value.ok_or("Trigger source text is unreadable")?);+ }+ Ok(text)+ }) {+ Ok(text) if !text.trim().is_empty() => {+ source.source = text;+ origin = next_origin;+ format = next_format;+ definition_state = available();+ break;+ }+ Ok(_) => {}+ Err(error) => definition_state = failure(&error),+ }+ }+ if source.source.is_empty() {+ source.source = first.statement.clone().unwrap_or_default();+ }+ let (errors, error_state) = match self.errors(owner, name).await {+ Ok(errors) => (Some(errors), available()),+ Err(error) => (None, failure(&error)),+ };+ let after = self.summaries(&predicate, true).await?;+ let stable = json!(before) == json!(after);+ let mut trigger = after.into_iter().next().unwrap_or_else(|| first.clone());+ let metadata = trigger.oracle_metadata.as_mut().ok_or("Missing trigger metadata")?;+ metadata.definition = Some(OracleTriggerDefinition {+ origin: origin.to_string(),+ format: format.to_string(),+ complete: stable && definition_state.state == "available" && format != "body",+ });+ metadata.errors = errors;+ metadata.reads.insert("definition".into(), definition_state);+ metadata.reads.insert("errors".into(), error_state);+ if !stable {+ let changed = state("incomplete", "Trigger changed while loading; reload");+ metadata.reads.insert("identity".into(), changed.clone());+ metadata.reads.insert("definition".into(), changed);+ }+ source.trigger = Some(trigger);+ Ok(source)+ }++ async fn errors(&mut self, owner: &str, name: &str) -> Result<Vec<OracleTriggerError>, String> {+ let result = self.read(format!("SELECT SEQUENCE,LINE,POSITION,TEXT,ATTRIBUTE FROM ALL_ERRORS WHERE OWNER={} AND NAME={} AND TYPE='TRIGGER' ORDER BY SEQUENCE", sql_string(owner), sql_string(name))).await?;+ result+ .rows+ .iter()+ .map(|row| {+ let number = |column: &str| {+ required(&result, row, column)?+ .parse::<i64>()+ .map_err(|_| "Trigger error location is unreadable".to_string())+ };+ Ok(OracleTriggerError {+ sequence: number("SEQUENCE")?,+ line: number("LINE")?,+ position: number("POSITION")?,+ text: required(&result, row, "TEXT")?,+ severity: cell(&result, row, "ATTRIBUTE"),+ })+ })+ .collect()+ }++ fn metadata(&self, owner: &str, name: &str) -> OracleTriggerMetadata {+ OracleTriggerMetadata {+ contract_version: 1,+ identity_mode: MetadataIdentityMode::Exact,+ engine: self.engine.clone(),+ engine_version: self.version.clone(),+ owner: owner.to_string(),+ name: name.to_string(),+ scope: "UNKNOWN".to_string(),+ scope_type: None,+ scope_owner: None,+ parent: None,+ object_id: None,+ last_ddl_time: None,+ definition: None,+ errors: None,+ reads: BTreeMap::new(),+ }+ }++ fn unknown(&self, owner: &str, name: &str, failure: OracleTriggerReadState) -> db::TriggerInfo {+ let mut metadata = self.metadata(owner, name);+ for field in ["identity", "scope", "parent", "enabled", "validity"] {+ metadata.reads.insert(field.to_string(), failure.clone());+ }+ db::TriggerInfo {+ name: name.to_string(),+ event: String::new(),+ timing: String::new(),+ level: None,+ language: None,+ comment: None,+ created_at: None,+ condition: None,+ statement: None,+ enabled: None,+ valid: None,+ oracle_metadata: Some(metadata),+ }+ }+}++fn require_identity(value: &str) -> Result<(), String> {+ if value.is_empty() {+ Err("Exact trigger metadata requires an owner and name".to_string())+ } else {+ Ok(())+ }+}++fn cell(result: &db::QueryResult, row: &[Value], column: &str) -> Option<String> {+ let index = result.columns.iter().position(|candidate| candidate.eq_ignore_ascii_case(column))?;+ match row.get(index)? {+ Value::Null => None,+ Value::String(value) => Some(value.clone()),+ value if value.is_number() => Some(value.to_string()),+ _ => None,+ }+}++fn required(result: &db::QueryResult, row: &[Value], column: &str) -> Result<String, String> {+ cell(result, row, column).ok_or_else(|| format!("Trigger metadata column {column} is unreadable"))+}++fn state(value: &str, message: &str) -> OracleTriggerReadState {+ OracleTriggerReadState { state: value.to_string(), message: (!message.is_empty()).then(|| message.to_string()) }+}++fn available() -> OracleTriggerReadState {+ state("available", "")+}++fn availability(available: bool, field: &str) -> OracleTriggerReadState {+ if available {+ self::available()+ } else {+ state("unavailable", &format!("{field} is not exposed by this dictionary"))+ }+}++fn failure(error: &str) -> OracleTriggerReadState {+ let code = if error.contains("ORA-01031") {+ "denied"+ } else if error.contains("ORA-00942") || error.contains("ORA-00904") {+ "unavailable"+ } else if error.contains("incomplete") {+ "incomplete"+ } else {+ "error"+ };+ state(code, "Trigger metadata read failed; reload or check dictionary access")+}diff --git a/crates/dbx-core/src/schema/oracle_triggers_tests.rs b/crates/dbx-core/src/schema/oracle_triggers_tests.rsnew file mode 100644index 0000000000..80c8f480b3--- /dev/null+++ b/crates/dbx-core/src/schema/oracle_triggers_tests.rs@@ -0,0 +1,356 @@+use super::*;+use std::sync::Mutex;++fn result(columns: &[&str], rows: Value) -> db::QueryResult {+ serde_json::from_value(json!({ "columns": columns, "rows": rows, "affected_rows": 0, "execution_time_ms": 0 }))+ .unwrap()+}++fn summary(id: &str, scope: &str) -> db::QueryResult {+ result(+ &[+ "OWNER",+ "TRIGGER_NAME",+ "TRIGGERING_EVENT",+ "TRIGGER_TYPE",+ "ENABLED_STATUS",+ "TABLE_OWNER",+ "TABLE_NAME",+ "BASE_OBJECT_TYPE",+ "OBJECT_ID",+ "LAST_DDL_TIME",+ "VALIDITY",+ "BODY",+ ],+ json!([[+ " Owner ",+ " Trigger ",+ "UPDATE",+ "BEFORE EACH ROW",+ "DISABLED",+ " Parent Owner ",+ if scope == "SCHEMA" { None } else { Some(" Parent ") },+ scope,+ id,+ "2026-10-21 08:00:00",+ "INVALID",+ "BEGIN NULL; END;"+ ]]),+ )+}++fn reader(mut boundary: impl FnMut(&str) -> Result<db::QueryResult, String> + Send + 'static) -> LegacyReader {+ LegacyReader::new(+ "oceanbase-oracle",+ Some("4.2.5.7".to_string()),+ Box::new(move |sql| {+ let response = boundary(&sql);+ Box::pin(async move { response })+ }),+ )+}++fn source_contract(text: &str, origin: &str) -> db::ObjectSource {+ serde_json::from_value(json!({+ "name":" Trigger ","schema":" Owner ","object_type":"TRIGGER","source":text,+ "trigger":{"name":" Trigger ","event":"UPDATE","timing":"BEFORE EACH ROW","enabled":false,"valid":false,+ "oracle_metadata":{"contractVersion":1,"identityMode":"exact","engine":"oceanbase-oracle","owner":" Owner ","name":" Trigger ","scope":"TABLE",+ "parent":{"owner":" Parent Owner ","name":" Parent ","objectType":"TABLE"},"objectId":"9007199254740993",+ "definition":{"origin":origin,"format":if origin == "DBMS_METADATA" {"ddl"} else {"declaration"},"complete":true},+ "reads":{"identity":{"state":"available"},"definition":{"state":"available"}},"errors":[{"sequence":1,"line":4,"position":7,"text":"Missing procedure"}]}}+ })).unwrap()+}++#[test]+fn complete_source_contract_is_clamped_at_the_core_boundary_without_discarding_raw_text_or_diagnostics() {+ let full = "TRIGGER \" Owner \".\" Trigger \" BEFORE INSERT ON \" Parent Owner \".\" Parent \" BEGIN NULL; END";+ for text in [+ full.replace("END", ""),+ full.replace("\" Trigger \"", "\"trigger\""),+ full.replace("\" Parent Owner \"", "\" Owner \""),+ format!("{full}; DROP TABLE \" Parent Owner \".\" Parent \";"),+ ] {+ let mut source = source_contract(&text, "ALL_SOURCE");+ validate_source_definition(&mut source, " Owner ", " Trigger ");+ let metadata = source.trigger.unwrap().oracle_metadata.unwrap();+ assert!(!metadata.definition.unwrap().complete, "{text}");+ assert_eq!(metadata.reads["definition"].state, "incomplete");+ assert_eq!(metadata.errors.unwrap()[0].text, "Missing procedure");+ assert_eq!(source.source, text);+ }+ let mut source = source_contract(full, "ALL_SOURCE");+ validate_source_definition(&mut source, " Owner ", " Trigger ");+ assert!(source.trigger.unwrap().oracle_metadata.unwrap().definition.unwrap().complete);+ assert_eq!(source.source, full);+ for scope in ["DATABASE", "TIMER"] {+ let mut source = source_contract(full, "ALL_SOURCE");+ let metadata = source.trigger.as_mut().unwrap().oracle_metadata.as_mut().unwrap();+ metadata.scope = scope.to_string();+ metadata.parent = None;+ validate_source_definition(&mut source, " Owner ", " Trigger ");+ assert!(!source.trigger.unwrap().oracle_metadata.unwrap().definition.unwrap().complete);+ }+}++#[test]+fn only_trusted_same_target_get_ddl_state_appendices_remain_complete() {+ let text = "CREATE TRIGGER \" Owner \".\" Trigger \" BEFORE INSERT ON \" Parent Owner \".\" Parent \" BEGIN NULL; END;\nALTER TRIGGER \" Owner \".\" Trigger \" DISABLE;";+ for (origin, complete) in [("DBMS_METADATA", true), ("ALL_SOURCE", false)] {+ let mut source = source_contract(text, origin);+ validate_source_definition(&mut source, " Owner ", " Trigger ");+ assert_eq!(source.trigger.unwrap().oracle_metadata.unwrap().definition.unwrap().complete, complete);+ assert_eq!(source.source, text);+ }+ let mut source = source_contract(text, "DBMS_METADATA");+ validate_source_definition(&mut source, " Owner ", "Trigger");+ let metadata = source.trigger.unwrap().oracle_metadata.unwrap();+ assert!(!metadata.definition.unwrap().complete);+ assert_eq!(metadata.reads["identity"].state, "incomplete");+}++#[tokio::test]+async fn visible_empty_identity_is_explicit_and_read_errors_do_not_claim_absence() {+ let mut empty = reader(|_| Ok(result(&["OWNER", "TRIGGER_NAME"], json!([]))));+ let source = empty.source(" Owner ", " Trigger ").await.unwrap();+ let metadata = source.trigger.unwrap().oracle_metadata.unwrap();+ assert_eq!(metadata.reads["identity"].state, "empty");+ assert_eq!(metadata.owner, " Owner ");+ assert_eq!(metadata.name, " Trigger ");+ assert!(metadata.object_id.is_none());+ assert!(metadata.definition.is_none());+ let mut denied = reader(|_| Err("ORA-01031".to_string()));+ assert!(denied.source(" Owner ", " Trigger ").await.unwrap_err().contains("ORA-01031"));+}++#[tokio::test]+async fn legacy_schema_discovery_filters_then_pages_and_enriches_only_the_page() {+ let calls = Arc::new(Mutex::new(Vec::new()));+ let recorded = calls.clone();+ let mut reader = reader(move |sql| {+ recorded.lock().unwrap().push(sql.to_string());+ if sql.contains("FROM ALL_OBJECTS o LEFT JOIN ALL_TAB_COMMENTS") {+ return Ok(result(+ &["OBJECT_NAME", "OBJECT_TYPE", "OWNER", "COMMENTS"],+ json!([[" Trigger ", "TRIGGER", " Owner ", null]]),+ ));+ }+ assert!(sql.contains("t.OWNER=' Owner ' AND t.TRIGGER_NAME IN (' Trigger ')"), "{sql}");+ Ok(summary("9007199254740993", "VIEW"))+ });+ let objects =+ reader.list_objects(" Owner ", Some("tri%"), Some(1), Some(2), Some(&["TRIGGER".to_string()])).await.unwrap();+ assert_eq!(objects.len(), 1);+ assert_eq!(objects[0].name, " Trigger ");+ assert_eq!(objects[0].parent_schema.as_deref(), Some(" Parent Owner "));+ let trigger = objects[0].trigger.as_ref().unwrap();+ assert_eq!((trigger.enabled, trigger.valid), (Some(false), Some(false)));+ assert_eq!(trigger.oracle_metadata.as_ref().unwrap().object_id.as_deref(), Some("9007199254740993"));+ let calls = calls.lock().unwrap();+ assert_eq!(calls.len(), 2);+ let query = &calls[0];+ assert!(query.contains("o.OWNER=' Owner '"));+ assert!(query.contains("'%T%R%I%~%%'"));+ assert!(query.find("LIKE").unwrap() < query.find("ORDER BY").unwrap());+ assert!(query.contains("ROWNUM <= 3") && query.contains("DBX_RN > 2"));+ assert!(!calls.iter().any(|query| query.contains("ALL_SOURCE")));+}++#[tokio::test]+async fn mixed_and_default_exact_lists_keep_type_specs_and_bodies_in_the_same_page() {+ for requested in [Some(vec!["TRIGGER".to_string(), "TYPE".to_string(), "TYPE_BODY".to_string()]), None] {+ let mut reader = reader(|sql| {+ if sql.contains("FROM ALL_OBJECTS o LEFT JOIN ALL_TAB_COMMENTS") {+ assert!(sql.contains("o.OWNER=' Owner '"), "{sql}");+ assert!(sql.contains("'TYPE'") && sql.contains("'TYPE BODY'") && sql.contains("'TRIGGER'"), "{sql}");+ assert!(sql.contains("ROWNUM <= 5") && sql.contains("DBX_RN > 2"), "{sql}");+ return Ok(result(+ &["OBJECT_NAME", "OBJECT_TYPE", "OWNER", "COMMENTS"],+ json!([+ [" Trigger ", "TRIGGER", " Owner ", null],+ [" Type ", "TYPE", " Owner ", null],+ [" Type ", "TYPE_BODY", " Owner ", null]+ ]),+ ));+ }+ assert!(sql.contains("t.TRIGGER_NAME IN (' Trigger ')"), "{sql}");+ Ok(summary("42", "VIEW"))+ });+ let objects = reader.list_objects(" Owner ", None, Some(3), Some(2), requested.as_deref()).await.unwrap();+ assert_eq!(+ objects.iter().map(|object| object.object_type.as_str()).collect::<Vec<_>>(),+ ["TRIGGER", "TYPE", "TYPE_BODY"]+ );+ assert_eq!(+ objects[0].trigger.as_ref().unwrap().oracle_metadata.as_ref().unwrap().object_id.as_deref(),+ Some("42")+ );+ for object in &objects[1..] {+ assert_eq!(object.name, " Type ");+ assert_eq!(object.schema.as_deref(), Some(" Owner "));+ assert!(object.trigger.is_none());+ }+ }+}++#[tokio::test]+async fn legacy_exact_lists_preserve_indexes_and_parent_identity_before_paging() {+ for requested in [Some(vec!["INDEX".to_string()]), Some(vec!["TRIGGER".to_string(), "INDEX".to_string()]), None] {+ let mut reader = reader(|sql| {+ assert!(sql.contains("'INDEX'"), "{sql}");+ assert!(sql.contains("i.OWNER=o.OWNER AND i.INDEX_NAME=o.OBJECT_NAME"), "{sql}");+ assert!(sql.contains("i.GENERATED='N' OR i.GENERATED IS NULL"), "{sql}");+ assert!(+ sql.starts_with("SELECT OBJECT_NAME,OBJECT_TYPE,OWNER,COMMENTS,PARENT_SCHEMA,PARENT_NAME"),+ "{sql}"+ );+ assert!(sql.find("LIKE").unwrap() < sql.find("ORDER BY").unwrap(), "{sql}");+ assert!(sql.contains("ROWNUM <= 3") && sql.contains("DBX_RN > 2"), "{sql}");+ Ok(result(+ &["OBJECT_NAME", "OBJECT_TYPE", "OWNER", "COMMENTS", "PARENT_SCHEMA", "PARENT_NAME"],+ json!([[" Index ", "INDEX", " Owner ", null, " Parent Owner ", " Parent "]]),+ ))+ });+ let objects =+ reader.list_objects(" Owner ", Some("index"), Some(1), Some(2), requested.as_deref()).await.unwrap();+ assert_eq!(objects.len(), 1);+ assert_eq!(objects[0].name, " Index ");+ assert_eq!(objects[0].schema.as_deref(), Some(" Owner "));+ assert_eq!(objects[0].parent_schema.as_deref(), Some(" Parent Owner "));+ assert_eq!(objects[0].parent_name.as_deref(), Some(" Parent "));+ assert!(objects[0].trigger.is_none());+ }+}++#[tokio::test]+async fn legacy_parent_list_uses_parent_owner_instead_of_trigger_owner() {+ let mut reader = reader(|sql| {+ assert!(sql.contains("t.TABLE_OWNER=' Parent Owner ' AND t.TABLE_NAME=' Parent '"), "{sql}");+ Ok(summary("1", "VIEW"))+ });+ let triggers = reader.list_triggers(" Parent Owner ", " Parent ").await.unwrap();+ let metadata = triggers[0].oracle_metadata.as_ref().unwrap();+ assert_eq!(metadata.owner, " Owner ");+ assert_eq!(metadata.parent.as_ref().unwrap().owner, " Parent Owner ");+ assert_eq!(metadata.parent.as_ref().unwrap().object_type, "VIEW");+}++#[tokio::test]+async fn legacy_schema_source_has_no_fabricated_table_parent() {+ let mut reader = reader(|sql| {+ if sql.contains("ALL_TRIGGERS") {+ return Ok(summary("1", "SCHEMA"));+ }+ if sql.contains("ALL_SOURCE") {+ return Ok(result(&["LINE", "TEXT"], json!([[1, "TRIGGER t AFTER CREATE ON SCHEMA BEGIN NULL; END;"]])));+ }+ Ok(result(&["SEQUENCE", "LINE", "POSITION", "TEXT", "ATTRIBUTE"], json!([])))+ });+ let source = reader.source(" Owner ", " Trigger ").await.unwrap();+ let metadata = source.trigger.unwrap().oracle_metadata.unwrap();+ assert_eq!(metadata.scope_owner.as_deref(), Some(" Parent Owner "));+ assert!(metadata.parent.is_none());+}++#[tokio::test]+async fn exact_getddl_fallback_never_substitutes_current_schema_for_a_whitespace_owner() {+ let mut reader = reader(|sql| {+ if sql.contains("ALL_TRIGGERS") {+ let mut response = summary("1", "TABLE");+ response.rows[0][0] = json!(" ");+ return Ok(response);+ }+ if sql.contains("ALL_SOURCE") {+ return Ok(result(&["LINE", "TEXT"], json!([])));+ }+ if sql.contains("GET_DDL") {+ assert!(sql.contains("GET_DDL('TRIGGER',' Trigger ', ' ')"), "{sql}");+ return Ok(result(+ &["DDL"],+ json!([["CREATE TRIGGER \" \".\" Trigger \" BEFORE INSERT ON T BEGIN NULL; END;"]]),+ ));+ }+ Ok(result(&["SEQUENCE", "LINE", "POSITION", "TEXT", "ATTRIBUTE"], json!([])))+ });+ let source = reader.source(" ", " Trigger ").await.unwrap();+ assert!(source.source.contains("\" \".\" Trigger \""));+}++#[tokio::test]+async fn legacy_source_keeps_long_definition_and_reads_validity_separately_from_errors() {+ let text = format!(+ "TRIGGER \" Trigger \" BEFORE UPDATE ON \" Parent Owner \".\" Parent \" BEGIN /* {} */ NULL; END;",+ "中文😀".repeat(12_000)+ );+ let expected = text.clone();+ let mut reader = reader(move |sql| {+ assert!(!sql.contains("SHOW CREATE"));+ if sql.contains("ALL_TRIGGERS") {+ return Ok(summary("9007199254740993", "TABLE"));+ }+ if sql.contains("ALL_SOURCE") {+ return Ok(result(&["LINE", "TEXT"], json!([[1, text]])));+ }+ assert!(sql.contains("ALL_ERRORS"), "{sql}");+ Ok(result(+ &["SEQUENCE", "LINE", "POSITION", "TEXT", "ATTRIBUTE"],+ json!([[1, 7, 4, "Missing procedure", "ERROR"]]),+ ))+ });+ let source = reader.source(" Owner ", " Trigger ").await.unwrap();+ assert_eq!(source.source, expected);+ let trigger = source.trigger.unwrap();+ let metadata = trigger.oracle_metadata.unwrap();+ assert!(metadata.definition.unwrap().complete);+ assert_eq!(metadata.errors.unwrap()[0].text, "Missing procedure");+ assert_eq!((trigger.enabled, trigger.valid), (Some(false), Some(false)));+}++#[tokio::test]+async fn legacy_export_appendix_survives_reading_but_concurrent_replacement_invalidates_baseline() {+ let mut reads = 0;+ let export = "CREATE TRIGGER \" Owner \".\" Trigger \" BEFORE INSERT ON T BEGIN NULL; END;\nALTER TRIGGER \" Owner \".\" Trigger \" DISABLE;";+ let mut reader = reader(move |sql| {+ if sql.contains("ALL_TRIGGERS") {+ reads += 1;+ return Ok(summary(if reads == 1 { "1" } else { "2" }, "TABLE"));+ }+ if sql.contains("ALL_SOURCE") {+ return Ok(result(&["LINE", "TEXT"], json!([])));+ }+ if sql.contains("GET_DDL") {+ return Ok(result(&["DDL"], json!([[export]])));+ }+ Ok(result(&["SEQUENCE", "LINE", "POSITION", "TEXT", "ATTRIBUTE"], json!([])))+ });+ let source = reader.source(" Owner ", " Trigger ").await.unwrap();+ assert_eq!(source.source, export);+ let metadata = source.trigger.unwrap().oracle_metadata.unwrap();+ assert!(!metadata.definition.unwrap().complete);+ assert_eq!(metadata.reads["identity"].state, "incomplete");+}++#[tokio::test]+async fn legacy_truncated_or_gapped_source_and_denied_errors_do_not_become_complete_or_empty() {+ for truncated in [true, false] {+ let mut reader = reader(move |sql| {+ if sql.contains("ALL_TRIGGERS") {+ return Ok(summary("1", "TABLE"));+ }+ if sql.contains("ALL_SOURCE") {+ let mut response = result(&["LINE", "TEXT"], json!([[2, "TRIGGER partial BEGIN NULL; END;"]]));+ response.truncated = truncated;+ return Ok(response);+ }+ if sql.contains("GET_DDL") {+ return Err("ORA-01031".to_string());+ }+ Err("ORA-01031".to_string())+ });+ let source = reader.source(" Owner ", " Trigger ").await.unwrap();+ assert_eq!(source.source, "BEGIN NULL; END;");+ let metadata = source.trigger.unwrap().oracle_metadata.unwrap();+ assert!(!metadata.definition.unwrap().complete);+ assert!(metadata.errors.is_none());+ assert_eq!(metadata.reads["errors"].state, "denied");+ }+}diff --git a/crates/dbx-core/src/schema/trigger_metadata_routing_tests.rs b/crates/dbx-core/src/schema/trigger_metadata_routing_tests.rsnew file mode 100644index 0000000000..7e223c0714--- /dev/null+++ b/crates/dbx-core/src/schema/trigger_metadata_routing_tests.rs@@ -0,0 +1,152 @@+use super::*;+use crate::plugins::{+ InstalledPlugin, PluginCompatibility, PluginDriverManifest, PluginDriverSession, PluginManifest, PluginRuntimeEnv,+};+use std::os::unix::fs::PermissionsExt;++async fn jdbc_fixture() -> (tempfile::TempDir, AppState) {+ let dir = tempfile::tempdir().unwrap();+ let executable = dir.path().join("plugin.py");+ std::fs::write(&executable, r#"#!/usr/bin/env python3+import json, pathlib, sys+metadata = {'contractVersion': 1, 'identityMode': 'exact', 'engine': 'oracle', 'engineVersion': '19', 'owner': ' Owner ', 'name': ' Trigger ', 'scope': 'VIEW', 'parent': {'owner': ' Parent Owner ', 'name': ' Parent ', 'objectType': 'VIEW'}, 'objectId': '9007199254740993', 'reads': {'identity': {'state': 'available'}}}+trigger = {'name': ' Trigger ', 'event': 'UPDATE', 'timing': 'INSTEAD OF', 'enabled': True, 'valid': False, 'oracle_metadata': metadata}+for line in sys.stdin:+ request = json.loads(line)+ params = request.get('params', {})+ with pathlib.Path(__file__).with_name('calls.jsonl').open('a') as log:+ log.write(json.dumps(request) + '\n')+ if params.get('schema') == 'missing-method':+ response = {'id': request['id'], 'error': {'code': -32601, 'message': 'Unsupported JDBC plugin method: ' + request['method']}}+ else:+ if request['method'] == 'listObjects':+ result = [{'name': trigger['name'], 'object_type': 'TRIGGER', 'schema': metadata['owner'], 'trigger': trigger}]+ elif request['method'] == 'listTriggers':+ result = [trigger]+ elif request['method'] == 'getObjectSource':+ result = {'name': trigger['name'], 'schema': metadata['owner'], 'object_type': 'TRIGGER', 'source': 'TRIGGER complete declaration', 'trigger': trigger}+ else:+ result = {}+ response = {'id': request['id'], 'result': result}+ print(json.dumps(response), flush=True)+"#).unwrap();+ std::fs::set_permissions(&executable, std::fs::Permissions::from_mode(0o755)).unwrap();+ let plugin = InstalledPlugin {+ manifest: PluginManifest {+ id: "jdbc".into(),+ name: "JDBC".into(),+ version: "test".into(),+ protocol_version: 1,+ executable: Some("plugin.py".into()),+ drivers: vec![PluginDriverManifest {+ id: "jdbc".into(),+ label: "JDBC".into(),+ kind: "external".into(),+ database_type: Some("jdbc".into()),+ }],+ ..Default::default()+ },+ path: dir.path().to_path_buf(),+ compatibility: PluginCompatibility {+ compatible: true,+ backend_executable: Some(executable),+ ..Default::default()+ },+ provenance: None,+ };+ let session = Arc::new(+ PluginDriverSession::start_for_test(plugin, "jdbc".into(), PluginRuntimeEnv::default()).await.unwrap(),+ );+ let state = AppState::new(crate::persistence::test_storage::open(&dir.path().join("dbx.db")).await.unwrap());+ let config: ConnectionConfig = serde_json::from_value(serde_json::json!({"id":"jdbc-trigger", "name":"JDBC trigger routing test", "db_type":"jdbc", "host":"127.0.0.1", "port":1521, "username":"fixture", "password":"", "database":"demo", "connection_string":"jdbc:oracle:thin:@127.0.0.1:1521/demo"})).unwrap();+ state.configs.write().await.insert(config.id.clone(), config.clone());+ state+ .update_connection_pools(|pools| {+ pools.insert(+ config.id.clone(),+ PoolKind::ExternalDriver { driver_id: "jdbc".into(), config: Arc::new(config), session },+ );+ })+ .await;+ (dir, state)+}++fn calls(dir: &tempfile::TempDir) -> Vec<serde_json::Value> {+ std::fs::read_to_string(dir.path().join("calls.jsonl"))+ .unwrap()+ .lines()+ .map(|line| serde_json::from_str(line).unwrap())+ .collect()+}++#[tokio::test]+async fn core_routes_exact_reads_to_the_existing_jdbc_methods_and_does_not_page_twice() {+ let (dir, state) = jdbc_fixture().await;+ let options =+ MetadataReadOptions { identity_mode: Some(MetadataIdentityMode::Exact), catalog: Some(" Catalog ".into()) };+ let objects = super::list_objects_core_with_options(+ &state,+ "jdbc-trigger",+ "demo",+ " Owner ",+ Some("trig"),+ Some(1),+ Some(2),+ Some(&["TRIGGER".into()]),+ None,+ &options,+ )+ .await+ .unwrap();+ assert_eq!(objects.len(), 1);+ let triggers =+ super::list_triggers_core_with_options(&state, "jdbc-trigger", "demo", " Parent Owner ", " Parent ", &options)+ .await+ .unwrap();+ assert_eq!(triggers[0].oracle_metadata.as_ref().unwrap().owner, " Owner ");+ let source = super::get_object_source_core_with_options(+ &state,+ "jdbc-trigger",+ "demo",+ " Owner ",+ " Trigger ",+ db::ObjectSourceKind::Trigger,+ None,+ None,+ &options,+ )+ .await+ .unwrap();+ assert_eq!(source.trigger.unwrap().oracle_metadata.unwrap().object_id.as_deref(), Some("9007199254740993"));+ let calls = calls(&dir);+ for request in &calls {+ assert_eq!(request["params"]["identity_mode"], "exact");+ assert_eq!(request["params"]["catalog"], " Catalog ");+ }+ assert_eq!(calls[0]["method"], "listObjects");+ assert_eq!(calls[0]["params"]["limit"], 1);+ assert_eq!(calls[0]["params"]["offset"], 2);+ assert_eq!(calls[1]["method"], "listTriggers");+ assert_eq!(calls[1]["params"]["schema"], " Parent Owner ");+ assert_eq!(calls[1]["params"]["table"], " Parent ");+ assert_eq!(calls[2]["method"], "getObjectSource");+ assert_eq!(calls[2]["params"]["schema"], " Owner ");+ assert_eq!(calls[2]["params"]["name"], " Trigger ");+ state.shutdown(Duration::from_secs(2)).await;+}++#[tokio::test]+async fn old_plugin_keeps_default_empty_trigger_contract_but_exact_request_reports_missing_method() {+ let (dir, state) = jdbc_fixture().await;+ assert!(super::list_triggers_core(&state, "jdbc-trigger", "demo", "missing-method", "T").await.unwrap().is_empty());+ let options = MetadataReadOptions { identity_mode: Some(MetadataIdentityMode::Exact), catalog: None };+ let error = super::list_triggers_core_with_options(&state, "jdbc-trigger", "demo", "missing-method", "T", &options)+ .await+ .unwrap_err();+ assert!(error.contains("listTriggers"), "{error}");+ let calls = calls(&dir);+ assert_eq!(calls.len(), 2);+ assert!(calls[0]["params"].get("identity_mode").is_none());+ assert_eq!(calls[1]["params"]["identity_mode"], "exact");+ state.shutdown(Duration::from_secs(2)).await;+}diff --git a/crates/dbx-core/tests/native_job_catalog.rs b/crates/dbx-core/tests/native_job_catalog.rsnew file mode 100644index 0000000000..db3471cb07--- /dev/null+++ b/crates/dbx-core/tests/native_job_catalog.rs@@ -0,0 +1,283 @@+use dbx_core::schema::native_jobs::{read_native_job_catalog_part_with, NativeJobCatalogFailure};+use dbx_sql::native_jobs::{NativeJobCatalogDialect, NativeJobCatalogPart, NativeJobCatalogQuery};+use dbx_types::native_jobs::{NativeJobMetadata, NativeJobRef, NativeJobScope};+use serde_json::{json, Value};+use std::collections::VecDeque;++fn target() -> NativeJobRef {+ NativeJobRef::Scheduler {+ scope: NativeJobScope { connection_id: "connection".into(), database: "".into(), context_id: "context".into() },+ owner: "Owner".into(),+ name: "Job".into(),+ }+}++fn result(columns: &[&str], rows: Value) -> Value {+ json!({ "columns": columns, "rows": rows, "affected_rows": 0, "execution_time_ms": 1 })+}++fn no_query(_: NativeJobCatalogQuery) -> std::future::Ready<Result<Value, NativeJobCatalogFailure>> {+ panic!("must not query")+}++#[tokio::test]+async fn catalog_fallback_requires_visibility_failure_not_an_empty_result() {+ let mut calls = Vec::new();+ let section = read_native_job_catalog_part_with(+ NativeJobCatalogDialect::Oracle,+ &target(),+ NativeJobCatalogPart::Definition,+ |query| {+ calls.push(query.source);+ std::future::ready(Ok(result(&["OWNER", "JOB_NAME"], json!([]))))+ },+ )+ .await+ .unwrap();+ assert!(matches!(section.data, NativeJobMetadata::Empty));+ assert_eq!(calls, ["SYS.DBA_SCHEDULER_JOBS"]);+ assert_eq!(section.source, Some("SYS.DBA_SCHEDULER_JOBS"));+}++#[tokio::test]+async fn owned_fallback_preserves_values_and_reports_the_limited_source() {+ let mut responses = VecDeque::from([+ Err(NativeJobCatalogFailure::sql(NativeJobCatalogDialect::Oracle, Some(1031), None)),+ Err(NativeJobCatalogFailure::sql(NativeJobCatalogDialect::Oracle, Some(942), None)),+ Ok(result(+ &["DBX_OWNER", "JOB_NAME", "JOB_ACTION", "JOB_CLASS", "END_DATE"],+ json!([["Owner", "Job", "BEGIN work; END;", "custom_class", null]]),+ )),+ ]);+ let section = read_native_job_catalog_part_with(+ NativeJobCatalogDialect::Oracle,+ &target(),+ NativeJobCatalogPart::Definition,+ |_| std::future::ready(responses.pop_front().unwrap()),+ )+ .await+ .unwrap();+ assert_eq!(section.source, Some("SYS.USER_SCHEDULER_JOBS"));+ assert_eq!(section.failures.len(), 2);+ let NativeJobMetadata::Available { value } = section.data else { panic!("definition unavailable") };+ assert_eq!(value[0]["JOB_ACTION"], "BEGIN work; END;");+ assert_eq!(value[0]["JOB_CLASS"], "custom_class");+ assert_eq!(value[0]["END_DATE"], Value::Null);+}++#[tokio::test]+async fn unclassified_sql_errors_are_not_retried_as_catalog_absence() {+ let mut calls = 0;+ let section = read_native_job_catalog_part_with(+ NativeJobCatalogDialect::Oracle,+ &target(),+ NativeJobCatalogPart::Definition,+ |_| {+ calls += 1;+ std::future::ready(Err(NativeJobCatalogFailure::sql(NativeJobCatalogDialect::Oracle, Some(600), None)))+ },+ )+ .await+ .unwrap();+ assert_eq!(calls, 1);+ assert!(+ matches!(section.data, NativeJobMetadata::Error { reason } if reason == "native_job_catalog_query_failed:600")+ );+}++#[tokio::test]+async fn transport_failure_does_not_probe_other_sources() {+ let mut calls = 0;+ let section = read_native_job_catalog_part_with(+ NativeJobCatalogDialect::Oracle,+ &target(),+ NativeJobCatalogPart::Definition,+ |_| {+ calls += 1;+ std::future::ready(Err(NativeJobCatalogFailure::Timeout))+ },+ )+ .await+ .unwrap();+ assert_eq!(calls, 1);+ assert!(matches!(section.data, NativeJobMetadata::Error { reason } if reason == "native_job_catalog_timeout"));+}++#[tokio::test]+async fn execution_error_rows_are_not_a_successful_catalog_read() {+ let mut calls = 0;+ let section = read_native_job_catalog_part_with(+ NativeJobCatalogDialect::Oracle,+ &target(),+ NativeJobCatalogPart::Definition,+ |_| {+ calls += 1;+ let mut failed = result(&["Error"], json!([["sensitive SQL and argument value ORA-00942"]]));+ failed["execution_error"] = json!(true);+ std::future::ready(Ok(failed))+ },+ )+ .await+ .unwrap();+ assert_eq!(calls, 1);+ assert!(matches!(section.data, NativeJobMetadata::Error { reason } if reason == "native_job_catalog_query_failed"));+ // Native diagnostics, unlike arbitrary error text, can justify a visibility fallback.+ let mut failure = result(&[], json!([]));+ failure["execution_error"] = json!(true);+ failure["error"] = json!({ "diagnostics": { "category": "sql", "vendorCode": 1031 } });+ let mut responses = VecDeque::from([failure, result(&["OWNER", "JOB_NAME"], json!([["Owner", "Job"]]))]);+ let section = read_native_job_catalog_part_with(+ NativeJobCatalogDialect::Oracle,+ &target(),+ NativeJobCatalogPart::Definition,+ |_| std::future::ready(Ok(responses.pop_front().unwrap())),+ )+ .await+ .unwrap();+ assert!(matches!(section.data, NativeJobMetadata::Available { .. }));+ assert_eq!(section.failures.len(), 1);+}++#[tokio::test]+async fn jdbc_native_diagnostics_keep_connection_timeout_and_cancel_failures_out_of_visibility_fallback() {+ for (category, reason) in [+ ("connection", "native_job_catalog_transport_failed"),+ ("timeout", "native_job_catalog_timeout"),+ ("canceled", "native_job_catalog_canceled"),+ ] {+ let mut calls = 0;+ let section = read_native_job_catalog_part_with(+ NativeJobCatalogDialect::Oracle,+ &target(),+ NativeJobCatalogPart::Definition,+ |_| {+ calls += 1;+ std::future::ready(Ok(+ json!({"execution_error":true,"error":{"diagnostics":{"category":category,"vendorCode":942}}}),+ ))+ },+ )+ .await+ .unwrap();+ assert_eq!(calls, 1);+ assert!(matches!(section.data, NativeJobMetadata::Error { reason: actual } if actual == reason));+ }+}++#[tokio::test]+async fn invalid_shape_duplicate_columns_and_a_different_target_cannot_become_a_baseline() {+ for response in [+ result(&["OWNER", "owner", "JOB_NAME"], json!([["Owner", "other", "Job"]])),+ result(&["OWNER", "JOB_NAME"], json!([["Owner"]])),+ result(&["OWNER", "JOB_NAME"], json!([["another-owner", "Job"]])),+ result(&["OWNER", "JOB_NAME"], json!([["Owner", "another-job"]])),+ result(&["OWNER", "JOB_NAME"], json!([["Owner", "Job"], ["Owner", "Job"]])),+ json!({}),+ ] {+ let mut calls = 0;+ let section = read_native_job_catalog_part_with(+ NativeJobCatalogDialect::Oracle,+ &target(),+ NativeJobCatalogPart::Definition,+ |_| {+ calls += 1;+ std::future::ready(Ok(response.clone()))+ },+ )+ .await+ .unwrap();+ assert!(matches!(section.data, NativeJobMetadata::Error { .. }));+ assert_eq!(calls, 1);+ }+}++#[tokio::test]+async fn selected_rows_keep_unsafe_integers_exact_and_mark_incomplete_reads() {+ let mut response = result(&["OWNER", "JOB_NAME", "INTERNAL_ID"], json!([["Owner", "Job", 9007199254740993_u64]]));+ response["has_more"] = json!(true);+ let section = read_native_job_catalog_part_with(+ NativeJobCatalogDialect::Oracle,+ &target(),+ NativeJobCatalogPart::Definition,+ |_| std::future::ready(Ok(response.clone())),+ )+ .await+ .unwrap();+ let NativeJobMetadata::Truncated { value, limit } = section.data else { panic!("incomplete read lost") };+ assert_eq!(limit, 1);+ assert_eq!(value[0]["INTERNAL_ID"], "9007199254740993");+}++#[tokio::test]+async fn legacy_id_is_a_string_and_does_not_relabel_its_three_users_as_owner() {+ let target = NativeJobRef::Legacy { scope: target().scope().clone(), job_id: "9007199254740993".into() };+ let response = result(+ &["DBX_JOB_ID", "LOG_USER", "PRIV_USER", "SCHEMA_USER"],+ json!([["9007199254740993", "login", "privileges", "parse_schema"]]),+ );+ let section = read_native_job_catalog_part_with(+ NativeJobCatalogDialect::Oracle,+ &target,+ NativeJobCatalogPart::Definition,+ |_| std::future::ready(Ok(response.clone())),+ )+ .await+ .unwrap();+ let NativeJobMetadata::Available { value } = section.data else { panic!("legacy unavailable") };+ assert_eq!(value[0]["LOG_USER"], "login");+ assert_eq!(value[0]["PRIV_USER"], "privileges");+ assert_eq!(value[0]["SCHEMA_USER"], "parse_schema");+ assert!(!value[0].contains_key("OWNER"));+}++#[tokio::test]+async fn invalid_identity_never_reaches_the_database_and_missing_history_is_not_faked() {+ let invalid = NativeJobRef::Legacy { scope: target().scope().clone(), job_id: "1;COMMIT".into() };+ let result = read_native_job_catalog_part_with(+ NativeJobCatalogDialect::Oracle,+ &invalid,+ NativeJobCatalogPart::Definition,+ no_query,+ )+ .await;+ assert!(result.is_err());+ let valid = NativeJobRef::Legacy { scope: target().scope().clone(), job_id: "1".into() };+ let section = read_native_job_catalog_part_with(+ NativeJobCatalogDialect::Oracle,+ &valid,+ NativeJobCatalogPart::History,+ no_query,+ )+ .await+ .unwrap();+ assert!(matches!(section.data, NativeJobMetadata::Unsupported { .. }));+}++#[tokio::test]+async fn generation_requires_a_real_positive_string_key_and_the_selected_legacy_id() {+ for response in [+ result(&["DBX_JOB_ID", "DBX_CREATED_AT"], json!([["0", "2026-10-20 20:00:00.000001"]])),+ result(&["DBX_JOB_ID", "DBX_CREATED_AT"], json!([[9007199254740993_u64, "2026-10-20 20:00:00.000001"]])),+ result(&["DBX_JOB_ID", "DBX_CREATED_AT"], json!([["123", null]])),+ ] {+ let section = read_native_job_catalog_part_with(+ NativeJobCatalogDialect::OceanbaseOracle,+ &target(),+ NativeJobCatalogPart::Generation,+ |_| std::future::ready(Ok(response.clone())),+ )+ .await+ .unwrap();+ assert!(matches!(section.data, NativeJobMetadata::Error { .. }));+ }+ let legacy = NativeJobRef::Legacy { scope: target().scope().clone(), job_id: "123".into() };+ let section = read_native_job_catalog_part_with(+ NativeJobCatalogDialect::Oracle,+ &legacy,+ NativeJobCatalogPart::Generation,+ |_| std::future::ready(Ok(result(&["DBX_JOB_ID"], json!([["124"]])))),+ )+ .await+ .unwrap();+ assert!(matches!(section.data, NativeJobMetadata::Error { .. }));+}diff --git a/crates/dbx-core/tests/native_job_configuration_transport.rs b/crates/dbx-core/tests/native_job_configuration_transport.rsnew file mode 100644index 0000000000..759fcbb081--- /dev/null+++ b/crates/dbx-core/tests/native_job_configuration_transport.rs@@ -0,0 +1,269 @@+#![recursion_limit = "256"]++use dbx_core::connection::{task_client_session_id, AppState, PoolKind};+use dbx_core::db::agent_driver::{AgentDriverClient, AgentLaunchSpec, PooledAgentClient};+use dbx_core::schema::native_jobs::*;+use dbx_types::native_jobs::*;+use serde_json::{json, Value};+use std::io::{BufRead, Write};+use std::sync::Arc;+use std::time::Duration;++fn query_result(columns: &[&str], rows: Value) -> Value {+ json!({"columns":columns,"rows":rows,"affected_rows":0,"execution_time_ms":0})+}++fn definition(enabled: bool, ep: i32, valid: &str) -> Value {+ query_result(+ &["DBX_JOB_ID", "NAME", "USERNAME", "CREATETIME", "ENABLE", "EP_SEQNO", "VALID", "SYS_FLAG"],+ json!([["41", "Job_1", "Owner", "creation", i32::from(enabled), ep, valid, 0]]),+ )+}++// A real child stdio peer exercises Core's existing Agent corridor. Only this external boundary is+// simulated; native_job_apply_core owns pool lookup, physical authorization, reads and cleanup.+#[test]+fn native_job_configuration_rpc_fixture() {+ let Ok(path) = std::env::var("DBX_NATIVE_JOB_RPC_LOG") else { return };+ let mode = std::env::var("DBX_NATIVE_JOB_RPC_MODE").unwrap();+ let mut log = std::fs::OpenOptions::new().create(true).append(true).open(path).unwrap();+ let mut enabled = false;+ let mut ep = 0;+ let mut valid = "Y";+ let mut operation = String::new();+ let token = "fixture-owned-physical-connection";+ let mut leased = false;+ println!("\n{}", json!({"ready":true}));+ std::io::stdout().flush().unwrap();+ for line in std::io::stdin().lock().lines() {+ let request: Value = serde_json::from_str(&line.unwrap()).unwrap();+ writeln!(log, "{request}").unwrap();+ log.flush().unwrap();+ let method = request["method"].as_str().unwrap();+ let params = &request["params"];+ let authorized = !leased+ || !matches!(method, "connection_info" | "execute_query")+ || (params["nativeJobOperationId"] == operation && params["nativeJobSessionToken"] == token);+ let value = if !authorized {+ json!({"jsonrpc":"2.0","id":request["id"],"error":{"code":-32000,"message":"fixture requires owned physical token"}})+ } else {+ let result = match method {+ "handshake" => json!({"protocolVersion":2,"agentProtocolVersion":2,+ "capabilities":["connect","metadata","query","native_job_session_v1"]}),+ "connection_info" => json!({"databaseInfo":{+ "productName":"DM DBMS",+ "productVersion":if leased && mode == "changed-version" { "different" } else { "8.1.fixture" },+ "currentDatabase":if leased && mode == "changed-database" { "OTHER" } else { "JOBDB" }+ }}),+ "open_native_job_session" => {+ operation = params["operationId"].as_str().unwrap().into();+ leased = true;+ json!({"operationId":operation,"sessionToken":token,+ "phase":if mode == "open-unknown" { "unknown" } else { "opened" }})+ }+ "close_native_job_session" => {+ assert_eq!(params["operationId"], operation);+ if mode != "open-unknown" {+ assert_eq!(params["sessionToken"], token);+ } else {+ assert!(params.get("sessionToken").is_none());+ }+ leased = false;+ json!({"operationId":operation,"sessionToken":token,+ "phase":if mode == "close-unknown" { "unknown" } else { "closed" }})+ }+ "execute_query" => {+ let sql = params["sql"].as_str().unwrap();+ if sql == "SELECT USER AS DBX_SESSION_USER FROM DUAL" {+ query_result(+ &["DBX_SESSION_USER"],+ json!([[if leased && mode == "changed-user" { "Other" } else { "Owner" }]]),+ )+ } else if sql.starts_with("DECLARE") {+ if sql.contains("SP_ENABLE_JOB('Job_1', 0)") {+ enabled = false;+ }+ if sql.contains("SP_JOB_CONFIG_START(") {+ valid = "N";+ }+ if sql.contains("SP_JOB_SET_EP_SEQNO('Job_1', 2)") {+ ep = 2;+ }+ if sql.contains("SP_JOB_CONFIG_COMMIT(") {+ valid = "Y";+ }+ query_result(&[], json!([]))+ } else if sql.contains("AS DBX_CREATED_AT") {+ query_result(&["DBX_JOB_ID", "DBX_CREATED_AT"], json!([["41", "creation"]]))+ } else if sql.contains("FROM SYSJOB.SYSJOBS J") {+ definition(enabled, ep, valid)+ } else {+ query_result(&["JOBID"], json!([]))+ }+ }+ _ => json!({}),+ };+ json!({"jsonrpc":"2.0","id":request["id"],"result":result})+ };+ println!("{value}");+ std::io::stdout().flush().unwrap();+ if method == "shutdown" {+ break;+ }+ }+}++async fn run(mode: &str) -> (NativeJobOperationStatus, Vec<Value>) {+ let dir = tempfile::tempdir().unwrap();+ let log = dir.path().join("requests.jsonl");+ let storage = dbx_core::persistence::test_storage::open(&dir.path().join("state.db")).await.unwrap();+ let state = Arc::new(AppState::new_with_plugin_and_agent_dir_and_app_version(+ storage,+ dir.path().join("plugins"),+ dir.path().join("agents"),+ "test",+ ));+ state.configs.write().await.insert(+ "c".into(),+ serde_json::from_value(json!({+ "id":"c","name":"fixture","db_type":"dameng","host":"127.0.0.1","port":1,+ "username":"Owner","password":"","query_timeout_secs":2,"connect_timeout_secs":2+ }))+ .unwrap(),+ );+ let context = native_job_open_context_with(&state, "c", "", |_| {+ std::future::ready(Ok(NativeJobRuntimeIdentity {+ database_info: Some(+ serde_json::from_value(json!({+ "productName":"DM DBMS", "productVersion":"8.1.fixture", "currentDatabase":"JOBDB"+ }))+ .unwrap(),+ ),+ session_user: "Owner".into(),+ }))+ })+ .await+ .unwrap();+ let target = NativeJobRef::DamengNative { scope: context.scope, job_id: "41".into(), name: "Job_1".into() };+ let read = |target: NativeJobRef| {+ let state = state.clone();+ async move {+ native_job_read_with(&state, &target, |query| {+ std::future::ready(Ok(if query.sql.contains("AS DBX_CREATED_AT") {+ query_result(&["DBX_JOB_ID", "DBX_CREATED_AT"], json!([["41", "creation"]]))+ } else if query.source == "SYSJOB.SYSJOBS" {+ definition(false, 0, "Y")+ } else {+ query_result(&["JOBID"], json!([]))+ }))+ })+ .await+ }+ };+ let initial = read(target.clone()).await.unwrap();+ let prepared = native_job_prepare_with(+ &state,+ NativeJobMutation {+ target,+ baseline: initial.snapshot.revision,+ change: NativeJobChange::Update {+ final_enabled: None,+ argument_target: None,+ attributes: vec![NativeJobAttributeChange {+ name: "EP_SEQNO".into(),+ change: NativeJobFieldChange::Set { value: json!(2) },+ }],+ arguments: vec![],+ },+ },+ read,+ )+ .await+ .unwrap();+ let launch = AgentLaunchSpec::new(std::env::current_exe().unwrap())+ .with_args(["--exact", "native_job_configuration_rpc_fixture", "--nocapture", "--test-threads=1"])+ .with_env(vec![+ ("DBX_NATIVE_JOB_RPC_LOG".into(), log.to_string_lossy().into_owned()),+ ("DBX_NATIVE_JOB_RPC_MODE".into(), mode.into()),+ ]);+ let mut client = AgentDriverClient::spawn(launch).await.unwrap();+ assert!(client.try_optional_handshake("test").await.is_some());+ let client = Arc::new(PooledAgentClient::new(client));+ let session_id = task_client_session_id("native-job-operation", &prepared.operation_id).replace(':', "_");+ let key = format!("c:session:{session_id}:role:metadata");+ state.update_connection_pools(|pools| pools.insert(key.clone(), PoolKind::Agent(client.clone()))).await;+ native_job_apply_core(state.clone(), &prepared.plan_id).unwrap();+ let status = tokio::time::timeout(Duration::from_secs(10), async {+ loop {+ let status = native_job_status(&state, &prepared.operation_id);+ if status.state == NativeJobOperationState::Finished {+ return status;+ }+ tokio::time::sleep(Duration::from_millis(10)).await;+ }+ })+ .await+ .unwrap();+ let removed = state.pool_handle(&key).await.is_none();+ client.lock().await.shutdown().await;+ state.shutdown(Duration::from_secs(2)).await;+ assert!(removed, "owned metadata route was not removed; operation reason: {:?}", status.reason);+ let requests =+ std::fs::read_to_string(log).unwrap().lines().map(|line| serde_json::from_str(line).unwrap()).collect();+ (status, requests)+}++#[tokio::test]+async fn production_owned_pool_binds_all_configuration_reads_and_writes_to_the_native_lease() {+ let (status, requests) = run("normal").await;+ assert!(status.outcome == NativeJobOperationOutcome::Verified, "{:?}", status.reason);+ let opened = requests.iter().position(|request| request["method"] == "open_native_job_session").unwrap();+ let closed = requests.iter().position(|request| request["method"] == "close_native_job_session").unwrap();+ let owned = &requests[opened + 1..closed];+ assert!(owned.iter().any(|request| request["method"] == "connection_info"));+ assert!(owned.iter().filter(|request| request["method"] == "execute_query").count() > 10);+ assert!(owned.iter().all(|request| request["params"]["nativeJobOperationId"] == status.operation_id+ && request["params"]["nativeJobSessionToken"] == "fixture-owned-physical-connection"));+ assert!(requests.iter().skip(closed + 1).all(|request| request["method"] != "execute_query"));+ assert!(!serde_json::to_string(&status).unwrap().contains("fixture-owned-physical-connection"));+}++#[tokio::test]+async fn production_cleanup_does_not_erase_a_native_unknown_close_with_a_successful_disconnect() {+ let (status, requests) = run("close-unknown").await;+ assert!(status.outcome == NativeJobOperationOutcome::Unknown);+ assert_eq!(status.reason.as_deref(), Some("native_job_session_cleanup_unknown"));+ assert!(requests.iter().any(|request| request["method"] == "disconnect"));+}++#[tokio::test]+async fn production_unknown_open_disposes_by_operation_id_without_guessing_a_token_or_writing_sql() {+ let (status, requests) = run("open-unknown").await;+ assert!(status.outcome == NativeJobOperationOutcome::NotApplied);+ assert!(requests.iter().any(|request| request["method"] == "close_native_job_session"));+ assert!(!requests+ .iter()+ .any(|request| request["params"]["sql"].as_str().is_some_and(|sql| sql.starts_with("DECLARE"))));+}++#[tokio::test]+async fn production_revalidates_the_actual_login_after_reserving_the_physical_connection() {+ let (status, requests) = run("changed-user").await;+ assert!(status.outcome == NativeJobOperationOutcome::NotApplied);+ assert_eq!(status.reason.as_deref(), Some("native_job_runtime_context_changed"));+ assert!(!requests+ .iter()+ .any(|request| request["params"]["sql"].as_str().is_some_and(|sql| sql.starts_with("DECLARE"))));+}++#[tokio::test]+async fn production_rejects_changed_database_or_version_on_the_reserved_physical_connection() {+ for mode in ["changed-database", "changed-version"] {+ let (status, requests) = run(mode).await;+ assert!(status.outcome == NativeJobOperationOutcome::NotApplied);+ assert_eq!(status.reason.as_deref(), Some("native_job_runtime_context_changed"));+ assert!(!requests+ .iter()+ .any(|request| request["params"]["sql"].as_str().is_some_and(|sql| sql.starts_with("DECLARE"))));+ }+}diff --git a/crates/dbx-core/tests/native_job_creation.rs b/crates/dbx-core/tests/native_job_creation.rsnew file mode 100644index 0000000000..6216531039--- /dev/null+++ b/crates/dbx-core/tests/native_job_creation.rs@@ -0,0 +1,526 @@+#![recursion_limit = "256"]++use dbx_core::connection::AppState;+use dbx_core::schema::native_jobs::*;+use dbx_sql::native_job_changes::NativeJobSqlStep;+use dbx_types::native_jobs::*;+use serde_json::json;+use std::sync::{+ atomic::{AtomicUsize, Ordering},+ Arc,+};++const JOB_ID: &str = "9007199254740993";++async fn setup() -> (tempfile::TempDir, Arc<AppState>, NativeJobScope) {+ setup_engine("oracle").await+}++async fn setup_engine(engine: &str) -> (tempfile::TempDir, Arc<AppState>, NativeJobScope) {+ let dir = tempfile::tempdir().unwrap();+ let storage = dbx_core::persistence::test_storage::open(&dir.path().join("state.db")).await.unwrap();+ let state = Arc::new(AppState::new_with_plugin_and_agent_dir_and_app_version(+ storage,+ dir.path().join("plugins"),+ dir.path().join("agents"),+ "0.0.0",+ ));+ let config = serde_json::from_value(+ json!({"id":"c","name":"test","db_type":engine,"host":"127.0.0.1","port":1,"username":"Owner","password":""}),+ )+ .unwrap();+ state.configs.write().await.insert("c".into(), config);+ let context = native_job_open_context_with(&state, "c", "", |_| {+ std::future::ready(Ok(NativeJobRuntimeIdentity { database_info: None, session_user: "Owner".into() }))+ })+ .await+ .unwrap();+ (dir, state, context.scope)+}++fn definition() -> NativeJobLegacyCreate {+ NativeJobLegacyCreate {+ what: "private_call('original');".into(),+ next_date: "2026-10-21 10:20:30".into(),+ interval: "SYSDATE + 1".into(),+ enabled: false,+ instance: 0,+ schema: "Owner".into(),+ zone: None,+ }+}++async fn preview(+ state: &AppState,+ scope: &NativeJobScope,+ definition: NativeJobLegacyCreate,+) -> Result<NativeJobPreparedPlan, &'static str> {+ native_job_prepare_request_with(+ state,+ NativeJobRequest::Create { scope: scope.clone(), definition: NativeJobCreateDefinition::Legacy(definition) },+ |_| std::future::ready(Err("preview must not query or execute a job")),+ )+ .await+}++fn receipt(phase: NativeJobLegacyPhase) -> NativeJobLegacyReceipt {+ NativeJobLegacyReceipt {+ operation_id: String::new(),+ phase,+ job_id: Some(JOB_ID.into()),+ reason: None,+ vendor_code: None,+ disposal_confirmed: None,+ }+}++struct Session {+ state: Arc<AppState>,+ definition: Option<NativeJobLegacyCreate>,+ prepared: NativeJobLegacyReceipt,+ committed: NativeJobLegacyReceipt,+ rolled_back: NativeJobLegacyReceipt,+ calls: Vec<(String, Option<String>)>,+ reads: Arc<AtomicUsize>,+ cancel_after_prepare: bool,+ invalidate_after_prepare: bool,+ readonly_after_prepare: bool,+ wrong_operation: bool,+ missing: bool,+ changed: bool,+ wrong_zone: bool,+ advanced_next_date: bool,+ fail_cleanup: bool,+ prepare_entered: Option<tokio::sync::oneshot::Sender<()>>,+ prepare_release: Option<tokio::sync::oneshot::Receiver<()>>,+ finish_entered: Option<tokio::sync::oneshot::Sender<()>>,+ finish_release: Option<tokio::sync::oneshot::Receiver<()>>,+}++impl Session {+ fn new(state: &Arc<AppState>) -> Self {+ Self {+ state: state.clone(),+ definition: None,+ prepared: receipt(NativeJobLegacyPhase::Prepared),+ committed: receipt(NativeJobLegacyPhase::Committed),+ rolled_back: receipt(NativeJobLegacyPhase::RolledBack),+ calls: Vec::new(),+ reads: Arc::new(AtomicUsize::new(0)),+ cancel_after_prepare: false,+ invalidate_after_prepare: false,+ readonly_after_prepare: false,+ wrong_operation: false,+ missing: false,+ changed: false,+ wrong_zone: false,+ advanced_next_date: false,+ fail_cleanup: false,+ prepare_entered: None,+ prepare_release: None,+ finish_entered: None,+ finish_release: None,+ }+ }+}++async fn read_definition(+ state: &AppState,+ target: &NativeJobRef,+ definition: &NativeJobLegacyCreate,+ missing: bool,+ changed: bool,+ advanced: bool,+) -> NativeJobDetails {+ let oceanbase =+ state.configs.read().await["c"].db_type == dbx_core::models::connection::DatabaseType::OceanbaseOracle;+ let instance = if oceanbase { json!(definition.zone) } else { json!(definition.instance) };+ native_job_read_with(state, target, |query| {+ let generation = query.sql.starts_with("SELECT TO_CHAR(J.JOB)");+ let mut raw = if generation {+ json!({"columns":["DBX_JOB_ID"],"rows":if missing { json!([]) } else { json!([[JOB_ID]]) }})+ } else if query.source.ends_with("_JOBS") {+ json!({"columns":["DBX_JOB_ID","WHAT","NEXT_DATE","INTERVAL","BROKEN","INSTANCE","LOG_USER","PRIV_USER","SCHEMA_USER"],+ "rows":if missing { json!([]) } else { json!([[JOB_ID,if changed { "external_call();" } else { &definition.what },+ if advanced { "2026-10-22T10:20:30" } else { "2026-10-21T10:20:30.000" }, definition.interval,+ if definition.enabled { "N" } else { "Y" }, instance,"Owner","Owner",definition.schema]]) }})+ } else { json!({"columns":["JOB"],"rows":[]}) };+ raw["affected_rows"] = json!(0);+ raw["execution_time_ms"] = json!(0);+ std::future::ready(Ok(raw))+ }).await.unwrap()+}++#[async_trait::async_trait]+impl NativeJobMutationSession for Session {+ async fn read(&mut self, target: &NativeJobRef) -> Result<NativeJobDetails, &'static str> {+ self.reads.fetch_add(1, Ordering::SeqCst);+ let NativeJobRef::Legacy { job_id, .. } = target else {+ panic!("new legacy Job must not use a Scheduler name")+ };+ assert_eq!(job_id, JOB_ID);+ let mut definition = self.definition.as_ref().unwrap().clone();+ if self.wrong_zone {+ definition.zone = Some("another-zone".into());+ }+ Ok(read_definition(&self.state, target, &definition, self.missing, self.changed, self.advanced_next_date).await)+ }+ async fn execute(&mut self, _step: &NativeJobSqlStep) -> NativeJobStepReceipt {+ self.calls.push(("execute".into(), None));+ self.definition.as_mut().unwrap().enabled = true;+ NativeJobStepReceipt { outcome: NativeJobDispatchOutcome::Applied, reason: None, vendor_code: None }+ }+ async fn prepare_legacy(&mut self, id: &str, definition: &NativeJobLegacyCreate) -> NativeJobLegacyReceipt {+ self.calls.push(("prepare".into(), None));+ self.definition = Some(definition.clone());+ assert!(native_job_status(&self.state, id).target.is_none());+ if let Some(entered) = self.prepare_entered.take() {+ entered.send(()).unwrap();+ }+ if let Some(release) = self.prepare_release.take() {+ release.await.unwrap();+ }+ if self.cancel_after_prepare {+ native_job_cancel(&self.state, id);+ }+ if self.invalidate_after_prepare {+ self.state.invalidate_connection_lifecycle("c");+ }+ if self.readonly_after_prepare {+ self.state.configs.write().await.get_mut("c").unwrap().read_only = true;+ }+ let mut prepared = self.prepared.clone();+ prepared.operation_id = if self.wrong_operation { "another operation".into() } else { id.into() };+ prepared+ }+ async fn finish_legacy(&mut self, id: &str, job_id: Option<&str>, commit: bool) -> NativeJobLegacyReceipt {+ self.calls.push((if commit { "commit".into() } else { "rollback".into() }, job_id.map(str::to_string)));+ if commit {+ assert_eq!(job_id, Some(JOB_ID));+ let NativeJobRef::Legacy { job_id: recorded, .. } = native_job_status(&self.state, id).target.unwrap()+ else {+ panic!("OUT identity must be persisted before COMMIT")+ };+ assert_eq!(recorded, JOB_ID);+ }+ let mut receipt = if commit { self.committed.clone() } else { self.rolled_back.clone() };+ receipt.operation_id = id.into();+ receipt+ }+ async fn finish(&mut self) -> Result<(), &'static str> {+ if let Some(entered) = self.finish_entered.take() {+ entered.send(()).unwrap();+ }+ if let Some(release) = self.finish_release.take() {+ release.await.unwrap();+ }+ if self.fail_cleanup {+ Err("close response lost")+ } else {+ Ok(())+ }+ }+}++#[tokio::test]+async fn preview_has_an_explicit_scope_but_no_invented_out_id_or_database_side_effects() {+ let (_dir, state, scope) = setup().await;+ let mut request = definition();+ request.schema.clear();+ let plan = preview(&state, &scope, request).await.unwrap();+ assert!(plan.target.is_none());+ assert_eq!(plan.scope, scope);+ assert_eq!(plan.steps.len(), 3);+ assert!(plan.steps[0].sql.contains("CURRENT_SCHEMA = \"Owner\""));+ assert!(plan.steps[0].sql.contains(":dbx_job_id"));+ assert!(plan.steps[0].sql.contains("DBMS_JOB.BROKEN"));+ for date in ["2026-02-30 10:20:30", "0000-01-01 10:20:30"] {+ let mut invalid = definition();+ invalid.next_date = date.into();+ assert_eq!(preview(&state, &scope, invalid).await.err(), Some("native_job_date_invalid"));+ }+ let mut forged = scope;+ forged.context_id = "forged".into();+ assert_eq!(preview(&state, &forged, definition()).await.err(), Some("native_job_context_expired"));+}++#[tokio::test]+async fn a_real_out_id_is_recorded_before_commit_and_duplicate_apply_never_submits_again() {+ let (_dir, state, scope) = setup().await;+ let plan = preview(&state, &scope, definition()).await.unwrap();+ let mut db = Session::new(&state);+ let status = native_job_apply_with(&state, &plan.plan_id, &mut db).await.unwrap();+ assert_eq!(status.outcome, NativeJobOperationOutcome::Verified);+ assert_eq!(db.calls, [("prepare".into(), None), ("commit".into(), Some(JOB_ID.into()))]);+ assert_eq!(db.reads.load(Ordering::SeqCst), 1);+ assert!(status.steps.iter().all(|step| step.state == NativeJobStepState::Applied));+ let mut unused = Session::new(&state);+ let again = native_job_apply_with(&state, &plan.plan_id, &mut unused).await.unwrap();+ assert_eq!(again.operation_id, status.operation_id);+ assert_eq!(again.target, status.target);+ assert!(unused.calls.is_empty());+}++#[tokio::test]+async fn ob_creation_records_out_before_commit_and_verifies_nullable_native_zone() {+ for zone in [None, Some("zone1".to_string())] {+ for enabled in [false, true] {+ let (_dir, state, scope) = setup_engine("oceanbase-oracle").await;+ let mut input = definition();+ input.zone = zone.clone();+ input.enabled = enabled;+ let plan = preview(&state, &scope, input).await.unwrap();+ assert!(plan.target.is_none());+ assert!(plan.steps[0].sql.contains("zone =>"));+ let mut db = Session::new(&state);+ db.advanced_next_date = enabled;+ let status = native_job_apply_with(&state, &plan.plan_id, &mut db).await.unwrap();+ assert_eq!(status.outcome, NativeJobOperationOutcome::Verified);+ assert_eq!(db.calls, [("prepare".into(), None), ("commit".into(), Some(JOB_ID.into()))]);+ let mut unused = Session::new(&state);+ native_job_apply_with(&state, &plan.plan_id, &mut unused).await.unwrap();+ assert!(unused.calls.is_empty());+ }+ }+}++#[tokio::test]+async fn ob_wrong_zone_is_not_verified_and_cancellation_after_out_never_commits() {+ for canceled in [false, true] {+ let (_dir, state, scope) = setup_engine("oceanbase-oracle").await;+ let mut input = definition();+ input.zone = Some("zone1".into());+ let plan = preview(&state, &scope, input).await.unwrap();+ let mut db = Session::new(&state);+ db.wrong_zone = !canceled;+ db.cancel_after_prepare = canceled;+ let status = native_job_apply_with(&state, &plan.plan_id, &mut db).await.unwrap();+ assert_eq!(+ status.outcome,+ if canceled { NativeJobOperationOutcome::NotApplied } else { NativeJobOperationOutcome::Partial }+ );+ assert_eq!(db.calls[1].0, if canceled { "rollback" } else { "commit" });+ }+}++#[tokio::test]+async fn readonly_and_cancel_before_dispatch_do_not_submit_and_the_existing_unlock_remains_usable() {+ let (_dir, state, scope) = setup().await;+ let plan = preview(&state, &scope, definition()).await.unwrap();+ state.configs.write().await.get_mut("c").unwrap().read_only = true;+ let mut db = Session::new(&state);+ assert_eq!(+ native_job_apply_with(&state, &plan.plan_id, &mut db).await.unwrap().outcome,+ NativeJobOperationOutcome::NotApplied+ );+ assert!(db.calls.is_empty());+ state.write_unlock_windows.unlock("c", 60).await.unwrap();+ let allowed = preview(&state, &scope, definition()).await.unwrap();+ assert_eq!(+ native_job_apply_with(&state, &allowed.plan_id, &mut db).await.unwrap().outcome,+ NativeJobOperationOutcome::Verified+ );+ let canceled = preview(&state, &scope, definition()).await.unwrap();+ native_job_cancel(&state, &canceled.operation_id);+ let mut unused = Session::new(&state);+ assert_eq!(+ native_job_apply_with(&state, &canceled.plan_id, &mut unused).await.unwrap().outcome,+ NativeJobOperationOutcome::NotApplied+ );+ assert!(unused.calls.is_empty());+}++#[tokio::test]+async fn cancellation_lifecycle_and_readonly_changes_after_out_trigger_owned_rollback_not_commit() {+ for reason in ["cancel", "lifecycle", "readonly"] {+ let (_dir, state, scope) = setup().await;+ let plan = preview(&state, &scope, definition()).await.unwrap();+ let mut db = Session::new(&state);+ db.cancel_after_prepare = reason == "cancel";+ db.invalidate_after_prepare = reason == "lifecycle";+ db.readonly_after_prepare = reason == "readonly";+ assert_eq!(+ native_job_apply_with(&state, &plan.plan_id, &mut db).await.unwrap().outcome,+ NativeJobOperationOutcome::NotApplied+ );+ assert_eq!(db.calls, [("prepare".into(), None), ("rollback".into(), Some(JOB_ID.into()))]);+ assert_eq!(db.reads.load(Ordering::SeqCst), 0);+ }+}++#[tokio::test]+async fn lost_prepare_response_rolls_back_by_operation_id_and_does_not_guess_an_id() {+ for rollback in [NativeJobLegacyPhase::RolledBack, NativeJobLegacyPhase::Unknown] {+ let (_dir, state, scope) = setup().await;+ let plan = preview(&state, &scope, definition()).await.unwrap();+ let mut db = Session::new(&state);+ db.prepared.phase = NativeJobLegacyPhase::Unknown;+ db.prepared.job_id = None;+ db.rolled_back.phase = rollback;+ let status = native_job_apply_with(&state, &plan.plan_id, &mut db).await.unwrap();+ assert_eq!(+ status.outcome,+ if rollback == NativeJobLegacyPhase::RolledBack {+ NativeJobOperationOutcome::NotApplied+ } else {+ NativeJobOperationOutcome::Unknown+ }+ );+ assert!(status.target.is_none());+ assert_eq!(db.calls, [("prepare".into(), None), ("rollback".into(), None)]);+ }+}++#[tokio::test]+async fn absent_invalid_or_mismatched_out_receipts_cannot_authorize_commit() {+ for id in [None, Some("0"), Some("01"), Some("1e3"), Some("1 OR 1=1"), Some(JOB_ID)] {+ let (_dir, state, scope) = setup().await;+ let plan = preview(&state, &scope, definition()).await.unwrap();+ let mut db = Session::new(&state);+ db.prepared.job_id = id.map(str::to_string);+ db.wrong_operation = id == Some(JOB_ID);+ let status = native_job_apply_with(&state, &plan.plan_id, &mut db).await.unwrap();+ assert_eq!(status.outcome, NativeJobOperationOutcome::NotApplied);+ assert!(status.target.is_none());+ assert_eq!(db.calls, [("prepare".into(), None), ("rollback".into(), None)]);+ }+}++#[tokio::test]+async fn native_failure_keeps_safe_diagnostics_and_a_confirmed_rollback_is_not_repeated() {+ let (_dir, state, scope) = setup().await;+ let plan = preview(&state, &scope, definition()).await.unwrap();+ let mut db = Session::new(&state);+ db.prepared.phase = NativeJobLegacyPhase::RolledBack;+ db.prepared.vendor_code = Some(27486);+ db.prepared.reason = Some("private body and arguments".into());+ let status = native_job_apply_with(&state, &plan.plan_id, &mut db).await.unwrap();+ assert_eq!(status.outcome, NativeJobOperationOutcome::NotApplied);+ assert_eq!(status.steps[0].vendor_code, Some(27486));+ assert_eq!(status.steps[0].reason.as_deref(), Some("native_job_legacy_protocol_error"));+ assert_eq!(db.calls.len(), 1);+}++#[tokio::test]+async fn commit_response_loss_is_resolved_only_by_exact_id_readback_without_native_replay() {+ for visible in [true, false] {+ let (_dir, state, scope) = setup().await;+ let plan = preview(&state, &scope, definition()).await.unwrap();+ let mut db = Session::new(&state);+ db.committed.phase = NativeJobLegacyPhase::Unknown;+ db.committed.job_id = None;+ db.missing = !visible;+ let status = native_job_apply_with(&state, &plan.plan_id, &mut db).await.unwrap();+ assert_eq!(+ status.outcome,+ if visible { NativeJobOperationOutcome::Verified } else { NativeJobOperationOutcome::Unknown }+ );+ assert_eq!(db.calls, [("prepare".into(), None), ("commit".into(), Some(JOB_ID.into()))]);+ assert_eq!(db.reads.load(Ordering::SeqCst), 1);+ }+}++#[tokio::test]+async fn enabled_jobs_may_advance_next_date_but_definition_changes_are_not_hidden() {+ for (enabled, changed, expected) in [+ (true, false, NativeJobOperationOutcome::Verified),+ (false, false, NativeJobOperationOutcome::Partial),+ (true, true, NativeJobOperationOutcome::Partial),+ ] {+ let (_dir, state, scope) = setup().await;+ let mut definition = definition();+ definition.enabled = enabled;+ let plan = preview(&state, &scope, definition).await.unwrap();+ let mut db = Session::new(&state);+ db.advanced_next_date = true;+ db.changed = changed;+ assert_eq!(native_job_apply_with(&state, &plan.plan_id, &mut db).await.unwrap().outcome, expected);+ assert_eq!(db.calls.len(), 2);+ }+}++#[tokio::test]+async fn interrupted_creation_remains_unknown_and_cannot_be_reapplied() {+ let (_dir, state, scope) = setup().await;+ let plan = preview(&state, &scope, definition()).await.unwrap();+ let mut db = Session::new(&state);+ let (entered, mut waiting) = tokio::sync::oneshot::channel();+ let (_release, blocked) = tokio::sync::oneshot::channel();+ db.prepare_entered = Some(entered);+ db.prepare_release = Some(blocked);+ let mut applying = Box::pin(native_job_apply_with(&state, &plan.plan_id, &mut db));+ tokio::select! { result = &mut applying => { panic!("native call unexpectedly completed: {}", result.is_ok()); }, _ = &mut waiting => {} }+ drop(applying);+ assert_eq!(native_job_status(&state, &plan.operation_id).outcome, NativeJobOperationOutcome::Unknown);+ let mut unused = Session::new(&state);+ assert_eq!(+ native_job_apply_with(&state, &plan.plan_id, &mut unused).await.unwrap().outcome,+ NativeJobOperationOutcome::Unknown+ );+ assert!(unused.calls.is_empty());+}++#[tokio::test]+async fn an_unconfirmed_cleanup_cannot_be_reported_as_verified_creation() {+ let (_dir, state, scope) = setup().await;+ let plan = preview(&state, &scope, definition()).await.unwrap();+ let mut db = Session::new(&state);+ db.fail_cleanup = true;+ let status = native_job_apply_with(&state, &plan.plan_id, &mut db).await.unwrap();+ assert_eq!(status.outcome, NativeJobOperationOutcome::Unknown);+ assert_eq!(status.reason.as_deref(), Some("native_job_session_cleanup_unknown"));+ assert_eq!(db.calls.len(), 2);+}++#[tokio::test]+async fn the_new_out_identity_remains_locked_through_physical_session_cleanup() {+ let (_dir, state, scope) = setup().await;+ let plan = preview(&state, &scope, definition()).await.unwrap();+ let mut creator = Session::new(&state);+ let (entered, mut closing) = tokio::sync::oneshot::channel();+ let (release, wait) = tokio::sync::oneshot::channel();+ creator.finish_entered = Some(entered);+ creator.finish_release = Some(wait);+ let mut creating = Box::pin(native_job_apply_with(&state, &plan.plan_id, &mut creator));+ tokio::select! { result = &mut creating => { panic!("cleanup unexpectedly completed: {}", result.is_ok()); }, _ = &mut closing => {} }+ let target = native_job_status(&state, &plan.operation_id).target.unwrap();+ let before = read_definition(&state, &target, &definition(), false, false, false).await;+ let update = native_job_prepare_with(+ &state,+ NativeJobMutation {+ target: target.clone(),+ baseline: before.snapshot.revision,+ change: NativeJobChange::Enable,+ },+ |target| {+ let state = state.clone();+ async move { Ok(read_definition(&state, &target, &definition(), false, false, false).await) }+ },+ )+ .await+ .unwrap();+ let mut editor = Session::new(&state);+ editor.definition = Some(definition());+ let reads = editor.reads.clone();+ let mut editing = Box::pin(native_job_apply_with(&state, &update.plan_id, &mut editor));+ let ready = std::future::poll_fn(|cx| {+ use std::future::Future;+ std::task::Poll::Ready(match editing.as_mut().poll(cx) {+ std::task::Poll::Ready(result) => Some(result),+ std::task::Poll::Pending => None,+ })+ })+ .await;+ let while_closing = reads.load(Ordering::SeqCst);+ release.send(()).unwrap();+ creating.await.unwrap();+ match ready {+ Some(result) => {+ result.unwrap();+ }+ None => {+ editing.await.unwrap();+ }+ }+ assert_eq!(while_closing, 0, "an edit must not pass a creation's unconfirmed cleanup");+}diff --git a/crates/dbx-core/tests/native_job_dameng_configuration.rs b/crates/dbx-core/tests/native_job_dameng_configuration.rsnew file mode 100644index 0000000000..30637e5ebb--- /dev/null+++ b/crates/dbx-core/tests/native_job_dameng_configuration.rs@@ -0,0 +1,1775 @@+#![recursion_limit = "256"]++use dbx_core::connection::AppState;+use dbx_core::schema::native_jobs::*;+use dbx_sql::native_job_changes::{+ NativeJobDamengChildAction, NativeJobDamengPart, NativeJobSqlStep, NativeJobStepEffect,+};+use dbx_sql::native_jobs::NativeJobCatalogQuery;+use dbx_types::native_jobs::*;+use serde_json::{json, Value};+use std::collections::BTreeMap;+use std::sync::Arc;++#[derive(Clone)]+struct Database {+ name: String,+ exists: bool,+ enabled: bool,+ description: &'static str,+ valid: &'static str,+ created: &'static str,+ ep_seqno: i32,+ email_operator: i32,+ unreadable_parts: bool,+ steps: Vec<NativeJobRow>,+ schedules: Vec<NativeJobRow>,+ owner: &'static str,+ system_definition: bool,+ system_parts: bool,+ legacy: Option<NativeJobRow>,+ legacy_denied: bool,+}++impl Default for Database {+ fn default() -> Self {+ Self {+ name: "Job_1".into(),+ exists: true,+ enabled: true,+ description: "old",+ valid: "Y",+ created: "creation",+ ep_seqno: 0,+ email_operator: 7,+ unreadable_parts: false,+ steps: serde_json::from_value(json!([+ {"ID":11,"JOBID":41,"NAME":"backup","SEQNO":1,"TYPE":6,"DBNAME":"DB","COMMAND":"native generated backup command","SUCC_ACTION":3,"FAIL_ACTION":1,"RETRY_ATTEMPTS":2,"RETRY_INTERVAL":1,"OUTPUT_FILE_PATH":null,"APPEND_FLAG":0,"SUCC_NEXT_STEP":"sql","FAIL_NEXT_STEP":null,"DESCRIBE":"keep backup"},+ {"ID":12,"JOBID":41,"NAME":"sql","SEQNO":2,"TYPE":0,"DBNAME":"DB","COMMAND":"BEGIN NULL; END;","SUCC_ACTION":1,"FAIL_ACTION":1,"RETRY_ATTEMPTS":0,"RETRY_INTERVAL":0,"OUTPUT_FILE_PATH":null,"APPEND_FLAG":0,"SUCC_NEXT_STEP":null,"FAIL_NEXT_STEP":null,"DESCRIBE":"keep sql"}+ ])).unwrap(),+ schedules: serde_json::from_value(json!([+ {"ID":21,"JOBID":41,"NAME":"daily","TYPE":1,"ENABLE":1,"FREQ_INTERVAL":1,"FREQ_SUB_INTERVAL":0,"FREQ_MINUTE_INTERVAL":5,"STARTTIME":"23:00:00","ENDTIME":"01:00:00","DURING_START_DATE":"2026-10-21","DURING_END_DATE":"2026-12-31","DESCRIBE":"keep daily","VALID":"Y","SCHNAME":"sch1","TRIGNAME":"trig1"},+ {"ID":22,"JOBID":41,"NAME":"weekly","TYPE":2,"ENABLE":0,"FREQ_INTERVAL":3,"FREQ_SUB_INTERVAL":68,"FREQ_MINUTE_INTERVAL":0,"STARTTIME":"09:00:00","ENDTIME":null,"DURING_START_DATE":"2026-10-21","DURING_END_DATE":null,"DESCRIBE":"keep weekly","VALID":"Y","SCHNAME":"sch2","TRIGNAME":"trig2"}+ ])).unwrap(),+ owner: "Owner", system_definition: false, system_parts: false, legacy: None, legacy_denied: false,+ }+ }+}++fn result(columns: &[&str], rows: Value) -> Value {+ json!({"columns":columns,"rows":rows,"affected_rows":0,"execution_time_ms":0})+}++fn part_result(rows: &[NativeJobRow]) -> Value {+ let columns = rows+ .iter()+ .flat_map(|row| row.keys().cloned())+ .chain(std::iter::once("ID".into()))+ .collect::<std::collections::BTreeSet<_>>()+ .into_iter()+ .collect::<Vec<_>>();+ let values = rows+ .iter()+ .map(|row| columns.iter().map(|key| row.get(key).cloned().unwrap_or(Value::Null)).collect::<Vec<_>>())+ .collect::<Vec<_>>();+ json!({"columns":columns,"rows":values,"affected_rows":0,"execution_time_ms":0})+}++fn catalog(query: NativeJobCatalogQuery, data: &Database) -> Result<Value, NativeJobCatalogFailure> {+ if matches!(query.source, "SYSJOB.DBA_JOBS" | "SYSJOB.USER_JOBS") {+ if data.legacy_denied {+ return Err(NativeJobCatalogFailure::Denied(Some(-5515)));+ }+ return Ok(part_result(&data.legacy.clone().into_iter().collect::<Vec<_>>()));+ }+ if (query.source == "SYSJOB.SYSJOBS" && !data.system_definition)+ || (matches!(query.source, "SYSJOB.SYSJOBSTEPS" | "SYSJOB.SYSJOBSCHEDULES") && !data.system_parts)+ {+ return Err(NativeJobCatalogFailure::Denied(Some(-5515)));+ }+ if matches!(query.source, "SYSJOB.SYSJOBS" | "SYSJOB.USER_JOBS_VIEW") {+ if !data.exists {+ return Ok(result(&["DBX_JOB_ID", "NAME", "USERNAME"], json!([])));+ }+ if query.sql.contains("UPPER(NAME) = UPPER(") {+ let matches = query.sql.contains(&format!("UPPER('{}')", data.name.replace('\'', "''")));+ return Ok(result(+ &["DBX_JOB_ID", "NAME", "USERNAME"],+ if matches { json!([["41", data.name, data.owner]]) } else { json!([]) },+ ));+ }+ if query.sql.contains("AS DBX_CREATED_AT, NAME") {+ return Ok(result(+ &["DBX_JOB_ID", "DBX_CREATED_AT", "NAME", "USERNAME", "SYS_FLAG"],+ json!([["41", data.created, data.name, data.owner, if data.legacy.is_some() { 2 } else { 0 }]]),+ ));+ }+ return Ok(if query.sql.contains("AS DBX_CREATED_AT") {+ result(&["DBX_JOB_ID", "DBX_CREATED_AT"], json!([["41", data.created]]))+ } else {+ result(+ &[+ "ID",+ "DBX_JOB_ID",+ "NAME",+ "USERNAME",+ "CREATETIME",+ "MODIFYTIME",+ "ENABLE",+ "ENABLE_EMAIL",+ "EMAIL_OPERID",+ "EMAIL_TYPE",+ "ENABLE_NETSEND",+ "NETSEND_OPERID",+ "NETSEND_TYPE",+ "DESCRIBE",+ "VALID",+ "SYS_FLAG",+ "EP_SEQNO",+ "RAFT_NAME",+ ],+ json!([[+ 41,+ "41",+ data.name,+ data.owner,+ data.created,+ "modified",+ i32::from(data.enabled),+ 1,+ data.email_operator,+ 2,+ 0,+ -1,+ 1,+ data.description,+ data.valid,+ if data.legacy.is_some() { 2 } else { 0 },+ data.ep_seqno,+ null+ ]]),+ )+ });+ }+ if data.unreadable_parts && query.source != "SYSJOB.SYSOPERATORS" {+ return Err(NativeJobCatalogFailure::Denied(Some(-5515)));+ }+ match query.source {+ "SYSJOB.SYSJOBSTEPS" | "SYSJOB.USER_JOBSTEPS_VIEW" => {+ Ok(part_result(if query.source == "SYSJOB.USER_JOBSTEPS_VIEW" && data.owner != "Owner" {+ &[]+ } else {+ &data.steps+ }))+ }+ "SYSJOB.SYSJOBSCHEDULES" | "SYSJOB.USER_JOBSCHEDULES_VIEW" => {+ Ok(part_result(if query.source == "SYSJOB.USER_JOBSCHEDULES_VIEW" && data.owner != "Owner" {+ &[]+ } else {+ &data.schedules+ }))+ }+ _ => Err(NativeJobCatalogFailure::Unavailable(Some(-2106))),+ }+}++async fn read(state: &AppState, target: &NativeJobRef, data: &Database) -> NativeJobDetails {+ native_job_read_with(state, target, |query| std::future::ready(catalog(query, data))).await.unwrap()+}++async fn setup(data: &Database) -> (tempfile::TempDir, Arc<AppState>, NativeJobRef) {+ let dir = tempfile::tempdir().unwrap();+ let storage = dbx_core::persistence::test_storage::open(&dir.path().join("state.db")).await.unwrap();+ let state = Arc::new(AppState::new_with_plugin_and_agent_dir_and_app_version(+ storage,+ dir.path().join("plugins"),+ dir.path().join("agents"),+ "0.0.0",+ ));+ state.configs.write().await.insert(+ "c".into(),+ serde_json::from_value(json!({+ "id":"c","name":"test","db_type":"dameng","host":"127.0.0.1","port":1,"username":"Owner","password":""+ }))+ .unwrap(),+ );+ let context = native_job_open_context_with(&state, "c", "", |_| {+ std::future::ready(Ok(NativeJobRuntimeIdentity { database_info: None, session_user: "Owner".into() }))+ })+ .await+ .unwrap();+ let target = NativeJobRef::DamengNative { scope: context.scope, job_id: "41".into(), name: "Job_1".into() };+ let _ = read(&state, &target, data).await;+ (dir, state, target)+}++async fn prepare(state: &AppState, target: &NativeJobRef, data: &Database, attributes: Value) -> NativeJobPreparedPlan {+ let initial = read(state, target, data).await;+ native_job_prepare_with(+ state,+ NativeJobMutation {+ target: target.clone(),+ baseline: initial.snapshot.revision,+ change: NativeJobChange::Update {+ final_enabled: None,+ argument_target: None,+ attributes: serde_json::from_value(attributes).unwrap(),+ arguments: vec![],+ },+ },+ |target| async move { Ok(read(state, &target, data).await) },+ )+ .await+ .unwrap()+}++fn legacy_database() -> Database {+ Database { legacy: Some(serde_json::from_value(json!({"DBX_JOB_ID":"41", "JOB":41, "WHAT":"work(); ", "NEXT_DATE":"native date", "NEXT_SEC":"native second", "INTERVAL":"86400", "INSTANCE":1})).unwrap()), ..Database::default() }+}++#[tokio::test]+async fn legacy_control_freezes_only_the_independent_definition_observed_in_its_original_baseline() {+ for (original_denied, prepare_denied, after, stop) in [+ (false, false, "changed", false),+ (false, false, "denied", false),+ (true, true, "denied", false),+ (true, false, "changed", false),+ (false, false, "changed", true),+ (false, false, "denied", true),+ (false, false, "natural-date", false),+ ] {+ let mut original = legacy_database();+ original.legacy_denied = original_denied;+ let (_dir, state, native) = setup(&original).await;+ let target = NativeJobRef::Legacy { scope: native.scope().clone(), job_id: "41".into() };+ let initial = read(&state, &target, &original).await;+ let mut current = original.clone();+ current.legacy_denied = prepare_denied;+ let plan = native_job_prepare_with(+ &state,+ NativeJobMutation {+ target: target.clone(),+ baseline: initial.snapshot.revision,+ change: if stop { NativeJobChange::Stop { force: false } } else { NativeJobChange::Run },+ },+ |target| {+ let state = &state;+ let current = ¤t;+ async move { Ok(read(state, &target, current).await) }+ },+ )+ .await+ .unwrap();+ match after {+ "changed" => {+ current.legacy.as_mut().unwrap().insert("WHAT".into(), json!("externally changed();"));+ }+ "denied" => current.legacy_denied = true,+ "natural-date" => {+ current.legacy.as_mut().unwrap().insert("NEXT_DATE".into(), json!("naturally advanced"));+ }+ _ => unreachable!(),+ }+ let mut session = Session::new(&state, current);+ session.leased = true;+ let status = native_job_apply_with(&state, &plan.plan_id, &mut session).await.unwrap();+ if !original_denied && !stop && after != "natural-date" {+ assert_eq!(status.outcome, NativeJobOperationOutcome::NotApplied);+ assert!(session.writes().is_empty());+ assert_eq!(+ status.reason.as_deref(),+ Some(if after == "denied" {+ "native_job_metadata_incomplete"+ } else {+ "native_job_definition_changed"+ })+ );+ } else {+ assert_eq!(status.outcome, NativeJobOperationOutcome::Accepted);+ assert_eq!(session.writes(), vec![if stop { "stop" } else { "run" }]);+ }+ }+}++#[tokio::test]+async fn native_and_legacy_job_rename_preserve_activation_and_publish_only_the_verified_target() {+ for (legacy, enabled) in [(false, true), (false, false), (true, true)] {+ let mut data = if legacy { legacy_database() } else { Database::default() };+ data.enabled = enabled;+ let (_dir, state, original) = setup(&data).await;+ let target = if legacy {+ NativeJobRef::Legacy { scope: original.scope().clone(), job_id: "41".into() }+ } else {+ original+ };+ let attributes = json!([{"name":"NAME","change":{"kind":"set","value":"Renamed_Job"}}]);+ let plan = if legacy {+ prepare(&state, &target, &data, attributes).await+ } else {+ prepare_configuration(&state, &target, &data, json!({"attributes":attributes})).await+ };+ let mut session = Session::new(&state, data);+ let status = native_job_apply_with(&state, &plan.plan_id, &mut session).await.unwrap();+ assert_eq!(status.outcome, NativeJobOperationOutcome::Verified);+ assert_eq!(session.writes(), ["rename"]);+ assert_eq!(session.data.enabled, enabled);+ assert_eq!(status.observed_identity.as_ref().unwrap()["NAME"], json!("Renamed_Job"));+ let next = status.target.as_ref().unwrap();+ assert!(+ matches!(next, NativeJobRef::Legacy { job_id, .. } if legacy && job_id == "41")+ || matches!(next, NativeJobRef::DamengNative { job_id, name, .. } if !legacy && job_id == "41" && name == "Renamed_Job")+ );+ let current = read(&state, next, &session.data).await;+ assert!(matches!(current.snapshot.definition, NativeJobMetadata::Available { .. }));+ assert!(plan.steps[0].sql.contains("SP_RENAME_JOB('Job_1',"));+ }+}++#[tokio::test]+async fn mixed_job_rename_rebinds_final_enable_and_retains_the_effective_target_after_activation_failure() {+ for legacy in [false, true] {+ for fail_enable in [false, true] {+ let data = if legacy { legacy_database() } else { Database::default() };+ let (_dir, state, original) = setup(&data).await;+ let target = if legacy {+ NativeJobRef::Legacy { scope: original.scope().clone(), job_id: "41".into() }+ } else {+ original+ };+ let plan = prepare(&state, &target, &data, json!([{"name":"NAME","change":{"kind":"set","value":"Renamed_Job"}}, {"name":"DESCRIBE","change":{"kind":"set","value":"new"}}])).await;+ let mut session = Session::new(&state, data);+ if fail_enable {+ session.receipts.insert("enable".into(), NativeJobDispatchOutcome::NotStarted);+ }+ let status = native_job_apply_with(&state, &plan.plan_id, &mut session).await.unwrap();+ assert_eq!(+ status.outcome,+ if fail_enable { NativeJobOperationOutcome::Partial } else { NativeJobOperationOutcome::Verified }+ );+ assert_eq!(session.writes(), ["pause", "definition", "config_start", "config_commit", "rename", "enable"]);+ assert!(session.sent_steps.last().unwrap().sql.contains("SP_ENABLE_JOB('Renamed_Job', 1)"));+ assert!(session.sent_steps.last().unwrap().sql.contains("NAME = 'Renamed_Job'"));+ assert_eq!(status.observed_identity.as_ref().unwrap()["NAME"], json!("Renamed_Job"));+ assert_eq!(session.data.enabled, !fail_enable);+ }+ }+}++#[tokio::test]+async fn rename_commit_unknown_does_not_follow_same_session_state_or_replay() {+ let data = Database::default();+ let (_dir, state, target) = setup(&data).await;+ let plan =+ prepare(&state, &target, &data, json!([{"name":"NAME","change":{"kind":"set","value":"Renamed_Job"}}])).await;+ let mut session = Session::new(&state, data);+ session.receipts.insert("rename".into(), NativeJobDispatchOutcome::Unknown);+ let status = native_job_apply_with(&state, &plan.plan_id, &mut session).await.unwrap();+ assert_eq!(status.outcome, NativeJobOperationOutcome::Unknown);+ assert_eq!(status.target.as_ref(), Some(&target));+ assert!(status.observed_identity.is_none());+ assert_eq!(session.data.name, "Renamed_Job");+ let calls = session.calls.clone();+ assert_eq!(+ native_job_apply_with(&state, &plan.plan_id, &mut session).await.unwrap().outcome,+ NativeJobOperationOutcome::Unknown+ );+ assert_eq!(session.calls, calls);+}++#[tokio::test]+async fn rename_conflict_and_incomplete_configuration_block_before_dispatch() {+ for issue in ["conflict", "pending"] {+ let mut data = Database::default();+ if issue == "pending" {+ data.valid = "N";+ }+ let (_dir, state, target) = setup(&data).await;+ let plan =+ prepare(&state, &target, &data, json!([{"name":"NAME","change":{"kind":"set","value":"Renamed_Job"}}]))+ .await;+ let mut session = Session::new(&state, data);+ session.rename_conflict = issue == "conflict";+ let status = native_job_apply_with(&state, &plan.plan_id, &mut session).await.unwrap();+ assert_eq!(status.outcome, NativeJobOperationOutcome::NotApplied);+ assert!(session.writes().is_empty());+ }+}++#[tokio::test]+async fn rename_replacement_third_name_and_preservation_changes_never_complete_as_verified() {+ for difference in ["generation", "third-name", "description", "schedule"] {+ let data = Database::default();+ let (_dir, state, target) = setup(&data).await;+ let plan =+ prepare(&state, &target, &data, json!([{"name":"NAME","change":{"kind":"set","value":"Renamed_Job"}}]))+ .await;+ let mut session = Session::new(&state, data);+ session.rename_side_effect = Some(difference);+ let status = native_job_apply_with(&state, &plan.plan_id, &mut session).await.unwrap();+ assert_eq!(status.outcome, NativeJobOperationOutcome::Partial, "{difference}");+ assert_eq!(session.writes(), ["rename"]);+ if matches!(difference, "generation" | "third-name") {+ assert!(status.observed_identity.is_none());+ }+ }+}++#[tokio::test]+async fn legacy_body_edit_requires_an_exact_committed_readback_before_activation() {+ let data = legacy_database();+ let (_dir, state, native) = setup(&data).await;+ let target = NativeJobRef::Legacy { scope: native.scope().clone(), job_id: "41".into() };+ let body = "BEGIN work('O''ne'); END; ";+ let plan = prepare(&state, &target, &data, json!([{"name":"WHAT","change":{"kind":"set","value":body}}])).await;+ let mut session = Session::new(&state, data);+ session.what_construction = Some(body.into());+ let status = native_job_apply_with(&state, &plan.plan_id, &mut session).await.unwrap();+ assert_eq!(status.outcome, NativeJobOperationOutcome::Verified);+ assert_eq!(session.writes(), ["pause", "legacy_what", "enable"]);+ assert_eq!(session.data.legacy.as_ref().unwrap()["WHAT"], json!(body));+ assert!(session.data.enabled);+}++#[tokio::test]+async fn legacy_body_construction_must_be_lossless_and_unknown_commit_cannot_enable_or_replay() {+ for construction in [None, Some("truncated"), Some("BEGIN 你好('\\'); END; ")] {+ let data = legacy_database();+ let (_dir, state, native) = setup(&data).await;+ let target = NativeJobRef::Legacy { scope: native.scope().clone(), job_id: "41".into() };+ let body = "BEGIN 你好('\\'); END; ";+ let plan = prepare(&state, &target, &data, json!([{"name":"WHAT","change":{"kind":"set","value":body}}])).await;+ let mut session = Session::new(&state, data);+ session.what_construction = construction.map(str::to_string);+ session.receipts.insert("legacy_what".into(), NativeJobDispatchOutcome::Unknown);+ let status = native_job_apply_with(&state, &plan.plan_id, &mut session).await.unwrap();+ if construction == Some(body) {+ assert_eq!(status.outcome, NativeJobOperationOutcome::Unknown);+ assert_eq!(session.writes(), ["pause", "legacy_what"]);+ assert!(!session.data.enabled);+ } else {+ assert_eq!(status.outcome, NativeJobOperationOutcome::NotApplied);+ assert!(session.writes().is_empty());+ }+ let calls = session.calls.clone();+ assert_eq!(native_job_apply_with(&state, &plan.plan_id, &mut session).await.unwrap().outcome, status.outcome);+ assert_eq!(session.calls, calls);+ }+}++#[tokio::test]+async fn legacy_next_date_freezes_the_old_date_and_requires_exact_readback_after_activation() {+ for scenario in+ ["success", "construct-loss", "changed", "last-prewrite-change", "unknown", "advanced", "pause-date-drift"]+ {+ let mut data = legacy_database();+ data.legacy.as_mut().unwrap().insert("NEXT_DATE".into(), json!("2032-01-02 03:04:05"));+ data.legacy.as_mut().unwrap().insert("NEXT_SEC".into(), json!("03:04:05"));+ let (_dir, state, native) = setup(&data).await;+ let target = NativeJobRef::Legacy { scope: native.scope().clone(), job_id: "41".into() };+ let plan = prepare(+ &state,+ &target,+ &data,+ json!([{"name":"NEXT_DATE","change":{"kind":"set","value":"2032-02-03T04:05:06.123456000"}}]),+ )+ .await;+ let mut session = Session::new(&state, data);+ session.date_construction = Some(+ if scenario == "construct-loss" { "2032-02-03 04:05:06.123455" } else { " 2032-02-03 04:05:06.123456" }+ .into(),+ );+ session.date_change_on_read = match scenario {+ "changed" => Some(1),+ "last-prewrite-change" => Some(2),+ _ => None,+ };+ session.advance_on_enable = scenario == "advanced";+ session.date_change_on_pause = scenario == "pause-date-drift";+ if scenario == "unknown" {+ session.receipts.insert("legacy_next_date".into(), NativeJobDispatchOutcome::Unknown);+ }+ let status = native_job_apply_with(&state, &plan.plan_id, &mut session).await.unwrap();+ match scenario {+ "success" => assert_eq!(status.outcome, NativeJobOperationOutcome::Verified),+ "advanced" => assert_eq!(status.outcome, NativeJobOperationOutcome::Partial),+ "pause-date-drift" => {+ assert_eq!(status.outcome, NativeJobOperationOutcome::Partial);+ assert_eq!(session.writes(), ["pause"]);+ }+ "unknown" => {+ assert_eq!(status.outcome, NativeJobOperationOutcome::Unknown);+ assert_eq!(session.writes(), ["pause", "legacy_next_date"]);+ assert!(!session.data.enabled);+ }+ _ => {+ assert_eq!(status.outcome, NativeJobOperationOutcome::NotApplied, "{scenario}");+ assert!(session.writes().is_empty(), "{scenario}");+ }+ }+ }+}++#[tokio::test]+async fn legacy_mixed_body_and_date_preflight_failure_never_pauses_the_job() {+ let mut data = legacy_database();+ data.legacy.as_mut().unwrap().insert("NEXT_DATE".into(), json!("2032-01-02 03:04:05"));+ data.legacy.as_mut().unwrap().insert("NEXT_SEC".into(), json!("03:04:05"));+ let (_dir, state, native) = setup(&data).await;+ let target = NativeJobRef::Legacy { scope: native.scope().clone(), job_id: "41".into() };+ let plan = prepare(+ &state,+ &target,+ &data,+ json!([+ {"name":"WHAT","change":{"kind":"set","value":"new(); "}},+ {"name":"NEXT_DATE","change":{"kind":"set","value":"2032-02-03 04:05:06"}}+ ]),+ )+ .await;+ let mut session = Session::new(&state, data);+ session.what_construction = Some("new(); ".into());+ let status = native_job_apply_with(&state, &plan.plan_id, &mut session).await.unwrap();+ assert_eq!(status.outcome, NativeJobOperationOutcome::NotApplied);+ assert!(session.writes().is_empty());+ assert!(session.data.enabled);+}++#[tokio::test]+async fn legacy_interval_uses_the_owned_driver_and_preserves_custom_acceptance_after_enable() {+ for (input, expected) in [+ ("900719925474099312345", NativeJobOperationOutcome::Verified),+ ("SYSDATE+custom_next()", NativeJobOperationOutcome::Accepted),+ ] {+ let data = legacy_database();+ let (_dir, state, native) = setup(&data).await;+ let target = NativeJobRef::Legacy { scope: native.scope().clone(), job_id: "41".into() };+ let plan =+ prepare(&state, &target, &data, json!([{"name":"INTERVAL","change":{"kind":"set","value":input}}])).await;+ let mut session = Session::new(&state, data);+ let status = native_job_apply_with(&state, &plan.plan_id, &mut session).await.unwrap();+ assert_eq!(status.outcome, expected);+ assert_eq!(session.writes(), ["pause", "legacy_interval", "enable"]);+ assert!(session.data.enabled);+ assert_eq!(+ status.steps[1].state,+ if expected == NativeJobOperationOutcome::Accepted {+ NativeJobStepState::Accepted+ } else {+ NativeJobStepState::Applied+ }+ );+ assert_eq!(status.steps[2].state, NativeJobStepState::Applied);+ let calls = session.calls.clone();+ assert_eq!(native_job_apply_with(&state, &plan.plan_id, &mut session).await.unwrap().outcome, expected);+ assert_eq!(session.calls, calls);+ }+}++#[tokio::test]+async fn legacy_interval_commit_unknown_is_not_promoted_by_same_session_values_or_replayed() {+ let data = legacy_database();+ let (_dir, state, native) = setup(&data).await;+ let target = NativeJobRef::Legacy { scope: native.scope().clone(), job_id: "41".into() };+ let plan = prepare(&state, &target, &data, json!([{"name":"INTERVAL","change":{"kind":"set","value":"60"}}])).await;+ let mut session = Session::new(&state, data);+ session.receipts.insert("legacy_interval".into(), NativeJobDispatchOutcome::Unknown);+ let status = native_job_apply_with(&state, &plan.plan_id, &mut session).await.unwrap();+ assert_eq!(status.outcome, NativeJobOperationOutcome::Unknown);+ assert_eq!(session.writes(), ["pause", "legacy_interval"]);+ assert_eq!(session.data.legacy.as_ref().unwrap()["INTERVAL"], json!("60"));+ assert!(!session.data.enabled);+ let calls = session.calls.clone();+ assert_eq!(+ native_job_apply_with(&state, &plan.plan_id, &mut session).await.unwrap().outcome,+ NativeJobOperationOutcome::Unknown+ );+ assert_eq!(session.calls, calls);+}++#[tokio::test]+async fn legacy_custom_interval_stays_accepted_after_native_configuration_and_cleanup_must_succeed() {+ for cleanup_unknown in [false, true] {+ let data = legacy_database();+ let (_dir, state, native) = setup(&data).await;+ let target = NativeJobRef::Legacy { scope: native.scope().clone(), job_id: "41".into() };+ let plan = prepare(&state, &target, &data, json!([{"name":"DESCRIBE","change":{"kind":"set","value":"new"}}, {"name":"INTERVAL","change":{"kind":"set","value":"SYSDATE+custom_next()"}}])).await;+ let mut session = Session::new(&state, data);+ session.cleanup_unknown = cleanup_unknown;+ let status = native_job_apply_with(&state, &plan.plan_id, &mut session).await.unwrap();+ assert_eq!(+ session.writes(),+ ["pause", "definition", "config_start", "config_commit", "legacy_interval", "enable"]+ );+ assert_eq!(+ status.outcome,+ if cleanup_unknown { NativeJobOperationOutcome::Unknown } else { NativeJobOperationOutcome::Accepted }+ );+ assert_eq!(status.steps[4].state, NativeJobStepState::Accepted);+ assert!(session.data.enabled);+ }+}++#[tokio::test]+async fn legacy_interval_preservation_differences_stop_before_final_activation() {+ for difference in ["date", "body", "seconds", "schedule", "enable"] {+ let data = legacy_database();+ let (_dir, state, native) = setup(&data).await;+ let target = NativeJobRef::Legacy { scope: native.scope().clone(), job_id: "41".into() };+ let plan =+ prepare(&state, &target, &data, json!([{"name":"INTERVAL","change":{"kind":"set","value":"60"}}])).await;+ let mut session = Session::new(&state, data);+ session.interval_side_effect = Some(difference);+ let status = native_job_apply_with(&state, &plan.plan_id, &mut session).await.unwrap();+ assert_eq!(status.outcome, NativeJobOperationOutcome::Partial, "{difference}");+ assert_eq!(session.writes(), ["pause", "legacy_interval"], "{difference}");+ }+}++#[tokio::test]+async fn legacy_interval_checks_its_own_baseline_and_adjacent_body_changes() {+ for at in [1, 4] {+ let data = legacy_database();+ let (_dir, state, native) = setup(&data).await;+ let target = NativeJobRef::Legacy { scope: native.scope().clone(), job_id: "41".into() };+ let plan =+ prepare(&state, &target, &data, json!([{"name":"INTERVAL","change":{"kind":"set","value":"60"}}])).await;+ let mut session = Session::new(&state, data);+ session.legacy_change_on_read = Some(at);+ let status = native_job_apply_with(&state, &plan.plan_id, &mut session).await.unwrap();+ assert_eq!(+ status.outcome,+ if at == 1 { NativeJobOperationOutcome::NotApplied } else { NativeJobOperationOutcome::Partial }+ );+ assert_eq!(session.writes(), if at == 1 { vec![] } else { vec!["pause"] });+ }+}++#[tokio::test]+async fn legacy_interval_only_cannot_bypass_an_unknown_configuration_close() {+ let data = legacy_database();+ let (_dir, state, native) = setup(&data).await;+ let target = NativeJobRef::Legacy { scope: native.scope().clone(), job_id: "41".into() };+ let first =+ prepare(&state, &target, &data, json!([{"name":"DESCRIBE","change":{"kind":"set","value":"new"}}])).await;+ let mut session = Session::new(&state, data);+ session.receipts.insert("config_commit".into(), NativeJobDispatchOutcome::Unknown);+ assert_eq!(+ native_job_apply_with(&state, &first.plan_id, &mut session).await.unwrap().outcome,+ NativeJobOperationOutcome::Unknown+ );+ let interval =+ prepare(&state, &target, &session.data, json!([{"name":"INTERVAL","change":{"kind":"set","value":"60"}}]))+ .await;+ let mut next = Session::new(&state, session.data.clone());+ let status = native_job_apply_with(&state, &interval.plan_id, &mut next).await.unwrap();+ assert_eq!(status.outcome, NativeJobOperationOutcome::NotApplied);+ assert_eq!(status.reason.as_deref(), Some("native_job_configuration_preview_required"));+ assert!(next.writes().is_empty());+}++#[tokio::test]+async fn legacy_interval_requires_complete_child_coverage_without_restricting_native_only_edits() {+ for owner in ["Owner", "Other"] {+ let mut data = legacy_database();+ data.owner = owner;+ data.system_definition = true;+ if owner == "Owner" {+ data.steps.clear();+ data.schedules.clear();+ }+ let (_dir, state, native) = setup(&data).await;+ let target = NativeJobRef::Legacy { scope: native.scope().clone(), job_id: "41".into() };+ let plan =+ prepare(&state, &target, &data, json!([{"name":"INTERVAL","change":{"kind":"set","value":"60"}}])).await;+ let mut session = Session::new(&state, data.clone());+ let status = native_job_apply_with(&state, &plan.plan_id, &mut session).await.unwrap();+ assert_eq!(+ status.outcome,+ if owner == "Owner" { NativeJobOperationOutcome::Verified } else { NativeJobOperationOutcome::NotApplied }+ );+ if owner == "Other" {+ assert!(session.writes().is_empty());+ assert_eq!(status.reason.as_deref(), Some("native_job_legacy_coverage_incomplete"));+ let ordinary =+ prepare(&state, &target, &data, json!([{"name":"DESCRIBE","change":{"kind":"set","value":"new"}}]))+ .await;+ let mut native_only = Session::new(&state, data);+ assert_eq!(+ native_job_apply_with(&state, &ordinary.plan_id, &mut native_only).await.unwrap().outcome,+ NativeJobOperationOutcome::Verified+ );+ }+ }+}++struct Session {+ state: Arc<AppState>,+ data: Database,+ leased: bool,+ calls: Vec<String>,+ receipts: BTreeMap<String, NativeJobDispatchOutcome>,+ read_count: usize,+ cancel_on_read: Option<(usize, String)>,+ cancel_on_step: Option<(String, String)>,+ readonly_on_read: Option<usize>,+ replace_on_read: Option<usize>,+ operator_denied: bool,+ cleanup_unknown: bool,+ leave_protocol_fields_unchanged: bool,+ wrong_operator: bool,+ sent_steps: Vec<NativeJobSqlStep>,+ replace_child_on_read: Option<(usize, String)>,+ tamper_unrelated: bool,+ hide_parts_after_drop: bool,+ interval_side_effect: Option<&'static str>,+ legacy_change_on_read: Option<usize>,+ rename_conflict: bool,+ rename_side_effect: Option<&'static str>,+ what_construction: Option<String>,+ date_construction: Option<String>,+ date_change_on_read: Option<usize>,+ advance_on_enable: bool,+ date_change_on_pause: bool,+}++impl Session {+ fn new(state: &Arc<AppState>, data: Database) -> Self {+ Self {+ state: state.clone(),+ data,+ leased: false,+ calls: vec![],+ receipts: BTreeMap::new(),+ read_count: 0,+ cancel_on_read: None,+ cancel_on_step: None,+ readonly_on_read: None,+ replace_on_read: None,+ operator_denied: false,+ cleanup_unknown: false,+ leave_protocol_fields_unchanged: false,+ wrong_operator: false,+ sent_steps: vec![],+ replace_child_on_read: None,+ tamper_unrelated: false,+ hide_parts_after_drop: false,+ interval_side_effect: None,+ legacy_change_on_read: None,+ rename_conflict: false,+ rename_side_effect: None,+ what_construction: None,+ date_construction: None,+ date_change_on_read: None,+ advance_on_enable: false,+ date_change_on_pause: false,+ }+ }+ fn writes(&self) -> Vec<&str> {+ self.calls.iter().filter_map(|call| call.strip_prefix("write:")).collect()+ }+}++#[async_trait::async_trait]+impl NativeJobMutationSession for Session {+ async fn begin_configure(&mut self, _: &str) -> Result<(), &'static str> {+ assert!(!self.leased);+ self.leased = true;+ self.calls.push("lease".into());+ Ok(())+ }+ async fn read(&mut self, target: &NativeJobRef) -> Result<NativeJobDetails, &'static str> {+ if !self.leased {+ return Err("fixture_configuration_read_requires_owned_physical_session");+ }+ self.read_count += 1;+ self.calls.push("read".into());+ if self.date_change_on_read == Some(self.read_count) {+ self.data.legacy.as_mut().unwrap().insert("NEXT_DATE".into(), json!("2032-01-03 03:04:05"));+ }+ if self.legacy_change_on_read == Some(self.read_count) {+ self.data.legacy.as_mut().unwrap().insert("WHAT".into(), json!("external_change();"));+ }+ if self.replace_on_read == Some(self.read_count) {+ self.data.created = "replacement";+ }+ if let Some((at, name)) = &self.replace_child_on_read {+ if *at == self.read_count {+ self.data+ .steps+ .iter_mut()+ .find(|row| row["NAME"].as_str() == Some(name))+ .unwrap()+ .insert("ID".into(), json!(999));+ }+ }+ let details = read(&self.state, target, &self.data).await;+ if let Some((count, id)) = &self.cancel_on_read {+ if *count == self.read_count {+ native_job_cancel(&self.state, id);+ }+ }+ if self.readonly_on_read == Some(self.read_count) {+ self.state.configs.write().await.get_mut("c").unwrap().read_only = true;+ }+ Ok(details)+ }+ async fn query(&mut self, query: NativeJobCatalogQuery) -> Result<Value, NativeJobCatalogFailure> {+ assert!(self.leased);+ if query.source == "DUAL" {+ self.calls.push("what_construct".into());+ return Ok(result(+ &["DBX_WHAT", "DBX_NEXT_DATE"],+ json!([[self.what_construction, self.date_construction]]),+ ));+ }+ if matches!(query.source, "SYSJOB.SYSJOBS" | "SYSJOB.USER_JOBS_VIEW") {+ self.calls.push("lookup".into());+ if self.rename_conflict && query.sql.contains("UPPER(NAME) = UPPER(") {+ return Ok(result(&["DBX_JOB_ID", "NAME", "USERNAME"], json!([["99", "Renamed_Job", "Owner"]])));+ }+ return catalog(query, &self.data);+ }+ assert_eq!(query.source, "SYSJOB.SYSOPERATORS");+ self.calls.push("operators".into());+ if self.operator_denied {+ return Err(NativeJobCatalogFailure::Denied(Some(-5515)));+ }+ Ok(result(+ &["DBX_OPERATOR_ID", "NAME", "DBX_MATCH_EMAIL_OPERID", "DBX_MATCH_NETSEND_OPERID"],+ json!([["7", "OnCall", 1, 0]]),+ ))+ }+ async fn execute(&mut self, step: &NativeJobSqlStep) -> NativeJobStepReceipt {+ assert!(self.leased);+ self.calls.push(format!("write:{}", step.id));+ self.sent_steps.push(step.clone());+ let outcome = self.receipts.get(&step.id).copied().unwrap_or(NativeJobDispatchOutcome::Applied);+ if outcome != NativeJobDispatchOutcome::NotStarted {+ match step.id.as_str() {+ "create" => {+ self.data.exists = true;+ self.data.enabled = false;+ self.data.description = "new";+ self.data.valid = "N";+ }+ "pause" => {+ self.data.enabled = false;+ if self.date_change_on_pause {+ self.data.legacy.as_mut().unwrap().insert("NEXT_DATE".into(), json!("2033-01-02 03:04:05"));+ }+ }+ "definition" => {+ self.data.description = "new";+ if self.wrong_operator {+ self.data.email_operator = 99;+ }+ }+ "config_start" if !self.leave_protocol_fields_unchanged => self.data.valid = "N",+ "config_commit" if !self.leave_protocol_fields_unchanged => self.data.valid = "Y",+ "attribute:EP_SEQNO" => self.data.ep_seqno = 2,+ "enable" => {+ self.data.enabled = true;+ if self.advance_on_enable {+ self.data+ .legacy+ .as_mut()+ .unwrap()+ .insert("NEXT_DATE".into(), json!("2033-02-03 04:05:06.123456"));+ }+ }+ "rename" => {+ let NativeJobStepEffect::DamengRenamed { new_name, .. } = &step.effect else { unreachable!() };+ self.data.name = new_name.clone();+ match self.rename_side_effect {+ Some("generation") => self.data.created = "replacement",+ Some("third-name") => self.data.name = "Third Name".into(),+ Some("description") => self.data.description = "external description",+ Some("schedule") => {+ self.data.schedules[0].insert("ID".into(), json!(999));+ }+ _ => {}+ }+ }+ "legacy_what" => {+ let NativeJobStepEffect::DamengLegacyWhat { expected } = &step.effect else { unreachable!() };+ self.data.legacy.as_mut().unwrap().insert("WHAT".into(), json!(expected));+ }+ "legacy_next_date" => {+ let NativeJobStepEffect::DamengLegacyNextDate { expected } = &step.effect else { unreachable!() };+ self.data.legacy.as_mut().unwrap().insert("NEXT_DATE".into(), json!(expected));+ self.data.legacy.as_mut().unwrap().insert("NEXT_SEC".into(), json!("04:05:06"));+ }+ "legacy_interval" => {+ let NativeJobStepEffect::DamengLegacyInterval { expected_seconds } = &step.effect else {+ unreachable!()+ };+ self.data+ .legacy+ .as_mut()+ .unwrap()+ .insert("INTERVAL".into(), json!(expected_seconds.as_deref().unwrap_or("12345")));+ match self.interval_side_effect {+ Some("date") => {+ self.data.legacy.as_mut().unwrap().insert("NEXT_DATE".into(), json!("changed date"));+ }+ Some("body") => {+ self.data.legacy.as_mut().unwrap().insert("WHAT".into(), json!("changed();"));+ }+ Some("seconds") => {+ self.data.legacy.as_mut().unwrap().insert("INTERVAL".into(), json!("999"));+ }+ Some("schedule") => {+ self.data.schedules[0].insert("ID".into(), json!(999));+ }+ Some("enable") => self.data.enabled = true,+ _ => {}+ }+ }+ _ => {}+ }+ if let NativeJobStepEffect::DamengChild(child) = &step.effect {+ let rows = if child.part == NativeJobDamengPart::Steps {+ &mut self.data.steps+ } else {+ &mut self.data.schedules+ };+ match &child.action {+ NativeJobDamengChildAction::Added => {+ let id = 100 + rows.len();+ let mut row: NativeJobRow =+ serde_json::from_value(json!({"ID":id,"JOBID":41,"NAME":child.name})).unwrap();+ if child.part == NativeJobDamengPart::Steps {+ row.extend(serde_json::from_value::<NativeJobRow>(json!({"SEQNO":rows.len()+1,"DBNAME":"DB","SUCC_NEXT_STEP":null,"FAIL_NEXT_STEP":null})).unwrap());+ } else {+ row.extend(+ serde_json::from_value::<NativeJobRow>(+ json!({"SCHNAME":"generated","TRIGNAME":"generated","VALID":"N"}),+ )+ .unwrap(),+ );+ }+ row.extend(child.fields.clone());+ for key in &child.acknowledged_fields {+ row.insert(+ key.clone(),+ json!(if key == "COMMAND" {+ "native generated replacement command"+ } else {+ "2026-10-21"+ }),+ );+ }+ rows.push(row);+ }+ NativeJobDamengChildAction::Changed => {+ let row = rows+ .iter_mut()+ .find(|row| row["NAME"].as_str().is_some_and(|name| name.eq_ignore_ascii_case(&child.name)))+ .unwrap();+ row.extend(child.fields.clone());+ for key in &child.acknowledged_fields {+ row.insert(+ key.clone(),+ json!(if key == "COMMAND" {+ "native generated replacement command"+ } else {+ "2026-10-21"+ }),+ );+ }+ }+ NativeJobDamengChildAction::Renamed(name) => {+ rows.iter_mut()+ .find(|row| row["NAME"].as_str() == Some(&child.name))+ .unwrap()+ .insert("NAME".into(), json!(name));+ // This fixture leaves old references unchanged, requiring the explicit link step.+ }+ NativeJobDamengChildAction::Dropped => {+ rows.retain(|row| row["NAME"].as_str() != Some(&child.name));+ if child.part == NativeJobDamengPart::Steps {+ for (index, row) in rows.iter_mut().enumerate() {+ row.insert("SEQNO".into(), json!(index + 1));+ }+ }+ if self.hide_parts_after_drop {+ self.data.system_parts = false;+ }+ }+ }+ if self.tamper_unrelated && child.part == NativeJobDamengPart::Steps {+ self.data.schedules[0].insert("DESCRIBE".into(), json!("external edit"));+ }+ }+ }+ if let Some((at, id)) = &self.cancel_on_step {+ if at == &step.id {+ native_job_cancel(&self.state, id);+ }+ }+ NativeJobStepReceipt { outcome, reason: None, vendor_code: None }+ }+ async fn finish(&mut self) -> Result<(), &'static str> {+ self.calls.push("close".into());+ self.leased = false;+ if self.cleanup_unknown {+ Err("fixture_dispose_unknown")+ } else {+ Ok(())+ }+ }+}++fn description_change() -> Value {+ json!([{"name":"DESCRIBE","change":{"kind":"set","value":"new"}}])+}++async fn prepare_control(+ state: &AppState,+ target: &NativeJobRef,+ data: &Database,+ change: NativeJobChange,+) -> NativeJobPreparedPlan {+ let before = read(state, target, data).await;+ native_job_prepare_with(+ state,+ NativeJobMutation { target: target.clone(), baseline: before.snapshot.revision, change },+ |target| async move { Ok(read(state, &target, data).await) },+ )+ .await+ .unwrap()+}++async fn prepare_configuration(+ state: &AppState,+ target: &NativeJobRef,+ data: &Database,+ configuration: Value,+) -> NativeJobPreparedPlan {+ prepare_control(+ state,+ target,+ data,+ NativeJobChange::ConfigureDameng { configuration: serde_json::from_value(configuration).unwrap() },+ )+ .await+}++#[tokio::test]+async fn metadata_edit_uses_one_owned_session_and_preserves_notifications_steps_and_schedules() {+ let data = Database::default();+ let (_dir, state, target) = setup(&data).await;+ let plan = prepare(&state, &target, &data, description_change()).await;+ let mut session = Session::new(&state, data);+ let status = native_job_apply_with(&state, &plan.plan_id, &mut session).await.unwrap();+ assert!(+ status.outcome == NativeJobOperationOutcome::Verified,+ "configuration must complete on its owned connection"+ );+ assert_eq!(session.calls.first().map(String::as_str), Some("lease"));+ assert_eq!(session.calls.last().map(String::as_str), Some("close"));+ assert_eq!(session.writes(), ["pause", "definition", "config_start", "config_commit", "enable"]);+ assert!(+ session.calls.iter().position(|call| call == "operators").unwrap()+ < session.calls.iter().position(|call| call == "write:pause").unwrap()+ );+ assert!(session.data.enabled);+ assert_eq!(session.data.email_operator, 7);+}++#[tokio::test]+async fn missing_operator_privilege_blocks_only_the_dependent_edit_before_any_pause() {+ let data = Database::default();+ let (_dir, state, target) = setup(&data).await;+ let plan = prepare(&state, &target, &data, description_change()).await;+ let mut session = Session::new(&state, data.clone());+ session.operator_denied = true;+ let status = native_job_apply_with(&state, &plan.plan_id, &mut session).await.unwrap();+ assert!(status.outcome == NativeJobOperationOutcome::NotApplied);+ assert_eq!(status.reason.as_deref(), Some("native_job_notification_operator_unverified"));+ assert!(session.writes().is_empty());+ let data = Database { enabled: false, unreadable_parts: true, ..data };+ let plan = prepare(&state, &target, &data, json!([{"name":"EP_SEQNO","change":{"kind":"set","value":2}}])).await;+ let mut session = Session::new(&state, data);+ session.operator_denied = true;+ let status = native_job_apply_with(&state, &plan.plan_id, &mut session).await.unwrap();+ assert!(status.outcome == NativeJobOperationOutcome::Verified);+ assert_eq!(session.writes(), ["pause", "config_start", "attribute:EP_SEQNO", "config_commit"]);+ assert!(!session.calls.iter().any(|call| call == "operators"));+}++#[tokio::test]+async fn cancellation_or_readonly_arriving_during_preflight_never_dispatches_a_native_write() {+ for readonly in [false, true] {+ let data = Database::default();+ let (_dir, state, target) = setup(&data).await;+ let plan = prepare(&state, &target, &data, description_change()).await;+ let mut session = Session::new(&state, data);+ if readonly {+ session.readonly_on_read = Some(1);+ } else {+ session.cancel_on_read = Some((1, plan.operation_id.clone()));+ }+ let status = native_job_apply_with(&state, &plan.plan_id, &mut session).await.unwrap();+ assert!(status.outcome == NativeJobOperationOutcome::NotApplied);+ assert!(session.writes().is_empty());+ assert_eq!(session.calls.last().map(String::as_str), Some("close"));+ }+}++#[tokio::test]+async fn lost_start_or_commit_receipt_stays_unknown_even_when_definition_fields_match() {+ for stage in ["config_start", "config_commit"] {+ let data = Database::default();+ let (_dir, state, target) = setup(&data).await;+ let plan = prepare(&state, &target, &data, description_change()).await;+ let mut session = Session::new(&state, data);+ session.receipts.insert(stage.into(), NativeJobDispatchOutcome::Unknown);+ session.leave_protocol_fields_unchanged = true;+ let status = native_job_apply_with(&state, &plan.plan_id, &mut session).await.unwrap();+ assert!(status.outcome == NativeJobOperationOutcome::Unknown);+ assert_eq!(session.writes().last().copied(), Some(stage));+ assert!(!session.data.enabled);+ assert!(status.steps.iter().any(|step| step.id == stage && step.state == NativeJobStepState::Unknown));+ let count = session.calls.len();+ native_job_apply_with(&state, &plan.plan_id, &mut session).await.unwrap();+ assert_eq!(session.calls.len(), count, "repeated apply must not replay the configuration");+ }+}++#[tokio::test]+async fn cancellation_after_start_closes_without_automatic_commit_or_activation() {+ let data = Database::default();+ let (_dir, state, target) = setup(&data).await;+ let plan = prepare(&state, &target, &data, description_change()).await;+ let mut session = Session::new(&state, data);+ session.cancel_on_step = Some(("config_start".into(), plan.operation_id.clone()));+ let status = native_job_apply_with(&state, &plan.plan_id, &mut session).await.unwrap();+ assert!(status.outcome == NativeJobOperationOutcome::Partial);+ assert_eq!(session.writes(), ["pause", "definition", "config_start"]);+ assert!(!session.data.enabled);+ assert_eq!(session.data.valid, "N");+}++#[tokio::test]+async fn ordinary_metadata_lost_receipt_can_be_resolved_by_exact_readback() {+ let data = Database::default();+ let (_dir, state, target) = setup(&data).await;+ let plan = prepare(&state, &target, &data, description_change()).await;+ let mut session = Session::new(&state, data);+ session.receipts.insert("definition".into(), NativeJobDispatchOutcome::Unknown);+ let status = native_job_apply_with(&state, &plan.plan_id, &mut session).await.unwrap();+ assert!(status.outcome == NativeJobOperationOutcome::Verified);+ assert_eq!(session.writes().iter().filter(|stage| **stage == "definition").count(), 1);+}++#[tokio::test]+async fn wrong_native_operator_or_replaced_generation_stops_the_remaining_configuration() {+ for replaced in [false, true] {+ let data = Database::default();+ let (_dir, state, target) = setup(&data).await;+ let plan = prepare(&state, &target, &data, description_change()).await;+ let mut session = Session::new(&state, data);+ if replaced {+ session.replace_on_read = Some(2);+ } else {+ session.wrong_operator = true;+ }+ let status = native_job_apply_with(&state, &plan.plan_id, &mut session).await.unwrap();+ assert!(status.outcome != NativeJobOperationOutcome::Verified);+ assert!(!session.writes().contains(&"config_start"));+ assert!(!session.writes().contains(&"enable"));+ }+}++#[tokio::test]+async fn final_activation_failure_preserves_confirmed_configuration_and_cleanup_unknown_is_not_success() {+ for cleanup in [false, true] {+ let data = Database::default();+ let (_dir, state, target) = setup(&data).await;+ let plan = prepare(&state, &target, &data, description_change()).await;+ let mut session = Session::new(&state, data);+ if cleanup {+ session.cleanup_unknown = true;+ } else {+ session.receipts.insert("enable".into(), NativeJobDispatchOutcome::NotStarted);+ }+ let status = native_job_apply_with(&state, &plan.plan_id, &mut session).await.unwrap();+ assert!(+ status.outcome+ == if cleanup { NativeJobOperationOutcome::Unknown } else { NativeJobOperationOutcome::Partial }+ );+ assert!(status+ .steps+ .iter()+ .any(|step| step.id == "config_commit" && step.state == NativeJobStepState::Applied));+ if !cleanup {+ assert!(!session.data.enabled);+ }+ assert_eq!(session.data.valid, "Y");+ assert_eq!(session.writes().iter().filter(|stage| **stage == "config_start").count(), 1);+ }+}++#[tokio::test]+async fn unknown_configuration_requires_a_new_cycle_even_if_a_previous_enable_or_run_preview_still_matches() {+ for control in [NativeJobChange::Enable, NativeJobChange::Run] {+ let data = Database { enabled: false, ..Default::default() };+ let (_dir, state, target) = setup(&data).await;+ let old = prepare_control(&state, &target, &data, control).await;+ let configure =+ prepare(&state, &target, &data, json!([{"name":"ENABLE","change":{"kind":"set","value":false}}])).await;+ let mut session = Session::new(&state, data.clone());+ session.leave_protocol_fields_unchanged = true;+ session.receipts.insert("config_commit".into(), NativeJobDispatchOutcome::Unknown);+ let status = native_job_apply_with(&state, &configure.plan_id, &mut session).await.unwrap();+ assert!(status.outcome == NativeJobOperationOutcome::Unknown);+ assert_eq!(session.data.valid, "Y");+ assert_eq!(session.data.description, data.description);+ let mut unused = Session::new(&state, session.data);+ let status = native_job_apply_with(&state, &old.plan_id, &mut unused).await.unwrap();+ assert!(status.outcome == NativeJobOperationOutcome::NotApplied);+ assert_eq!(status.reason.as_deref(), Some("native_job_configuration_preview_required"));+ assert!(unused.writes().is_empty());+ }+}++#[tokio::test]+async fn new_enable_preview_finishes_unknown_configuration_in_a_new_session_without_replaying_fields() {+ let data = Database::default();+ let (_dir, state, target) = setup(&data).await;+ let first = prepare(&state, &target, &data, description_change()).await;+ let mut session = Session::new(&state, data);+ session.receipts.insert("config_commit".into(), NativeJobDispatchOutcome::Unknown);+ assert!(+ native_job_apply_with(&state, &first.plan_id, &mut session).await.unwrap().outcome+ == NativeJobOperationOutcome::Unknown+ );+ let resume = prepare_control(&state, &target, &session.data, NativeJobChange::Enable).await;+ assert_eq!(+ resume.steps.iter().map(|step| step.id.as_str()).collect::<Vec<_>>(),+ ["pause", "config_start", "config_commit", "enable"]+ );+ let mut new_session = Session::new(&state, session.data);+ let status = native_job_apply_with(&state, &resume.plan_id, &mut new_session).await.unwrap();+ assert!(status.outcome == NativeJobOperationOutcome::Verified);+ assert_eq!(new_session.writes(), ["pause", "config_start", "config_commit", "enable"]);+ assert_eq!(new_session.data.description, "new");+ assert!(native_job_status(&state, &first.operation_id).outcome == NativeJobOperationOutcome::Unknown);+ let after = prepare_control(&state, &target, &new_session.data, NativeJobChange::Enable).await;+ assert_eq!(after.steps.len(), 1, "a confirmed new cycle resolves the pending-protocol guard");+}++#[tokio::test]+async fn a_confirmed_configuration_with_failed_activation_previews_and_executes_only_the_remaining_enable() {+ let data = Database::default();+ let (_dir, state, target) = setup(&data).await;+ let first = prepare(&state, &target, &data, description_change()).await;+ let mut session = Session::new(&state, data);+ session.receipts.insert("enable".into(), NativeJobDispatchOutcome::NotStarted);+ assert!(+ native_job_apply_with(&state, &first.plan_id, &mut session).await.unwrap().outcome+ == NativeJobOperationOutcome::Partial+ );+ let resume = prepare_control(&state, &target, &session.data, NativeJobChange::Enable).await;+ assert_eq!(resume.steps.iter().map(|step| step.id.as_str()).collect::<Vec<_>>(), ["enable"]);+ let mut ordinary = Session::new(&state, session.data);+ ordinary.leased = true;+ assert!(+ native_job_apply_with(&state, &resume.plan_id, &mut ordinary).await.unwrap().outcome+ == NativeJobOperationOutcome::Verified+ );+ assert_eq!(ordinary.writes(), ["enable"]);+ assert!(!ordinary.calls.iter().any(|call| call == "lease"));+}++#[tokio::test]+async fn a_configuration_call_known_not_started_does_not_create_a_spurious_recovery_requirement() {+ let data = Database::default();+ let (_dir, state, target) = setup(&data).await;+ let first = prepare(&state, &target, &data, description_change()).await;+ let mut session = Session::new(&state, data);+ session.receipts.insert("definition".into(), NativeJobDispatchOutcome::NotStarted);+ assert!(+ native_job_apply_with(&state, &first.plan_id, &mut session).await.unwrap().outcome+ == NativeJobOperationOutcome::Partial+ );+ let resume = prepare_control(&state, &target, &session.data, NativeJobChange::Enable).await;+ assert_eq!(resume.steps.len(), 1);+}++#[tokio::test]+async fn an_observed_incomplete_native_definition_uses_start_and_commit_even_without_a_local_operation_record() {+ let data = Database { enabled: false, valid: "N", ..Default::default() };+ let (_dir, state, target) = setup(&data).await;+ let plan = prepare_control(&state, &target, &data, NativeJobChange::Enable).await;+ assert_eq!(+ plan.steps.iter().map(|step| step.id.as_str()).collect::<Vec<_>>(),+ ["pause", "config_start", "config_commit", "enable"]+ );+ let mut session = Session::new(&state, data);+ assert!(+ native_job_apply_with(&state, &plan.plan_id, &mut session).await.unwrap().outcome+ == NativeJobOperationOutcome::Verified+ );+}++#[tokio::test]+async fn step_and_schedule_edits_preserve_unmodified_native_configuration_on_the_owned_session() {+ let data = Database::default();+ let (_dir, state, target) = setup(&data).await;+ let plan = prepare_configuration(+ &state,+ &target,+ &data,+ json!({+ "steps":[{"kind":"update","name":"sql","attributes":[+ {"name":"COMMAND_INPUT","change":{"kind":"set","value":"BEGIN work('private'); END;"}},+ {"name":"RETRY_ATTEMPTS","change":{"kind":"set","value":3}}+ ]}],+ "schedules":[{"kind":"update","name":"weekly","attributes":[+ {"name":"ENABLE","change":{"kind":"set","value":true}},+ {"name":"DURING_END_DATE","change":{"kind":"set","value":"2027-01-01"}}+ ]}]+ }),+ )+ .await;+ let mut session = Session::new(&state, data.clone());+ let status = native_job_apply_with(&state, &plan.plan_id, &mut session).await.unwrap();+ assert!(status.outcome == NativeJobOperationOutcome::Verified, "{}", serde_json::to_value(&status).unwrap());+ assert_eq!(session.data.steps[0], data.steps[0]);+ assert_eq!(session.data.schedules[0], data.schedules[0]);+ assert_eq!(session.data.steps[1]["COMMAND"], "BEGIN work('private'); END;");+ assert_eq!(session.data.steps[1]["RETRY_ATTEMPTS"], 3);+ assert_eq!(session.data.schedules[1]["ENABLE"], true);+ assert_eq!(session.data.schedules[1]["DURING_END_DATE"], "2027-01-01");+ assert_eq!(session.data.email_operator, data.email_operator);+ assert!(session.data.enabled);+ assert_eq!(session.calls.first().map(String::as_str), Some("lease"));+ assert_eq!(session.calls.last().map(String::as_str), Some("close"));+ assert!(!session.calls.iter().any(|call| call == "operators"));+}++#[tokio::test]+async fn added_steps_use_acknowledged_native_ids_for_forward_links_without_rewriting_the_body() {+ let data = Database::default();+ let (_dir, state, target) = setup(&data).await;+ let body = "BEGIN work(':dbx_created_step_id', ':dbx_created_reference_id_0'); END;";+ let plan = prepare_configuration(&state, &target, &data, json!({"steps":[+ {"kind":"add","name":"new_a","attributes":[+ {"name":"COMMAND_INPUT","change":{"kind":"set","value":body}},+ {"name":"SUCC_ACTION","change":{"kind":"set","value":3}},+ {"name":"SUCC_NEXT_STEP","change":{"kind":"set","value":"new_b"}}+ ]},+ {"kind":"add","name":"new_b","attributes":[{"name":"COMMAND_INPUT","change":{"kind":"set","value":"SELECT 3;"}}]}+ ]})).await;+ let mut session = Session::new(&state, data);+ let status = native_job_apply_with(&state, &plan.plan_id, &mut session).await.unwrap();+ assert!(status.outcome == NativeJobOperationOutcome::Verified, "{}", serde_json::to_value(&status).unwrap());+ let linked =+ session.sent_steps.iter().find(|step| step.sql.contains("SP_JOB_STEP_SET_NEXT_STEP('Job_1', 'new_a'")).unwrap();+ assert!(linked.sql.contains("ID = 102") && linked.sql.contains("ID = 103"));+ assert!(!linked.sql.contains(":dbx_created"));+ assert_eq!(session.data.steps[2]["COMMAND"], body);+ assert_eq!(session.data.steps[2]["SUCC_NEXT_STEP"], "new_b");+ let added = session.sent_steps.iter().rposition(|step| step.sql.contains("SP_ADD_JOB_STEP_EX")).unwrap();+ let linked = session.sent_steps.iter().position(|step| step.sql.contains("SP_JOB_STEP_SET_NEXT_STEP")).unwrap();+ assert!(added < linked);+}++#[tokio::test]+async fn unknown_add_or_generated_command_receipt_never_adopts_matching_catalog_fields_or_replays() {+ for configuration in [+ json!({"steps":[{"kind":"add","name":"new_step","attributes":[{"name":"COMMAND_INPUT","change":{"kind":"set","value":"SELECT 2;"}}]}]}),+ json!({"steps":[{"kind":"update","name":"backup","attributes":[{"name":"COMMAND_INPUT","change":{"kind":"set","value":"01000000E:\\backups"}}]}]}),+ json!({"schedules":[{"kind":"add","name":"new_schedule"}]}),+ ] {+ let data = Database::default();+ let (_dir, state, target) = setup(&data).await;+ let plan = prepare_configuration(&state, &target, &data, configuration).await;+ let child = plan+ .steps+ .iter()+ .find(|step| step.id.starts_with("steps:") || step.id.starts_with("schedules:"))+ .unwrap()+ .id+ .clone();+ let mut session = Session::new(&state, data);+ session.receipts.insert(child.clone(), NativeJobDispatchOutcome::Unknown);+ let status = native_job_apply_with(&state, &plan.plan_id, &mut session).await.unwrap();+ assert!(status.outcome == NativeJobOperationOutcome::Unknown);+ assert_eq!(session.writes().last().copied(), Some(child.as_str()));+ assert!(!session.data.enabled);+ assert!(!session.writes().contains(&"config_commit"));+ let count = session.sent_steps.len();+ native_job_apply_with(&state, &plan.plan_id, &mut session).await.unwrap();+ assert_eq!(session.sent_steps.len(), count);+ }+}++#[tokio::test]+async fn unknown_sql_step_receipt_is_resolved_by_exact_identity_and_complete_readback() {+ let data = Database::default();+ let (_dir, state, target) = setup(&data).await;+ let plan = prepare_configuration(&state, &target, &data, json!({"steps":[{"kind":"update","name":"sql","attributes":[{"name":"RETRY_INTERVAL","change":{"kind":"set","value":10}}]}]})).await;+ let child = plan.steps.iter().find(|step| step.id.starts_with("steps:")).unwrap().id.clone();+ let mut session = Session::new(&state, data);+ session.receipts.insert(child.clone(), NativeJobDispatchOutcome::Unknown);+ let status = native_job_apply_with(&state, &plan.plan_id, &mut session).await.unwrap();+ assert!(status.outcome == NativeJobOperationOutcome::Verified);+ assert_eq!(session.writes().iter().filter(|id| **id == child).count(), 1);+ assert_eq!(session.data.steps[1]["RETRY_INTERVAL"], 10);+}++#[tokio::test]+async fn cancellation_after_a_child_edit_preserves_it_and_new_preview_applies_only_the_remaining_changes() {+ let data = Database::default();+ let (_dir, state, target) = setup(&data).await;+ let plan = prepare_configuration(&state, &target, &data, json!({+ "steps":[{"kind":"update","name":"sql","attributes":[{"name":"RETRY_INTERVAL","change":{"kind":"set","value":10}}]}],+ "schedules":[{"kind":"drop","name":"weekly"}]+ })).await;+ let child = plan.steps.iter().find(|step| step.id.starts_with("steps:")).unwrap().id.clone();+ let mut session = Session::new(&state, data);+ session.cancel_on_step = Some((child.clone(), plan.operation_id.clone()));+ let status = native_job_apply_with(&state, &plan.plan_id, &mut session).await.unwrap();+ assert!(status.outcome == NativeJobOperationOutcome::Partial);+ assert_eq!(session.data.steps[1]["RETRY_INTERVAL"], 10);+ assert_eq!(session.data.schedules.len(), 2);+ assert!(!session.data.enabled);+ assert_eq!(session.writes().last().copied(), Some(child.as_str()));+ let resume = prepare_configuration(+ &state,+ &target,+ &session.data,+ json!({+ "attributes":[{"name":"ENABLE","change":{"kind":"set","value":true}}],+ "schedules":[{"kind":"drop","name":"weekly"}]+ }),+ )+ .await;+ assert!(!resume.steps.iter().any(|step| step.id.starts_with("steps:")));+ let mut next = Session::new(&state, session.data);+ let status = native_job_apply_with(&state, &resume.plan_id, &mut next).await.unwrap();+ assert!(status.outcome == NativeJobOperationOutcome::Verified);+ assert_eq!(next.data.steps[1]["RETRY_INTERVAL"], 10);+ assert_eq!(next.data.schedules.len(), 1);+ assert!(next.data.enabled);+}++#[tokio::test]+async fn renaming_a_step_keeps_identity_and_explicitly_repairs_references_not_updated_by_the_database() {+ let data = Database::default();+ let (_dir, state, target) = setup(&data).await;+ let plan = prepare_configuration(&state, &target, &data, json!({"steps":[{"kind":"update","name":"sql","attributes":[{"name":"NAME","change":{"kind":"set","value":"renamed"}}]}]})).await;+ let mut session = Session::new(&state, data);+ let status = native_job_apply_with(&state, &plan.plan_id, &mut session).await.unwrap();+ assert!(status.outcome == NativeJobOperationOutcome::Verified);+ assert_eq!(session.data.steps[1]["ID"], 12);+ assert_eq!(session.data.steps[1]["NAME"], "renamed");+ assert_eq!(session.data.steps[0]["SUCC_NEXT_STEP"], "renamed");+ assert!(session+ .sent_steps+ .iter()+ .any(|step| step.sql.contains("SP_JOB_STEP_SET_NEXT_STEP('Job_1', 'backup', 'renamed', NULL)")));+}++#[tokio::test]+async fn referenced_steps_are_dropped_only_after_link_correction_and_surviving_order_is_preserved() {+ let data = Database::default();+ let (_dir, state, target) = setup(&data).await;+ let plan = prepare_configuration(&state, &target, &data, json!({"steps":[+ {"kind":"drop","name":"backup"},+ {"kind":"add","name":"last_step","attributes":[{"name":"COMMAND_INPUT","change":{"kind":"set","value":"SELECT 2;"}}]}+ ]})).await;+ let mut session = Session::new(&state, data);+ let status = native_job_apply_with(&state, &plan.plan_id, &mut session).await.unwrap();+ assert!(status.outcome == NativeJobOperationOutcome::Verified, "{}", serde_json::to_value(&status).unwrap());+ assert_eq!(+ session.data.steps.iter().map(|row| row["NAME"].as_str().unwrap()).collect::<Vec<_>>(),+ ["sql", "last_step"]+ );+ assert_eq!(session.data.steps[0]["SEQNO"], 1);+ let cleared = session+ .sent_steps+ .iter()+ .position(|step| step.sql.contains("SP_JOB_STEP_SET_NEXT_STEP('Job_1', 'backup', NULL, NULL)"))+ .unwrap();+ let dropped =+ session.sent_steps.iter().position(|step| step.sql.contains("SP_DROP_JOB_STEP('Job_1', 'backup')")).unwrap();+ assert!(cleared < dropped);+}++#[tokio::test]+async fn external_child_replacement_before_a_forward_link_stops_without_linking_the_replacement() {+ let data = Database::default();+ let (_dir, state, target) = setup(&data).await;+ let plan = prepare_configuration(+ &state,+ &target,+ &data,+ json!({"steps":[+ {"kind":"update","name":"sql","attributes":[{"name":"NAME","change":{"kind":"set","value":"renamed"}}]}+ ]}),+ )+ .await;+ let mut session = Session::new(&state, data);+ // initial + (pre/post pause) + (pre/post START) + (pre/post rename) + link preflight+ session.replace_child_on_read = Some((8, "renamed".into()));+ let status = native_job_apply_with(&state, &plan.plan_id, &mut session).await.unwrap();+ assert!(status.outcome == NativeJobOperationOutcome::Partial);+ assert_eq!(status.reason.as_deref(), Some("native_job_definition_changed"));+ assert!(!session.sent_steps.iter().any(|step| step.sql.contains("SP_JOB_STEP_SET_NEXT_STEP")));+ assert!(!session.writes().contains(&"config_commit"));+}++#[tokio::test]+async fn unrelated_catalog_mutation_after_a_step_edit_prevents_configuration_commit_and_activation() {+ let data = Database::default();+ let (_dir, state, target) = setup(&data).await;+ let plan = prepare_configuration(&state, &target, &data, json!({"steps":[{"kind":"update","name":"sql","attributes":[{"name":"RETRY_INTERVAL","change":{"kind":"set","value":10}}]}]})).await;+ let mut session = Session::new(&state, data);+ session.tamper_unrelated = true;+ let status = native_job_apply_with(&state, &plan.plan_id, &mut session).await.unwrap();+ assert!(status.outcome == NativeJobOperationOutcome::Partial);+ assert!(!session.writes().contains(&"config_commit"));+ assert!(!session.data.enabled);+}++#[tokio::test]+async fn loss_of_global_child_visibility_does_not_prove_another_owners_step_was_deleted() {+ let data = Database { owner:"Other", system_definition:true, system_parts:true, schedules:vec![], steps:vec![+ serde_json::from_value(json!({"ID":12,"JOBID":41,"NAME":"sql","SEQNO":1,"TYPE":0,"DBNAME":"DB","COMMAND":"SELECT 1;","SUCC_ACTION":1,"FAIL_ACTION":1,"RETRY_ATTEMPTS":0,"RETRY_INTERVAL":0,"OUTPUT_FILE_PATH":null,"APPEND_FLAG":0,"SUCC_NEXT_STEP":null,"FAIL_NEXT_STEP":null,"DESCRIBE":null})).unwrap()+ ], ..Default::default() };+ let (_dir, state, target) = setup(&data).await;+ let plan = prepare_configuration(&state, &target, &data, json!({"steps":[{"kind":"drop","name":"sql"}]})).await;+ let child = plan.steps.iter().find(|step| step.id.starts_with("steps:")).unwrap().id.clone();+ let mut session = Session::new(&state, data);+ session.hide_parts_after_drop = true;+ session.receipts.insert(child, NativeJobDispatchOutcome::Unknown);+ let status = native_job_apply_with(&state, &plan.plan_id, &mut session).await.unwrap();+ assert!(status.outcome == NativeJobOperationOutcome::Unknown);+ assert!(!session.writes().contains(&"config_commit"));+ assert!(!session.data.enabled);+}++#[tokio::test]+async fn an_empty_rebased_draft_still_previews_pending_configuration_termination_without_replaying_fields() {+ for lost_commit in [false, true] {+ let data = Database { enabled: false, ..Default::default() };+ let (_dir, state, target) = setup(&data).await;+ let plan = prepare_configuration(&state, &target, &data, json!({"steps":[{"kind":"update","name":"sql","attributes":[{"name":"RETRY_INTERVAL","change":{"kind":"set","value":10}}]}]})).await;+ let child = plan.steps.iter().find(|step| step.id.starts_with("steps:")).unwrap().id.clone();+ let mut session = Session::new(&state, data);+ if lost_commit {+ session.receipts.insert("config_commit".into(), NativeJobDispatchOutcome::Unknown);+ } else {+ session.cancel_on_step = Some((child, plan.operation_id.clone()));+ }+ let first = native_job_apply_with(&state, &plan.plan_id, &mut session).await.unwrap();+ assert!(+ first.outcome+ == if lost_commit { NativeJobOperationOutcome::Unknown } else { NativeJobOperationOutcome::Partial }+ );+ assert_eq!(session.data.steps[1]["RETRY_INTERVAL"], 10);+ let resume = prepare_configuration(&state, &target, &session.data, json!({})).await;+ assert_eq!(+ resume.steps.iter().map(|step| step.id.as_str()).collect::<Vec<_>>(),+ ["pause", "config_start", "config_commit"]+ );+ let mut next = Session::new(&state, session.data);+ let status = native_job_apply_with(&state, &resume.plan_id, &mut next).await.unwrap();+ assert!(status.outcome == NativeJobOperationOutcome::Verified);+ assert!(!next.data.enabled);+ assert_eq!(next.data.steps[1]["RETRY_INTERVAL"], 10);+ let after = prepare_control(&state, &target, &next.data, NativeJobChange::Enable).await;+ assert_eq!(after.steps.len(), 1);+ }+}++#[tokio::test]+async fn unknown_link_after_an_acknowledged_add_can_be_verified_using_the_captured_child_id() {+ let data = Database::default();+ let (_dir, state, target) = setup(&data).await;+ let plan = prepare_configuration(+ &state,+ &target,+ &data,+ json!({"steps":[{"kind":"add","name":"new_step","attributes":[+ {"name":"COMMAND_INPUT","change":{"kind":"set","value":"SELECT 2;"}},+ {"name":"SUCC_ACTION","change":{"kind":"set","value":3}},+ {"name":"SUCC_NEXT_STEP","change":{"kind":"set","value":"sql"}}+ ]}]}),+ )+ .await;+ let linked = plan.steps.iter().find(|step| step.sql.contains("SP_JOB_STEP_SET_NEXT_STEP")).unwrap().id.clone();+ let mut session = Session::new(&state, data);+ session.receipts.insert(linked.clone(), NativeJobDispatchOutcome::Unknown);+ let status = native_job_apply_with(&state, &plan.plan_id, &mut session).await.unwrap();+ assert!(status.outcome == NativeJobOperationOutcome::Verified);+ assert_eq!(session.writes().iter().filter(|id| **id == linked).count(), 1);+}++fn absent_database() -> Database {+ Database { exists: false, steps: vec![], schedules: vec![], ..Default::default() }+}++async fn prepare_create(state: &AppState, target: &NativeJobRef, enabled: bool) -> NativeJobPreparedPlan {+ let request:NativeJobRequest = serde_json::from_value(json!({+ "action":"create", "scope":target.scope(),+ "definition":{"kind":"dameng-native", "name":"Job_1", "enabled":enabled,+ "configuration":{+ "attributes":[+ {"name":"DESCRIBE","change":{"kind":"set","value":"new"}},+ {"name":"ENABLE_EMAIL","change":{"kind":"set","value":true}},+ {"name":"EMAIL_OPERATOR_NAME","change":{"kind":"set","value":"OnCall"}},+ {"name":"EMAIL_TYPE","change":{"kind":"set","value":2}},+ {"name":"NETSEND_TYPE","change":{"kind":"set","value":1}}+ ],+ "steps":[+ {"kind":"add","name":"first","attributes":[+ {"name":"COMMAND_INPUT","change":{"kind":"set","value":"SELECT 1;"}},+ {"name":"SUCC_ACTION","change":{"kind":"set","value":3}},+ {"name":"SUCC_NEXT_STEP","change":{"kind":"set","value":"last"}}+ ]},+ {"kind":"add","name":"last","attributes":[{"name":"TYPE","change":{"kind":"set","value":3}}]}+ ],+ "schedules":[{"kind":"add","name":"daily","attributes":[{"name":"DURING_START_DATE","change":{"kind":"set","value":"2026-10-21"}}]}]+ }+ }+ })).unwrap();+ native_job_prepare_request_with(state, request, |_| async {+ panic!("no invented ID may be read during creation preview")+ })+ .await+ .unwrap()+}++#[tokio::test]+async fn native_create_uses_one_physical_session_and_activates_only_after_configuration_is_verified() {+ for enabled in [false, true] {+ let data = absent_database();+ let (_dir, state, target) = setup(&data).await;+ let plan = prepare_create(&state, &target, enabled).await;+ assert!(plan.target.is_none());+ let mut session = Session::new(&state, data);+ let status = native_job_apply_with(&state, &plan.plan_id, &mut session).await.unwrap();+ assert!(status.outcome == NativeJobOperationOutcome::Verified, "{:?}", status.reason);+ assert_eq!(status.target, Some(target));+ assert_eq!(session.calls.first().unwrap(), "lease");+ assert_eq!(session.calls.last().unwrap(), "close");+ assert_eq!(session.data.enabled, enabled);+ assert_eq!(session.data.valid, "Y");+ assert_eq!(session.data.steps.len(), 2);+ assert_eq!(status.created_children.len(), 3);+ assert_eq!(status.created_children[0].partition, "steps");+ assert_eq!(status.created_children[0].name, "first");+ assert_eq!(status.created_children[0].id, "100");+ assert_eq!(session.data.steps[0]["SUCC_NEXT_STEP"], "last");+ assert_eq!(session.data.schedules.len(), 1);+ let commit = session.writes().iter().position(|id| *id == "config_commit").unwrap();+ assert!(session.writes().iter().position(|id| *id == "enable").is_none_or(|enable| enable > commit));+ assert!(status.steps.iter().all(|step| step.state == NativeJobStepState::Applied));+ }+}++#[tokio::test]+async fn create_refuses_an_existing_native_name_without_altering_or_initializing_it() {+ let data = Database::default();+ let (_dir, state, target) = setup(&data).await;+ let plan = prepare_create(&state, &target, true).await;+ let mut session = Session::new(&state, data);+ let status = native_job_apply_with(&state, &plan.plan_id, &mut session).await.unwrap();+ assert!(status.outcome == NativeJobOperationOutcome::NotApplied);+ assert_eq!(status.reason.as_deref(), Some("native_job_creation_target_not_absent"));+ assert!(session.writes().is_empty());+ assert_eq!(session.data.description, "old");+}++#[tokio::test]+async fn lost_create_receipt_does_not_adopt_or_activate_a_same_name_job_and_duplicate_apply_does_not_recreate() {+ let data = absent_database();+ let (_dir, state, target) = setup(&data).await;+ let plan = prepare_create(&state, &target, true).await;+ let mut session = Session::new(&state, data);+ session.receipts.insert("create".into(), NativeJobDispatchOutcome::Unknown);+ let first = native_job_apply_with(&state, &plan.plan_id, &mut session).await.unwrap();+ assert!(first.outcome == NativeJobOperationOutcome::Unknown);+ assert!(first.target.is_none());+ assert_eq!(session.writes(), ["create"]);+ assert!(!session.data.enabled);+ let again = native_job_apply_with(&state, &plan.plan_id, &mut session).await.unwrap();+ assert!(again.outcome == NativeJobOperationOutcome::Unknown);+ assert_eq!(session.writes(), ["create"]);+}++#[tokio::test]+async fn cancel_after_create_keeps_the_exact_disabled_job_and_requires_fresh_configuration_before_enable() {+ let data = absent_database();+ let (_dir, state, target) = setup(&data).await;+ let plan = prepare_create(&state, &target, true).await;+ let mut session = Session::new(&state, data);+ session.cancel_on_step = Some(("create".into(), plan.operation_id.clone()));+ let status = native_job_apply_with(&state, &plan.plan_id, &mut session).await.unwrap();+ assert!(status.outcome == NativeJobOperationOutcome::Partial);+ assert_eq!(status.target, Some(target.clone()));+ assert_eq!(session.writes(), ["create"]);+ assert!(!session.data.enabled);+ let resume = prepare_control(&state, &target, &session.data, NativeJobChange::Enable).await;+ assert_eq!(+ resume.steps.iter().map(|step| step.id.as_str()).collect::<Vec<_>>(),+ ["pause", "config_start", "config_commit", "enable"]+ );+}++#[tokio::test]+async fn create_commit_unknown_never_enables_and_corrected_existing_job_does_not_recreate() {+ let data = absent_database();+ let (_dir, state, target) = setup(&data).await;+ let plan = prepare_create(&state, &target, true).await;+ let mut session = Session::new(&state, data);+ session.receipts.insert("config_commit".into(), NativeJobDispatchOutcome::Unknown);+ let status = native_job_apply_with(&state, &plan.plan_id, &mut session).await.unwrap();+ assert!(status.outcome == NativeJobOperationOutcome::Unknown);+ assert_eq!(status.target, Some(target.clone()));+ assert!(!session.data.enabled);+ assert!(!session.writes().contains(&"enable"));+ let resume = prepare_configuration(&state, &target, &session.data, json!({})).await;+ assert_eq!(+ resume.steps.iter().map(|step| step.id.as_str()).collect::<Vec<_>>(),+ ["pause", "config_start", "config_commit"]+ );+ assert!(!resume+ .steps+ .iter()+ .any(|step| step.id == "create" || step.id.starts_with("steps:") || step.id.starts_with("schedules:")));+}++#[tokio::test]+async fn creation_operator_preflight_failure_never_creates_a_job() {+ let data = absent_database();+ let (_dir, state, target) = setup(&data).await;+ let plan = prepare_create(&state, &target, true).await;+ let mut session = Session::new(&state, data);+ session.operator_denied = true;+ let status = native_job_apply_with(&state, &plan.plan_id, &mut session).await.unwrap();+ assert!(status.outcome == NativeJobOperationOutcome::NotApplied);+ assert!(session.writes().is_empty());+ assert!(!session.data.exists);+}++#[tokio::test]+async fn create_final_enable_failure_repreviews_only_enable_without_replaying_create_or_configuration() {+ let data = absent_database();+ let (_dir, state, target) = setup(&data).await;+ let plan = prepare_create(&state, &target, true).await;+ let mut session = Session::new(&state, data);+ session.receipts.insert("enable".into(), NativeJobDispatchOutcome::NotStarted);+ let status = native_job_apply_with(&state, &plan.plan_id, &mut session).await.unwrap();+ assert!(status.outcome == NativeJobOperationOutcome::Partial);+ assert_eq!(status.target, Some(target.clone()));+ assert!(!session.data.enabled);+ assert_eq!(session.data.valid, "Y");+ let next = prepare_control(&state, &target, &session.data, NativeJobChange::Enable).await;+ assert_eq!(next.steps.iter().map(|step| step.id.as_str()).collect::<Vec<_>>(), ["enable"]);+}diff --git a/crates/dbx-core/tests/native_job_legacy_transport.rs b/crates/dbx-core/tests/native_job_legacy_transport.rsnew file mode 100644index 0000000000..4796de2bb2--- /dev/null+++ b/crates/dbx-core/tests/native_job_legacy_transport.rs@@ -0,0 +1,172 @@+#![recursion_limit = "256"]++use dbx_core::connection::{task_client_session_id, AppState, PoolKind};+use dbx_core::db::agent_driver::{AgentDriverClient, AgentLaunchSpec, AgentRuntimeClient, PooledAgentClient};+use dbx_core::schema::native_jobs::*;+use dbx_types::native_jobs::*;+use serde_json::{json, Value};+use std::io::{BufRead, Write};+use std::sync::Arc;+use std::time::Duration;++#[test]+fn native_job_legacy_rpc_fixture() {+ let Ok(path) = std::env::var("DBX_LEGACY_RPC_LOG") else { return };+ let mode = std::env::var("DBX_LEGACY_RPC_MODE").unwrap();+ let mut log = std::fs::OpenOptions::new().create(true).append(true).open(path).unwrap();+ println!("\n{}", json!({"ready":true}));+ std::io::stdout().flush().unwrap();+ let mut operation = String::new();+ for line in std::io::stdin().lock().lines() {+ let request: Value = serde_json::from_str(&line.unwrap()).unwrap();+ writeln!(log, "{request}").unwrap();+ log.flush().unwrap();+ let method = request["method"].as_str().unwrap();+ let result = match method {+ "handshake" => json!({"protocolVersion":2,"agentProtocolVersion":2,"capabilities":[+ "connect","metadata","query","multi_session",if mode=="old-package" {"native_job_legacy_v1"} else {"native_job_legacy_ob_v1"}+ ]}),+ "connection_info" => {+ json!({"databaseInfo":{"productName":"OceanBase","productVersion":"4.2.5.7","currentDatabase":"ORACLETEST","compatibilityMode":"oracle"}})+ }+ "execute_query" => {+ json!({"columns":["DBX_SESSION_USER"],"rows":[["Owner"]],"affected_rows":0,"execution_time_ms":0})+ }+ "prepare_legacy_job" => {+ operation = request["params"]["operationId"].as_str().unwrap().into();+ let mut result = json!({"operationId":operation,"phase":"rolled_back","jobId":"41"});+ if mode != "lost-terminal" {+ result["disposalConfirmed"] = json!(mode != "close-failed");+ }+ result+ }+ "legacy_job_status" => {+ json!({"operationId":operation,"phase":"rolled_back","jobId":"41","disposalConfirmed":mode!="close-failed"})+ }+ // The real MultiSession runtime accepts logical close before physical cleanup finishes.+ "close_session" | "open_session" | "shutdown" => json!({"ok":true}),+ _ => panic!("unexpected native dispatch: {method}"),+ };+ println!("{}", json!({"jsonrpc":"2.0","id":request["id"],"result":result}));+ std::io::stdout().flush().unwrap();+ if method == "shutdown" {+ break;+ }+ }+}++async fn run(mode: &str) -> (NativeJobOperationStatus, Vec<Value>) {+ let dir = tempfile::tempdir().unwrap();+ let log = dir.path().join("requests.jsonl");+ let storage = dbx_core::persistence::test_storage::open(&dir.path().join("state.db")).await.unwrap();+ let state = Arc::new(AppState::new_with_plugin_and_agent_dir_and_app_version(+ storage,+ dir.path().join("plugins"),+ dir.path().join("agents"),+ "test",+ ));+ state.configs.write().await.insert(+ "c".into(),+ serde_json::from_value(json!({+ "id":"c","name":"fixture","db_type":"oceanbase-oracle","host":"127.0.0.1","port":1,+ "username":"Owner","password":"","query_timeout_secs":2,"connect_timeout_secs":2+ }))+ .unwrap(),+ );+ let context=native_job_open_context_with(&state,"c","",|_|std::future::ready(Ok(NativeJobRuntimeIdentity{+ database_info:Some(serde_json::from_value(json!({"productName":"OceanBase","productVersion":"4.2.5.7","currentDatabase":"ORACLETEST","compatibilityMode":"oracle"})).unwrap()),+ session_user:"Owner".into(),+ }))).await.unwrap();+ let plan = native_job_prepare_request_with(+ &state,+ NativeJobRequest::Create {+ scope: context.scope,+ definition: NativeJobCreateDefinition::Legacy(NativeJobLegacyCreate {+ what: "private_call();".into(),+ next_date: "2026-10-21 10:20:30".into(),+ interval: "SYSDATE+1".into(),+ enabled: false,+ instance: 0,+ schema: "Owner".into(),+ zone: Some("zone1".into()),+ }),+ },+ |_| std::future::ready(Err("preview must not query")),+ )+ .await+ .unwrap();+ let launch = AgentLaunchSpec::new(std::env::current_exe().unwrap())+ .with_args(["--exact", "native_job_legacy_rpc_fixture", "--nocapture", "--test-threads=1"])+ .with_env(vec![+ ("DBX_LEGACY_RPC_LOG".into(), log.to_string_lossy().into_owned()),+ ("DBX_LEGACY_RPC_MODE".into(), mode.into()),+ ]);+ let runtime = AgentRuntimeClient::spawn(launch, "test").await.unwrap();+ let session_id = "legacy-owned-session";+ runtime+ .call::<Value>("open_session", json!({"agentSessionId":session_id}), Some(Duration::from_secs(2)), None)+ .await+ .unwrap();+ runtime.increment_session_count();+ let client =+ Arc::new(PooledAgentClient::new(AgentDriverClient::shared_session(runtime.clone(), session_id.into())));+ let client_id = task_client_session_id("native-job-operation", &plan.operation_id).replace(':', "_");+ let key = format!("c:session:{client_id}:role:metadata");+ state.update_connection_pools(|pools| pools.insert(key.clone(), PoolKind::Agent(client))).await;+ native_job_apply_core(state.clone(), &plan.plan_id).unwrap();+ let status = tokio::time::timeout(Duration::from_secs(10), async {+ loop {+ let status = native_job_status(&state, &plan.operation_id);+ if status.state == NativeJobOperationState::Finished {+ break status;+ }+ tokio::time::sleep(Duration::from_millis(10)).await;+ }+ })+ .await+ .unwrap();+ assert!(state.pool_handle(&key).await.is_none());+ runtime.kill();+ state.shutdown(Duration::from_secs(2)).await;+ let requests =+ std::fs::read_to_string(log).unwrap().lines().map(|line| serde_json::from_str(line).unwrap()).collect();+ (status, requests)+}++#[tokio::test]+async fn production_ob_legacy_binds_zone_and_requires_original_physical_disposal_before_logical_close() {+ for mode in ["confirmed", "close-failed", "lost-terminal"] {+ let (status, requests) = run(mode).await;+ assert_eq!(+ status.outcome,+ if mode == "close-failed" {+ NativeJobOperationOutcome::Unknown+ } else {+ NativeJobOperationOutcome::NotApplied+ }+ );+ let prepared = requests.iter().find(|r| r["method"] == "prepare_legacy_job").unwrap();+ assert_eq!(prepared["params"]["dialect"], "oceanbase-oracle");+ assert_eq!(prepared["params"]["zone"], "zone1");+ assert_eq!(prepared["params"]["instance"], 0);+ assert!(requests+ .iter()+ .all(|r| !matches!(r["method"].as_str(), Some("commit_legacy_job" | "rollback_legacy_job"))));+ let closed = requests.iter().position(|r| r["method"] == "close_session").unwrap();+ if mode == "lost-terminal" {+ let checked = requests.iter().position(|r| r["method"] == "legacy_job_status").unwrap();+ assert!(checked < closed);+ }+ if mode == "close-failed" {+ assert_eq!(status.reason.as_deref(), Some("native_job_session_cleanup_unknown"));+ }+ }+}++#[tokio::test]+async fn an_old_oracle_legacy_capability_does_not_claim_the_ob_protocol() {+ let (status, requests) = run("old-package").await;+ assert_eq!(status.outcome, NativeJobOperationOutcome::NotApplied);+ assert_eq!(status.reason.as_deref(), Some("native_job_legacy_runtime_update_required"));+ assert!(!requests.iter().any(|r| r["method"] == "prepare_legacy_job"));+}diff --git a/crates/dbx-core/tests/native_job_operations.rs b/crates/dbx-core/tests/native_job_operations.rsnew file mode 100644index 0000000000..2eba554040--- /dev/null+++ b/crates/dbx-core/tests/native_job_operations.rs@@ -0,0 +1,921 @@+#![recursion_limit = "256"]++use dbx_core::connection::AppState;+use dbx_core::schema::native_jobs::*;+use dbx_core::session_credentials::with_credential_owner;+use dbx_sql::native_job_changes::NativeJobSqlStep;+use dbx_sql::native_jobs::NativeJobCatalogQuery;+use dbx_types::native_jobs::*;+use serde_json::{json, Value};+use std::collections::VecDeque;+use std::sync::{+ atomic::{AtomicUsize, Ordering},+ Arc,+};++async fn setup(engine: &str) -> (tempfile::TempDir, Arc<AppState>, NativeJobRef) {+ let dir = tempfile::tempdir().unwrap();+ let storage = dbx_core::persistence::test_storage::open(&dir.path().join("state.db")).await.unwrap();+ let state = Arc::new(AppState::new_with_plugin_and_agent_dir_and_app_version(+ storage,+ dir.path().join("plugins"),+ dir.path().join("agents"),+ "0.0.0",+ ));+ let config = serde_json::from_value(+ json!({"id":"c","name":"test","db_type":engine,"host":"127.0.0.1","port":1,"username":"Owner","password":""}),+ )+ .unwrap();+ state.configs.write().await.insert("c".into(), config);+ let ctx = native_job_open_context_with(&state, "c", "", |_| {+ std::future::ready(Ok(NativeJobRuntimeIdentity { database_info: None, session_user: "Owner".into() }))+ })+ .await+ .unwrap();+ let job = NativeJobRef::Scheduler { scope: ctx.scope, owner: "Owner".into(), name: "Job".into() };+ (dir, state, job)+}++#[derive(Clone)]+struct DbState {+ enabled: bool,+ comments: &'static str,+ action: &'static str,+ duration: &'static str,+ zone: Option<&'static str>,+ id: &'static str,+ deny_arguments: bool,+}+impl Default for DbState {+ fn default() -> Self {+ Self {+ enabled: false,+ comments: "old",+ action: "PROC",+ duration: "+000 00:01:00",+ zone: Some("zone1"),+ id: "41",+ deny_arguments: false,+ }+ }+}++fn result(columns: &[&str], rows: Value) -> Value {+ json!({"columns":columns,"rows":rows,"affected_rows":0,"execution_time_ms":0})+}+fn query(query: NativeJobCatalogQuery, data: &DbState) -> Result<Value, NativeJobCatalogFailure> {+ if query.source.ends_with("JOB_ARGS") && data.deny_arguments {+ return Err(NativeJobCatalogFailure::Denied(Some(942)));+ }+ if query.sql.starts_with("SELECT TO_CHAR(J.JOB) AS DBX_JOB_ID FROM") {+ return Ok(result(&["DBX_JOB_ID"], json!([[data.id]])));+ }+ if matches!(query.source, "SYS.DBA_JOBS" | "SYS.USER_JOBS") {+ return Ok(result(+ &[+ "DBX_JOB_ID",+ "WHAT",+ "INTERVAL",+ "NEXT_DATE",+ "BROKEN",+ "INSTANCE",+ "LOG_USER",+ "PRIV_USER",+ "SCHEMA_USER",+ ],+ json!([[+ data.id,+ data.action,+ "SYSDATE+1",+ "2030-01-01 00:00:00",+ if data.enabled { "N" } else { "Y" },+ data.zone,+ "Owner",+ "Owner",+ "Owner"+ ]]),+ ));+ }+ if query.source.ends_with("_OBJECTS") || query.source.contains("VIRTUAL_TENANT") {+ return Ok(result(&["DBX_JOB_ID", "DBX_CREATED_AT"], json!([[data.id, "creation"]])));+ }+ if query.source.ends_with("SCHEDULER_JOBS") {+ return Ok(result(+ &[+ "OWNER",+ "JOB_NAME",+ "JOB_TYPE",+ "JOB_ACTION",+ "COMMENTS",+ "ENABLED",+ "NUMBER_OF_ARGUMENTS",+ "MAX_RUN_DURATION",+ "INSTANCE_ID",+ ],+ json!([[+ "Owner",+ "Job",+ "STORED_PROCEDURE",+ data.action,+ data.comments,+ if data.enabled { "TRUE" } else { "FALSE" },+ 0,+ data.duration,+ "RANDOM"+ ]]),+ ));+ }+ Ok(result(&["JOB_NAME"], json!([])))+}+async fn read(state: &AppState, job: &NativeJobRef, data: DbState) -> NativeJobDetails {+ native_job_read_with(state, job, |q| std::future::ready(query(q, &data))).await.unwrap()+}+async fn prepare(state: &AppState, job: &NativeJobRef, change: NativeJobChange) -> NativeJobPreparedPlan {+ let initial = read(state, job, DbState::default()).await;+ native_job_prepare_with(+ state,+ NativeJobMutation { target: job.clone(), baseline: initial.snapshot.revision, change },+ |target| async move { Ok(read(state, &target, DbState::default()).await) },+ )+ .await+ .unwrap()+}++struct Session {+ state: Arc<AppState>,+ reads: VecDeque<DbState>,+ receipts: VecDeque<NativeJobDispatchOutcome>,+ calls: Arc<AtomicUsize>,+ read_calls: Arc<AtomicUsize>,+ finishes: Arc<AtomicUsize>,+ entered: Option<tokio::sync::oneshot::Sender<()>>,+ release: Option<tokio::sync::oneshot::Receiver<()>>,+ cancel_on_read: Option<(usize, String)>,+ invalidate_on_execute: bool,+ fail_cleanup: bool,+ finish_entered: Option<tokio::sync::oneshot::Sender<()>>,+ finish_release: Option<tokio::sync::oneshot::Receiver<()>>,+ execution_read: Option<Result<NativeJobDetails, &'static str>>,+}+impl Session {+ fn new(state: &Arc<AppState>, reads: Vec<DbState>, receipts: Vec<NativeJobDispatchOutcome>) -> Self {+ Self {+ state: state.clone(),+ reads: reads.into(),+ receipts: receipts.into(),+ calls: Arc::new(AtomicUsize::new(0)),+ read_calls: Arc::new(AtomicUsize::new(0)),+ finishes: Arc::new(AtomicUsize::new(0)),+ entered: None,+ release: None,+ cancel_on_read: None,+ invalidate_on_execute: false,+ fail_cleanup: false,+ finish_entered: None,+ finish_release: None,+ execution_read: None,+ }+ }+}+#[async_trait::async_trait]+impl NativeJobMutationSession for Session {+ async fn read_execution(&mut self, _target: &NativeJobRef) -> Result<NativeJobExecutionRead, &'static str> {+ self.execution_read+ .clone()+ .unwrap_or(Err("fixture observation unavailable"))+ .map(|details| NativeJobExecutionRead::from_details(&details))+ }+ async fn read(&mut self, target: &NativeJobRef) -> Result<NativeJobDetails, &'static str> {+ let count = self.read_calls.fetch_add(1, Ordering::SeqCst) + 1;+ let data = self.reads.pop_front().expect("unexpected database read");+ let result = read(&self.state, target, data).await;+ if let Some((at, id)) = &self.cancel_on_read {+ if count == *at {+ native_job_cancel(&self.state, id);+ }+ }+ Ok(result)+ }+ async fn execute(&mut self, _step: &NativeJobSqlStep) -> NativeJobStepReceipt {+ self.calls.fetch_add(1, Ordering::SeqCst);+ if let Some(entered) = self.entered.take() {+ entered.send(()).unwrap();+ }+ if let Some(release) = self.release.take() {+ release.await.unwrap();+ }+ if self.invalidate_on_execute {+ self.state.invalidate_connection_lifecycle("c");+ }+ NativeJobStepReceipt {+ outcome: self.receipts.pop_front().expect("unexpected native dispatch"),+ reason: None,+ vendor_code: None,+ }+ }+ async fn finish(&mut self) -> Result<(), &'static str> {+ if let Some(entered) = self.finish_entered.take() {+ entered.send(()).unwrap();+ }+ if let Some(release) = self.finish_release.take() {+ release.await.unwrap();+ }+ self.finishes.fetch_add(1, Ordering::SeqCst);+ if self.fail_cleanup {+ Err("cleanup failed")+ } else {+ Ok(())+ }+ }+}++#[tokio::test]+async fn accepted_and_unknown_run_receipts_keep_their_outcome_when_fast_failure_is_observed() {+ for receipt in [NativeJobDispatchOutcome::Applied, NativeJobDispatchOutcome::Unknown] {+ let (_dir, state, job) = setup("oracle").await;+ let plan = prepare(&state, &job, NativeJobChange::Run).await;+ let mut observed = read(&state, &job, DbState::default()).await;+ observed.history = NativeJobMetadata::Available {+ value: vec![serde_json::from_value(+ json!({"LOG_ID":"900719925474099312345","STATUS":"FAILED","ERROR#":20001}),+ )+ .unwrap()],+ };+ let mut db = Session::new(&state, vec![DbState::default()], vec![receipt]);+ db.execution_read = Some(Ok(observed));+ let status = native_job_apply_with(&state, &plan.plan_id, &mut db).await.unwrap();+ assert_eq!(+ status.outcome,+ if receipt == NativeJobDispatchOutcome::Applied {+ NativeJobOperationOutcome::Accepted+ } else {+ NativeJobOperationOutcome::Unknown+ }+ );+ let observation = status.execution_observation.unwrap();+ assert_eq!(observation.association, "uncertain");+ assert_eq!(observation.candidates.len(), 1);+ assert_eq!(observation.candidates[0].native_key, "900719925474099312345");+ assert_eq!(observation.candidates[0].row["STATUS"], "FAILED");+ assert_eq!(db.read_calls.load(Ordering::SeqCst), 1);+ assert_eq!(db.finishes.load(Ordering::SeqCst), 1);+ let polled = native_job_status_observed_core(&state, &plan.operation_id, false).await;+ assert_eq!(polled.outcome, status.outcome);+ assert_eq!(polled.execution_observation.unwrap().candidates[0].native_key, "900719925474099312345");+ native_job_apply_with(&state, &plan.plan_id, &mut db).await.unwrap();+ assert_eq!(db.calls.load(Ordering::SeqCst), 1);+ with_credential_owner(Some("other actor".into()), async {+ assert!(native_job_status_observed_core(&state, &plan.operation_id, true)+ .await+ .execution_observation+ .is_none());+ })+ .await;+ }+}++#[tokio::test]+async fn observation_failure_does_not_turn_an_accepted_request_into_not_applied() {+ let (_dir, state, job) = setup("oracle").await;+ let plan = prepare(&state, &job, NativeJobChange::Run).await;+ let mut db = Session::new(&state, vec![DbState::default()], vec![NativeJobDispatchOutcome::Applied]);+ db.execution_read = Some(Err("catalog denied"));+ let status = native_job_apply_with(&state, &plan.plan_id, &mut db).await.unwrap();+ assert_eq!(status.outcome, NativeJobOperationOutcome::Accepted);+ assert_eq!(status.execution_observation.unwrap().association, "unavailable");+ assert_eq!(db.finishes.load(Ordering::SeqCst), 1);+}++#[tokio::test]+async fn native_stop_can_dispatch_beside_a_waiting_run_without_releasing_other_writers() {+ async fn poll_once<T>(future: std::pin::Pin<&mut impl std::future::Future<Output = T>>) -> Option<T> {+ let mut future = future;+ std::future::poll_fn(|cx| {+ std::task::Poll::Ready(match future.as_mut().poll(cx) {+ std::task::Poll::Ready(value) => Some(value),+ std::task::Poll::Pending => None,+ })+ })+ .await+ }+ for engine in ["oracle", "oceanbase-oracle"] {+ let (_dir, state, job) = setup(engine).await;+ let run_plan = prepare(&state, &job, NativeJobChange::Run).await;+ let stop_plan = prepare(&state, &job, NativeJobChange::Stop { force: false }).await;+ let writer_plan = prepare(+ &state,+ &job,+ NativeJobChange::Update {+ final_enabled: None,+ argument_target: None,+ attributes: vec![NativeJobAttributeChange {+ name: "MAX_RUN_DURATION".into(),+ change: NativeJobFieldChange::Set { value: json!("0 00:02:00") },+ }],+ arguments: vec![],+ },+ )+ .await;+ let mut run_db = Session::new(&state, vec![DbState::default()], vec![NativeJobDispatchOutcome::Applied]);+ let (run_entered, mut running) = tokio::sync::oneshot::channel();+ let (release_run, wait_run) = tokio::sync::oneshot::channel();+ run_db.entered = Some(run_entered);+ run_db.release = Some(wait_run);+ let mut run = Box::pin(native_job_apply_with(&state, &run_plan.plan_id, &mut run_db));+ tokio::select! { _ = &mut run => panic!("Run returned before its receipt"), _ = &mut running => {} }++ let mut writer_db = Session::new(+ &state,+ vec![DbState::default(), DbState { duration: "0 00:02:00", ..Default::default() }],+ vec![NativeJobDispatchOutcome::Applied],+ );+ let writer_reads = writer_db.read_calls.clone();+ let mut writer = Box::pin(native_job_apply_with(&state, &writer_plan.plan_id, &mut writer_db));+ assert!(poll_once(writer.as_mut()).await.is_none());+ let mut stop_db = Session::new(&state, vec![DbState::default()], vec![NativeJobDispatchOutcome::Applied]);+ let (release_stop, wait_stop) = tokio::sync::oneshot::channel();+ stop_db.finish_release = Some(wait_stop);+ let stop_calls = stop_db.calls.clone();+ let mut stop = Box::pin(native_job_apply_with(&state, &stop_plan.plan_id, &mut stop_db));+ assert!(poll_once(stop.as_mut()).await.is_none());+ let dispatched_beside_run = stop_calls.load(Ordering::SeqCst);+ release_run.send(()).unwrap();+ let run_result = run.await.unwrap();+ let early_writer = poll_once(writer.as_mut()).await;+ let reads_before_stop_cleanup = writer_reads.load(Ordering::SeqCst);+ release_stop.send(()).unwrap();+ let stop_result = stop.await.unwrap();+ let writer_result = match early_writer {+ Some(result) => result.unwrap(),+ None => writer.await.unwrap(),+ };+ assert_eq!(dispatched_beside_run, 1, "{engine}: Stop waited behind Run or the queued writer");+ assert_eq!(reads_before_stop_cleanup, 0, "{engine}: writer passed Stop cleanup");+ assert_eq!(run_result.outcome, NativeJobOperationOutcome::Accepted);+ assert_eq!(stop_result.outcome, NativeJobOperationOutcome::Accepted);+ assert_eq!(writer_result.outcome, NativeJobOperationOutcome::Verified);+ }+}++#[tokio::test]+async fn two_stops_remain_serial_and_do_not_rewrite_a_canceled_or_unknown_run() {+ async fn poll_once<T>(mut future: std::pin::Pin<&mut impl std::future::Future<Output = T>>) -> Option<T> {+ std::future::poll_fn(|cx| {+ std::task::Poll::Ready(match future.as_mut().poll(cx) {+ std::task::Poll::Ready(value) => Some(value),+ std::task::Poll::Pending => None,+ })+ })+ .await+ }+ for (receipt, cleanup_failed) in [+ (NativeJobDispatchOutcome::Applied, false),+ (NativeJobDispatchOutcome::Unknown, false),+ (NativeJobDispatchOutcome::Applied, true),+ ] {+ let (_dir, state, job) = setup("oceanbase-oracle").await;+ let run_plan = prepare(&state, &job, NativeJobChange::Run).await;+ let first_plan = prepare(&state, &job, NativeJobChange::Stop { force: false }).await;+ let second_plan = prepare(&state, &job, NativeJobChange::Stop { force: false }).await;+ let mut run_db = Session::new(&state, vec![DbState::default()], vec![receipt]);+ run_db.fail_cleanup = cleanup_failed;+ let (entered, mut running) = tokio::sync::oneshot::channel();+ let (release_run, wait_run) = tokio::sync::oneshot::channel();+ run_db.entered = Some(entered);+ run_db.release = Some(wait_run);+ let mut run = Box::pin(native_job_apply_with(&state, &run_plan.plan_id, &mut run_db));+ tokio::select! { _ = &mut run => panic!("Run returned before its receipt"), _ = &mut running => {} }+ assert!(native_job_cancel(&state, &run_plan.operation_id).cancel_requested);+ let mut first_db = Session::new(&state, vec![DbState::default()], vec![NativeJobDispatchOutcome::Applied]);+ let (release_first, wait_first) = tokio::sync::oneshot::channel();+ first_db.release = Some(wait_first);+ let first_calls = first_db.calls.clone();+ let mut first = Box::pin(native_job_apply_with(&state, &first_plan.plan_id, &mut first_db));+ assert!(poll_once(first.as_mut()).await.is_none());+ let mut second_db = Session::new(&state, vec![DbState::default()], vec![NativeJobDispatchOutcome::Applied]);+ let second_calls = second_db.calls.clone();+ let mut second = Box::pin(native_job_apply_with(&state, &second_plan.plan_id, &mut second_db));+ let early_second = poll_once(second.as_mut()).await;+ let serial_count = second_calls.load(Ordering::SeqCst);+ let first_count = first_calls.load(Ordering::SeqCst);+ release_first.send(()).unwrap();+ let first_result = tokio::time::timeout(std::time::Duration::from_secs(3), first)+ .await+ .expect("Stop did not dispatch beside the canceled Run")+ .unwrap();+ let second_result = match early_second {+ Some(result) => Some(result),+ None => poll_once(second.as_mut()).await,+ };+ let second_before_run_finished = second_calls.load(Ordering::SeqCst);+ release_run.send(()).unwrap();+ let run_result = run.await.unwrap();+ let second_result = match second_result {+ Some(result) => result.unwrap(),+ None => second.await.unwrap(),+ };+ assert_eq!(first_count, 1);+ assert_eq!(serial_count, 0);+ assert_eq!(second_before_run_finished, 1);+ assert_eq!(first_result.outcome, NativeJobOperationOutcome::Accepted);+ assert_eq!(second_result.outcome, NativeJobOperationOutcome::Accepted);+ assert_eq!(+ run_result.outcome,+ if receipt == NativeJobDispatchOutcome::Unknown || cleanup_failed {+ NativeJobOperationOutcome::Unknown+ } else {+ NativeJobOperationOutcome::Accepted+ }+ );+ assert!(run_result.cancel_requested);+ assert_eq!(native_job_status(&state, &run_plan.operation_id).outcome, run_result.outcome);+ let mut duplicate = Session::new(&state, vec![], vec![]);+ native_job_apply_with(&state, &second_plan.plan_id, &mut duplicate).await.unwrap();+ assert_eq!(duplicate.calls.load(Ordering::SeqCst), 0);+ }+}++#[tokio::test]+async fn stop_cannot_borrow_a_run_lock_from_another_native_generation() {+ let (_dir, state, job) = setup("oceanbase-oracle").await;+ let run_plan = prepare(&state, &job, NativeJobChange::Run).await;+ let mut run_db = Session::new(&state, vec![DbState::default()], vec![NativeJobDispatchOutcome::Applied]);+ let (entered, mut running) = tokio::sync::oneshot::channel();+ let (release_run, wait_run) = tokio::sync::oneshot::channel();+ run_db.entered = Some(entered);+ run_db.release = Some(wait_run);+ let mut run = Box::pin(native_job_apply_with(&state, &run_plan.plan_id, &mut run_db));+ tokio::select! { _ = &mut run => panic!("Run returned before its receipt"), _ = &mut running => {} }+ let replacement = DbState { id: "42", ..Default::default() };+ let fresh = read(&state, &job, replacement.clone()).await;+ let stop_plan = native_job_prepare_with(+ &state,+ NativeJobMutation {+ target: job.clone(),+ baseline: fresh.snapshot.revision,+ change: NativeJobChange::Stop { force: false },+ },+ |target| {+ let state = &state;+ let replacement = replacement.clone();+ async move { Ok(read(state, &target, replacement).await) }+ },+ )+ .await+ .unwrap();+ let mut stop_db = Session::new(&state, vec![replacement], vec![NativeJobDispatchOutcome::Applied]);+ let calls = stop_db.calls.clone();+ let mut stop = Box::pin(native_job_apply_with(&state, &stop_plan.plan_id, &mut stop_db));+ let early = std::future::poll_fn(|cx| {+ use std::future::Future;+ std::task::Poll::Ready(match stop.as_mut().poll(cx) {+ std::task::Poll::Ready(value) => Some(value),+ std::task::Poll::Pending => None,+ })+ })+ .await;+ release_run.send(()).unwrap();+ run.await.unwrap();+ let status = match early {+ Some(result) => result.unwrap(),+ None => stop.await.unwrap(),+ };+ assert_eq!(calls.load(Ordering::SeqCst), 0);+ assert_eq!(status.outcome, NativeJobOperationOutcome::NotApplied);+ assert_eq!(status.reason.as_deref(), Some("native_job_replaced"));+}++#[tokio::test]+async fn same_job_lock_is_held_until_the_owned_session_has_finished_cleanup() {+ let (_dir, state, job) = setup("oracle").await;+ let a = prepare(&state, &job, NativeJobChange::Run).await;+ let b = prepare(&state, &job, NativeJobChange::Run).await;+ let mut first_db = Session::new(&state, vec![DbState::default()], vec![NativeJobDispatchOutcome::Applied]);+ let mut second_db = Session::new(&state, vec![DbState::default()], vec![NativeJobDispatchOutcome::Applied]);+ let (entered, mut closing) = tokio::sync::oneshot::channel();+ let (release, wait) = tokio::sync::oneshot::channel();+ first_db.finish_entered = Some(entered);+ first_db.finish_release = Some(wait);+ let second_reads = second_db.read_calls.clone();+ let mut first = Box::pin(native_job_apply_with(&state, &a.plan_id, &mut first_db));+ tokio::select! { result = &mut first => { assert!(result.is_err()); panic!("session closed before its acknowledgement"); }, _ = &mut closing => {} }+ let mut second = Box::pin(native_job_apply_with(&state, &b.plan_id, &mut second_db));+ let second_result = std::future::poll_fn(|cx| {+ use std::future::Future;+ std::task::Poll::Ready(match second.as_mut().poll(cx) {+ std::task::Poll::Ready(result) => Some(result),+ std::task::Poll::Pending => None,+ })+ })+ .await;+ let reads_while_closing = second_reads.load(Ordering::SeqCst);+ release.send(()).unwrap();+ first.await.unwrap();+ match second_result {+ Some(result) => {+ result.unwrap();+ }+ None => {+ second.await.unwrap();+ }+ }+ assert_eq!(reads_while_closing, 0, "a second operation read the job before the first session finished cleanup");+}++#[tokio::test]+async fn stable_definition_still_allows_stop_with_unavailable_argument_metadata() {+ for engine in ["oracle", "oceanbase-oracle"] {+ let (_dir, state, job) = setup(engine).await;+ let data = DbState { deny_arguments: true, ..Default::default() };+ let initial = read(&state, &job, data.clone()).await;+ if engine == "oracle" {+ assert!(matches!(initial.parameter_metadata, NativeJobMetadata::Denied { .. }));+ } else {+ assert!(matches!(+ initial.parameter_metadata,+ NativeJobMetadata::Unknown { .. } | NativeJobMetadata::Unsupported { .. }+ ));+ }+ let plan = native_job_prepare_with(+ &state,+ NativeJobMutation {+ target: job,+ baseline: initial.snapshot.revision,+ change: NativeJobChange::Stop { force: false },+ },+ |target| {+ let state = &state;+ let data = data.clone();+ async move { Ok(read(state, &target, data).await) }+ },+ )+ .await+ .unwrap();+ let mut session = Session::new(&state, vec![data], vec![NativeJobDispatchOutcome::Applied]);+ let status = native_job_apply_with(&state, &plan.plan_id, &mut session).await.unwrap();+ assert_eq!(status.outcome, NativeJobOperationOutcome::Accepted);+ assert_eq!(session.calls.load(Ordering::SeqCst), 1);+ }+}++#[tokio::test]+async fn control_previews_reject_changed_bodies_before_dispatch_on_the_same_native_generation() {+ for engine in ["oracle", "oceanbase-oracle"] {+ for legacy in [false, true] {+ for change in [+ NativeJobChange::Run,+ NativeJobChange::Enable,+ NativeJobChange::Disable,+ NativeJobChange::Drop { force: false },+ ] {+ let (_dir, state, scheduler) = setup(engine).await;+ let job = if legacy {+ NativeJobRef::Legacy { scope: scheduler.scope().clone(), job_id: "41".into() }+ } else {+ scheduler+ };+ let plan = prepare(&state, &job, change).await;+ let changed = DbState { action: "EXTERNAL_BODY", ..Default::default() };+ let mut db =+ Session::new(&state, vec![changed.clone(), changed], vec![NativeJobDispatchOutcome::Applied]);+ let status = native_job_apply_with(&state, &plan.plan_id, &mut db).await.unwrap();+ assert_eq!(db.calls.load(Ordering::SeqCst), 0, "{engine}, legacy={legacy}");+ assert_eq!(status.outcome, NativeJobOperationOutcome::NotApplied);+ assert_eq!(status.reason.as_deref(), Some("native_job_definition_changed"));+ assert_eq!(db.finishes.load(Ordering::SeqCst), 1);+ }+ }+ }+}++#[tokio::test]+async fn duplicate_confirmation_returns_the_same_operation_without_redispatch() {+ let (_dir, state, job) = setup("oracle").await;+ let plan = prepare(&state, &job, NativeJobChange::Enable).await;+ let mut db = Session::new(+ &state,+ vec![DbState::default(), DbState { enabled: true, ..Default::default() }],+ vec![NativeJobDispatchOutcome::Applied],+ );+ let first = native_job_apply_with(&state, &plan.plan_id, &mut db).await.unwrap();+ assert!(first.outcome == NativeJobOperationOutcome::Verified);+ let mut unused = Session::new(&state, vec![], vec![]);+ let second = native_job_apply_with(&state, &plan.plan_id, &mut unused).await.unwrap();+ assert_eq!(first.operation_id, second.operation_id);+ assert_eq!(db.calls.load(Ordering::SeqCst), 1);+ assert_eq!(unused.calls.load(Ordering::SeqCst), 0);+}++#[tokio::test]+async fn backend_readonly_gate_blocks_and_the_existing_unlock_allows_the_adjacent_path() {+ let (_dir, state, job) = setup("oracle").await;+ let plan = prepare(&state, &job, NativeJobChange::Enable).await;+ state.configs.write().await.get_mut("c").unwrap().read_only = true;+ let mut denied = Session::new(&state, vec![], vec![]);+ let result = native_job_apply_with(&state, &plan.plan_id, &mut denied).await.unwrap();+ assert!(result.outcome == NativeJobOperationOutcome::NotApplied);+ assert_eq!(denied.calls.load(Ordering::SeqCst), 0);+ state.write_unlock_windows.unlock("c", 60).await.unwrap();+ let new_plan = prepare(&state, &job, NativeJobChange::Enable).await;+ let mut allowed = Session::new(+ &state,+ vec![DbState::default(), DbState { enabled: true, ..Default::default() }],+ vec![NativeJobDispatchOutcome::Applied],+ );+ assert!(+ native_job_apply_with(&state, &new_plan.plan_id, &mut allowed).await.unwrap().outcome+ == NativeJobOperationOutcome::Verified+ );+}++#[tokio::test]+async fn canceling_a_prepared_plan_never_sends_a_native_statement() {+ let (_dir, state, job) = setup("oracle").await;+ let plan = prepare(&state, &job, NativeJobChange::Run).await;+ let canceled = native_job_cancel(&state, &plan.operation_id);+ assert!(canceled.outcome == NativeJobOperationOutcome::NotApplied);+ let mut unused = Session::new(&state, vec![], vec![]);+ let result = native_job_apply_with(&state, &plan.plan_id, &mut unused).await.unwrap();+ assert!(result.cancel_requested);+ assert_eq!(unused.calls.load(Ordering::SeqCst), 0);+}++#[tokio::test]+async fn cancel_after_dispatch_waits_for_the_receipt_and_is_not_native_stop_or_rollback() {+ let (_dir, state, job) = setup("oracle").await;+ let plan = prepare(&state, &job, NativeJobChange::Enable).await;+ let mut db = Session::new(+ &state,+ vec![DbState::default(), DbState { enabled: true, ..Default::default() }],+ vec![NativeJobDispatchOutcome::Applied],+ );+ let (entered, mut started) = tokio::sync::oneshot::channel();+ let (release, wait) = tokio::sync::oneshot::channel();+ db.entered = Some(entered);+ db.release = Some(wait);+ let calls = db.calls.clone();+ let mut first = Box::pin(native_job_apply_with(&state, &plan.plan_id, &mut db));+ tokio::select! {result=&mut first=>{assert!(result.is_err());panic!("dispatch ended before its receipt");},_=&mut started=>{}}+ let canceled = native_job_cancel(&state, &plan.operation_id);+ assert!(canceled.state == NativeJobOperationState::Running);+ let mut unused = Session::new(&state, vec![], vec![]);+ let duplicate = native_job_apply_with(&state, &plan.plan_id, &mut unused).await.unwrap();+ assert!(duplicate.state == NativeJobOperationState::Running);+ release.send(()).unwrap();+ let finished = first.await.unwrap();+ assert!(finished.cancel_requested);+ assert!(finished.outcome == NativeJobOperationOutcome::Verified);+ assert_eq!(calls.load(Ordering::SeqCst), 1);+ assert_eq!(unused.calls.load(Ordering::SeqCst), 0);+}++#[tokio::test]+async fn unknown_run_response_stays_unknown_and_does_not_replay_the_business_job() {+ let (_dir, state, job) = setup("oracle").await;+ let plan = prepare(&state, &job, NativeJobChange::Run).await;+ let mut db = Session::new(&state, vec![DbState::default()], vec![NativeJobDispatchOutcome::Unknown]);+ let result = native_job_apply_with(&state, &plan.plan_id, &mut db).await.unwrap();+ assert!(result.outcome == NativeJobOperationOutcome::Unknown);+ let mut unused = Session::new(&state, vec![], vec![]);+ native_job_apply_with(&state, &plan.plan_id, &mut unused).await.unwrap();+ assert_eq!(db.calls.load(Ordering::SeqCst), 1);+ assert_eq!(unused.calls.load(Ordering::SeqCst), 0);+ assert!(native_job_status(&state, "missing-record").outcome == NativeJobOperationOutcome::Unknown);+}++#[tokio::test]+async fn asynchronous_acceptance_is_not_reported_as_a_completed_run() {+ let (_dir, state, job) = setup("oracle").await;+ let plan = prepare(&state, &job, NativeJobChange::Run).await;+ let mut db = Session::new(&state, vec![DbState::default()], vec![NativeJobDispatchOutcome::Applied]);+ assert!(+ native_job_apply_with(&state, &plan.plan_id, &mut db).await.unwrap().outcome+ == NativeJobOperationOutcome::Accepted+ );+ assert_eq!(db.read_calls.load(Ordering::SeqCst), 1);+}++#[tokio::test]+async fn a_connection_change_before_dispatch_blocks_writes_and_one_after_dispatch_remains_unknown() {+ let (_dir, state, job) = setup("oracle").await;+ let plan = prepare(&state, &job, NativeJobChange::Enable).await;+ state.invalidate_connection_lifecycle("c");+ let mut unused = Session::new(&state, vec![], vec![]);+ assert!(+ native_job_apply_with(&state, &plan.plan_id, &mut unused).await.unwrap().outcome+ == NativeJobOperationOutcome::NotApplied+ );+ let (_dir2, state2, job2) = setup("oracle").await;+ let plan2 = prepare(&state2, &job2, NativeJobChange::Enable).await;+ let mut db = Session::new(&state2, vec![DbState::default()], vec![NativeJobDispatchOutcome::Applied]);+ db.invalidate_on_execute = true;+ assert!(+ native_job_apply_with(&state2, &plan2.plan_id, &mut db).await.unwrap().outcome+ == NativeJobOperationOutcome::Unknown+ );+ assert_eq!(db.read_calls.load(Ordering::SeqCst), 1);+}++#[tokio::test]+async fn cancellation_between_attributes_preserves_partial_success_and_skips_remaining_steps() {+ let (_dir, state, job) = setup("oceanbase-oracle").await;+ let changes = NativeJobChange::Update {+ final_enabled: None,+ argument_target: None,+ attributes: vec![+ NativeJobAttributeChange {+ name: "MAX_RUN_DURATION".into(),+ change: NativeJobFieldChange::Set { value: json!("0 00:02:00") },+ },+ NativeJobAttributeChange {+ name: "INSTANCE_ID".into(),+ change: NativeJobFieldChange::Set { value: json!("zone1") },+ },+ ],+ arguments: vec![],+ };+ let plan = prepare(&state, &job, changes).await;+ assert_eq!(plan.steps.len(), 2);+ let mut db = Session::new(+ &state,+ vec![DbState::default(), DbState { duration: "+000 00:02:00", ..Default::default() }],+ vec![NativeJobDispatchOutcome::Applied],+ );+ db.cancel_on_read = Some((2, plan.operation_id.clone()));+ let result = native_job_apply_with(&state, &plan.plan_id, &mut db).await.unwrap();+ assert!(result.outcome == NativeJobOperationOutcome::Partial);+ assert!(result.steps[0].state == NativeJobStepState::Applied);+ assert!(result.steps[1].state == NativeJobStepState::Skipped);+ assert_eq!(db.calls.load(Ordering::SeqCst), 1);+}++#[tokio::test]+async fn ob_legacy_zone_edits_verify_raw_instance_without_hiding_other_definition_changes() {+ for (zone, changed) in [(None, false), (Some("zone2"), false), (Some("zone2"), true)] {+ let (_dir, state, scheduler) = setup("oceanbase-oracle").await;+ let job = NativeJobRef::Legacy { scope: scheduler.scope().clone(), job_id: "41".into() };+ let change = NativeJobChange::Update {+ final_enabled: None,+ argument_target: None,+ attributes: vec![NativeJobAttributeChange {+ name: "ZONE".into(),+ change: zone+ .map(|zone| NativeJobFieldChange::Set { value: json!(zone) })+ .unwrap_or(NativeJobFieldChange::Clear),+ }],+ arguments: vec![],+ };+ let plan = prepare(&state, &job, change).await;+ let after = DbState { zone, action: if changed { "EXTERNAL" } else { "PROC" }, ..Default::default() };+ let mut db = Session::new(&state, vec![DbState::default(), after], vec![NativeJobDispatchOutcome::Applied]);+ let status = native_job_apply_with(&state, &plan.plan_id, &mut db).await.unwrap();+ assert_eq!(+ status.outcome,+ if changed { NativeJobOperationOutcome::Partial } else { NativeJobOperationOutcome::Verified }+ );+ assert_eq!(db.calls.load(Ordering::SeqCst), 1);+ }+}++#[tokio::test]+async fn an_external_change_before_apply_is_not_overwritten_and_cleanup_failure_is_not_hidden() {+ let (_dir, state, job) = setup("oracle").await;+ let changes = NativeJobChange::Update {+ final_enabled: None,+ argument_target: None,+ attributes: vec![NativeJobAttributeChange {+ name: "COMMENTS".into(),+ change: NativeJobFieldChange::Set { value: json!("new") },+ }],+ arguments: vec![],+ };+ let plan = prepare(&state, &job, changes).await;+ let mut changed = Session::new(&state, vec![DbState { comments: "external", ..Default::default() }], vec![]);+ assert!(+ native_job_apply_with(&state, &plan.plan_id, &mut changed).await.unwrap().outcome+ == NativeJobOperationOutcome::NotApplied+ );+ assert_eq!(changed.calls.load(Ordering::SeqCst), 0);+ let plan = prepare(&state, &job, NativeJobChange::Enable).await;+ let mut db = Session::new(+ &state,+ vec![DbState::default(), DbState { enabled: true, ..Default::default() }],+ vec![NativeJobDispatchOutcome::Applied],+ );+ db.fail_cleanup = true;+ let result = native_job_apply_with(&state, &plan.plan_id, &mut db).await.unwrap();+ assert!(result.outcome == NativeJobOperationOutcome::Unknown);+ assert!(result.steps[0].state == NativeJobStepState::Applied);+}++#[tokio::test]+async fn different_operations_for_the_same_native_job_wait_before_preflight() {+ let (_dir, state, job) = setup("oracle").await;+ let first_plan = prepare(&state, &job, NativeJobChange::Enable).await;+ let second_plan = prepare(&state, &job, NativeJobChange::Disable).await;+ let mut first_db = Session::new(+ &state,+ vec![DbState::default(), DbState { enabled: true, ..Default::default() }],+ vec![NativeJobDispatchOutcome::Applied],+ );+ let mut second_db = Session::new(+ &state,+ vec![DbState { enabled: true, ..Default::default() }, DbState::default()],+ vec![NativeJobDispatchOutcome::Applied],+ );+ let (entered, mut started) = tokio::sync::oneshot::channel();+ let (release, wait) = tokio::sync::oneshot::channel();+ first_db.entered = Some(entered);+ first_db.release = Some(wait);+ let second_reads = second_db.read_calls.clone();+ let mut first = Box::pin(native_job_apply_with(&state, &first_plan.plan_id, &mut first_db));+ tokio::select! { result = &mut first => { assert!(result.is_err()); panic!("native call finished before its receipt"); }, _ = &mut started => {} }+ let mut second = Box::pin(native_job_apply_with(&state, &second_plan.plan_id, &mut second_db));+ std::future::poll_fn(|cx| {+ use std::future::Future;+ assert!(second.as_mut().poll(cx).is_pending());+ std::task::Poll::Ready(())+ })+ .await;+ assert_eq!(second_reads.load(Ordering::SeqCst), 0);+ release.send(()).unwrap();+ let (first, second) = tokio::join!(first, second);+ assert!(first.unwrap().outcome == NativeJobOperationOutcome::Verified);+ let second = second.unwrap();+ assert_eq!(second.outcome, NativeJobOperationOutcome::NotApplied);+ assert_eq!(second.reason.as_deref(), Some("native_job_definition_changed"));+ assert_eq!(second_db.calls.load(Ordering::SeqCst), 0);+ let enabled = DbState { enabled: true, ..Default::default() };+ let fresh = read(&state, &job, enabled.clone()).await;+ let plan = native_job_prepare_with(+ &state,+ NativeJobMutation { target: job.clone(), baseline: fresh.snapshot.revision, change: NativeJobChange::Disable },+ |target| {+ let state = &state;+ let enabled = enabled.clone();+ async move { Ok(read(state, &target, enabled).await) }+ },+ )+ .await+ .unwrap();+ let mut fresh_db = Session::new(&state, vec![enabled, DbState::default()], vec![NativeJobDispatchOutcome::Applied]);+ assert_eq!(+ native_job_apply_with(&state, &plan.plan_id, &mut fresh_db).await.unwrap().outcome,+ NativeJobOperationOutcome::Verified+ );+}++#[tokio::test]+async fn another_actor_cannot_confirm_cancel_or_read_the_prepared_operation() {+ let (_dir, state, job) = setup("oracle").await;+ let plan = prepare(&state, &job, NativeJobChange::Run).await;+ with_credential_owner(Some("another-authenticated-user".into()), async {+ let mut unused = Session::new(&state, vec![], vec![]);+ assert!(native_job_apply_with(&state, &plan.plan_id, &mut unused).await.is_err());+ let status = native_job_cancel(&state, &plan.operation_id);+ assert!(status.outcome == NativeJobOperationOutcome::Unknown);+ assert!(status.target.is_none());+ })+ .await;+ assert!(native_job_status(&state, &plan.operation_id).state == NativeJobOperationState::Prepared);+}++#[tokio::test]+async fn an_interrupted_authenticated_worker_becomes_unknown_and_cannot_be_replayed() {+ let (_dir, state, _job) = setup("oracle").await;+ let actor = Some("authenticated-owner".into());+ let (job, plan) = with_credential_owner(actor.clone(), async {+ let ctx = native_job_open_context_with(&state, "c", "", |_| {+ std::future::ready(Ok(NativeJobRuntimeIdentity { database_info: None, session_user: "Owner".into() }))+ })+ .await+ .unwrap();+ let job = NativeJobRef::Scheduler { scope: ctx.scope, owner: "Owner".into(), name: "Job".into() };+ let plan = prepare(&state, &job, NativeJobChange::Run).await;+ (job, plan)+ })+ .await;+ let mut db = Session::new(&state, vec![DbState::default()], vec![NativeJobDispatchOutcome::Applied]);+ let (entered, mut started) = tokio::sync::oneshot::channel();+ let (_release, wait) = tokio::sync::oneshot::channel();+ db.entered = Some(entered);+ db.release = Some(wait);+ let mut work =+ Box::pin(with_credential_owner(actor.clone(), native_job_apply_with(&state, &plan.plan_id, &mut db)));+ tokio::select! { result = &mut work => { assert!(result.is_err()); panic!("native call ended before interruption"); }, _ = &mut started => {} }+ drop(work);+ with_credential_owner(actor, async {+ let interrupted = native_job_status(&state, &plan.operation_id);+ assert!(interrupted.outcome == NativeJobOperationOutcome::Unknown);+ assert!(interrupted.steps[0].state == NativeJobStepState::Unknown);+ let mut unused = Session::new(&state, vec![], vec![]);+ assert!(+ native_job_apply_with(&state, &plan.plan_id, &mut unused).await.unwrap().outcome+ == NativeJobOperationOutcome::Unknown+ );+ assert_eq!(unused.calls.load(Ordering::SeqCst), 0);+ })+ .await;+ assert_eq!(db.calls.load(Ordering::SeqCst), 1);+ assert!(matches!(job, NativeJobRef::Scheduler { .. }));+}diff --git a/crates/dbx-core/tests/native_job_scheduler_creation.rs b/crates/dbx-core/tests/native_job_scheduler_creation.rsnew file mode 100644index 0000000000..ff1cd98969--- /dev/null+++ b/crates/dbx-core/tests/native_job_scheduler_creation.rs@@ -0,0 +1,723 @@+#![recursion_limit = "256"]++use dbx_core::connection::AppState;+use dbx_core::schema::native_jobs::*;+use dbx_sql::native_job_changes::{NativeJobSqlStep, NativeJobStepEffect};+use dbx_types::native_jobs::*;+use serde_json::{json, Value};+use std::sync::{+ atomic::{AtomicUsize, Ordering},+ Arc,+};++const CREATED_ID: &str = "900719925474099312345";++#[tokio::test]+async fn ob_non_microsecond_dates_reject_before_catalog_reads_or_plan_registration() {+ for named in [false, true] {+ for end in [false, true] {+ let (_dir, state, scope) = setup("oceanbase-oracle").await;+ let mut input = definition();+ input.attributes.clear();+ input.arguments.clear();+ input.start_date = Some("2032-01-01T23:54:25.123456000Z".into());+ input.end_date = Some("2032-01-02T00:04:25.987654000Z".into());+ if end {+ input.end_date = Some("2032-01-02T00:04:25.987654321Z".into());+ } else {+ input.start_date = Some("2032-01-01T23:54:25.123456789Z".into());+ }+ if named {+ input.program = Some(NativeJobObjectReference { owner: input.owner.clone(), name: "Program".into() });+ input.job_type = None;+ input.job_action = None;+ input.number_of_arguments = 0;+ }+ let result = native_job_prepare_request_with(+ &state,+ NativeJobRequest::Create {+ scope: scope.clone(),+ definition: NativeJobCreateDefinition::Scheduler(Box::new(input.clone())),+ },+ |_| std::future::ready(Err("unexpected_catalog_read")),+ )+ .await;+ assert_eq!(result.err(), Some("native_job_timestamp_precision_microseconds"));+ input.start_date = Some("2032-01-01T23:54:25.123456000Z".into());+ input.end_date = Some("2032-01-02T00:04:25.987654000Z".into());+ assert!(preview(&state, &scope, input, &Catalog::default()).await.is_ok());+ }+ }+}++#[tokio::test]+async fn event_creation_checks_null_condition_and_agent_and_preserves_generated_watcher_queues() {+ for (watcher, corrupt) in+ [(true, None), (true, Some("event-condition")), (false, Some("event-condition")), (false, Some("event-agent"))]+ {+ let (_dir, state, scope) = setup("oracle").await;+ let mut input = definition();+ input.event_source = Some(if watcher {+ NativeJobEventSource::FileWatcher {+ reference: NativeJobObjectReference { owner: "Owner".into(), name: "Watch.er".into() },+ }+ } else {+ NativeJobEventSource::Queue { owner: "Owner".into(), name: "Queue".into(), agent: None }+ });+ input.event_condition = None;+ let plan = preview(&state, &scope, input.clone(), &Catalog::default()).await.unwrap();+ let mut db = Session::new(&state, &input, &plan);+ db.native_watcher_queues = watcher;+ db.after_create = corrupt;+ let status = native_job_apply_with(&state, &plan.plan_id, &mut db).await.unwrap();+ assert_eq!(+ status.outcome,+ if corrupt.is_none() { NativeJobOperationOutcome::Verified } else { NativeJobOperationOutcome::Partial },+ "{watcher} {corrupt:?}"+ );+ assert_eq!(db.calls.iter().any(|step| step == "enable"), corrupt.is_none());+ if corrupt.is_some() {+ assert_eq!(db.calls, ["create"]);+ }+ }+}++async fn setup(engine: &str) -> (tempfile::TempDir, Arc<AppState>, NativeJobScope) {+ let dir = tempfile::tempdir().unwrap();+ let storage = dbx_core::persistence::test_storage::open(&dir.path().join("state.db")).await.unwrap();+ let state = Arc::new(AppState::new_with_plugin_and_agent_dir_and_app_version(+ storage,+ dir.path().join("plugins"),+ dir.path().join("agents"),+ "0.0.0",+ ));+ let config = serde_json::from_value(+ json!({"id":"c","name":"test","db_type":engine,"host":"127.0.0.1","port":1,"username":"Owner","password":""}),+ )+ .unwrap();+ state.configs.write().await.insert("c".into(), config);+ let context = native_job_open_context_with(&state, "c", "", |_| {+ std::future::ready(Ok(NativeJobRuntimeIdentity { database_info: None, session_user: "Owner".into() }))+ })+ .await+ .unwrap();+ (dir, state, context.scope)+}++fn definition() -> NativeJobSchedulerCreate {+ serde_json::from_value(json!({"owner":"Owner","name":"Job's, Exact","jobType":"STORED_PROCEDURE","jobAction":"private_proc","numberOfArguments":1,"enabled":true,"autoDrop":false,+ "attributes":[{"name":"JOB_PRIORITY","change":{"kind":"set","value":4}}],+ "arguments":[{"position":1,"dataType":"VARCHAR2","value":{"kind":"value","value":"private argument"}}]+ })).unwrap()+}++#[derive(Clone, Default)]+struct Catalog {+ row: Option<NativeJobRow>,+ arguments: Vec<NativeJobRow>,+ generation: String,+}++fn created(input: &NativeJobSchedulerCreate) -> Catalog {+ let mut row: NativeJobRow = serde_json::from_value(json!({"OWNER":input.owner,"JOB_NAME":input.name,"JOB_TYPE":input.job_type,"JOB_ACTION":input.job_action,"NUMBER_OF_ARGUMENTS":input.number_of_arguments,"ENABLED":false,"AUTO_DROP":input.auto_drop,"JOB_PRIORITY":3,"COMMENTS":input.comments})).unwrap();+ row.extend(serde_json::from_value::<NativeJobRow>(json!({"EVENT_CONDITION":null,"EVENT_QUEUE_OWNER":null,"EVENT_QUEUE_NAME":null,"EVENT_QUEUE_AGENT":null,"FILE_WATCHER_OWNER":null,"FILE_WATCHER_NAME":null,"NUMBER_OF_DESTINATIONS":null})).unwrap());+ if let Some(program) = &input.program {+ row.insert("PROGRAM_OWNER".into(), json!(program.owner));+ row.insert("PROGRAM_NAME".into(), json!(program.name));+ }+ if let Some(schedule) = &input.schedule {+ row.insert("SCHEDULE_OWNER".into(), json!(schedule.owner));+ row.insert("SCHEDULE_NAME".into(), json!(schedule.name));+ }+ if let Some(date) = &input.start_date {+ row.insert("START_DATE".into(), json!(date));+ }+ if let Some(date) = &input.end_date {+ row.insert("END_DATE".into(), json!(date));+ }+ if let Some(repeat) = &input.repeat_interval {+ row.insert("REPEAT_INTERVAL".into(), json!(repeat));+ }+ if let Some(source) = &input.event_source {+ row.extend(serde_json::from_value::<NativeJobRow>(json!({"EVENT_CONDITION":input.event_condition,"EVENT_QUEUE_OWNER":null,"EVENT_QUEUE_NAME":null,"EVENT_QUEUE_AGENT":null,"FILE_WATCHER_OWNER":null,"FILE_WATCHER_NAME":null,"NUMBER_OF_DESTINATIONS":null})).unwrap());+ match source {+ NativeJobEventSource::Queue { owner, name, agent } => {+ row.insert("EVENT_QUEUE_OWNER".into(), json!(owner));+ row.insert("EVENT_QUEUE_NAME".into(), json!(name));+ row.insert("EVENT_QUEUE_AGENT".into(), json!(agent));+ }+ NativeJobEventSource::FileWatcher { reference } => {+ row.insert("FILE_WATCHER_OWNER".into(), json!(reference.owner));+ row.insert("FILE_WATCHER_NAME".into(), json!(reference.name));+ }+ }+ }+ Catalog { row: Some(row), arguments: Vec::new(), generation: CREATED_ID.into() }+}++async fn read_catalog(state: &AppState, target: &NativeJobRef, catalog: &Catalog) -> NativeJobDetails {+ let catalog = catalog.clone();+ native_job_read_with(state, target, move |query| {+ let rows = if query.sql.contains("AS DBX_JOB_ID") {+ catalog+ .row+ .as_ref()+ .map(|_| {+ NativeJobRow::from([+ ("DBX_JOB_ID".into(), json!(catalog.generation)),+ ("DBX_CREATED_AT".into(), json!("creation")),+ ])+ })+ .into_iter()+ .collect::<Vec<_>>()+ } else if query.source.ends_with("SCHEDULER_JOBS") {+ catalog.row.clone().into_iter().collect()+ } else if query.source.ends_with("SCHEDULER_JOB_ARGS") {+ catalog.arguments.clone()+ } else {+ Vec::new()+ };+ // A real zero-row JDBC result still carries its projected columns. An empty column list+ // is an invalid response, not evidence that the selected native job is absent.+ let columns: Vec<String> = rows.first().map(|row| row.keys().cloned().collect()).unwrap_or_else(|| {+ if query.sql.contains("AS DBX_JOB_ID") {+ vec!["DBX_JOB_ID".into(), "DBX_CREATED_AT".into()]+ } else {+ vec!["OWNER".into(), "JOB_NAME".into()]+ }+ });+ let values: Vec<Vec<Value>> =+ rows.iter().map(|row| columns.iter().map(|key| row[key].clone()).collect()).collect();+ let raw = json!({"columns":columns,"rows":values,"affected_rows":0,"execution_time_ms":0});+ serde_json::from_value::<dbx_types::types::QueryResult>(raw.clone())+ .expect("database fixture must implement the real QueryResult wire schema");+ std::future::ready(Ok(raw))+ })+ .await+ .unwrap()+}++async fn preview(+ state: &AppState,+ scope: &NativeJobScope,+ input: NativeJobSchedulerCreate,+ catalog: &Catalog,+) -> Result<NativeJobPreparedPlan, &'static str> {+ native_job_prepare_request_with(+ state,+ NativeJobRequest::Create {+ scope: scope.clone(),+ definition: NativeJobCreateDefinition::Scheduler(Box::new(input)),+ },+ |target| async move { Ok(read_catalog(state, &target, catalog).await) },+ )+ .await+}++struct Session {+ state: Arc<AppState>,+ input: NativeJobSchedulerCreate,+ catalog: Catalog,+ calls: Vec<String>,+ sql: Vec<String>,+ operation_id: String,+ after_create: Option<&'static str>,+ unknown_step: Option<&'static str>,+ reject_step: Option<&'static str>,+ replace_at_read: usize,+ stop_at_read: Option<(usize, &'static str)>,+ wire_values: NativeJobRow,+ reads: usize,+ fail_cleanup: bool,+ read_events: Arc<AtomicUsize>,+ finish_entered: Option<tokio::sync::oneshot::Sender<Catalog>>,+ finish_release: Option<tokio::sync::oneshot::Receiver<()>>,+ native_watcher_queues: bool,+}++impl Session {+ fn new(state: &Arc<AppState>, input: &NativeJobSchedulerCreate, plan: &NativeJobPreparedPlan) -> Self {+ Self {+ state: state.clone(),+ input: input.clone(),+ catalog: Catalog::default(),+ calls: Vec::new(),+ sql: Vec::new(),+ operation_id: plan.operation_id.clone(),+ after_create: None,+ unknown_step: None,+ reject_step: None,+ replace_at_read: 0,+ stop_at_read: None,+ wire_values: NativeJobRow::new(),+ reads: 0,+ fail_cleanup: false,+ read_events: Arc::new(AtomicUsize::new(0)),+ finish_entered: None,+ finish_release: None,+ native_watcher_queues: false,+ }+ }+}++#[async_trait::async_trait]+impl NativeJobMutationSession for Session {+ async fn read(&mut self, target: &NativeJobRef) -> Result<NativeJobDetails, &'static str> {+ self.reads += 1;+ self.read_events.fetch_add(1, Ordering::SeqCst);+ if self.reads == self.replace_at_read {+ self.catalog.generation = "900719925474099312346".into();+ }+ let details = read_catalog(&self.state, target, &self.catalog).await;+ if let Some((at, reason)) = self.stop_at_read {+ if self.reads == at {+ if reason == "cancel" {+ native_job_cancel(&self.state, &self.operation_id);+ } else {+ self.state.configs.write().await.get_mut("c").unwrap().read_only = true;+ }+ }+ }+ Ok(details)+ }+ async fn execute(&mut self, step: &NativeJobSqlStep) -> NativeJobStepReceipt {+ self.calls.push(step.id.clone());+ self.sql.push(step.sql.clone());+ if self.reject_step == Some(step.id.as_str()) {+ return NativeJobStepReceipt {+ outcome: NativeJobDispatchOutcome::NotStarted,+ reason: Some("native_job_permission_denied".into()),+ vendor_code: Some(1031),+ };+ }+ match &step.effect {+ NativeJobStepEffect::Created => {+ self.catalog = created(&self.input);+ match self.after_create {+ Some("cancel") => {+ native_job_cancel(&self.state, &self.operation_id);+ }+ Some("readonly") => {+ self.state.configs.write().await.get_mut("c").unwrap().read_only = true;+ }+ Some("changed") => {+ self.catalog.row.as_mut().unwrap().insert("JOB_ACTION".into(), json!("external_proc"));+ }+ Some("offset") => {+ self.catalog.row.as_mut().unwrap().insert("START_DATE".into(), json!("2030-01-01T02:20:30Z"));+ }+ Some("event-condition") => {+ self.catalog+ .row+ .as_mut()+ .unwrap()+ .insert("EVENT_CONDITION".into(), json!("external condition"));+ }+ Some("event-agent") => {+ self.catalog.row.as_mut().unwrap().insert("EVENT_QUEUE_AGENT".into(), json!("ExternalAgent"));+ }+ _ => {}+ }+ }+ NativeJobStepEffect::Fields(changes)+ | NativeJobStepEffect::SchedulerDefinition(+ dbx_sql::native_job_changes::NativeJobSchedulerDefinitionEffect { columns: changes, .. },+ ) => {+ for change in changes {+ let value = match &change.change {+ NativeJobFieldChange::Set { value } => value.clone(),+ NativeJobFieldChange::Clear => Value::Null,+ NativeJobFieldChange::Keep => continue,+ };+ let value = self.wire_values.get(&change.name).cloned().unwrap_or(value);+ self.catalog.row.as_mut().unwrap().insert(change.name.clone(), value);+ }+ }+ NativeJobStepEffect::ArgumentValidated => {}+ NativeJobStepEffect::Argument(change, expected) => {+ let value = match &change.value {+ NativeJobArgumentValue::Value { value } => value.clone(),+ _ => Value::Null,+ };+ let mut row: NativeJobRow = serde_json::from_value(json!({"OWNER":self.input.owner,"JOB_NAME":self.input.name,"ARGUMENT_POSITION":change.position,"ARGUMENT_TYPE":"VARCHAR2","VALUE":value,"OUT_ARGUMENT":false,"DBX_ANYDATA_PRESENT":0})).unwrap();+ if let Some(expected) = expected {+ let canonical = json!({"typeName":expected.scalar_type.fixed_name().unwrap_or("fixture-native-type"),"isNull":expected.value.is_none(),"value":expected.value});+ row.insert("VALUE".into(), Value::Null);+ row.insert("DBX_ANYDATA_PRESENT".into(), json!(1));+ row.insert("DBX_ANYDATA_TYPE".into(), canonical["typeName"].clone());+ row.insert("DBX_ANYDATA_CODEC".into(), json!(expected.scalar_type.token()));+ row.insert("DBX_ANYDATA_CONSTRUCTOR_TYPE".into(), canonical["typeName"].clone());+ row.insert("DBX_ANYDATA_IS_NULL".into(), canonical["isNull"].clone());+ row.insert("DBX_ANYDATA_TEXT".into(), canonical["value"].clone());+ }+ self.catalog.arguments.push(row);+ }+ NativeJobStepEffect::Enabled(enabled) => {+ self.catalog.row.as_mut().unwrap().insert("ENABLED".into(), json!(enabled));+ }+ _ => panic!("unexpected scheduler creation step"),+ }+ if self.native_watcher_queues {+ self.catalog.row.as_mut().unwrap().insert("EVENT_QUEUE_OWNER".into(), json!("SYS"));+ self.catalog+ .row+ .as_mut()+ .unwrap()+ .insert("EVENT_QUEUE_NAME".into(), json!(format!("NATIVE_QUEUE_{}", self.calls.len())));+ self.catalog.row.as_mut().unwrap().insert("EVENT_QUEUE_AGENT".into(), json!("NATIVE_AGENT"));+ }+ NativeJobStepReceipt {+ outcome: if self.unknown_step == Some(step.id.as_str()) {+ NativeJobDispatchOutcome::Unknown+ } else {+ NativeJobDispatchOutcome::Applied+ },+ reason: None,+ vendor_code: None,+ }+ }+ async fn finish(&mut self) -> Result<(), &'static str> {+ if let Some(entered) = self.finish_entered.take() {+ entered.send(self.catalog.clone()).ok().unwrap();+ }+ if let Some(release) = self.finish_release.take() {+ release.await.unwrap();+ }+ if self.fail_cleanup {+ Err("unconfirmed native close")+ } else {+ Ok(())+ }+ }+}++#[tokio::test]+async fn scheduler_preview_uses_real_absence_and_preserves_named_target_without_writing() {+ let (_dir, state, scope) = setup("oracle").await;+ let input = definition();+ let plan = preview(&state, &scope, input.clone(), &Catalog::default()).await.unwrap();+ assert_eq!(+ plan.steps.iter().map(|step| step.id.as_str()).collect::<Vec<_>>(),+ ["create", "attributes", "argument:1", "enable"]+ );+ assert!(+ matches!(&plan.target, Some(NativeJobRef::Scheduler { owner, name, .. }) if owner == "Owner" && name == "Job's, Exact")+ );+ assert!(plan.steps[0].sql.contains("enabled => FALSE"));+ assert_eq!(+ preview(&state, &scope, input.clone(), &created(&input)).await.err(),+ Some("native_job_creation_target_not_absent")+ );+}++#[tokio::test]+async fn invalid_typed_character_input_is_not_allowed_to_create_a_partial_job() {+ let (_dir, state, scope) = setup("oracle").await;+ let mut input = definition();+ input.arguments[0].value = NativeJobArgumentValue::Value {+ value: json!({"$dbx":"oracle-anydata-v1","scalarType":"nvarchar2","value":"keep original creation draft"}),+ };+ let plan = preview(&state, &scope, input.clone(), &Catalog::default()).await.unwrap();+ assert_eq!(plan.steps[0].id, "validate-argument:1");+ let mut db = Session::new(&state, &input, &plan);+ db.reject_step = Some("validate-argument:1");+ let status = native_job_apply_with(&state, &plan.plan_id, &mut db).await.unwrap();+ assert_eq!(status.outcome, NativeJobOperationOutcome::NotApplied);+ assert_eq!(db.calls, ["validate-argument:1"]);+ assert!(db.catalog.row.is_none());+}++#[tokio::test]+async fn complete_configuration_and_native_generation_are_verified_before_activation_without_replay() {+ let (_dir, state, scope) = setup("oracle").await;+ let input = definition();+ let plan = preview(&state, &scope, input.clone(), &Catalog::default()).await.unwrap();+ let mut db = Session::new(&state, &input, &plan);+ let status = native_job_apply_with(&state, &plan.plan_id, &mut db).await.unwrap();+ assert_eq!(status.outcome, NativeJobOperationOutcome::Verified);+ assert_eq!(status.observed_identity.as_ref().unwrap()["DBX_JOB_ID"], json!(CREATED_ID));+ assert_eq!(db.calls, ["create", "attributes", "argument:1", "enable"]);+ assert!(status.steps.iter().all(|step| step.state == NativeJobStepState::Applied));+ let mut unused = Session::new(&state, &input, &plan);+ assert_eq!(+ native_job_apply_with(&state, &plan.plan_id, &mut unused).await.unwrap().operation_id,+ status.operation_id+ );+ assert!(unused.calls.is_empty());+ assert_eq!(unused.reads, 0);+}++#[tokio::test]+async fn unknown_create_receipt_does_not_adopt_or_activate_an_appearing_object() {+ let (_dir, state, scope) = setup("oracle").await;+ let input = definition();+ let plan = preview(&state, &scope, input.clone(), &Catalog::default()).await.unwrap();+ let mut db = Session::new(&state, &input, &plan);+ db.unknown_step = Some("create");+ let result = native_job_apply_with(&state, &plan.plan_id, &mut db).await.unwrap();+ assert_eq!(result.outcome, NativeJobOperationOutcome::Unknown);+ assert_eq!(result.reason.as_deref(), Some("native_job_creation_outcome_unknown"));+ assert_eq!(db.calls, ["create"]);+ assert_eq!(result.observed_identity.unwrap()["DBX_JOB_ID"], json!(CREATED_ID));+ assert_eq!(db.catalog.row.unwrap()["ENABLED"], json!(false));+}++#[tokio::test]+async fn cancellation_or_readonly_after_create_leaves_known_disabled_partial_configuration() {+ for reason in ["cancel", "readonly"] {+ let (_dir, state, scope) = setup("oracle").await;+ let input = definition();+ let plan = preview(&state, &scope, input.clone(), &Catalog::default()).await.unwrap();+ let mut db = Session::new(&state, &input, &plan);+ db.after_create = Some(reason);+ let result = native_job_apply_with(&state, &plan.plan_id, &mut db).await.unwrap();+ assert_eq!(result.outcome, NativeJobOperationOutcome::Partial);+ assert_eq!(db.calls, ["create"]);+ assert_eq!(db.catalog.row.unwrap()["ENABLED"], json!(false));+ }+}++#[tokio::test]+async fn cancellation_or_readonly_during_preflight_read_prevents_the_next_configuration_call() {+ for reason in ["cancel", "readonly"] {+ let (_dir, state, scope) = setup("oracle").await;+ let input = definition();+ let plan = preview(&state, &scope, input.clone(), &Catalog::default()).await.unwrap();+ let mut db = Session::new(&state, &input, &plan);+ // Read 1 confirms absence, 2 observes CREATE, and 3 checks before attributes.+ db.stop_at_read = Some((3, reason));+ let result = native_job_apply_with(&state, &plan.plan_id, &mut db).await.unwrap();+ assert_eq!(result.outcome, NativeJobOperationOutcome::Partial);+ assert_eq!(db.calls, ["create"], "{reason} must be rechecked after the awaited read");+ assert_eq!(result.steps[1].state, NativeJobStepState::Skipped);+ assert_eq!(db.catalog.row.unwrap()["ENABLED"], json!(false));+ }+}++#[tokio::test]+async fn native_numeric_interval_and_timestamp_wire_formats_do_not_make_applied_fields_partial() {+ check_native_field_values(None, NativeJobOperationOutcome::Verified).await;+ for (field, wrong) in [+ ("JOB_PRIORITY", "4.0001"),+ ("MAX_RUN_DURATION", "+000000000 01:02:03.400001"),+ ("END_DATE", "2031-01-01 10:20:30.000000 +00:00"),+ ] {+ check_native_field_values(Some((field, wrong)), NativeJobOperationOutcome::Partial).await;+ }+}++async fn check_native_field_values(wrong: Option<(&str, &str)>, outcome: NativeJobOperationOutcome) {+ let (_dir, state, scope) = setup("oracle").await;+ let input = definition();+ let mut catalog = created(&input);+ catalog.row.as_mut().unwrap().insert("END_DATE".into(), Value::Null);+ catalog.row.as_mut().unwrap().insert("MAX_RUN_DURATION".into(), Value::Null);+ let target = NativeJobRef::Scheduler { scope, owner: input.owner.clone(), name: input.name.clone() };+ let before = read_catalog(&state, &target, &catalog).await;+ let mutation = NativeJobMutation {+ target,+ baseline: before.snapshot.revision,+ change: NativeJobChange::Update {+ final_enabled: None,+ argument_target: None,+ attributes: serde_json::from_value(json!([+ {"name":"JOB_PRIORITY","change":{"kind":"set","value":4}},+ {"name":"MAX_RUN_DURATION","change":{"kind":"set","value":"0 01:02:03.4"}},+ {"name":"END_DATE","change":{"kind":"set","value":"2031-01-01T10:20:30+08:00"}}+ ]))+ .unwrap(),+ arguments: Vec::new(),+ },+ };+ let prepare_state = state.clone();+ let plan = native_job_prepare_with(&state, mutation, |target| async move {+ Ok(read_catalog(&prepare_state, &target, &catalog).await)+ })+ .await+ .unwrap();+ let mut db = Session::new(&state, &input, &plan);+ db.catalog = created(&input);+ db.catalog.row.as_mut().unwrap().insert("END_DATE".into(), Value::Null);+ db.catalog.row.as_mut().unwrap().insert("MAX_RUN_DURATION".into(), Value::Null);+ db.wire_values = serde_json::from_value(json!({+ "JOB_PRIORITY":"4.0000",+ "MAX_RUN_DURATION":"+000000000 01:02:03.400000",+ "END_DATE":"2031-01-01 02:20:30.000000 +00:00"+ }))+ .unwrap();+ if let Some((field, wrong)) = wrong {+ db.wire_values.insert(field.into(), json!(wrong));+ }+ let result = native_job_apply_with(&state, &plan.plan_id, &mut db).await.unwrap();+ assert_eq!(result.outcome, outcome, "wire override {wrong:?}");+ assert_eq!(db.calls, ["attributes"]);+}++#[tokio::test]+async fn changed_or_recreated_native_object_cannot_receive_the_remaining_configuration() {+ for change in ["definition", "generation"] {+ let (_dir, state, scope) = setup("oracle").await;+ let input = definition();+ let plan = preview(&state, &scope, input.clone(), &Catalog::default()).await.unwrap();+ let mut db = Session::new(&state, &input, &plan);+ if change == "definition" {+ db.after_create = Some("changed");+ } else {+ db.replace_at_read = 3;+ }+ let result = native_job_apply_with(&state, &plan.plan_id, &mut db).await.unwrap();+ assert_eq!(result.outcome, NativeJobOperationOutcome::Partial);+ assert_eq!(db.calls, ["create"]);+ assert_eq!(db.catalog.row.unwrap()["ENABLED"], json!(false));+ }+}++#[tokio::test]+async fn an_existing_object_at_apply_is_not_overwritten_and_rejected_create_is_not_partial() {+ let (_dir, state, scope) = setup("oracle").await;+ let input = definition();+ let plan = preview(&state, &scope, input.clone(), &Catalog::default()).await.unwrap();+ let mut db = Session::new(&state, &input, &plan);+ db.catalog = created(&input);+ assert_eq!(+ native_job_apply_with(&state, &plan.plan_id, &mut db).await.unwrap().outcome,+ NativeJobOperationOutcome::NotApplied+ );+ assert!(db.calls.is_empty());+ let plan = preview(&state, &scope, input.clone(), &Catalog::default()).await.unwrap();+ let mut db = Session::new(&state, &input, &plan);+ db.reject_step = Some("create");+ let result = native_job_apply_with(&state, &plan.plan_id, &mut db).await.unwrap();+ assert_eq!(result.outcome, NativeJobOperationOutcome::NotApplied);+ assert_eq!(result.steps[0].vendor_code, Some(1031));+ assert!(db.catalog.row.is_none());+}++#[tokio::test]+async fn a_lost_configuration_receipt_can_be_resolved_by_exact_generation_and_field_readback() {+ let (_dir, state, scope) = setup("oracle").await;+ let input = definition();+ let plan = preview(&state, &scope, input.clone(), &Catalog::default()).await.unwrap();+ let mut db = Session::new(&state, &input, &plan);+ db.unknown_step = Some("attributes");+ assert_eq!(+ native_job_apply_with(&state, &plan.plan_id, &mut db).await.unwrap().outcome,+ NativeJobOperationOutcome::Verified+ );+ assert_eq!(db.calls, ["create", "attributes", "argument:1", "enable"]);+}++#[tokio::test]+async fn disabled_creation_keeps_explicit_time_zone_and_does_not_require_activation() {+ let (_dir, state, scope) = setup("oracle").await;+ let mut input = definition();+ input.enabled = false;+ input.attributes.clear();+ input.arguments.clear();+ input.start_date = Some("2030-01-01T10:20:30+08:00".into());+ let plan = preview(&state, &scope, input.clone(), &Catalog::default()).await.unwrap();+ let mut db = Session::new(&state, &input, &plan);+ db.after_create = Some("offset");+ assert_eq!(+ native_job_apply_with(&state, &plan.plan_id, &mut db).await.unwrap().outcome,+ NativeJobOperationOutcome::Verified+ );+ assert_eq!(db.calls, ["create"]);+}++#[tokio::test]+async fn ob_creation_uses_its_actual_literal_namespace_and_binds_the_returned_generation_only() {+ let (_dir, state, scope) = setup("oceanbase-oracle").await;+ let mut input = definition();+ input.attributes.clear();+ input.arguments.clear();+ let plan = preview(&state, &scope, input.clone(), &Catalog::default()).await.unwrap();+ let mut db = Session::new(&state, &input, &plan);+ assert_eq!(+ native_job_apply_with(&state, &plan.plan_id, &mut db).await.unwrap().outcome,+ NativeJobOperationOutcome::Verified+ );+ assert!(db.sql[0].contains("number_of_argument => 1"));+ assert!(db.sql[1].contains(&format!("JOB = {CREATED_ID}")));+ assert!(!db.sql[1].contains(":dbx_created_job_id"));+ input.owner = "AnotherOwner".into();+ assert_eq!(+ preview(&state, &scope, input, &Catalog::default()).await.err(),+ Some("native_job_create_owner_mapping_unverified")+ );+}++#[tokio::test]+async fn failed_final_activation_and_unknown_cleanup_do_not_repeat_creation_or_business_execution() {+ for failure in ["enable", "cleanup"] {+ let (_dir, state, scope) = setup("oracle").await;+ let input = definition();+ let plan = preview(&state, &scope, input.clone(), &Catalog::default()).await.unwrap();+ let mut db = Session::new(&state, &input, &plan);+ if failure == "enable" {+ db.reject_step = Some("enable");+ } else {+ db.fail_cleanup = true;+ }+ let result = native_job_apply_with(&state, &plan.plan_id, &mut db).await.unwrap();+ assert_eq!(+ result.outcome,+ if failure == "enable" { NativeJobOperationOutcome::Partial } else { NativeJobOperationOutcome::Unknown }+ );+ assert_eq!(db.calls.iter().filter(|id| *id == "create").count(), 1);+ assert!(!db.sql.iter().any(|sql| sql.contains("RUN_JOB") || sql.contains("DROP_JOB")));+ if failure == "enable" {+ assert_eq!(db.catalog.row.unwrap()["ENABLED"], json!(false));+ }+ }+}++#[tokio::test]+async fn name_scoped_creation_lock_covers_the_new_generation_and_physical_cleanup() {+ let (_dir, state, scope) = setup("oracle").await;+ let input = definition();+ let plan = preview(&state, &scope, input.clone(), &Catalog::default()).await.unwrap();+ let target = plan.target.clone().unwrap();+ let (entered, when_finishing) = tokio::sync::oneshot::channel();+ let (release, after_finish) = tokio::sync::oneshot::channel();+ let mut db = Session::new(&state, &input, &plan);+ db.finish_entered = Some(entered);+ db.finish_release = Some(after_finish);+ let creating_state = state.clone();+ let creation =+ tokio::spawn(async move { native_job_apply_with(&creating_state, &plan.plan_id, &mut db).await.unwrap() });+ let catalog = when_finishing.await.unwrap();+ let current = read_catalog(&state, &target, &catalog).await;+ let mutation = NativeJobMutation {+ target: target.clone(),+ baseline: current.snapshot.revision.clone(),+ change: NativeJobChange::Disable,+ };+ let prepare_state = state.clone();+ let prepare_catalog = catalog.clone();+ let following = native_job_prepare_with(&state, mutation, |target| async move {+ Ok(read_catalog(&prepare_state, &target, &prepare_catalog).await)+ })+ .await+ .unwrap();+ let mut db = Session::new(&state, &input, &following);+ db.catalog = catalog;+ let reads = db.read_events.clone();+ let (started, is_started) = tokio::sync::oneshot::channel();+ let following_state = state.clone();+ let disabling = tokio::spawn(async move {+ started.send(()).unwrap();+ native_job_apply_with(&following_state, &following.plan_id, &mut db).await.unwrap()+ });+ is_started.await.unwrap();+ tokio::task::yield_now().await;+ assert_eq!(+ reads.load(Ordering::SeqCst),+ 0,+ "the new ID must not get a different lock while creation is cleaning up"+ );+ release.send(()).unwrap();+ assert_eq!(creation.await.unwrap().outcome, NativeJobOperationOutcome::Verified);+ assert_eq!(disabling.await.unwrap().outcome, NativeJobOperationOutcome::Verified);+ assert!(reads.load(Ordering::SeqCst) > 0);+}diff --git a/crates/dbx-core/tests/native_job_scheduler_transitions.rs b/crates/dbx-core/tests/native_job_scheduler_transitions.rsnew file mode 100644index 0000000000..1ff9322182--- /dev/null+++ b/crates/dbx-core/tests/native_job_scheduler_transitions.rs@@ -0,0 +1,1206 @@+#![recursion_limit = "256"]++use dbx_core::connection::AppState;+use dbx_core::schema::native_jobs::*;+use dbx_sql::native_job_changes::{NativeJobSqlStep, NativeJobStepEffect};+use dbx_types::native_jobs::*;+use serde_json::{json, Value};+use std::sync::{+ atomic::{AtomicUsize, Ordering},+ Arc,+};++#[derive(Clone)]+struct Catalog {+ definition: NativeJobRow,+ args: Vec<NativeJobRow>,+ count: usize,+ metadata_position: Option<usize>,+ reference_changed: bool,+ extra_references: Vec<(NativeJobReferenceKind, NativeJobMetadata<Vec<NativeJobRow>>)>,+ first_type: &'static str,+}++impl Catalog {+ fn new() -> Self {+ let mut catalog = Self { definition: serde_json::from_value(json!({"OWNER":"Owner","JOB_NAME":"Job","PROGRAM_OWNER":"Owner","PROGRAM_NAME":"P1","JOB_TYPE":null,"JOB_ACTION":null,"NUMBER_OF_ARGUMENTS":null,"ENABLED":true,"COMMENTS":"keep","AUTO_DROP":false,"SCHEDULE_OWNER":null,"SCHEDULE_NAME":null,"SCHEDULE_TYPE":"CALENDAR","REPEAT_INTERVAL":"FREQ=DAILY","START_DATE":"2030-01-01T00:00:00+08:00","END_DATE":null,"JOB_STYLE":"REGULAR"})).unwrap(), args: vec![argument(1, "old"), argument(2, "retained")], count: 2, metadata_position: None, reference_changed: false, extra_references: Vec::new(), first_type: "VARCHAR2" };+ catalog.definition.extend(serde_json::from_value::<NativeJobRow>(json!({"FLAGS":0,"EVENT_RULE":null,"NUMBER_OF_DESTINATIONS":null,"EVENT_CONDITION":null,"EVENT_QUEUE_OWNER":null,"EVENT_QUEUE_NAME":null,"EVENT_QUEUE_AGENT":null,"FILE_WATCHER_OWNER":null,"FILE_WATCHER_NAME":null,"DESTINATION_OWNER":null,"DESTINATION":null})).unwrap());+ catalog+ }+ fn program(&self, name: &str) -> NativeJobRow {+ serde_json::from_value(json!({"DBX_OWNER":"Owner","DBX_NAME":name,"PROGRAM_NAME":name,"PROGRAM_TYPE":"STORED_PROCEDURE","PROGRAM_ACTION":if self.reference_changed && name == "P2" { "external_proc" } else { "proc" },"NUMBER_OF_ARGUMENTS":if name == "P1" { 2 } else { self.count },"ENABLED":true})).unwrap()+ }+ fn program_args(&self, name: &str) -> Vec<NativeJobRow> {+ (1..=if name == "P1" { 2 } else { self.count }).map(|position| serde_json::from_value(json!({"DBX_OWNER":"Owner","DBX_NAME":name,"PROGRAM_NAME":name,"ARGUMENT_POSITION":position,"ARGUMENT_NAME":format!("{name}_{position}"),"ARGUMENT_TYPE":if position == 1 { self.first_type } else { "VARCHAR2" },"DBX_ANYDATA_PRESENT":0,"DEFAULT_VALUE":"default","METADATA_ATTRIBUTE":if name == "P2" && self.metadata_position == Some(position) { json!("EVENT_MESSAGE") } else { Value::Null },"OUT_ARGUMENT":false})).unwrap()).collect()+ }+}++fn argument(position: usize, value: &str) -> NativeJobRow {+ serde_json::from_value(json!({"OWNER":"Owner","JOB_NAME":"Job","ARGUMENT_POSITION":position,"ARGUMENT_NAME":format!("old_{position}"),"ARGUMENT_TYPE":"VARCHAR2","DBX_ANYDATA_PRESENT":0,"VALUE":value,"OUT_ARGUMENT":false,"DBX_ANYDATA_TYPE":null,"DBX_ANYDATA_IS_NULL":null})).unwrap()+}++fn result(rows: Vec<NativeJobRow>) -> Value {+ let columns: Vec<_> = if rows.is_empty() {+ vec!["OWNER".into(), "JOB_NAME".into()]+ } else {+ rows.iter().flat_map(|row| row.keys().cloned()).collect::<std::collections::BTreeSet<_>>().into_iter().collect()+ };+ let values: Vec<Vec<Value>> = rows+ .iter()+ .map(|row| columns.iter().map(|key| row.get(key).cloned().unwrap_or(Value::Null)).collect())+ .collect();+ json!({"columns":columns,"rows":values,"affected_rows":0,"execution_time_ms":0})+}++async fn read(state: &AppState, target: &NativeJobRef, catalog: &Catalog) -> NativeJobDetails {+ native_job_read_with(state, target, |query| {+ let name = if query.sql.contains("'P2'") { "P2" } else { "P1" };+ let rows = if query.sql.contains("AS DBX_JOB_ID") {+ vec![serde_json::from_value(json!({"DBX_JOB_ID":"42","DBX_CREATED_AT":"creation"})).unwrap()]+ } else if query.source.ends_with("SCHEDULER_PROGRAM_ARGS") {+ catalog.program_args(name)+ } else if query.source.ends_with("SCHEDULER_PROGRAMS") {+ vec![catalog.program(name)]+ } else if query.source.ends_with("SCHEDULER_JOB_ARGS") {+ catalog.args.clone()+ } else if query.source.ends_with("SCHEDULER_JOBS") {+ vec![catalog.definition.clone()]+ } else {+ vec![]+ };+ std::future::ready(Ok(result(rows)))+ })+ .await+ .unwrap()+}++fn references(catalog: &Catalog, request: &NativeJobReferenceListRequest) -> NativeJobReferenceCatalog {+ let name = request.name.as_deref().unwrap();+ let objects = if let Some((_, value)) = catalog.extra_references.iter().find(|(kind, _)| *kind == request.kind) {+ value.clone()+ } else if request.kind == NativeJobReferenceKind::ProgramArguments {+ NativeJobMetadata::Available { value: catalog.program_args(name) }+ } else {+ assert_eq!(request.kind, NativeJobReferenceKind::Program);+ NativeJobMetadata::Available { value: vec![catalog.program(name)] }+ };+ NativeJobReferenceCatalog {+ objects,+ source: NativeJobCatalogSource {+ source: Some("fixture".into()),+ coverage: Some(NativeJobCatalogCoverage::Accessible),+ },+ offset: 0,+ limit: request.limit,+ }+}++async fn setup() -> (tempfile::TempDir, Arc<AppState>, NativeJobRef) {+ setup_for("oracle").await+}++async fn setup_for(engine: &str) -> (tempfile::TempDir, Arc<AppState>, NativeJobRef) {+ let dir = tempfile::tempdir().unwrap();+ let storage = dbx_core::persistence::test_storage::open(&dir.path().join("state.db")).await.unwrap();+ let state = Arc::new(AppState::new_with_plugin_and_agent_dir_and_app_version(+ storage,+ dir.path().join("plugins"),+ dir.path().join("agents"),+ "0.0.0",+ ));+ state.configs.write().await.insert("c".into(), serde_json::from_value(json!({"id":"c","name":"test","db_type":engine,"host":"127.0.0.1","port":1,"username":"Owner","password":""})).unwrap());+ let context = native_job_open_context_with(&state, "c", "", |_| {+ std::future::ready(Ok(NativeJobRuntimeIdentity { database_info: None, session_user: "Owner".into() }))+ })+ .await+ .unwrap();+ (dir, state, NativeJobRef::Scheduler { scope: context.scope, owner: "Owner".into(), name: "Job".into() })+}++fn mutation(initial: &NativeJobDetails, count: usize) -> NativeJobMutation {+ serde_json::from_value(json!({"action":"update","target":initial.snapshot.job_ref,"baseline":initial.snapshot.revision,"finalEnabled":true,"attributes":[{"name":"PROGRAM_NAME","change":{"kind":"set","value":{"owner":"Owner","name":"P2"}}}],"arguments":[],"argumentTarget":{"program":{"owner":"Owner","name":"P2"},"arguments":(1..=count).map(|position| json!({"position":position,"dataType":"VARCHAR2","value":if position==1 { json!({"kind":"value","value":"new"}) } else { json!({"kind":"inherit"}) }})).collect::<Vec<_>>()}})).unwrap()+}++async fn prepare(state: &AppState, target: &NativeJobRef, catalog: &Catalog) -> NativeJobPreparedPlan {+ let initial = read(state, target, catalog).await;+ native_job_prepare_with_references(+ state,+ mutation(&initial, catalog.count),+ |target| async move { Ok(read(state, &target, catalog).await) },+ |request| std::future::ready(Ok(references(catalog, &request))),+ )+ .await+ .unwrap()+}++struct Session {+ state: Arc<AppState>,+ catalog: Catalog,+ clear_native: bool,+ calls: Vec<String>,+ operation: String,+ cancel_after: Option<&'static str>,+ reject: Option<&'static str>,+ unknown: Option<&'static str>,+ poison: Option<&'static str>,+ changed_reference_at_end: bool,+ dependency_reads: usize,+ finish_calls: Arc<AtomicUsize>,+ after_definition: NativeJobRow,+ member_change_at: Option<usize>,+ reverse_members: bool,+}++impl Session {+ fn new(state: &Arc<AppState>, catalog: Catalog, plan: &NativeJobPreparedPlan) -> Self {+ Self {+ state: state.clone(),+ catalog,+ clear_native: false,+ calls: vec![],+ operation: plan.operation_id.clone(),+ cancel_after: None,+ reject: None,+ unknown: None,+ poison: None,+ changed_reference_at_end: false,+ dependency_reads: 0,+ finish_calls: Arc::new(AtomicUsize::new(0)),+ after_definition: NativeJobRow::new(),+ member_change_at: None,+ reverse_members: false,+ }+ }+}++#[async_trait::async_trait]+impl NativeJobMutationSession for Session {+ async fn read(&mut self, target: &NativeJobRef) -> Result<NativeJobDetails, &'static str> {+ Ok(read(&self.state, target, &self.catalog).await)+ }+ async fn read_reference(+ &mut self,+ request: NativeJobReferenceListRequest,+ ) -> Result<NativeJobReferenceCatalog, &'static str> {+ self.dependency_reads += 1;+ let mut catalog = self.catalog.clone();+ if self.changed_reference_at_end && self.dependency_reads > 2 {+ catalog.reference_changed = true;+ }+ let mut reference = references(&catalog, &request);+ if request.kind == NativeJobReferenceKind::DestinationGroupMembers {+ if let NativeJobMetadata::Available { value } = &mut reference.objects {+ if self.member_change_at.is_some_and(|at| self.dependency_reads >= at) {+ value[0].insert("MEMBER_NAME".into(), json!("[email protected]"));+ }+ if self.reverse_members {+ value.reverse();+ }+ }+ }+ Ok(reference)+ }+ async fn execute(&mut self, step: &NativeJobSqlStep) -> NativeJobStepReceipt {+ self.calls.push(step.id.clone());+ if self.reject == Some(step.id.as_str()) {+ return NativeJobStepReceipt {+ outcome: NativeJobDispatchOutcome::NotStarted,+ reason: Some("native denied".into()),+ vendor_code: Some(1031),+ };+ }+ match &step.effect {+ NativeJobStepEffect::ArgumentValidated => {}+ NativeJobStepEffect::Enabled(enabled) => {+ self.catalog.definition.insert("ENABLED".into(), json!(enabled));+ }+ NativeJobStepEffect::SchedulerDefinition(effect) => {+ for column in &effect.columns {+ self.catalog.definition.insert(+ column.name.clone(),+ match &column.change {+ NativeJobFieldChange::Set { value } => value.clone(),+ _ => Value::Null,+ },+ );+ }+ if self.clear_native {+ self.catalog.args.clear();+ }+ if self.poison == Some("definition") {+ self.catalog.args = vec![argument(1, "external")];+ }+ if self.poison == Some("untouched") {+ self.catalog.definition.insert("COMMENTS".into(), json!("external"));+ }+ self.catalog.definition.extend(self.after_definition.clone());+ }+ NativeJobStepEffect::Argument(change, expected) => {+ self.catalog.args.retain(|row| row["ARGUMENT_POSITION"] != json!(change.position));+ if let Some(expected) = expected {+ let mut row = argument(change.position, "");+ row.insert("VALUE".into(), Value::Null);+ let canonical = json!({"typeName":expected.scalar_type.fixed_name().unwrap_or("fixture-native-type"),"isNull":expected.value.is_none(),"value":expected.value});+ row.insert("DBX_ANYDATA_PRESENT".into(), json!(1));+ row.insert("DBX_ANYDATA_CODEC".into(), json!(expected.scalar_type.token()));+ row.insert("DBX_ANYDATA_CONSTRUCTOR_TYPE".into(), canonical["typeName"].clone());+ row.insert(+ "DBX_ANYDATA_TYPE".into(),+ if self.poison == Some("wrong-null-type") {+ json!("SYS.NUMBER")+ } else {+ canonical["typeName"].clone()+ },+ );+ row.insert(+ "DBX_ANYDATA_IS_NULL".into(),+ if self.poison == Some("null-evidence") { Value::Null } else { canonical["isNull"].clone() },+ );+ row.insert("DBX_ANYDATA_TEXT".into(), canonical["value"].clone());+ if self.poison == Some("number-rounding") {+ row.insert("DBX_ANYDATA_TEXT".into(), json!("9007199254740992"));+ }+ if self.poison.is_none() {+ assert!(+ expected.matches(&dbx_sql::native_job_arguments::decode_argument(&row, false)),+ "database fixture projection must represent the setter type: {:?}",+ expected.scalar_type+ );+ }+ self.catalog.args.push(row);+ } else if let NativeJobArgumentValue::Value { value } = &change.value {+ self.catalog.args.push(argument(change.position, value.as_str().unwrap()));+ }+ }+ _ => panic!("unexpected transition step"),+ }+ if self.poison == Some("generated") {+ self.catalog.definition.insert("FLAGS".into(), json!(self.calls.len()));+ self.catalog.definition.insert("EVENT_RULE".into(), json!(format!("native-rule:{}", self.calls.len())));+ self.catalog.definition.insert("NUMBER_OF_DESTINATIONS".into(), json!(self.calls.len().to_string()));+ }+ if self.poison == Some("watcher-queue") && !self.catalog.definition["FILE_WATCHER_NAME"].is_null() {+ self.catalog.definition.insert("EVENT_QUEUE_OWNER".into(), json!("SYS"));+ self.catalog+ .definition+ .insert("EVENT_QUEUE_NAME".into(), json!(format!("NATIVE_QUEUE_{}", self.calls.len())));+ self.catalog.definition.insert("EVENT_QUEUE_AGENT".into(), json!("NATIVE_AGENT"));+ }+ if self.poison == Some("missing-count") {+ self.catalog.definition.remove("NUMBER_OF_DESTINATIONS");+ }+ if self.cancel_after == Some(step.id.as_str()) {+ native_job_cancel(&self.state, &self.operation);+ }+ NativeJobStepReceipt {+ outcome: if self.unknown == Some(step.id.as_str()) {+ NativeJobDispatchOutcome::Unknown+ } else {+ NativeJobDispatchOutcome::Applied+ },+ reason: None,+ vendor_code: None,+ }+ }+ async fn finish(&mut self) -> Result<(), &'static str> {+ self.finish_calls.fetch_add(1, Ordering::SeqCst);+ Ok(())+ }+}++#[tokio::test]+async fn dameng_program_effective_definition_allows_only_its_own_mirror_changes() {+ for changed in ["JOB_ACTION", "SCHEDULE_TYPE", "COMMENTS"] {+ let (_dir, state, target) = setup_for("dameng").await;+ let catalog = Catalog::new();+ let plan = prepare(&state, &target, &catalog).await;+ assert!(!plan.steps.iter().any(|step| step.id == "argument:2"));+ let mut db = Session::new(&state, catalog, &plan);+ db.clear_native = true;+ db.after_definition.insert(changed.into(), json!("native mirror"));+ let status = native_job_apply_with(&state, &plan.plan_id, &mut db).await.unwrap();+ assert_eq!(+ status.outcome,+ if changed == "JOB_ACTION" {+ NativeJobOperationOutcome::Verified+ } else {+ NativeJobOperationOutcome::Partial+ },+ "{changed}"+ );+ assert_eq!(db.calls.iter().any(|id| id == "enable"), changed == "JOB_ACTION");+ }+}++#[tokio::test]+async fn dameng_schedule_projection_does_not_relax_program_or_activation_checks() {+ for changed in ["SCHEDULE_TYPE", "JOB_ACTION", "ENABLED"] {+ let (_dir, state, target) = setup_for("dameng").await;+ let mut catalog = Catalog::new();+ catalog.definition.insert("SCHEDULE_OWNER".into(), json!("Owner"));+ catalog.definition.insert("SCHEDULE_NAME".into(), json!("S1"));+ catalog.extra_references.push((NativeJobReferenceKind::Schedule, NativeJobMetadata::Available {+ value: vec![serde_json::from_value(json!({"DBX_OWNER":"Owner","DBX_NAME":"S2","SCHEDULE_TYPE":"ONCE","START_DATE":"2031-01-01","REPEAT_INTERVAL":null,"END_DATE":null})).unwrap()],+ }));+ let initial = read(&state, &target, &catalog).await;+ let mutation = serde_json::from_value(json!({"action":"update","target":target,"baseline":initial.snapshot.revision,"finalEnabled":true,"attributes":[{"name":"SCHEDULE_NAME","change":{"kind":"set","value":{"owner":"Owner","name":"S2"}}}],"arguments":[]})).unwrap();+ let plan = native_job_prepare_with_references(+ &state,+ mutation,+ |target| {+ let catalog = &catalog;+ let state = &state;+ async move { Ok(read(state, &target, catalog).await) }+ },+ |request| std::future::ready(Ok(references(&catalog, &request))),+ )+ .await+ .unwrap();+ let mut db = Session::new(&state, catalog, &plan);+ db.after_definition+ .insert(changed.into(), if changed == "ENABLED" { json!(true) } else { json!("native mirror") });+ let status = native_job_apply_with(&state, &plan.plan_id, &mut db).await.unwrap();+ assert_eq!(+ status.outcome,+ if changed == "SCHEDULE_TYPE" {+ NativeJobOperationOutcome::Verified+ } else {+ NativeJobOperationOutcome::Partial+ },+ "{changed}"+ );+ }+}++#[tokio::test]+async fn dameng_two_slot_plan_does_not_activate_the_second_projection_early() {+ let (_dir, state, target) = setup_for("dameng").await;+ let mut catalog = Catalog::new();+ catalog.definition.insert("SCHEDULE_OWNER".into(), json!("Owner"));+ catalog.definition.insert("SCHEDULE_NAME".into(), json!("S1"));+ catalog.extra_references.push((NativeJobReferenceKind::Schedule, NativeJobMetadata::Available {+ value: vec![serde_json::from_value(json!({"DBX_OWNER":"Owner","DBX_NAME":"S2","SCHEDULE_TYPE":"ONCE","START_DATE":"2031-01-01","REPEAT_INTERVAL":null,"END_DATE":null})).unwrap()],+ }));+ let initial = read(&state, &target, &catalog).await;+ let mut mutation = mutation(&initial, catalog.count);+ let NativeJobChange::Update { attributes, .. } = &mut mutation.change else { unreachable!() };+ attributes.push(NativeJobAttributeChange {+ name: "SCHEDULE_NAME".into(),+ change: NativeJobFieldChange::Set { value: json!({"owner":"Owner","name":"S2"}) },+ });+ let plan = native_job_prepare_with_references(+ &state,+ mutation,+ |target| {+ let catalog = &catalog;+ let state = &state;+ async move { Ok(read(state, &target, catalog).await) }+ },+ |request| std::future::ready(Ok(references(&catalog, &request))),+ )+ .await+ .unwrap();+ let mut db = Session::new(&state, catalog, &plan);+ db.clear_native = true;+ db.after_definition.insert("SCHEDULE_TYPE".into(), json!("changed before schedule setter"));+ let status = native_job_apply_with(&state, &plan.plan_id, &mut db).await.unwrap();+ assert_eq!(status.outcome, NativeJobOperationOutcome::Partial);+ assert!(!db.calls.iter().any(|id| id == "enable" || id == "attribute:SCHEDULE_NAME"));+}++#[tokio::test]+async fn dameng_inherit_residual_stops_immediately_after_the_program_setter() {+ let (_dir, state, target) = setup_for("dameng").await;+ let catalog = Catalog::new();+ let plan = prepare(&state, &target, &catalog).await;+ let mut db = Session::new(&state, catalog, &plan);+ let status = native_job_apply_with(&state, &plan.plan_id, &mut db).await.unwrap();+ assert_eq!(status.outcome, NativeJobOperationOutcome::Partial);+ assert!(!db.calls.iter().any(|id| id.starts_with("argument:") || id == "enable"));+ assert_eq!(db.catalog.definition["PROGRAM_NAME"], json!("P2"));+ assert_eq!(db.catalog.definition["ENABLED"], json!(false));+}++#[tokio::test]+async fn native_clear_and_native_preserve_both_reconcile_the_full_target_before_enabling() {+ for clear_native in [false, true] {+ let (_dir, state, target) = setup().await;+ let catalog = Catalog::new();+ let plan = prepare(&state, &target, &catalog).await;+ let mut db = Session::new(&state, catalog, &plan);+ db.clear_native = clear_native;+ let status = native_job_apply_with(&state, &plan.plan_id, &mut db).await.unwrap();+ assert_eq!(status.outcome, NativeJobOperationOutcome::Verified);+ assert_eq!(db.calls.last().map(String::as_str), Some("enable"));+ assert_eq!(db.catalog.args.len(), 1);+ assert_eq!(db.catalog.args[0]["VALUE"], json!("new"));+ assert_eq!(db.calls.iter().any(|id| id == "argument:2"), !clear_native);+ assert_eq!(db.finish_calls.load(Ordering::SeqCst), 1);+ let calls = db.calls.len();+ native_job_apply_with(&state, &plan.plan_id, &mut db).await.unwrap();+ assert_eq!(db.calls.len(), calls);+ }+}++#[tokio::test]+async fn a_reduced_count_retires_old_positions_while_the_old_program_is_still_active() {+ let (_dir, state, target) = setup().await;+ let mut catalog = Catalog::new();+ catalog.count = 1;+ let plan = prepare(&state, &target, &catalog).await;+ assert_eq!(plan.steps[1].id, "retire-argument:2");+ let mut db = Session::new(&state, catalog, &plan);+ assert_eq!(+ native_job_apply_with(&state, &plan.plan_id, &mut db).await.unwrap().outcome,+ NativeJobOperationOutcome::Verified+ );+ let retiring = db.calls.iter().position(|id| id == "retire-argument:2").unwrap();+ let definition = db.calls.iter().position(|id| id == "attributes").unwrap();+ assert!(retiring < definition);+}++#[tokio::test]+async fn cancellation_rejection_and_conflicting_readback_never_enable_a_partial_conversion() {+ for failure in ["cancel", "reject", "definition", "untouched"] {+ let (_dir, state, target) = setup().await;+ let catalog = Catalog::new();+ let plan = prepare(&state, &target, &catalog).await;+ let mut db = Session::new(&state, catalog, &plan);+ match failure {+ "cancel" => db.cancel_after = Some("attributes"),+ "reject" => db.reject = Some("argument:1"),+ _ => db.poison = Some(failure),+ }+ let status = native_job_apply_with(&state, &plan.plan_id, &mut db).await.unwrap();+ assert_eq!(status.outcome, NativeJobOperationOutcome::Partial, "{failure}");+ assert!(!db.calls.iter().any(|id| id == "enable"));+ assert_eq!(db.catalog.definition["ENABLED"], json!(false));+ }+}++#[tokio::test]+async fn changed_target_metadata_fails_before_dispatch_or_final_activation() {+ for at_end in [false, true] {+ let (_dir, state, target) = setup().await;+ let catalog = Catalog::new();+ let plan = prepare(&state, &target, &catalog).await;+ let mut db = Session::new(&state, catalog, &plan);+ if at_end {+ db.changed_reference_at_end = true;+ } else {+ db.catalog.reference_changed = true;+ }+ let status = native_job_apply_with(&state, &plan.plan_id, &mut db).await.unwrap();+ assert_eq!(+ status.outcome,+ if at_end { NativeJobOperationOutcome::Partial } else { NativeJobOperationOutcome::NotApplied }+ );+ assert!(!db.calls.iter().any(|id| id == "enable"));+ if !at_end {+ assert!(db.calls.is_empty());+ }+ }+}++#[tokio::test]+async fn a_verified_lost_definition_receipt_is_not_resent_and_new_preview_only_reconciles_remaining_values() {+ let (_dir, state, target) = setup().await;+ let catalog = Catalog::new();+ let plan = prepare(&state, &target, &catalog).await;+ let mut db = Session::new(&state, catalog, &plan);+ db.unknown = Some("attributes");+ db.cancel_after = Some("attributes");+ assert_eq!(+ native_job_apply_with(&state, &plan.plan_id, &mut db).await.unwrap().outcome,+ NativeJobOperationOutcome::Partial+ );+ let original = read(&state, &target, &db.catalog).await;+ let mut next = mutation(&original, 2);+ if let NativeJobChange::Update { attributes, .. } = &mut next.change {+ attributes.clear();+ }+ let state_ref = state.as_ref();+ let catalog_ref = &db.catalog;+ let repaired = native_job_prepare_with_references(+ &state,+ next,+ |target| async move { Ok(read(state_ref, &target, catalog_ref).await) },+ |request| std::future::ready(Ok(references(&db.catalog, &request))),+ )+ .await+ .unwrap();+ assert!(!repaired.steps.iter().any(|step| step.id == "attributes"));+ let mut resumed = Session::new(&state, db.catalog, &repaired);+ assert_eq!(+ native_job_apply_with(&state, &repaired.plan_id, &mut resumed).await.unwrap().outcome,+ NativeJobOperationOutcome::Verified+ );+ assert!(!resumed.calls.iter().any(|id| id == "pause" || id == "attributes"));+}++#[tokio::test]+async fn ordinary_edits_still_call_the_original_fnonce_reader_once_without_new_reference_reads() {+ let (_dir, state, target) = setup().await;+ let catalog = Catalog::new();+ let initial = read(&state, &target, &catalog).await;+ let mutation = serde_json::from_value(json!({"target":target,"baseline":initial.snapshot.revision,"action":"update","attributes":[{"name":"COMMENTS","change":{"kind":"set","value":"new"}}],"arguments":[]})).unwrap();+ let reads = AtomicUsize::new(0);+ let state_ref = state.as_ref();+ let catalog_ref = &catalog;+ let plan = native_job_prepare_with_references(+ &state,+ mutation,+ |target| {+ reads.fetch_add(1, Ordering::SeqCst);+ async move { Ok(read(state_ref, &target, catalog_ref).await) }+ },+ |_| -> std::future::Ready<Result<NativeJobReferenceCatalog, &'static str>> {+ panic!("ordinary edit read a reference")+ },+ )+ .await+ .unwrap();+ assert_eq!(reads.load(Ordering::SeqCst), 1);+ assert_eq!(plan.steps.len(), 1);+}++#[tokio::test]+async fn inline_to_program_and_back_use_independent_complete_argument_contexts() {+ let (_dir, state, target) = setup().await;+ let mut catalog = Catalog::new();+ catalog.definition.extend(serde_json::from_value::<NativeJobRow>(json!({"PROGRAM_OWNER":null,"PROGRAM_NAME":null,"JOB_TYPE":"STORED_PROCEDURE","JOB_ACTION":"inline_proc","NUMBER_OF_ARGUMENTS":2})).unwrap());+ let plan = prepare(&state, &target, &catalog).await;+ let mut db = Session::new(&state, catalog, &plan);+ assert_eq!(+ native_job_apply_with(&state, &plan.plan_id, &mut db).await.unwrap().outcome,+ NativeJobOperationOutcome::Verified+ );+ let initial = read(&state, &target, &db.catalog).await;+ let mutation = serde_json::from_value(json!({"action":"update","target":target,"baseline":initial.snapshot.revision,"finalEnabled":false,"attributes":[{"name":"PROGRAM_NAME","change":{"kind":"clear"}},{"name":"JOB_TYPE","change":{"kind":"set","value":"STORED_PROCEDURE"}},{"name":"JOB_ACTION","change":{"kind":"set","value":"new_inline"}},{"name":"NUMBER_OF_ARGUMENTS","change":{"kind":"set","value":1}}],"arguments":[],"argumentTarget":{"program":null,"arguments":[{"position":1,"dataType":"VARCHAR2","value":{"kind":"value","value":"inline only"}}]}})).unwrap();+ let state_ref = state.as_ref();+ let catalog_ref = &db.catalog;+ let plan = native_job_prepare_with_references(+ &state,+ mutation,+ |target| async move { Ok(read(state_ref, &target, catalog_ref).await) },+ |_| -> std::future::Ready<Result<NativeJobReferenceCatalog, &'static str>> {+ panic!("inline target read an unrelated reference")+ },+ )+ .await+ .unwrap();+ let mut db = Session::new(&state, db.catalog, &plan);+ assert_eq!(+ native_job_apply_with(&state, &plan.plan_id, &mut db).await.unwrap().outcome,+ NativeJobOperationOutcome::Verified+ );+ assert_eq!(db.catalog.definition["PROGRAM_NAME"], Value::Null);+ assert_eq!(db.catalog.definition["JOB_ACTION"], json!("new_inline"));+ assert_eq!(db.catalog.definition["ENABLED"], json!(false));+ assert_eq!(db.catalog.args[0]["VALUE"], json!("inline only"));+}++#[tokio::test]+async fn target_metadata_arguments_are_retired_in_the_old_context_not_user_overridden() {+ let (_dir, state, target) = setup().await;+ let mut catalog = Catalog::new();+ catalog.metadata_position = Some(2);+ let plan = prepare(&state, &target, &catalog).await;+ assert!(plan.steps.iter().any(|step| step.id == "retire-argument:2"));+ let mut db = Session::new(&state, catalog, &plan);+ assert_eq!(+ native_job_apply_with(&state, &plan.plan_id, &mut db).await.unwrap().outcome,+ NativeJobOperationOutcome::Verified+ );+ assert!(!db.calls.iter().any(|step| step == "argument:2"));+}++#[tokio::test]+async fn an_unresettable_residual_requires_an_explicit_original_context_preview() {+ let (_dir, state, target) = setup().await;+ let mut catalog = Catalog::new();+ catalog.count = 1;+ catalog.definition.insert("PROGRAM_NAME".into(), json!("P2"));+ let initial = read(&state, &target, &catalog).await;+ let state_ref = state.as_ref();+ let catalog_ref = &catalog;+ let result = native_job_prepare_with_references(+ &state,+ mutation(&initial, 1),+ |target| async move { Ok(read(state_ref, &target, catalog_ref).await) },+ |request| std::future::ready(Ok(references(&catalog, &request))),+ )+ .await;+ assert_eq!(result.err(), Some("native_job_argument_retirement_requires_original_context"));+}++#[tokio::test]+async fn explicit_null_needs_native_typed_null_evidence_not_the_retained_client_value() {+ for poison in [Some("null-evidence"), Some("wrong-null-type"), None] {+ let known = poison.is_none();+ let (_dir, state, target) = setup().await;+ let catalog = Catalog::new();+ let initial = read(&state, &target, &catalog).await;+ let mut mutation = mutation(&initial, 2);+ if let NativeJobChange::Update { argument_target: Some(target), .. } = &mut mutation.change {+ target.arguments[0].value = NativeJobArgumentValue::Null;+ target.arguments[0].data_type = "NUMBER".into();+ }+ let state_ref = state.as_ref();+ let catalog_ref = &catalog;+ let plan = native_job_prepare_with_references(+ &state,+ mutation,+ |target| async move { Ok(read(state_ref, &target, catalog_ref).await) },+ |request| std::future::ready(Ok(references(&catalog, &request))),+ )+ .await+ .unwrap();+ let argument = plan.steps.iter().find(|step| step.id == "argument:1").unwrap();+ assert!(argument.sql.contains("ConvertVarchar2"), "the bound Program type must replace the stale caller type");+ let mut db = Session::new(&state, catalog, &plan);+ db.poison = poison;+ let result = native_job_apply_with(&state, &plan.plan_id, &mut db).await.unwrap();+ assert_eq!(+ result.outcome,+ if known { NativeJobOperationOutcome::Verified } else { NativeJobOperationOutcome::Partial }+ );+ assert_eq!(db.calls.iter().any(|step| step == "enable"), known);+ }+}++#[tokio::test]+async fn number_conversion_uses_the_anydata_setter_and_compares_exactly_without_replaying_satisfied_values() {+ for mode in ["write", "satisfied", "rounded"] {+ let (_dir, state, target) = setup().await;+ let mut catalog = Catalog::new();+ catalog.first_type = "NUMBER";+ if mode == "satisfied" {+ catalog.args[0].extend(serde_json::from_value::<NativeJobRow>(json!({"DBX_ANYDATA_PRESENT":1,"DBX_ANYDATA_TYPE":"SYS.NUMBER","DBX_ANYDATA_IS_NULL":0,"DBX_ANYDATA_TEXT":"9.007199254740993123e15","ANYDATA_VALUE":"locator","VALUE":"wrong fallback"})).unwrap());+ }+ let initial = read(&state, &target, &catalog).await;+ let mut request = mutation(&initial, 2);+ let NativeJobChange::Update { argument_target: Some(arguments), .. } = &mut request.change else {+ unreachable!()+ };+ arguments.arguments[0].value = NativeJobArgumentValue::Value {+ value: json!({"$dbx":"oracle-anydata-v1","typeName":"SYS.NUMBER","value":"9007199254740993.123"}),+ };+ let state_ref = state.as_ref();+ let catalog_ref = &catalog;+ let plan = native_job_prepare_with_references(+ &state,+ request,+ |target| async move { Ok(read(state_ref, &target, catalog_ref).await) },+ |request| std::future::ready(Ok(references(&catalog, &request))),+ )+ .await+ .unwrap();+ assert!(plan.steps.iter().find(|step| step.id == "argument:1").unwrap().sql.contains("SET_JOB_ANYDATA_VALUE"));+ let mut db = Session::new(&state, catalog, &plan);+ if mode == "rounded" {+ db.poison = Some("number-rounding");+ }+ let result = native_job_apply_with(&state, &plan.plan_id, &mut db).await.unwrap();+ assert_eq!(+ result.outcome,+ if mode == "rounded" { NativeJobOperationOutcome::Partial } else { NativeJobOperationOutcome::Verified },+ "{mode}: reason={:?}, calls={:?}",+ result.reason,+ db.calls+ );+ assert_eq!(db.calls.iter().any(|step| step == "argument:1"), mode != "satisfied", "{mode}");+ assert_eq!(db.calls.iter().any(|step| step == "enable"), mode != "rounded", "{mode}");+ }+}++#[tokio::test]+async fn a_later_character_validation_failure_or_cancel_never_pauses_or_converts_the_enabled_job() {+ for stop in ["reject-second", "cancel-first", "unknown-first"] {+ let (_dir, state, target) = setup().await;+ let mut catalog = Catalog::new();+ catalog.first_type = "NVARCHAR2";+ let initial = read(&state, &target, &catalog).await;+ let mut request = mutation(&initial, 2);+ let NativeJobChange::Update { argument_target: Some(arguments), .. } = &mut request.change else {+ unreachable!()+ };+ for (index, argument) in arguments.arguments.iter_mut().enumerate() {+ argument.value = NativeJobArgumentValue::Value {+ value: json!({"$dbx":"oracle-anydata-v1","scalarType":if index == 0 { "nvarchar2" } else { "varchar2" },"value":"must be checked before pause"}),+ };+ }+ let state_ref = state.as_ref();+ let catalog_ref = &catalog;+ let plan = native_job_prepare_with_references(+ &state,+ request,+ |target| async move { Ok(read(state_ref, &target, catalog_ref).await) },+ |request| std::future::ready(Ok(references(&catalog, &request))),+ )+ .await+ .unwrap();+ assert_eq!(plan.steps[0].id, "validate-argument:1");+ assert_eq!(plan.steps[1].id, "validate-argument:2");+ let mut db = Session::new(&state, catalog, &plan);+ match stop {+ "reject-second" => db.reject = Some("validate-argument:2"),+ "cancel-first" => db.cancel_after = Some("validate-argument:1"),+ _ => db.unknown = Some("validate-argument:1"),+ }+ let result = native_job_apply_with(&state, &plan.plan_id, &mut db).await.unwrap();+ assert_eq!(result.outcome, NativeJobOperationOutcome::NotApplied, "{stop}");+ assert!(db.calls.iter().all(|step| step.starts_with("validate-argument:")), "{stop}");+ assert_eq!(db.catalog.definition["ENABLED"], json!(true));+ assert_eq!(db.catalog.definition["PROGRAM_NAME"], json!("P1"));+ assert_eq!(db.catalog.args[0]["VALUE"], json!("old"));+ }+}++#[tokio::test]+async fn generated_observations_do_not_become_user_definition_conflicts_at_any_transition_phase() {+ let (_dir, state, target) = setup().await;+ let catalog = Catalog::new();+ let plan = prepare(&state, &target, &catalog).await;+ let mut db = Session::new(&state, catalog, &plan);+ db.catalog.definition.insert("FLAGS".into(), json!(500));+ db.catalog.definition.insert("EVENT_RULE".into(), json!("new-native-rule"));+ db.catalog.definition.insert("NUMBER_OF_DESTINATIONS".into(), json!("7"));+ db.poison = Some("generated");+ let status = native_job_apply_with(&state, &plan.plan_id, &mut db).await.unwrap();+ assert_eq!(status.outcome, NativeJobOperationOutcome::Verified);+ assert!(db.calls.iter().any(|step| step == "argument:1"));+ assert_eq!(db.calls.last().map(String::as_str), Some("enable"));+}++async fn prepare_attributes(+ state: &AppState,+ target: &NativeJobRef,+ catalog: &Catalog,+ attributes: Value,+) -> Result<NativeJobPreparedPlan, &'static str> {+ let initial = read(state, target, catalog).await;+ let mutation = serde_json::from_value(json!({"action":"update","target":target,"baseline":initial.snapshot.revision,"finalEnabled":true,"attributes":attributes,"arguments":[]})).unwrap();+ native_job_prepare_with_references(+ state,+ mutation,+ |target| async move { Ok(read(state, &target, catalog).await) },+ |request| std::future::ready(Ok(references(catalog, &request))),+ )+ .await+}++fn file_watcher(catalog: &mut Catalog) {+ catalog.extra_references.push((NativeJobReferenceKind::FileWatcher, NativeJobMetadata::Available {+ value: vec![serde_json::from_value(json!({"DBX_OWNER":"Owner","DBX_NAME":"Watch.er","ENABLED":true,"DIRECTORY_PATH":"/drop","FILE_NAME":"*.csv"})).unwrap()],+ }));+}++fn event_fields(condition: Value, watcher: bool) -> NativeJobRow {+ serde_json::from_value(json!({"EVENT_CONDITION":condition,"EVENT_QUEUE_OWNER":if watcher { Value::Null } else { json!("Owner") },"EVENT_QUEUE_NAME":if watcher { Value::Null } else { json!("Queue") },"EVENT_QUEUE_AGENT":if watcher { Value::Null } else { json!("Agent") },"FILE_WATCHER_OWNER":if watcher { json!("Owner") } else { Value::Null },"FILE_WATCHER_NAME":if watcher { json!("Watch.er") } else { Value::Null }})).unwrap()+}++#[tokio::test]+async fn destination_count_null_and_integral_representations_are_observations_not_a_formula() {+ for count in [Value::Null, json!(0), json!(3), json!("7")] {+ let (_dir, state, target) = setup().await;+ let mut catalog = Catalog::new();+ catalog.definition.insert("NUMBER_OF_DESTINATIONS".into(), count.clone());+ let plan = prepare(&state, &target, &catalog).await;+ let mut db = Session::new(&state, catalog, &plan);+ db.after_definition.insert("NUMBER_OF_DESTINATIONS".into(), json!(99));+ let status = native_job_apply_with(&state, &plan.plan_id, &mut db).await.unwrap();+ assert_eq!(status.outcome, NativeJobOperationOutcome::Verified, "{count}");+ }+}++#[tokio::test]+async fn missing_negative_and_fractional_destination_observations_never_enable_or_hide_lost_receipts() {+ for (count, unknown) in [(None, false), (Some(json!(-1)), false), (Some(json!(1.5)), false), (None, true)] {+ let (_dir, state, target) = setup().await;+ let catalog = Catalog::new();+ let plan = prepare(&state, &target, &catalog).await;+ let mut db = Session::new(&state, catalog, &plan);+ if let Some(count) = count {+ db.after_definition.insert("NUMBER_OF_DESTINATIONS".into(), count);+ } else {+ db.poison = Some("missing-count");+ }+ if unknown {+ db.unknown = Some("pause");+ }+ let status = native_job_apply_with(&state, &plan.plan_id, &mut db).await.unwrap();+ assert_eq!(+ status.outcome,+ if unknown { NativeJobOperationOutcome::Unknown } else { NativeJobOperationOutcome::Partial }+ );+ assert!(!db.calls.iter().any(|step| step == "enable"));+ }+}++#[tokio::test]+async fn unrelated_and_unknown_definition_columns_remain_strict_during_reference_changes() {+ for field in ["COMMENTS", "NLS_ENV", "FUTURE_NATIVE_COLUMN"] {+ let (_dir, state, target) = setup().await;+ let catalog = Catalog::new();+ let plan = prepare(&state, &target, &catalog).await;+ let mut db = Session::new(&state, catalog, &plan);+ db.after_definition.insert(field.into(), json!("external"));+ let status = native_job_apply_with(&state, &plan.plan_id, &mut db).await.unwrap();+ assert_eq!(status.outcome, NativeJobOperationOutcome::Partial, "{field}");+ assert!(!db.calls.iter().any(|step| step == "enable"));+ }+}++#[tokio::test]+async fn watcher_generated_queues_are_checked_through_definition_arguments_and_final_activation() {+ let (_dir, state, target) = setup().await;+ let mut catalog = Catalog::new();+ file_watcher(&mut catalog);+ let initial = read(&state, &target, &catalog).await;+ let mut change = mutation(&initial, 2);+ if let NativeJobChange::Update { attributes, .. } = &mut change.change {+ attributes.push(serde_json::from_value(json!({"name":"EVENT_SPEC","change":{"kind":"set","value":{"condition":null,"source":{"kind":"file-watcher","reference":{"owner":"Owner","name":"Watch.er"}}}}})).unwrap());+ }+ let state_ref = state.as_ref();+ let catalog_ref = &catalog;+ let plan = native_job_prepare_with_references(+ &state,+ change,+ |target| async move { Ok(read(state_ref, &target, catalog_ref).await) },+ |request| std::future::ready(Ok(references(&catalog, &request))),+ )+ .await+ .unwrap();+ let mut db = Session::new(&state, catalog, &plan);+ db.poison = Some("watcher-queue");+ assert_eq!(+ native_job_apply_with(&state, &plan.plan_id, &mut db).await.unwrap().outcome,+ NativeJobOperationOutcome::Verified+ );+ assert!(db.calls.iter().any(|step| step == "argument:1"));+ assert_eq!(db.calls.last().map(String::as_str), Some("enable"));+ assert!(!db.catalog.definition["EVENT_QUEUE_NAME"].is_null());+ assert!(db.catalog.definition["EVENT_CONDITION"].is_null());+}++#[tokio::test]+async fn queue_and_watcher_conversions_require_exact_raw_condition_and_source_identity() {+ for (watcher_target, corrupt) in+ [(true, None), (false, None), (true, Some("condition")), (true, Some("watcher")), (false, Some("agent"))]+ {+ let (_dir, state, target) = setup().await;+ let mut catalog = Catalog::new();+ catalog.definition.extend(event_fields(json!("old condition"), !watcher_target));+ catalog.definition.insert("SCHEDULE_TYPE".into(), json!("EVENT"));+ catalog.definition.insert("REPEAT_INTERVAL".into(), Value::Null);+ file_watcher(&mut catalog);+ let source = if watcher_target {+ json!({"kind":"file-watcher","reference":{"owner":"Owner","name":"Watch.er"}})+ } else {+ json!({"kind":"queue","owner":"Owner","name":"Queue","agent":"Agent"})+ };+ let plan = prepare_attributes(+ &state,+ &target,+ &catalog,+ json!([{"name":"EVENT_SPEC","change":{"kind":"set","value":{"condition":" x = 1 ","source":source}}}]),+ )+ .await+ .unwrap();+ let mut db = Session::new(&state, catalog, &plan);+ if let Some(corrupt) = corrupt {+ let (column, value) = match corrupt {+ "condition" => ("EVENT_CONDITION", json!("x = 1")),+ "watcher" => ("FILE_WATCHER_NAME", json!("Watch")),+ _ => ("EVENT_QUEUE_AGENT", Value::Null),+ };+ db.after_definition.insert(column.into(), value);+ }+ let status = native_job_apply_with(&state, &plan.plan_id, &mut db).await.unwrap();+ assert_eq!(+ status.outcome,+ if corrupt.is_none() { NativeJobOperationOutcome::Verified } else { NativeJobOperationOutcome::Partial },+ "{watcher_target} {corrupt:?}"+ );+ assert_eq!(db.calls.iter().any(|step| step == "enable"), corrupt.is_none());+ }+}++#[tokio::test]+async fn named_event_schedule_accepts_null_materialization_but_never_a_different_nonnull_condition() {+ for (watcher, wrong, materialized) in+ [(false, false, false), (false, false, true), (false, true, true), (true, false, true), (true, true, true)]+ {+ let (_dir, state, target) = setup().await;+ let mut catalog = Catalog::new();+ let source_fields = event_fields(json!(" x = 1 "), watcher);+ let mut schedule = source_fields.clone();+ schedule.extend(+ serde_json::from_value::<NativeJobRow>(+ json!({"DBX_OWNER":"Owner","DBX_NAME":"Schedule","SCHEDULE_TYPE":"EVENT"}),+ )+ .unwrap(),+ );+ catalog+ .extra_references+ .push((NativeJobReferenceKind::Schedule, NativeJobMetadata::Available { value: vec![schedule] }));+ let plan = prepare_attributes(+ &state,+ &target,+ &catalog,+ json!([{"name":"SCHEDULE_NAME","change":{"kind":"set","value":{"owner":"Owner","name":"Schedule"}}}]),+ )+ .await+ .unwrap();+ let mut db = Session::new(&state, catalog, &plan);+ if materialized {+ db.after_definition = source_fields;+ }+ if watcher {+ db.poison = Some("watcher-queue");+ }+ if wrong {+ db.after_definition.insert("EVENT_CONDITION".into(), json!("x = 1"));+ }+ let status = native_job_apply_with(&state, &plan.plan_id, &mut db).await.unwrap();+ assert_eq!(+ status.outcome,+ if wrong { NativeJobOperationOutcome::Partial } else { NativeJobOperationOutcome::Verified },+ "{watcher} {wrong} {materialized}"+ );+ assert_eq!(db.calls.iter().any(|step| step == "enable"), !wrong);+ }+}++fn destination_group(catalog: &mut Catalog, members: NativeJobMetadata<Vec<NativeJobRow>>) {+ // An inline definition avoids reading an unrelated Program for group compatibility.+ catalog.definition.extend(serde_json::from_value::<NativeJobRow>(json!({"PROGRAM_OWNER":null,"PROGRAM_NAME":null,"JOB_TYPE":"STORED_PROCEDURE","JOB_ACTION":"proc","NUMBER_OF_ARGUMENTS":0})).unwrap());+ catalog.args.clear();+ catalog.extra_references.push((+ NativeJobReferenceKind::DestinationGroup,+ NativeJobMetadata::Available {+ value: vec![+ serde_json::from_value(json!({"DBX_OWNER":"Owner","DBX_NAME":"Group","GROUP_TYPE":"DB_DEST"})).unwrap()+ ],+ },+ ));+ catalog.extra_references.push((NativeJobReferenceKind::DestinationGroupMembers, members));+}++fn members() -> Vec<NativeJobRow> {+ ["[email protected]", "Database.2"]+ .iter()+ .map(|name| serde_json::from_value(json!({"DBX_OWNER":"Owner","DBX_NAME":"Group","MEMBER_NAME":name})).unwrap())+ .collect()+}++fn destination_change() -> Value {+ json!([{"name":"DESTINATION_NAME","change":{"kind":"set","value":{"owner":"Owner","name":"Group","kind":"destination-group"}}}])+}++#[tokio::test]+async fn destination_group_member_order_is_irrelevant_but_same_count_credential_changes_stop_before_definition_or_enable(+) {+ for changed_at in [None, Some(3), Some(5)] {+ let (_dir, state, target) = setup().await;+ let mut catalog = Catalog::new();+ destination_group(&mut catalog, NativeJobMetadata::Available { value: members() });+ let plan = prepare_attributes(&state, &target, &catalog, destination_change()).await.unwrap();+ let mut db = Session::new(&state, catalog, &plan);+ db.reverse_members = true;+ db.member_change_at = changed_at;+ let status = native_job_apply_with(&state, &plan.plan_id, &mut db).await.unwrap();+ assert_eq!(+ status.outcome,+ if changed_at.is_none() { NativeJobOperationOutcome::Verified } else { NativeJobOperationOutcome::Partial }+ );+ assert_eq!(db.calls.iter().any(|step| step == "attributes"), changed_at != Some(3));+ assert_eq!(db.calls.iter().any(|step| step == "enable"), changed_at.is_none());+ }+}++#[tokio::test]+async fn empty_destination_members_are_known_empty_while_denied_truncated_duplicate_and_wrong_identity_block() {+ for case in ["empty", "denied", "truncated", "duplicate", "identity"] {+ let (_dir, state, target) = setup().await;+ let mut catalog = Catalog::new();+ let mut value = members();+ let metadata = match case {+ "empty" => NativeJobMetadata::Empty,+ "denied" => NativeJobMetadata::Denied { reason: "denied".into() },+ "truncated" => NativeJobMetadata::Truncated { value, limit: 1 },+ "duplicate" => {+ value.push(value[0].clone());+ NativeJobMetadata::Available { value }+ }+ _ => {+ value[0].insert("DBX_NAME".into(), json!("AnotherGroup"));+ NativeJobMetadata::Available { value }+ }+ };+ destination_group(&mut catalog, metadata);+ let result = prepare_attributes(&state, &target, &catalog, destination_change()).await;+ if case == "empty" {+ let plan = result.unwrap();+ let mut db = Session::new(&state, catalog, &plan);+ assert_eq!(+ native_job_apply_with(&state, &plan.plan_id, &mut db).await.unwrap().outcome,+ NativeJobOperationOutcome::Verified+ );+ } else {+ assert!(result.is_err(), "{case}");+ }+ }+}++#[tokio::test]+async fn an_unchanged_legacy_host_remains_raw_during_program_conversion_without_destination_reads() {+ let (_dir, state, target) = setup().await;+ let mut catalog = Catalog::new();+ catalog.definition.insert("DESTINATION".into(), json!("host.with.dots:1500"));+ let plan = prepare(&state, &target, &catalog).await;+ let mut db = Session::new(&state, catalog, &plan);+ let status = native_job_apply_with(&state, &plan.plan_id, &mut db).await.unwrap();+ assert_eq!(status.outcome, NativeJobOperationOutcome::Verified);+ assert_eq!(db.catalog.definition["DESTINATION"], json!("host.with.dots:1500"));+ assert!(db.catalog.definition["DESTINATION_OWNER"].is_null());+}++#[tokio::test]+async fn existing_watcher_generated_queues_do_not_invalidate_the_preview_baseline() {+ let (_dir, state, target) = setup().await;+ let mut catalog = Catalog::new();+ catalog.definition.extend(event_fields(Value::Null, true));+ catalog.definition.insert("SCHEDULE_TYPE".into(), json!("EVENT"));+ catalog.definition.insert("REPEAT_INTERVAL".into(), Value::Null);+ let plan = prepare(&state, &target, &catalog).await;+ let mut db = Session::new(&state, catalog, &plan);+ db.catalog.definition.insert("EVENT_QUEUE_OWNER".into(), json!("SYS"));+ db.catalog.definition.insert("EVENT_QUEUE_NAME".into(), json!("NATIVE_REASSIGNED_QUEUE"));+ db.poison = Some("watcher-queue");+ let status = native_job_apply_with(&state, &plan.plan_id, &mut db).await.unwrap();+ assert_eq!(status.outcome, NativeJobOperationOutcome::Verified);+ assert_eq!(db.calls.last().map(String::as_str), Some("enable"));+}++#[tokio::test]+async fn an_independent_schedule_change_does_not_require_unreadable_old_program_arguments() {+ let (_dir, state, target) = setup().await;+ let mut catalog = Catalog::new();+ let mut schedule = event_fields(Value::Null, false);+ for value in schedule.values_mut() {+ *value = Value::Null;+ }+ schedule.extend(+ serde_json::from_value::<NativeJobRow>(+ json!({"DBX_OWNER":"Owner","DBX_NAME":"Schedule","SCHEDULE_TYPE":"CALENDAR"}),+ )+ .unwrap(),+ );+ catalog+ .extra_references+ .push((NativeJobReferenceKind::Schedule, NativeJobMetadata::Available { value: vec![schedule] }));+ let mut initial = read(&state, &target, &catalog).await;+ initial.program = Some(NativeJobMetadata::Denied { reason: "old Program unreadable".into() });+ initial.program_arguments = Some(NativeJobMetadata::Denied { reason: "old arguments unreadable".into() });+ initial.snapshot.arguments = NativeJobMetadata::Unknown { reason: "old arguments unreadable".into() };+ let change = serde_json::from_value(json!({"action":"update","target":target,"baseline":initial.snapshot.revision,"finalEnabled":true,"attributes":[{"name":"SCHEDULE_NAME","change":{"kind":"set","value":{"owner":"Owner","name":"Schedule"}}}],"arguments":[]})).unwrap();+ let plan = native_job_prepare_with_references(+ &state,+ change,+ |_| std::future::ready(Ok(initial.clone())),+ |request| {+ assert_eq!(request.kind, NativeJobReferenceKind::Schedule);+ std::future::ready(Ok(references(&catalog, &request)))+ },+ )+ .await+ .unwrap();+ let mut db = Session::new(&state, catalog, &plan);+ assert_eq!(+ native_job_apply_with(&state, &plan.plan_id, &mut db).await.unwrap().outcome,+ NativeJobOperationOutcome::Verified+ );+ assert_eq!(db.catalog.definition["PROGRAM_NAME"], json!("P1"));+}++#[tokio::test]+async fn missing_named_schedule_event_columns_cannot_masquerade_as_unmaterialized_nulls() {+ let (_dir, state, target) = setup().await;+ let mut catalog = Catalog::new();+ catalog.extra_references.push((+ NativeJobReferenceKind::Schedule,+ NativeJobMetadata::Available {+ value: vec![serde_json::from_value(+ json!({"DBX_OWNER":"Owner","DBX_NAME":"Schedule","SCHEDULE_TYPE":"EVENT","EVENT_CONDITION":null}),+ )+ .unwrap()],+ },+ ));+ let result = prepare_attributes(+ &state,+ &target,+ &catalog,+ json!([{"name":"SCHEDULE_NAME","change":{"kind":"set","value":{"owner":"Owner","name":"Schedule"}}}]),+ )+ .await;+ assert_eq!(result.err(), Some("native_job_event_projection_unavailable"));+}++#[tokio::test]+async fn raw_destination_set_and_clear_preserve_exact_values_without_reference_reads() {+ for enabled in [true, false] {+ for change in [json!({"kind":"set","value":"Host.With.Dots:1501"}), json!({"kind":"clear"})] {+ let (_dir, state, target) = setup().await;+ let mut catalog = Catalog::new();+ catalog.definition.insert("ENABLED".into(), json!(enabled));+ catalog.definition.insert("DESTINATION".into(), json!("old.host:1500"));+ let initial = read(&state, &target, &catalog).await;+ let mutation = serde_json::from_value(json!({"action":"update","target":target,"baseline":initial.snapshot.revision,"attributes":[{"name":"DESTINATION","change":change}],"arguments":[]})).unwrap();+ let plan = native_job_prepare_with_references(+ &state,+ mutation,+ |target| {+ let state = &state;+ let catalog = &catalog;+ async move { Ok(read(state, &target, catalog).await) }+ },+ |_| std::future::ready(Err("unexpected_destination_reference")),+ )+ .await+ .unwrap();+ let mut db = Session::new(&state, catalog, &plan);+ let status = native_job_apply_with(&state, &plan.plan_id, &mut db).await.unwrap();+ assert_eq!(status.outcome, NativeJobOperationOutcome::Verified);+ assert_eq!(db.dependency_reads, 0);+ assert_eq!(db.catalog.definition["DESTINATION_OWNER"], Value::Null);+ assert_eq!(db.catalog.definition["DESTINATION"], change.get("value").cloned().unwrap_or(Value::Null));+ assert_eq!(db.catalog.definition["ENABLED"], json!(enabled));+ assert_eq!(+ db.calls.first().map(String::as_str),+ Some(if enabled { "pause" } else { "attribute:DESTINATION" })+ );+ assert_eq!(db.calls.contains(&"enable".into()), enabled);+ }+ }+}++#[tokio::test]+async fn a_raw_destination_with_the_wrong_owner_or_unexpected_activation_never_reaches_final_enable() {+ for (column, value) in [("DESTINATION_OWNER", json!("UnexpectedOwner")), ("ENABLED", json!(true))] {+ let (_dir, state, target) = setup().await;+ let mut catalog = Catalog::new();+ catalog.definition.insert("DESTINATION".into(), json!("old.host:1500"));+ let plan =+ prepare_attributes(&state, &target, &catalog, json!([{"name":"DESTINATION","change":{"kind":"clear"}}]))+ .await+ .unwrap();+ let mut db = Session::new(&state, catalog, &plan);+ db.after_definition.insert(column.into(), value);+ let status = native_job_apply_with(&state, &plan.plan_id, &mut db).await.unwrap();+ assert_eq!(status.outcome, NativeJobOperationOutcome::Partial);+ assert_eq!(db.calls, ["pause", "attribute:DESTINATION"]);+ assert_eq!(db.dependency_reads, 0);+ }+}diff --git a/crates/dbx-core/tests/native_job_service.rs b/crates/dbx-core/tests/native_job_service.rsnew file mode 100644index 0000000000..c6fcee5e7d--- /dev/null+++ b/crates/dbx-core/tests/native_job_service.rs@@ -0,0 +1,1415 @@+#![recursion_limit = "256"]++use dbx_core::connection::{session_credentials::with_credential_owner, AppState};+use dbx_core::models::connection::{ConnectionConfig, DatabaseConnectionInfo};+use dbx_core::schema::native_jobs::{+ native_job_list_with, native_job_open_context_with, native_job_read_with, native_job_references_with,+ NativeJobCatalogFailure, NativeJobRuntimeIdentity,+};+use dbx_sql::native_jobs::NativeJobCatalogQuery;+use dbx_types::native_jobs::{+ NativeJobArgumentValue, NativeJobCatalogCoverage, NativeJobContext, NativeJobEngine, NativeJobKind,+ NativeJobListRequest, NativeJobMetadata, NativeJobRef, NativeJobReferenceKind, NativeJobReferenceListRequest,+};+use serde_json::{json, Value};++async fn state(db_type: &str) -> (tempfile::TempDir, AppState) {+ let directory = tempfile::tempdir().unwrap();+ let storage = dbx_core::persistence::test_storage::open(&directory.path().join("state.db")).await.unwrap();+ let state = AppState::new_with_plugin_and_agent_dir_and_app_version(+ storage,+ directory.path().join("plugins"),+ directory.path().join("agents"),+ "0.0.0",+ );+ let config: ConnectionConfig = serde_json::from_value(json!({+ "id": "connection", "name": "Job fixture", "db_type": db_type, "host": "127.0.0.1", "port": 1,+ "username": "Owner", "password": "", "database": ""+ }))+ .unwrap();+ state.configs.write().await.insert("connection".into(), config);+ (directory, state)+}++fn identity() -> NativeJobRuntimeIdentity {+ NativeJobRuntimeIdentity {+ database_info: Some(DatabaseConnectionInfo {+ product_name: Some("Oracle".into()),+ current_database: Some("PDB".into()),+ ..Default::default()+ }),+ session_user: "Owner".into(),+ }+}++async fn context(state: &AppState) -> NativeJobContext {+ native_job_open_context_with(state, "connection", "", |_| std::future::ready(Ok(identity()))).await.unwrap()+}++fn target(context: &NativeJobContext) -> NativeJobRef {+ NativeJobRef::Scheduler { scope: context.scope.clone(), owner: "Owner".into(), name: "Job".into() }+}++fn result(columns: &[&str], rows: Value) -> Value {+ json!({ "columns": columns, "rows": rows, "affected_rows": 0, "execution_time_ms": 1 })+}++#[tokio::test]+async fn dm_legacy_definition_preserves_the_native_partition_and_exact_id() {+ let (_directory, state) = state("dameng").await;+ let target = NativeJobRef::Legacy { scope: context(&state).await.scope, job_id: "900719925474099312345".into() };+ let mut first_revision: Option<String> = None;+ for mode in ["available", "next-date-shift", "changed-body", "denied", "empty", "wrong-id"] {+ let details = native_job_read_with(&state, &target, |query| {+ std::future::ready(if query.source == "SYSJOB.DBA_JOBS" || query.source == "SYSJOB.USER_JOBS" {+ match mode {+ "denied" => Err(NativeJobCatalogFailure::Denied(None)),+ "empty" => Ok(result(&["DBX_JOB_ID", "WHAT"], json!([]))),+ _ => Ok(result(+ &["DBX_JOB_ID", "WHAT", "NEXT_DATE", "INTERVAL", "INSTANCE"],+ json!([[+ if mode == "wrong-id" { "41" } else { "900719925474099312345" },+ if mode == "changed-body" {+ "external_change();"+ } else {+ "begin\n work('多字节');\nend; "+ },+ if mode == "next-date-shift" { "another native date" } else { "native unparsed date" },+ "86400",+ 2+ ]]),+ )),+ }+ } else if query.sql.contains("DBX_CREATED_AT") {+ Ok(result(&["DBX_JOB_ID", "DBX_CREATED_AT"], json!([["900719925474099312345", "created"]])))+ } else if query.source == "SYSJOB.SYSJOBS" {+ Ok(result(+ &["DBX_JOB_ID", "ID", "NAME", "USERNAME", "ENABLE", "SYS_FLAG"],+ json!([["900719925474099312345", "900719925474099312345", "Legacy Native Name", "Owner", 0, 2]]),+ ))+ } else {+ Ok(result(&["JOBID"], json!([])))+ })+ })+ .await+ .unwrap();+ assert!(+ matches!(&details.snapshot.definition, NativeJobMetadata::Available { value } if value["NAME"] == json!("Legacy Native Name") && !value.contains_key("WHAT"))+ );+ assert!(matches!(details.consistency, NativeJobMetadata::Available { .. }));+ let legacy = details.legacy_definition.as_ref().unwrap();+ match mode {+ "available" => {+ assert!(+ matches!(legacy, NativeJobMetadata::Available { value } if value["WHAT"] == json!("begin\n work('多字节');\nend; ") && value["NEXT_DATE"] == json!("native unparsed date") && value["INTERVAL"] == json!("86400") && value["INSTANCE"] == json!(2))+ );+ assert_eq!(details.sources["legacyDefinition"].source.as_deref(), Some("SYSJOB.DBA_JOBS"));+ }+ "next-date-shift" | "changed-body" => assert!(matches!(legacy, NativeJobMetadata::Available { .. })),+ "denied" => assert!(matches!(legacy, NativeJobMetadata::Denied { .. })),+ "empty" => assert!(matches!(legacy, NativeJobMetadata::Empty)),+ _ => assert!(+ matches!(legacy, NativeJobMetadata::Error { reason } if reason == "native_job_catalog_identity_mismatch")+ ),+ }+ if let Some(previous) = &first_revision {+ assert_eq!(+ state.native_jobs.compare_baseline(+ &state,+ &target,+ previous,+ &details.snapshot.revision,+ &["definition"],+ false+ ),+ Ok(())+ );+ assert_eq!(+ state.native_jobs.compare_baseline(+ &state,+ &target,+ previous,+ &details.snapshot.revision,+ &["legacyDefinition"],+ false+ ),+ match mode {+ "next-date-shift" => Ok(()),+ "changed-body" => Err("native_job_definition_changed"),+ _ => Err("native_job_metadata_incomplete"),+ }+ );+ } else {+ first_revision = Some(details.snapshot.revision.clone());+ }+ }+}++fn reference_request(context: &NativeJobContext) -> NativeJobReferenceListRequest {+ NativeJobReferenceListRequest {+ scope: context.scope.clone(),+ kind: NativeJobReferenceKind::Program,+ schema: None,+ name: None,+ filter: String::new(),+ offset: 0,+ limit: 100,+ }+}++#[tokio::test]+async fn program_reference_defaults_use_the_shared_lossless_codec_and_preserve_raw_columns() {+ let (_directory, state) = state("oracle").await;+ let ctx = context(&state).await;+ let mut request = reference_request(&ctx);+ request.kind = NativeJobReferenceKind::ProgramArguments;+ request.schema = Some("Owner".into());+ request.name = Some("Program".into());+ let read = native_job_references_with(&state, &request, |_| {+ std::future::ready(Ok(result(+ &[+ "DBX_OWNER",+ "DBX_NAME",+ "ARGUMENT_POSITION",+ "ARGUMENT_TYPE",+ "DEFAULT_VALUE",+ "DEFAULT_ANYDATA_VALUE",+ "DBX_ANYDATA_PRESENT",+ "DBX_ANYDATA_TYPE",+ "DBX_ANYDATA_IS_NULL",+ "DBX_ANYDATA_TEXT",+ ],+ json!([+ [+ "Owner",+ "Program",+ 1,+ "NUMBER",+ "wrong text",+ "locator 1",+ 1,+ "SYS.NUMBER",+ 0,+ "9007199254740993.123"+ ],+ ["Owner", "Program", 2, "VARCHAR2", "wrong text", "locator 2", 1, "SYS.CHAR", 1, null],+ ["Owner", "Program", 3, "OBJECT", "wrong text", "locator 3", 1, "APP.OBJECT", 0, null]+ ]),+ )))+ })+ .await+ .unwrap();+ let NativeJobMetadata::Available { value } = read.objects else { panic!("catalog required") };+ assert_eq!(value[0]["DEFAULT_VALUE"], "wrong text");+ assert_eq!(value[0]["DEFAULT_ANYDATA_VALUE"], "locator 1");+ assert_eq!(+ value[0]["DBX_ARGUMENT_DEFAULT"],+ json!({"status":"available","value":{"kind":"value","value":{"$dbx":"oracle-anydata-v1","typeName":"SYS.NUMBER","value":"9.007199254740993123E15"}}})+ );+ assert_eq!(+ value[1]["DBX_ARGUMENT_DEFAULT"],+ json!({"status":"available","value":{"kind":"value","value":{"$dbx":"oracle-anydata-v1","scalarType":"char","value":null}}})+ );+ assert_eq!(value[2]["DBX_ARGUMENT_DEFAULT"]["value"]["kind"], "opaque");+}++#[tokio::test]+async fn references_share_the_authenticated_context_and_reject_scope_changes_before_query() {+ let (_directory, state) = state("oracle").await;+ let ctx = context(&state).await;+ let mut request = reference_request(&ctx);+ let mut calls = 0;+ request.scope.database = "another database".into();+ let read = native_job_references_with(&state, &request, |_| {+ calls += 1;+ std::future::ready(Err(NativeJobCatalogFailure::Transport))+ })+ .await;+ assert!(matches!(read, Err("native_job_context_expired")));+ assert_eq!(calls, 0);+ request.scope = ctx.scope;+ let read = with_credential_owner(+ Some("another-authenticated-owner".into()),+ native_job_references_with(&state, &request, |_| {+ calls += 1;+ std::future::ready(Err(NativeJobCatalogFailure::Transport))+ }),+ )+ .await;+ assert!(matches!(read, Err("native_job_context_expired")));+ assert_eq!(calls, 0);+}++#[tokio::test]+async fn references_only_fall_back_after_typed_catalog_failures_and_keep_source_coverage() {+ let (_directory, state) = state("oracle").await;+ let ctx = context(&state).await;+ let request = reference_request(&ctx);+ let mut calls = Vec::new();+ let read = native_job_references_with(&state, &request, |query| {+ calls.push(query.source);+ std::future::ready(if query.source == "SYS.DBA_SCHEDULER_PROGRAMS" {+ Err(NativeJobCatalogFailure::Denied(Some(1031)))+ } else {+ Ok(result(&["DBX_OWNER", "DBX_NAME", "ENABLED"], json!([["Owner.One", "Exact,\"Program", "TRUE"]])))+ })+ })+ .await+ .unwrap();+ assert_eq!(calls, ["SYS.DBA_SCHEDULER_PROGRAMS", "SYS.ALL_SCHEDULER_PROGRAMS"]);+ assert_eq!(read.source.coverage, Some(NativeJobCatalogCoverage::Accessible));+ let NativeJobMetadata::Available { value } = read.objects else { panic!("catalog unavailable") };+ assert_eq!(value[0]["DBX_NAME"], "Exact,\"Program");+ for failure in [None, Some(NativeJobCatalogFailure::Query(Some(6550)))] {+ let mut calls = 0;+ let read = native_job_references_with(&state, &request, |_| {+ calls += 1;+ std::future::ready(match &failure {+ Some(error) => Err(error.clone()),+ None => Ok(result(&["DBX_OWNER", "DBX_NAME"], json!([]))),+ })+ })+ .await+ .unwrap();+ assert_eq!(calls, 1);+ assert!(match failure {+ None => matches!(read.objects, NativeJobMetadata::Empty),+ Some(_) => matches!(read.objects, NativeJobMetadata::Error { .. }),+ });+ }+}++#[tokio::test]+async fn reference_identity_faults_do_not_fall_back_and_program_argument_positions_are_unique() {+ let (_directory, state) = state("oracle").await;+ let ctx = context(&state).await;+ let mut request = reference_request(&ctx);+ request.schema = Some("Owner".into());+ request.name = Some("Program".into());+ for (columns, rows) in [+ (vec!["DBX_OWNER", "DBX_NAME"], json!([["Another", "Program"]])),+ (vec!["DBX_OWNER", "DBX_NAME"], json!([["Owner", "Program"], ["Owner", "Program"]])),+ ] {+ let mut calls = 0;+ let read = native_job_references_with(&state, &request, |_| {+ calls += 1;+ std::future::ready(Ok(result(&columns, rows.clone())))+ })+ .await+ .unwrap();+ assert_eq!(calls, 1);+ assert!(matches!(read.objects, NativeJobMetadata::Error { .. }));+ }+ request.kind = NativeJobReferenceKind::ProgramArguments;+ let read = native_job_references_with(&state, &request, |_| {+ std::future::ready(Ok(result(+ &["DBX_OWNER", "DBX_NAME", "ARGUMENT_POSITION", "DEFAULT_VALUE"],+ json!([["Owner", "Program", 1, "keep default"], ["Owner", "Program", 2, null]]),+ )))+ })+ .await+ .unwrap();+ assert!(matches!(read.objects, NativeJobMetadata::Available { value } if value.len() == 2));+}++#[tokio::test]+async fn reference_group_categories_reject_a_wrong_or_missing_native_type_without_fallback() {+ let (_directory, state) = state("oracle").await;+ let ctx = context(&state).await;+ for (kind, accepted, rejected) in [+ (NativeJobReferenceKind::WindowGroup, vec!["WINDOW"], vec!["JOB", "DB_DEST", "EXTERNAL_DEST", ""]),+ (NativeJobReferenceKind::DestinationGroup, vec!["DB_DEST", "EXTERNAL_DEST"], vec!["WINDOW", "JOB", ""]),+ ] {+ let mut request = reference_request(&ctx);+ request.kind = kind;+ for group_type in accepted.iter().chain(&rejected) {+ let mut calls = 0;+ let read = native_job_references_with(&state, &request, |_| {+ calls += 1;+ std::future::ready(Ok(result(+ &["DBX_OWNER", "DBX_NAME", "GROUP_TYPE"],+ json!([["SYS", "Exact.Group,One", group_type]]),+ )))+ })+ .await+ .unwrap();+ assert_eq!(calls, 1);+ assert_eq!(matches!(read.objects, NativeJobMetadata::Available { .. }), accepted.contains(group_type));+ }+ let read = native_job_references_with(&state, &request, |_| {+ std::future::ready(Ok(result(&["DBX_OWNER", "DBX_NAME"], json!([["SYS", "Group"]]))))+ })+ .await+ .unwrap();+ assert!(matches!(read.objects, NativeJobMetadata::Error { .. }));+ }+}++#[tokio::test]+async fn destination_group_inventory_keeps_raw_credentials_and_distinguishes_empty_invalid_and_truncated() {+ let (_directory, state) = state("oracle").await;+ let ctx = context(&state).await;+ let mut request = reference_request(&ctx);+ request.kind = NativeJobReferenceKind::DestinationGroupMembers;+ request.schema = Some("Owner".into());+ request.name = Some("Group".into());+ let columns = ["DBX_OWNER", "DBX_NAME", "MEMBER_NAME"];+ for (rows, available) in [+ (json!([["Owner", "Group", "[email protected]"], ["Owner", "Group", "Database.2"]]), true),+ (json!([["Owner", "Group", "Database.1"], ["Owner", "Group", "Database.1"]]), false),+ (json!([["Owner", "OtherGroup", "Database.1"]]), false),+ (json!([["Owner", "Group", null]]), false),+ (json!([["Owner", "Group", ""]]), false),+ ] {+ let mut reads = 0;+ let catalog = native_job_references_with(&state, &request, |_| {+ reads += 1;+ std::future::ready(Ok(result(&columns, rows.clone())))+ })+ .await+ .unwrap();+ assert_eq!(reads, 1);+ if available {+ let NativeJobMetadata::Available { value } = catalog.objects else { panic!("missing exact members") };+ assert_eq!(value[0]["MEMBER_NAME"], json!("[email protected]"));+ } else {+ assert!(matches!(catalog.objects, NativeJobMetadata::Error { .. }));+ }+ }+ let empty = native_job_references_with(&state, &request, |_| std::future::ready(Ok(result(&columns, json!([])))))+ .await+ .unwrap();+ assert!(matches!(empty.objects, NativeJobMetadata::Empty));+ request.limit = 1;+ let truncated = native_job_references_with(&state, &request, |_| {+ std::future::ready(Ok(result(&columns, json!([["Owner", "Group", "One"], ["Owner", "Group", "Two"]]))))+ })+ .await+ .unwrap();+ assert!(matches!(truncated.objects, NativeJobMetadata::Truncated { limit: 1, .. }));+}++#[tokio::test]+async fn another_owners_destination_members_cannot_become_empty_through_a_user_only_fallback() {+ let (_directory, state) = state("oracle").await;+ let ctx = context(&state).await;+ for owner in ["OtherOwner", "Owner"] {+ let mut request = reference_request(&ctx);+ request.kind = NativeJobReferenceKind::DestinationGroupMembers;+ request.schema = Some(owner.into());+ request.name = Some("Group".into());+ let mut reads = Vec::new();+ let catalog = native_job_references_with(&state, &request, |query| {+ reads.push(query.source);+ std::future::ready(if query.coverage == NativeJobCatalogCoverage::CurrentUser {+ Ok(result(&["DBX_OWNER", "DBX_NAME", "MEMBER_NAME"], json!([])))+ } else {+ Err(NativeJobCatalogFailure::Denied(Some(1031)))+ })+ })+ .await+ .unwrap();+ if owner == "Owner" {+ assert!(matches!(catalog.objects, NativeJobMetadata::Empty));+ assert_eq!(reads.len(), 3);+ } else {+ assert!(matches!(catalog.objects, NativeJobMetadata::Denied { .. }));+ assert_eq!(reads.len(), 2);+ }+ }+}++#[tokio::test]+async fn only_oracle_scheduler_baselines_classify_the_three_native_generated_observations() {+ for db_type in ["oracle", "oceanbase-oracle", "dameng"] {+ let (_directory, state) = state(db_type).await;+ let job = target(&context(&state).await);+ let read = |version| {+ native_job_read_with(&state, &job, move |query| {+ std::future::ready(Ok(if query.sql.contains("AS DBX_JOB_ID") {+ result(&["DBX_JOB_ID", "DBX_CREATED_AT"], json!([["41", "created"]]))+ } else if query.source.ends_with("SCHEDULER_JOBS") {+ result(+ &["OWNER", "JOB_NAME", "NUMBER_OF_ARGUMENTS", "FLAGS", "EVENT_RULE", "NUMBER_OF_DESTINATIONS"],+ json!([["Owner", "Job", 0, version, format!("native-rule-{version}"), version]]),+ )+ } else {+ result(&["JOB_NAME"], json!([]))+ }))+ })+ };+ let before = read(0).await.unwrap();+ let after = read(1).await.unwrap();+ assert!(+ matches!(&after.snapshot.definition, NativeJobMetadata::Available { value } if value["FLAGS"] == json!(1)),+ "raw observation lost for {db_type}"+ );+ let compared = state.native_jobs.compare_baseline(+ &state,+ &job,+ &before.snapshot.revision,+ &after.snapshot.revision,+ &["definition"],+ false,+ );+ assert_eq!(compared.is_ok(), db_type == "oracle", "{db_type}: {compared:?}");+ }+}++#[tokio::test]+async fn watcher_queue_observations_do_not_mask_queue_jobs_or_changed_watcher_identity_and_condition() {+ let (_directory, state) = state("oracle").await;+ let job = target(&context(&state).await);+ for (watcher, changed) in [(true, "queue"), (false, "queue"), (true, "watcher"), (true, "condition")] {+ let read = |after| {+ native_job_read_with(&state, &job, move |query| {+ std::future::ready(Ok(if query.sql.contains("AS DBX_JOB_ID") {+ result(&["DBX_JOB_ID", "DBX_CREATED_AT"], json!([["41", "created"]]))+ } else if query.source.ends_with("SCHEDULER_JOBS") {+ result(+ &[+ "OWNER",+ "JOB_NAME",+ "NUMBER_OF_ARGUMENTS",+ "FILE_WATCHER_OWNER",+ "FILE_WATCHER_NAME",+ "EVENT_CONDITION",+ "EVENT_QUEUE_OWNER",+ "EVENT_QUEUE_NAME",+ "EVENT_QUEUE_AGENT",+ ],+ json!([[+ "Owner",+ "Job",+ 0,+ if watcher { json!("Owner") } else { Value::Null },+ if watcher {+ json!(if after && changed == "watcher" { "OtherWatcher" } else { "Watcher" })+ } else {+ Value::Null+ },+ if after && changed == "condition" { json!("TRUE") } else { Value::Null },+ "SYS",+ if after { "NewQueue" } else { "OldQueue" },+ "Agent"+ ]]),+ )+ } else {+ result(&["JOB_NAME"], json!([]))+ }))+ })+ };+ let before = read(false).await.unwrap();+ let after = read(true).await.unwrap();+ let compared = state.native_jobs.compare_baseline(+ &state,+ &job,+ &before.snapshot.revision,+ &after.snapshot.revision,+ &["definition"],+ false,+ );+ assert_eq!(compared.is_ok(), watcher && changed == "queue", "{watcher} {changed}: {compared:?}");+ }+}++#[tokio::test]+async fn references_preserve_paging_and_a_context_invalidated_during_read_cannot_return_choices() {+ let (_directory, state) = state("oracle").await;+ let ctx = context(&state).await;+ let mut request = reference_request(&ctx);+ request.limit = 1;+ request.offset = 100;+ let read = native_job_references_with(&state, &request, |_| {+ std::future::ready(Ok(result(+ &["DBX_OWNER", "DBX_NAME"],+ json!([["Owner", "Program1"], ["Owner", "Program2"]]),+ )))+ })+ .await+ .unwrap();+ assert_eq!(read.offset, 100);+ assert_eq!(read.limit, 1);+ assert!(matches!(read.objects, NativeJobMetadata::Truncated { value, limit: 1 } if value.len() == 1));+ let read = native_job_references_with(&state, &request, |_| {+ state.invalidate_connection_lifecycle("connection");+ std::future::ready(Ok(result(&["DBX_OWNER", "DBX_NAME"], json!([["Owner", "Program"]]))))+ })+ .await;+ assert!(matches!(read, Err("native_job_context_changed") | Err("native_job_context_expired")));+}++fn fixture(+ query: NativeJobCatalogQuery,+ id: &str,+ body: &str,+ runs: i32,+ opaque: &str,+) -> Result<Value, NativeJobCatalogFailure> {+ if query.source.ends_with("_OBJECTS") {+ return Ok(result(&["DBX_JOB_ID", "DBX_CREATED_AT"], json!([[id, "2026-10-20 20:00:00"]])));+ }+ if query.source.ends_with("SCHEDULER_JOBS") {+ return Ok(result(+ &[+ "OWNER",+ "JOB_NAME",+ "JOB_TYPE",+ "JOB_ACTION",+ "NUMBER_OF_ARGUMENTS",+ "STATE",+ "RUN_COUNT",+ "NEXT_RUN_DATE",+ "PROGRAM_NAME",+ ],+ json!([["Owner", "Job", "STORED_PROCEDURE", body, 2, "SCHEDULED", runs, format!("next-{runs}"), null]]),+ ));+ }+ if query.source.ends_with("JOB_ARGS") {+ return Ok(result(+ &[+ "OWNER",+ "JOB_NAME",+ "ARGUMENT_POSITION",+ "ARGUMENT_TYPE",+ "VALUE",+ "OUT_ARGUMENT",+ "ANYDATA_VALUE",+ "DBX_ANYDATA_PRESENT",+ ],+ json!([+ ["Owner", "Job", 1, "VARCHAR2", "known", "FALSE", null, 0],+ ["Owner", "Job", 2, "OBJECT", null, "FALSE", opaque, 1]+ ]),+ ));+ }+ if query.source.ends_with("RUNNING_JOBS") {+ return Err(NativeJobCatalogFailure::sql(+ dbx_sql::native_jobs::NativeJobCatalogDialect::Oracle,+ Some(942),+ None,+ ));+ }+ if query.source.ends_with("JOB_RUN_DETAILS") {+ return Ok(result(&["OWNER", "JOB_NAME", "LOG_ID"], json!([])));+ }+ panic!("unexpected catalog source")+}++#[tokio::test]+async fn context_is_reused_only_for_the_same_lifecycle_and_authentication_owner() {+ let (_directory, state) = state("oracle").await;+ let first = context(&state).await;+ let second = context(&state).await;+ assert_eq!(first.scope, second.scope);+ let another = with_credential_owner(Some("other-authenticated-session".into()), context(&state)).await;+ assert_ne!(first.scope.context_id, another.scope.context_id);+ let denied = with_credential_owner(+ Some("other-authenticated-session".into()),+ native_job_read_with(&state, &target(&first), |_| {+ std::future::ready::<Result<Value, NativeJobCatalogFailure>>(Err(NativeJobCatalogFailure::Transport))+ }),+ )+ .await;+ assert!(matches!(denied, Err("native_job_context_expired")));+ state.invalidate_connection_lifecycle("connection");+ let third = context(&state).await;+ assert_ne!(first.scope.context_id, third.scope.context_id);+}++#[tokio::test]+async fn a_configuration_change_during_identity_read_cannot_issue_a_context() {+ let (_directory, state) = state("oracle").await;+ let opened = native_job_open_context_with(&state, "connection", "", |_| {+ state.invalidate_connection_lifecycle("connection");+ std::future::ready(Ok(identity()))+ })+ .await;+ assert!(matches!(opened, Err("native_job_context_changed")));+}++#[tokio::test]+async fn runtime_engine_discovery_does_not_assume_oceanbase_means_oracle_mode() {+ let (_directory, state) = state("jdbc").await;+ state.configs.write().await.get_mut("connection").unwrap().database_info = Some(DatabaseConnectionInfo {+ product_name: Some("OceanBase".into()),+ compatibility_mode: Some("oracle".into()),+ ..Default::default()+ });+ let oracle = native_job_open_context_with(&state, "connection", "", |_| {+ std::future::ready(Ok(NativeJobRuntimeIdentity {+ database_info: Some(DatabaseConnectionInfo {+ product_name: Some("OceanBase".into()),+ compatibility_mode: Some("oracle".into()),+ ..Default::default()+ }),+ session_user: "Owner".into(),+ }))+ })+ .await+ .unwrap();+ assert_eq!(oracle.engine, NativeJobEngine::OceanbaseOracle);+ for mode in [None, Some("mysql")] {+ let opened = native_job_open_context_with(&state, "connection", "", |_| {+ std::future::ready(Ok(NativeJobRuntimeIdentity {+ database_info: Some(DatabaseConnectionInfo {+ product_name: Some("OceanBase".into()),+ compatibility_mode: mode.map(str::to_string),+ ..Default::default()+ }),+ session_user: "Owner".into(),+ }))+ })+ .await;+ assert!(matches!(opened, Err("native_job_engine_unresolved")));+ }+}++#[tokio::test]+async fn dm_list_uses_one_native_record_for_a_proven_legacy_alias_and_never_fakes_running() {+ let (_directory, state) = state("dameng").await;+ let ctx = native_job_open_context_with(&state, "connection", "", |_| {+ std::future::ready(Ok(NativeJobRuntimeIdentity { database_info: None, session_user: "Owner".into() }))+ })+ .await+ .unwrap();+ let request = NativeJobListRequest {+ scope: ctx.scope,+ kind: NativeJobKind::DamengNative,+ schema: None,+ filter: "".into(),+ offset: 0,+ limit: 100,+ };+ let list = native_job_list_with(&state, &request, |query| {+ assert!(!query.sql.contains("COMMAND"));+ assert!(!query.sql.contains("RUNNING"));+ std::future::ready(Ok(result(+ &["DBX_JOB_ID", "NAME", "ENABLE", "USERNAME", "SYS_FLAG"],+ json!([["9007199254740993", "exact,name", 1, "Owner", 2]]),+ )))+ })+ .await+ .unwrap();+ let NativeJobMetadata::Available { value } = list.jobs else { panic!("list unavailable") };+ assert_eq!(value.len(), 1);+ assert!(matches!(&value[0].job_ref, NativeJobRef::Legacy { job_id, .. } if job_id == "9007199254740993"));+ assert!(matches!(&value[0].aliases[0], NativeJobRef::DamengNative { name, .. } if name == "exact,name"));+ assert!(value[0].state.is_none());+}++#[tokio::test]+async fn list_scope_tampering_is_rejected_before_any_database_query() {+ let (_directory, state) = state("oracle").await;+ let mut ctx = context(&state).await;+ ctx.scope.database = "another database".into();+ let request = NativeJobListRequest {+ scope: ctx.scope,+ kind: NativeJobKind::Scheduler,+ schema: None,+ filter: "".into(),+ offset: 0,+ limit: 100,+ };+ let mut calls = 0;+ let list = native_job_list_with(&state, &request, |_| {+ calls += 1;+ std::future::ready(Err(NativeJobCatalogFailure::Transport))+ })+ .await;+ assert!(matches!(list, Err("native_job_context_expired")));+ assert_eq!(calls, 0);+}++#[tokio::test]+async fn details_preserve_opaque_arguments_and_keep_unavailable_runtime_separate() {+ let (_directory, state) = state("oracle").await;+ let ctx = context(&state).await;+ let job = target(&ctx);+ let details = native_job_read_with(&state, &job, |query| {+ std::future::ready(fixture(query, "41", "first", 0, "opaque-object"))+ })+ .await+ .unwrap();+ assert!(!details.snapshot.revision.is_empty());+ assert!(matches!(details.consistency, NativeJobMetadata::Available { .. }));+ assert!(matches!(details.running, NativeJobMetadata::Unknown { .. }));+ assert!(matches!(details.history, NativeJobMetadata::Empty));+ let NativeJobMetadata::Available { value } = &details.snapshot.arguments else { panic!("arguments unavailable") };+ assert!(matches!(&value[0].value, NativeJobArgumentValue::Value { value } if value == "known"));+ assert!(matches!(value[1].value, NativeJobArgumentValue::Opaque { .. }));+ assert!(!value[1].editable);+}++#[tokio::test]+async fn truncated_argument_metadata_remains_raw_and_does_not_panic_or_authorize_an_empty_snapshot() {+ let (_directory, state) = state("oracle").await;+ let job = target(&context(&state).await);+ let read = native_job_read_with(&state, &job, |query| {+ std::future::ready(if query.source.ends_with("SCHEDULER_JOB_ARGS") {+ Ok(result(+ &["OWNER", "JOB_NAME", "ARGUMENT_POSITION"],+ Value::Array((1..=10_001).map(|position| json!(["Owner", "Job", position])).collect()),+ ))+ } else {+ fixture(query, "41", "body", 0, "opaque")+ })+ })+ .await+ .unwrap();+ assert!(matches!(read.parameter_metadata, NativeJobMetadata::Truncated { limit: 10_000, .. }));+ assert!(+ matches!(&read.snapshot.arguments, NativeJobMetadata::Unknown { reason } if reason == "native_job_arguments_truncated")+ );+ assert!(matches!(read.snapshot.definition, NativeJobMetadata::Available { .. }));+}++fn program_fixture(query: NativeJobCatalogQuery, default: &str) -> Result<Value, NativeJobCatalogFailure> {+ if query.source.ends_with("SCHEDULER_PROGRAMS") {+ return Ok(result(+ &["DBX_OWNER", "DBX_NAME", "NUMBER_OF_ARGUMENTS", "PROGRAM_ACTION"],+ json!([["Program.Owner", "Program,One", 3, "original_procedure"]]),+ ));+ }+ if query.source.ends_with("SCHEDULER_PROGRAM_ARGS") {+ return Ok(result(+ &[+ "DBX_OWNER",+ "DBX_NAME",+ "ARGUMENT_POSITION",+ "ARGUMENT_NAME",+ "ARGUMENT_TYPE",+ "DEFAULT_VALUE",+ "DEFAULT_ANYDATA_VALUE",+ "DBX_ANYDATA_PRESENT",+ "METADATA_ATTRIBUTE",+ "OUT_ARGUMENT",+ ],+ json!([+ ["Program.Owner", "Program,One", 1, "TEXT", "VARCHAR2", default, null, 0, null, "FALSE"],+ ["Program.Owner", "Program,One", 2, "OPTIONAL", "VARCHAR2", null, null, 0, null, "FALSE"],+ ["Program.Owner", "Program,One", 3, "NATIVE_NAME", "VARCHAR2", null, null, 0, "JOB_NAME", "FALSE"]+ ]),+ ));+ }+ if query.source.ends_with("SCHEDULER_JOBS") {+ return Ok(result(+ &[+ "OWNER",+ "JOB_NAME",+ "PROGRAM_OWNER",+ "PROGRAM_NAME",+ "JOB_TYPE",+ "JOB_ACTION",+ "NUMBER_OF_ARGUMENTS",+ "COMMENTS",+ ],+ json!([["Owner", "Job", "Program.Owner", "Program,One", null, null, null, "keep"]]),+ ));+ }+ if query.source.ends_with("SCHEDULER_JOB_ARGS") {+ return Ok(result(+ &[+ "OWNER",+ "JOB_NAME",+ "ARGUMENT_POSITION",+ "ARGUMENT_NAME",+ "ARGUMENT_TYPE",+ "VALUE",+ "OUT_ARGUMENT",+ "DBX_ANYDATA_PRESENT",+ ],+ json!([["Owner", "Job", 1, "TEXT", "VARCHAR2", "explicit override", "FALSE", 0]]),+ ));+ }+ fixture(query, "41", "unused", 0, "unused")+}++#[tokio::test]+async fn ordinary_argument_preview_cannot_follow_an_external_program_switch_with_identical_arguments() {+ use dbx_core::schema::native_jobs::{+ native_job_apply_with, native_job_prepare_with, NativeJobDispatchOutcome, NativeJobMutationSession,+ NativeJobStepReceipt,+ };+ use dbx_types::native_jobs::{+ NativeJobArgumentChange, NativeJobChange, NativeJobDetails, NativeJobMutation, NativeJobOperationOutcome,+ };+ async fn read_program(state: &AppState, target: &NativeJobRef, program: &str) -> NativeJobDetails {+ native_job_read_with(state, target, |query| {+ std::future::ready(program_fixture(query, "same default").map(|mut value| {+ for row in value["rows"].as_array_mut().unwrap() {+ for cell in row.as_array_mut().unwrap() {+ if cell == "Program,One" {+ *cell = json!(program);+ }+ }+ }+ value+ }))+ })+ .await+ .unwrap()+ }+ struct Session<'a> {+ state: &'a AppState,+ calls: usize,+ }+ #[async_trait::async_trait]+ impl NativeJobMutationSession for Session<'_> {+ async fn read(&mut self, target: &NativeJobRef) -> Result<NativeJobDetails, &'static str> {+ Ok(read_program(self.state, target, "Program,Two").await)+ }+ async fn execute(&mut self, _: &dbx_sql::native_job_changes::NativeJobSqlStep) -> NativeJobStepReceipt {+ self.calls += 1;+ NativeJobStepReceipt { outcome: NativeJobDispatchOutcome::Applied, reason: None, vendor_code: None }+ }+ async fn finish(&mut self) -> Result<(), &'static str> {+ Ok(())+ }+ }+ let (_directory, state) = state("oracle").await;+ let job = target(&context(&state).await);+ let initial = read_program(&state, &job, "Program,One").await;+ let plan = native_job_prepare_with(+ &state,+ NativeJobMutation {+ target: job.clone(),+ baseline: initial.snapshot.revision,+ change: NativeJobChange::Update {+ final_enabled: None,+ argument_target: None,+ attributes: vec![],+ arguments: vec![NativeJobArgumentChange {+ position: 1,+ value: NativeJobArgumentValue::Value { value: json!("new override for A") },+ }],+ },+ },+ |target| {+ let state = &state;+ async move { Ok(read_program(state, &target, "Program,One").await) }+ },+ )+ .await+ .unwrap();+ let mut session = Session { state: &state, calls: 0 };+ let status = native_job_apply_with(&state, &plan.plan_id, &mut session).await.unwrap();+ assert_eq!(session.calls, 0);+ assert_eq!(status.outcome, NativeJobOperationOutcome::NotApplied);+ assert_eq!(status.reason.as_deref(), Some("native_job_definition_changed"));+}++#[tokio::test]+async fn anydata_number_baselines_ignore_only_decoded_locator_and_decimal_spelling_changes() {+ let (_directory, state) = state("oracle").await;+ let job = target(&context(&state).await);+ let mut reads = Vec::new();+ for (number, locator) in [+ ("9007199254740993.1200", "locator-1"),+ ("9.00719925474099312e15", "locator-2"),+ ("9007199254740993.121", "locator-2"),+ ] {+ let read = native_job_read_with(&state, &job, |query| {+ std::future::ready(if query.source.ends_with("SCHEDULER_JOB_ARGS") {+ Ok(result(+ &[+ "OWNER",+ "JOB_NAME",+ "ARGUMENT_POSITION",+ "ARGUMENT_TYPE",+ "VALUE",+ "ANYDATA_VALUE",+ "DBX_ANYDATA_PRESENT",+ "DBX_ANYDATA_TYPE",+ "DBX_ANYDATA_IS_NULL",+ "DBX_ANYDATA_TEXT",+ ],+ json!([["Owner", "Job", 1, "NUMBER", "misleading fallback", locator, 1, "SYS.NUMBER", 0, number]]),+ ))+ } else {+ fixture(query, "41", "body", 0, "unused")+ })+ })+ .await+ .unwrap();+ let NativeJobMetadata::Available { value } = &read.snapshot.arguments else { panic!("arguments required") };+ assert!(value[0].editable);+ assert!(+ matches!(&value[0].value, NativeJobArgumentValue::Value { value } if value["typeName"] == "SYS.NUMBER")+ );+ reads.push(read);+ }+ for partition in ["argument:1", "arguments", "argument-inventory"] {+ assert!(+ state+ .native_jobs+ .compare_baseline(+ &state,+ &job,+ &reads[0].snapshot.revision,+ &reads[1].snapshot.revision,+ &[partition],+ false+ )+ .is_ok(),+ "{partition}"+ );+ assert_eq!(+ state.native_jobs.compare_baseline(+ &state,+ &job,+ &reads[0].snapshot.revision,+ &reads[2].snapshot.revision,+ &[partition],+ false+ ),+ Err("native_job_definition_changed"),+ "{partition}"+ );+ }+}++#[tokio::test]+async fn anydata_presence_type_and_null_evidence_control_editability_and_null_baselines() {+ let (_directory, state) = state("oracle").await;+ let job = target(&context(&state).await);+ let mut revisions = Vec::new();+ for (type_name, is_null, editable) in [+ ("SYS.NUMBER", json!(1), true),+ ("SYS.DATE", json!(1), true),+ ("APP.OBJECT", json!(0), false),+ ("SYS.NUMBER", Value::Null, false),+ ] {+ let read = native_job_read_with(&state, &job, |query| {+ std::future::ready(if query.source.ends_with("SCHEDULER_JOB_ARGS") {+ Ok(result(+ &[+ "OWNER",+ "JOB_NAME",+ "ARGUMENT_POSITION",+ "ARGUMENT_TYPE",+ "VALUE",+ "ANYDATA_VALUE",+ "DBX_ANYDATA_PRESENT",+ "DBX_ANYDATA_TYPE",+ "DBX_ANYDATA_IS_NULL",+ ],+ json!([["Owner", "Job", 1, "NUMBER", "not a fallback", "locator", 1, type_name, is_null]]),+ ))+ } else {+ fixture(query, "41", "body", 0, "unused")+ })+ })+ .await+ .unwrap();+ let NativeJobMetadata::Available { value } = &read.snapshot.arguments else { panic!("arguments required") };+ assert_eq!(value[0].editable, editable);+ if editable {+ let scalar_type = if type_name == "SYS.NUMBER" { "number" } else { "date" };+ assert!(+ value[0].value+ == NativeJobArgumentValue::Value {+ value: json!({"$dbx":"oracle-anydata-v1","scalarType":scalar_type,"value":null})+ }+ );+ } else {+ assert!(matches!(value[0].value, NativeJobArgumentValue::Opaque { .. }));+ }+ revisions.push(read.snapshot.revision);+ }+ assert_eq!(+ state.native_jobs.compare_baseline(&state, &job, &revisions[0], &revisions[1], &["argument:1"], false),+ Err("native_job_definition_changed")+ );+}++#[tokio::test]+async fn civil_display_auxiliary_fields_do_not_change_the_argument_storage_baseline() {+ let (_directory, state) = state("oracle").await;+ let job = target(&context(&state).await);+ let mut revisions = Vec::new();+ for civil in [Value::Null, json!("-0001-12-31")] {+ let read = native_job_read_with(&state, &job, |query| {+ std::future::ready(if query.source.ends_with("SCHEDULER_JOB_ARGS") {+ Ok(result(+ &[+ "OWNER",+ "JOB_NAME",+ "ARGUMENT_POSITION",+ "ARGUMENT_TYPE",+ "VALUE",+ "ANYDATA_VALUE",+ "DBX_ANYDATA_PRESENT",+ "DBX_ANYDATA_TYPE",+ "DBX_ANYDATA_IS_NULL",+ "DBX_ANYDATA_DAY",+ "DBX_ANYDATA_SECONDS",+ "DBX_ANYDATA_CIVIL_DATE",+ ],+ json!([[+ "Owner",+ "Job",+ 1,+ "TIMESTAMP",+ null,+ "locator",+ 1,+ "SYS.TIMESTAMP",+ 0,+ "1234567",+ "1.123456789",+ civil+ ]]),+ ))+ } else {+ fixture(query, "41", "body", 0, "unused")+ })+ })+ .await+ .unwrap();+ revisions.push(read.snapshot.revision);+ }+ assert_eq!(+ state.native_jobs.compare_baseline(+ &state,+ &job,+ &revisions[0],+ &revisions[1],+ &["argument:1", "arguments", "argument-inventory"],+ false+ ),+ Ok(())+ );+}++#[tokio::test]+async fn referenced_program_counts_defaults_overrides_and_metadata_arguments_are_not_inline_columns() {+ let (_directory, state) = state("oracle").await;+ let job = target(&context(&state).await);+ let read = native_job_read_with(&state, &job, |query| {+ if query.source.ends_with("SCHEDULER_PROGRAMS") || query.source.ends_with("SCHEDULER_PROGRAM_ARGS") {+ assert!(query.sql.contains("J.OWNER = 'Program.Owner'"));+ assert!(query.sql.contains("J.PROGRAM_NAME = 'Program,One'"));+ }+ std::future::ready(program_fixture(query, "default one"))+ })+ .await+ .unwrap();+ assert!(+ matches!(&read.program, Some(NativeJobMetadata::Available { value }) if value["PROGRAM_ACTION"] == "original_procedure")+ );+ let NativeJobMetadata::Available { value: args } = &read.snapshot.arguments else {+ panic!("program arguments unavailable")+ };+ assert_eq!(args.len(), 3);+ assert!(matches!(&args[0].value, NativeJobArgumentValue::Value { value } if value == "explicit override"));+ assert!(+ matches!(&args[0].default_value, Some(NativeJobMetadata::Available { value: NativeJobArgumentValue::Value { value } }) if value == "default one")+ );+ assert!(matches!(args[1].value, NativeJobArgumentValue::Inherit));+ assert!(args[1].editable);+ assert!(matches!(&args[1].default_value, Some(NativeJobMetadata::Unknown { .. })));+ assert_eq!(args[2].metadata_attribute.as_deref(), Some("JOB_NAME"));+ assert!(!args[2].editable);+ assert_eq!(read.sources["program"].source.as_deref(), Some("SYS.DBA_SCHEDULER_PROGRAMS"));+}++#[tokio::test]+async fn changed_program_defaults_invalidate_only_the_argument_baseline_they_affect() {+ let (_directory, state) = state("oracle").await;+ let job = target(&context(&state).await);+ let before =+ native_job_read_with(&state, &job, |query| std::future::ready(program_fixture(query, "before"))).await.unwrap();+ let after =+ native_job_read_with(&state, &job, |query| std::future::ready(program_fixture(query, "after"))).await.unwrap();+ assert!(state+ .native_jobs+ .compare_baseline(&state, &job, &before.snapshot.revision, &after.snapshot.revision, &["definition"], false)+ .is_ok());+ assert!(matches!(+ state.native_jobs.compare_baseline(+ &state,+ &job,+ &before.snapshot.revision,+ &after.snapshot.revision,+ &["argument:1"],+ false+ ),+ Err("native_job_definition_changed")+ ));+}++#[tokio::test]+async fn unreadable_program_metadata_keeps_the_job_definition_readable_without_inventing_zero_arguments() {+ let (_directory, state) = state("oracle").await;+ let job = target(&context(&state).await);+ let read = native_job_read_with(&state, &job, |query| {+ std::future::ready(if query.source.contains("SCHEDULER_PROGRAM") {+ Err(NativeJobCatalogFailure::Denied(Some(1031)))+ } else {+ program_fixture(query, "unused")+ })+ })+ .await+ .unwrap();+ assert!(matches!(read.snapshot.definition, NativeJobMetadata::Available { .. }));+ assert!(matches!(read.program, Some(NativeJobMetadata::Denied { .. })));+ assert!(matches!(read.snapshot.arguments, NativeJobMetadata::Unknown { .. }));+ assert!(state+ .native_jobs+ .compare_baseline(&state, &job, &read.snapshot.revision, &read.snapshot.revision, &["definition"], false)+ .is_ok());+}++#[tokio::test]+async fn oceanbase_placeholder_views_cannot_turn_a_program_with_real_arguments_into_an_empty_snapshot() {+ let (_directory, state) = state("oceanbase-oracle").await;+ let ctx = context(&state).await;+ let job = target(&ctx);+ let read = native_job_read_with(&state, &job, |query| {+ assert!(!query.source.ends_with("_ARGS"), "placeholder view must not be treated as actual parameters");+ std::future::ready(if query.source == "SYS.DBA_SCHEDULER_PROGRAM" {+ Ok(result(&["DBX_OWNER", "DBX_NAME", "NUMBER_OF_ARGUMENTS"], json!([["Program.Owner", "Program,One", 3]])))+ } else if query.source == "SYS.ALL_VIRTUAL_TENANT_SCHEDULER_JOB_REAL_AGENT" {+ Ok(result(&["DBX_JOB_ID", "DBX_CREATED_AT"], json!([["41", "created"]])))+ } else {+ program_fixture(query, "unused")+ })+ })+ .await+ .unwrap();+ assert!(matches!(&read.program,Some(NativeJobMetadata::Available { value }) if value["NUMBER_OF_ARGUMENTS"]==3));+ assert!(matches!(read.parameter_metadata, NativeJobMetadata::Unsupported { .. }));+ assert!(matches!(read.program_arguments, Some(NativeJobMetadata::Unsupported { .. })));+ assert!(matches!(read.snapshot.arguments, NativeJobMetadata::Unsupported { .. }));+}++#[tokio::test]+async fn oceanbase_reads_effective_failure_limits_without_changing_generation_identity() {+ let (_directory, state) = state("oceanbase-oracle").await;+ let job = target(&context(&state).await);+ let read = |limit| {+ native_job_read_with(&state, &job, move |query| {+ std::future::ready(Ok(if query.source == "SYS.ALL_VIRTUAL_TENANT_SCHEDULER_JOB_REAL_AGENT" {+ if query.sql.contains("MAX_FAILURES") {+ result(+ &["DBX_JOB_ID", "DBX_CREATED_AT", "DBX_OWNER", "JOB_NAME", "MAX_FAILURES"],+ json!([["41", "created", "Owner", "Job", limit]]),+ )+ } else {+ result(&["DBX_JOB_ID", "DBX_CREATED_AT"], json!([["41", "created"]]))+ }+ } else if query.source.ends_with("SCHEDULER_JOBS") {+ result(+ &["OWNER", "JOB_NAME", "MAX_FAILURES", "MAX_RUN_DURATION", "NUMBER_OF_ARGUMENTS"],+ json!([["Owner", "Job", null, "+000 00:02:00", 0]]),+ )+ } else {+ result(&["JOB_NAME"], json!([]))+ }))+ })+ };+ let before = read(2).await.unwrap();+ let after = read(3).await.unwrap();+ assert!(matches!(&before.snapshot.definition, NativeJobMetadata::Available { value } if value["MAX_FAILURES"]==2));+ assert!(matches!(&after.snapshot.definition, NativeJobMetadata::Available { value } if value["MAX_FAILURES"]==3));+ assert!(+ matches!(&before.native_identity, NativeJobMetadata::Available { value } if !value.contains_key("MAX_FAILURES"))+ );+ assert!(state+ .native_jobs+ .compare_baseline(&state, &job, &before.snapshot.revision, &after.snapshot.revision, &[], false)+ .is_ok());+ assert!(matches!(+ state.native_jobs.compare_baseline(+ &state,+ &job,+ &before.snapshot.revision,+ &after.snapshot.revision,+ &["definition"],+ false+ ),+ Err("native_job_definition_changed")+ ));+}++#[tokio::test]+async fn unavailable_or_wrong_identity_native_limits_do_not_become_null_or_hide_other_fields() {+ let (_directory, state) = state("oceanbase-oracle").await;+ let job = target(&context(&state).await);+ for denied in [false, true] {+ let read = native_job_read_with(&state, &job, |query| {+ std::future::ready(if query.source == "SYS.ALL_VIRTUAL_TENANT_SCHEDULER_JOB_REAL_AGENT" {+ if query.sql.contains("MAX_FAILURES") {+ if denied {+ Err(NativeJobCatalogFailure::Denied(Some(1031)))+ } else {+ Ok(result(+ &["DBX_JOB_ID", "DBX_CREATED_AT", "DBX_OWNER", "JOB_NAME", "MAX_FAILURES"],+ json!([["42", "replaced", "Owner", "Job", 2]]),+ ))+ }+ } else {+ Ok(result(&["DBX_JOB_ID", "DBX_CREATED_AT"], json!([["41", "created"]])))+ }+ } else if query.source.ends_with("SCHEDULER_JOBS") {+ Ok(result(+ &["OWNER", "JOB_NAME", "MAX_FAILURES", "MAX_RUN_DURATION", "NUMBER_OF_ARGUMENTS"],+ json!([["Owner", "Job", null, "+000 00:02:00", 0]]),+ ))+ } else {+ Ok(result(&["JOB_NAME"], json!([])))+ })+ })+ .await+ .unwrap();+ assert!(+ matches!(&read.snapshot.definition, NativeJobMetadata::Available { value } if !value.contains_key("MAX_FAILURES") && value["MAX_RUN_DURATION"]=="+000 00:02:00")+ );+ assert!(state+ .native_jobs+ .compare_baseline(&state, &job, &read.snapshot.revision, &read.snapshot.revision, &["definition"], false)+ .is_ok());+ }+}++#[tokio::test]+async fn baselines_ignore_natural_runtime_progress_but_detect_changed_definitions_and_replacements() {+ let (_directory, state) = state("oracle").await;+ let job = target(&context(&state).await);+ let a =+ native_job_read_with(&state, &job, |query| std::future::ready(fixture(query, "41", "first", 0, "opaque-a")))+ .await+ .unwrap();+ let b =+ native_job_read_with(&state, &job, |query| std::future::ready(fixture(query, "41", "first", 1, "opaque-b")))+ .await+ .unwrap();+ assert!(state+ .native_jobs+ .compare_baseline(+ &state,+ &job,+ &a.snapshot.revision,+ &b.snapshot.revision,+ &["definition", "argument:1"],+ false+ )+ .is_ok());+ assert!(matches!(+ state.native_jobs.compare_baseline(+ &state,+ &job,+ &a.snapshot.revision,+ &b.snapshot.revision,+ &["argument:2"],+ false+ ),+ Err("native_job_metadata_incomplete")+ ));+ let c = native_job_read_with(&state, &job, |query| {+ std::future::ready(fixture(query, "41", "changed body", 1, "opaque-b"))+ })+ .await+ .unwrap();+ assert!(matches!(+ state.native_jobs.compare_baseline(+ &state,+ &job,+ &b.snapshot.revision,+ &c.snapshot.revision,+ &["definition"],+ false+ ),+ Err("native_job_definition_changed")+ ));+ let replaced = native_job_read_with(&state, &job, |query| {+ std::future::ready(fixture(query, "42", "changed body", 1, "opaque-b"))+ })+ .await+ .unwrap();+ assert!(matches!(+ state.native_jobs.compare_baseline(&state, &job, &c.snapshot.revision, &replaced.snapshot.revision, &[], false),+ Err("native_job_replaced")+ ));+}++#[tokio::test]+async fn stable_temporal_text_keeps_definition_baselines_but_changed_dates_are_rejected() {+ let (_directory, state) = state("oracle").await;+ let job = target(&context(&state).await);+ let mut previous = None;+ for date in [+ "2032-01-01 23:54:25.123456789 +5:30",+ "2032-01-01 23:54:25.123456789 +5:30",+ "2032-01-01 23:54:25.123456788 +5:30",+ ] {+ let details = native_job_read_with(&state, &job, |query| {+ let definition = query.source.ends_with("SCHEDULER_JOBS");+ let value = fixture(query, "41", "same body", 0, "opaque").map(|mut value| {+ if definition {+ value["columns"].as_array_mut().unwrap().push(json!("START_DATE"));+ value["rows"][0].as_array_mut().unwrap().push(json!(date));+ }+ value+ });+ std::future::ready(value)+ })+ .await+ .unwrap();+ if let Some(previous) = previous.as_deref() {+ assert_eq!(+ state.native_jobs.compare_baseline(+ &state,+ &job,+ previous,+ &details.snapshot.revision,+ &["definition"],+ false+ ),+ if date.ends_with("789 +5:30") { Ok(()) } else { Err("native_job_definition_changed") }+ );+ }+ previous = Some(details.snapshot.revision.clone());+ }+}++#[tokio::test]+async fn replacement_during_details_read_keeps_the_readable_data_but_cannot_authorize_a_write() {+ let (_directory, state) = state("oracle").await;+ let job = target(&context(&state).await);+ let mut generations = 0;+ let read = native_job_read_with(&state, &job, |query| {+ if query.source.ends_with("_OBJECTS") {+ generations += 1;+ }+ std::future::ready(fixture(query, if generations > 1 { "42" } else { "41" }, "readable", 0, "opaque"))+ })+ .await+ .unwrap();+ assert!(+ matches!(&read.consistency, NativeJobMetadata::Error { reason } if reason == "native_job_replaced_during_read")+ );+ assert!(+ matches!(&read.snapshot.definition, NativeJobMetadata::Available { value } if value["JOB_ACTION"] == "readable")+ );+ assert!(matches!(+ state.native_jobs.compare_baseline(&state, &job, &read.snapshot.revision, &read.snapshot.revision, &[], false),+ Err("native_job_identity_unverified")+ ));+}++#[tokio::test]+async fn invalidation_cancels_an_inflight_read_without_recording_a_late_baseline() {+ let (_directory, state) = state("oracle").await;+ let job = target(&context(&state).await);+ let (entered, mut started) = tokio::sync::oneshot::channel();+ let mut entered = Some(entered);+ let mut read = Box::pin(native_job_read_with(&state, &job, |_| {+ entered.take().unwrap().send(()).unwrap();+ std::future::pending::<Result<Value, NativeJobCatalogFailure>>()+ }));+ tokio::select! { result = &mut read => { assert!(result.is_err()); panic!("read ended before invalidation"); }, _ = &mut started => {} }+ state.invalidate_connection_lifecycle("connection");+ assert!(matches!(read.await, Err("native_job_context_changed")));+}diff --git a/crates/dbx-driver-agent/assets/agent-protocol-v2.json b/crates/dbx-driver-agent/assets/agent-protocol-v2.jsonindex 3b472f8a5b..1528b78844 100644--- a/crates/dbx-driver-agent/assets/agent-protocol-v2.json+++ b/crates/dbx-driver-agent/assets/agent-protocol-v2.json@@ -2,9 +2,52 @@"protocolVersion": 2,"handshakeMethod": "handshake","handshakeResponseFields": ["protocolVersion", "agentProtocolVersion", "capabilities"],- "allCapabilities": ["connect", "test_connection", "metadata", "query", "paged_query", "transaction", "ddl", "kv", "kv_ttl", "kv_cas", "kv_list_values", "kv_status", "kv_history", "etcd_compaction", "etcd_defrag", "etcd_watch", "etcd_lease", "etcd_auth", "mongo_drop_database", "mongo_clone_collection", "mongo_run_command", "mongo_insert_documents", "mongo_replace_document", "mongo_bulk_write", "mongo_rename_collection", "mongo_find_cursor", "exact_metadata_identity_v1", "multi_session", "structured_error_v1", "blob_bind_statements_v1"],+ "allCapabilities": ["connect", "test_connection", "metadata", "query", "paged_query", "transaction", "ddl", "kv", "kv_ttl", "kv_cas", "kv_list_values", "kv_status", "kv_history", "etcd_compaction", "etcd_defrag", "etcd_watch", "etcd_lease", "etcd_auth", "mongo_drop_database", "mongo_clone_collection", "mongo_run_command", "mongo_insert_documents", "mongo_replace_document", "mongo_bulk_write", "mongo_rename_collection", "mongo_find_cursor", "native_job_legacy_v1", "native_job_session_v1", "exact_metadata_identity_v1", "multi_session", "structured_error_v1", "blob_bind_statements_v1", "native_job_legacy_ob_v1"],"capabilities": ["connect", "test_connection", "metadata", "query", "paged_query", "transaction", "ddl", "multi_session"],"defaultSqlCapabilities": ["connect", "test_connection", "metadata", "query", "paged_query", "transaction", "ddl", "multi_session", "structured_error_v1"],+ "nativeJobLegacyMethods": ["prepare_legacy_job", "commit_legacy_job", "rollback_legacy_job", "legacy_job_status"],+ "nativeJobSessionMethods": ["open_native_job_session", "close_native_job_session"],+ "nativeJobSessionV1": {+ "capability": "native_job_session_v1",+ "calledDuring": "confirmed Core apply on an operation-owned metadata logical session",+ "openFields": ["operationId"],+ "queryFields": ["nativeJobOperationId", "nativeJobSessionToken"],+ "queryMethods": ["execute_query", "connection_info"],+ "closeFields": ["operationId", "sessionToken?"],+ "resultFields": ["operationId", "sessionToken", "phase", "reason?", "vendorCode?"],+ "phases": ["not_started", "opened", "closed", "unknown"],+ "ownership": "independent non-pooled physical connection; autoCommit false; existing runtime physical budget and watchdogs apply",+ "guardRule": "same operation and opaque lease token required before every query; no editor transaction, cursor, reconnect, connection replacement or configuration change",+ "lostOpenRule": "the exact operationId may close only its owned connection without knowing the lost token; a replacement logical session cannot confirm old ownership",+ "cleanupRule": "close physical connection once; cache confirmed or unknown disposal; never commit, CONFIG_COMMIT, enable or return unfinished configuration to a pool",+ "configurationRule": "Core owns native SQL, configuration phases and dispatch deduplication; connection close does not prove native configuration rollback or completion"+ },+ "nativeJobLegacyV1": {+ "capability": "native_job_legacy_v1",+ "calledDuring": "confirmed Core apply only; never during SQL preview",+ "prepareFields": ["operationId", "what", "nextDate", "interval", "enabled", "instance", "schema", "timeoutSecs"],+ "finishFields": ["operationId", "jobId"],+ "resultFields": ["operationId", "jobId", "phase", "reason", "vendorCode"],+ "phases": ["not_started", "submitting", "configuring", "prepared", "commit_sent", "committed", "rolled_back", "unknown"],+ "prepareRule": "one owned physical transaction; SUBMIT returns an exact OUT ID, BROKEN sets the final state with explicit nextDate, then same-session readback; no commit",+ "commitRule": "Core records the returned ID before commit; the exact operationId and jobId must match; repeated requests return existing facts without dispatch",+ "rollbackRule": "operationId identifies this operation's owned transaction; jobId may be absent only for rollback after a lost prepare response; commit still requires the exact returned ID",+ "unknownRule": "lost commit response stays unknown; read the exact ID, never replay SUBMIT, commit or BROKEN",+ "cleanupRule": "before commit, confirm rollback or report unknown; discard the physical connection, never activate during cleanup",+ "scope": "native Oracle DBMS_JOB; independent of the editor transaction; nextDate is YYYY-MM-DD HH:mm:ss"+ },+ "nativeJobLegacyObV1": {+ "capability": "native_job_legacy_ob_v1",+ "calledDuring": "confirmed Core apply on its own metadata session; control dispatch precedes pool checkout and reconnect",+ "prepareFields": ["operationId", "dialect", "what", "nextDate", "interval", "enabled", "instance", "zone", "schema", "timeoutSecs"],+ "dialect": "oceanbase-oracle",+ "zoneRule": "zone is a nullable string, instance must be zero; native INSTANCE readback remains VARCHAR2 or SQL NULL",+ "prepareRule": "owned physical transaction; local BINARY_INTEGER to VARCHAR OUT; BROKEN and complete initial readback before first commit",+ "finishRule": "reuse nativeJobLegacyV1 operation/ID binding and no-replay rules; the Oracle legacy capability and requests remain unchanged",+ "resultFields": ["operationId", "jobId?", "phase", "reason?", "vendorCode?", "disposalConfirmed?"],+ "disposalRule": "terminal receipt or same-operation status must explicitly confirm original physical disposal; false is permanent, prepared is not disposed; logical close_session ok does not confirm it",+ "lostTerminalRule": "query original status only; never send another commit or rollback after a terminal dispatch"+ },"commonMethods": ["handshake","connect",diff --git a/crates/dbx-driver-agent/src/agent_driver.rs b/crates/dbx-driver-agent/src/agent_driver.rsindex 8c237cd78d..6685680f53 100644--- a/crates/dbx-driver-agent/src/agent_driver.rs+++ b/crates/dbx-driver-agent/src/agent_driver.rs@@ -1067,6 +1067,9 @@ pub enum AgentCapability {MongoBulkWrite,MongoRenameCollection,MongoFindCursor,+ NativeJobLegacyV1,+ NativeJobSessionV1,+ NativeJobLegacyObV1,MultiSession,StructuredErrorV1,}@@ -1149,7 +1152,7 @@ fn parse_agent_rpc_error_header(header: &str) -> (Option<i64>, String) {}impl AgentCapability {- pub const ALL: [Self; 30] = [+ pub const ALL: [Self; 33] = [Self::Connect,Self::TestConnection,Self::Metadata,@@ -1176,16 +1179,22 @@ impl AgentCapability {Self::MongoBulkWrite,Self::MongoRenameCollection,Self::MongoFindCursor,+ Self::NativeJobLegacyV1,+ Self::NativeJobSessionV1,Self::ExactMetadataIdentityV1,Self::MultiSession,Self::StructuredErrorV1,Self::BlobBindStatementsV1,+ Self::NativeJobLegacyObV1,];pub fn as_str(self) -> &'static str {match self {Self::ExactMetadataIdentityV1 => "exact_metadata_identity_v1",Self::BlobBindStatementsV1 => "blob_bind_statements_v1",+ Self::NativeJobLegacyV1 => "native_job_legacy_v1",+ Self::NativeJobSessionV1 => "native_job_session_v1",+ Self::NativeJobLegacyObV1 => "native_job_legacy_ob_v1",Self::Connect => "connect",Self::TestConnection => "test_connection",Self::Metadata => "metadata",@@ -2319,6 +2328,30 @@ impl AgentDriverClient {offset: Option<usize>,object_types: Option<&[String]>,timeout_duration: Option<Duration>,+ ) -> Result<T, String> {+ self.list_objects_with_options(+ database,+ schema,+ filter,+ limit,+ offset,+ object_types,+ &Default::default(),+ timeout_duration,+ )+ .await+ }++ pub async fn list_objects_with_options<T: DeserializeOwned + Send + 'static>(+ &mut self,+ database: &str,+ schema: &str,+ filter: Option<&str>,+ limit: Option<usize>,+ offset: Option<usize>,+ object_types: Option<&[String]>,+ options: &dbx_types::oracle_trigger::MetadataReadOptions,+ timeout_duration: Option<Duration>,) -> Result<T, String> {let mut params = agent_schema_params(database, schema);if let Some(filter) = filter.map(str::trim).filter(|filter| !filter.is_empty()) {@@ -2334,6 +2367,7 @@ impl AgentDriverClient {params["object_types"] = serde_json::json!(object_types);params["objectTypes"] = serde_json::json!(object_types);}+ options.apply_to(&mut params);self.call_method_with_timeout(AgentMethod::ListObjects, params, timeout_duration).await}@@ -2417,7 +2451,7 @@ impl AgentDriverClient {.await}- pub async fn get_object_source_with_origin<T: DeserializeOwned + Send + 'static, K: Serialize>(+ pub async fn get_object_source_with_options<T: DeserializeOwned + Send + 'static, K: Serialize>(&mut self,database: &str,schema: &str,@@ -2425,14 +2459,43 @@ impl AgentDriverClient {object_type: &K,signature: Option<&str>,relation_name: Option<&str>,+ options: &dbx_types::oracle_trigger::MetadataReadOptions,+ include_source_origin: bool,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);+ options.apply_to(&mut params);+ if include_source_origin {+ params["include_source_origin"] = serde_json::json!(true);+ }self.call_method_with_timeout(AgentMethod::GetObjectSource, params, timeout_duration).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> {+ self.get_object_source_with_options(+ database,+ schema,+ name,+ object_type,+ signature,+ relation_name,+ &dbx_types::oracle_trigger::MetadataReadOptions::default(),+ true,+ timeout_duration,+ )+ .await+ }+pub async fn get_columns<T: DeserializeOwned + Send + 'static>(&mut self,database: &str,@@ -2527,12 +2590,20 @@ impl AgentDriverClient {table: &str,timeout_duration: Option<Duration>,) -> Result<T, String> {- self.call_method_with_timeout(- AgentMethod::ListTriggers,- agent_schema_table_params(database, schema, table),- timeout_duration,- )- .await+ self.list_triggers_with_options(database, schema, table, &Default::default(), timeout_duration).await+ }++ pub async fn list_triggers_with_options<T: DeserializeOwned + Send + 'static>(+ &mut self,+ database: &str,+ schema: &str,+ table: &str,+ options: &dbx_types::oracle_trigger::MetadataReadOptions,+ timeout_duration: Option<Duration>,+ ) -> Result<T, String> {+ let mut params = agent_schema_table_params(database, schema, table);+ options.apply_to(&mut params);+ self.call_method_with_timeout(AgentMethod::ListTriggers, params, timeout_duration).await}pub async fn list_constraints<T: DeserializeOwned + Send + 'static>(@@ -6055,8 +6126,11 @@ for line in sys.stdin:assert_eq!(AgentCapability::MultiSession.as_str(), "multi_session");assert_eq!(AgentCapability::StructuredErrorV1.as_str(), "structured_error_v1");assert_eq!(AgentCapability::BlobBindStatementsV1.as_str(), "blob_bind_statements_v1");+ assert_eq!(AgentCapability::NativeJobLegacyV1.as_str(), "native_job_legacy_v1");+ assert_eq!(AgentCapability::NativeJobSessionV1.as_str(), "native_job_session_v1");+ assert_eq!(AgentCapability::NativeJobLegacyObV1.as_str(), "native_job_legacy_ob_v1");assert_eq!(AgentCapability::ExactMetadataIdentityV1.as_str(), "exact_metadata_identity_v1");- assert_eq!(AgentCapability::ALL.len(), 30);+ assert_eq!(AgentCapability::ALL.len(), 33);}#[test]diff --git a/crates/dbx-driver-mysql/src/mysql.rs b/crates/dbx-driver-mysql/src/mysql.rsindex cb945951d8..0c2dda60bf 100644--- a/crates/dbx-driver-mysql/src/mysql.rs+++ b/crates/dbx-driver-mysql/src/mysql.rs@@ -7364,6 +7364,7 @@ pub async fn list_triggers(pool: &MySqlPool, database: &str, table: &str) -> Resvalid: None,comment: None,created_at: None,+ oracle_metadata: None,statement: Some(get_str_by_name(row, "ACTION_STATEMENT")).filter(|value| !value.is_empty()),}).collect())diff --git a/crates/dbx-driver-mysql/src/ob_oracle.rs b/crates/dbx-driver-mysql/src/ob_oracle.rsindex c330ceac6e..258188bb08 100644--- a/crates/dbx-driver-mysql/src/ob_oracle.rs+++ b/crates/dbx-driver-mysql/src/ob_oracle.rs@@ -364,6 +364,7 @@ pub async fn list_triggers(pool: &mysql_async::Pool, schema: &str, table: &str)valid: None,comment: None,created_at: None,+ oracle_metadata: None,statement: None,}})diff --git a/crates/dbx-driver-postgres/src/postgres.rs b/crates/dbx-driver-postgres/src/postgres.rsindex 365bf33697..a6bb23ac12 100644--- a/crates/dbx-driver-postgres/src/postgres.rs+++ b/crates/dbx-driver-postgres/src/postgres.rs@@ -10378,6 +10378,7 @@ pub async fn list_triggers(pool: &Pool, schema: &str, table: &str) -> Result<Vecvalid: None,comment: None,created_at: None,+ oracle_metadata: None,statement: None,}).collect())diff --git a/crates/dbx-driver-sqlserver/src/sqlserver.rs b/crates/dbx-driver-sqlserver/src/sqlserver.rsindex 5f56c15f6e..1c4d965b5c 100644--- a/crates/dbx-driver-sqlserver/src/sqlserver.rs+++ b/crates/dbx-driver-sqlserver/src/sqlserver.rs@@ -3583,6 +3583,7 @@ pub async fn list_triggers(valid: None,comment: None,created_at: None,+ oracle_metadata: None,statement: row.get::<&str, _>(3).map(str::to_string),}).collect())diff --git a/crates/dbx-drivers/src/db/cloudflare_d1/mod.rs b/crates/dbx-drivers/src/db/cloudflare_d1/mod.rsindex 375092ae41..eb43471bff 100644--- a/crates/dbx-drivers/src/db/cloudflare_d1/mod.rs+++ b/crates/dbx-drivers/src/db/cloudflare_d1/mod.rs@@ -372,6 +372,7 @@ pub async fn list_triggers(valid: None,comment: None,created_at: None,+ oracle_metadata: None,statement,}})@@ -415,6 +416,7 @@ pub async fn object_source(source,editable: None,routine_parameters: None,+ trigger: None,})}diff --git a/crates/dbx-drivers/src/db/rqlite_driver.rs b/crates/dbx-drivers/src/db/rqlite_driver.rsindex fe70c70fb5..def2ace5e2 100644--- a/crates/dbx-drivers/src/db/rqlite_driver.rs+++ b/crates/dbx-drivers/src/db/rqlite_driver.rs@@ -254,6 +254,7 @@ pub async fn list_triggers(client: &RqliteClient, _schema: &str, table: &str) ->valid: None,comment: None,created_at: None,+ oracle_metadata: None,statement: value_as_string(row.get(1)),}})@@ -297,6 +298,7 @@ pub async fn object_source(source,editable: None,routine_parameters: None,+ trigger: None,})}diff --git a/crates/dbx-drivers/src/db/sqlite.rs b/crates/dbx-drivers/src/db/sqlite.rsindex 0ca7441040..665c4ffaa2 100644--- a/crates/dbx-drivers/src/db/sqlite.rs+++ b/crates/dbx-drivers/src/db/sqlite.rs@@ -2687,6 +2687,7 @@ pub async fn list_triggers(pool: &SqliteHandle, schema: &str, table: &str) -> Revalid: None,comment: None,created_at: None,+ oracle_metadata: None,statement: if sql_text.is_empty() { None } else { Some(sql_text) },}})@@ -2732,6 +2733,7 @@ pub async fn list_triggers(pool: &SqliteHandle, schema: &str, table: &str) -> Revalid: None,comment: None,created_at: None,+ oracle_metadata: None,statement: sql_text,})})diff --git a/crates/dbx-drivers/src/db/turso_driver.rs b/crates/dbx-drivers/src/db/turso_driver.rsindex 339470c3b4..5b589c08d7 100644--- a/crates/dbx-drivers/src/db/turso_driver.rs+++ b/crates/dbx-drivers/src/db/turso_driver.rs@@ -315,6 +315,7 @@ pub async fn list_triggers(client: &TursoClient, _schema: &str, table: &str) ->valid: None,comment: None,created_at: None,+ oracle_metadata: None,statement: value_as_string(row.get(1)),}})@@ -358,6 +359,7 @@ pub async fn object_source(source,editable: None,routine_parameters: None,+ trigger: None,})}diff --git a/crates/dbx-plugin-runtime/src/plugins.rs b/crates/dbx-plugin-runtime/src/plugins.rsindex 47a27c29b6..390cc0f31c 100644--- a/crates/dbx-plugin-runtime/src/plugins.rs+++ b/crates/dbx-plugin-runtime/src/plugins.rs@@ -556,6 +556,34 @@ impl PluginDriverSession {self.sidecar.shutdown().await}+ /// Confirm JDBC cleanup for an owned native-operation scope. Ordinary shutdown remains best effort.+ pub async fn shutdown_confirmed(&self) -> Result<(), String> {+ if let Some(logical) = &self.logical {+ return logical.close_confirmed().await;+ }+ if self.driver_id == "jdbc" {+ let closed: Result<serde_json::Value, _> = self+ .sidecar+ .invoke_with_timeout(+ "close",+ serde_json::json!({}),+ Some(&self.driver_id),+ Some(Duration::from_secs(3)),+ )+ .await;+ let acknowledged = closed.and_then(|value| {+ if value["ok"] == true {+ Ok(())+ } else {+ Err("JDBC session cleanup was not confirmed".to_string())+ }+ });+ let stopped = self.sidecar.shutdown().await;+ return acknowledged.and(stopped);+ }+ self.sidecar.shutdown().await+ }+pub fn is_available(&self) -> bool {self.logical.as_ref().is_none_or(|logical| logical.is_available())}diff --git a/crates/dbx-plugin-runtime/src/plugins/jdbc_sessions.rs b/crates/dbx-plugin-runtime/src/plugins/jdbc_sessions.rsindex fe1f30e998..5e402c8faf 100644--- a/crates/dbx-plugin-runtime/src/plugins/jdbc_sessions.rs+++ b/crates/dbx-plugin-runtime/src/plugins/jdbc_sessions.rs@@ -26,7 +26,7 @@ pub(super) struct JdbcLogicalSession {id: String,closed: AtomicBool,operation: Mutex<()>,- close_done: tokio::sync::watch::Sender<bool>,+ close_done: tokio::sync::watch::Sender<Option<Result<(), String>>>,}impl PluginRegistry {@@ -83,7 +83,7 @@ impl PluginRegistry {id: uuid::Uuid::new_v4().to_string(),closed: AtomicBool::new(false),operation: Mutex::new(()),- close_done: tokio::sync::watch::channel(false).0,+ close_done: tokio::sync::watch::channel(None).0,});let opened: Result<serde_json::Value, _> =logical.invoke("openJdbcSession", serde_json::json!({}), Some(Duration::from_secs(3))).await;@@ -133,8 +133,17 @@ impl JdbcLogicalSession {}pub(super) async fn close(self: &Arc<Self>) {+ let _ = self.close_confirmed().await;+ }++ pub(super) async fn close_confirmed(self: &Arc<Self>) -> Result<(), String> {self.close_in_background();- let _ = self.close_done.subscribe().wait_for(|done| *done).await;+ let mut done = self.close_done.subscribe();+ let result = done+ .wait_for(|done| done.is_some())+ .await+ .map_err(|_| "JDBC session cleanup outcome is unavailable".to_string())?;+ result.as_ref().expect("completed close").clone()}pub(super) fn close_in_background(self: &Arc<Self>) {@@ -145,7 +154,7 @@ impl JdbcLogicalSession {let session = self.clone();handle.spawn(async move {let runtime = &session.runtime;- let _: Result<serde_json::Value, _> = runtime+ let mut closed = runtime.process.sidecar.invoke_with_timeout(@@ -154,16 +163,26 @@ impl JdbcLogicalSession {Some("jdbc"),Some(Duration::from_secs(3)),)- .await;+ .await+ .and_then(|value: serde_json::Value| {+ if value["ok"] == true {+ Ok(())+ } else {+ Err("JDBC logical session cleanup was not confirmed".to_string())+ }+ });let mut members = runtime.members.lock().await;members.0 -= 1;if members.0 == 0 {members.1 = true;if let Err(error) = runtime.process.sidecar.shutdown().await {log::warn!("Failed to stop the shared JDBC plugin runtime: {error}");+ if closed.is_ok() {+ closed = Err(error);+ }}}- session.close_done.send_replace(true);+ session.close_done.send_replace(Some(closed));});}}@@ -194,3 +213,72 @@ impl Drop for CancelOnDrop {}}}++#[cfg(all(test, any(windows, unix)))]+mod tests {+ use super::super::lifecycle_tests::{install, registry, ID};+ use super::*;++ #[tokio::test]+ async fn unknown_native_close_is_reported_without_closing_a_sibling() {+ let temp = tempfile::tempdir().unwrap();+ let root = temp.path().join("plugins");+ let log = temp.path().join("closed.txt");+ install(&root, "0.3.4");+ let registry = registry(&root);+ let process = PluginDriverSession::start(+ registry.find_plugin(ID).unwrap().unwrap(),+ "jdbc".into(),+ "0.6.14".into(),+ PluginRuntimeEnv::default().with_var("DBX_JDBC_CLOSE_LOG", log.to_string_lossy().into_owned()),+ registry.lifecycle().begin_connection(ID, "Native job close fixture").unwrap(),+ )+ .await+ .unwrap();+ let runtime = Arc::new(JdbcRuntime { process: Arc::new(process), members: Mutex::new((2, false)) });+ let driver = |id: &str| PluginDriverSession {+ sidecar: runtime.process.sidecar.clone(),+ driver_id: "jdbc".into(),+ _activity: None,+ logical: Some(Arc::new(JdbcLogicalSession {+ runtime: runtime.clone(),+ id: id.into(),+ closed: AtomicBool::new(false),+ operation: Mutex::new(()),+ close_done: tokio::sync::watch::channel(None).0,+ })),+ };+ let failed = driver("failed");+ let sibling = driver("survivor");+ let close = failed.shutdown_confirmed().await;+ assert_eq!(failed.shutdown_confirmed().await, close, "closed failure must be retained without reissuing close");+ assert!(failed.shutdown().await.is_ok(), "ordinary callers keep the existing best-effort shutdown contract");+ let live: Result<String, _> = sibling.invoke("version", serde_json::json!({})).await;+ assert_eq!(live.unwrap(), "0.3.4");+ sibling.shutdown_confirmed().await.unwrap();+ assert_eq!(std::fs::read_to_string(log).unwrap().lines().filter(|id| *id == "failed").count(), 1);+ assert!(close.is_err(), "an RPC-confirmed native cleanup failure must not become successful shutdown");+ }++ #[tokio::test]+ async fn dedicated_jdbc_close_requires_native_acknowledgment_and_always_stops_its_process() {+ for (mode, confirmed) in [("acknowledged", true), ("unconfirmed", false)] {+ let temp = tempfile::tempdir().unwrap();+ let root = temp.path().join("plugins");+ install(&root, "0.3.4");+ let registry = registry(&root);+ let process = PluginDriverSession::start(+ registry.find_plugin(ID).unwrap().unwrap(),+ "jdbc".into(),+ "0.6.14".into(),+ PluginRuntimeEnv::default().with_var("DBX_JDBC_ROOT_CLOSE", mode),+ registry.lifecycle().begin_connection(ID, "Owned native job session").unwrap(),+ )+ .await+ .unwrap();+ assert!(process.pid().await.is_some());+ assert_eq!(process.shutdown_confirmed().await.is_ok(), confirmed);+ assert!(process.pid().await.is_none(), "unconfirmed native cleanup must still retire the owned process");+ }+ }+}diff --git a/crates/dbx-plugin-runtime/src/plugins/lifecycle_tests.rs b/crates/dbx-plugin-runtime/src/plugins/lifecycle_tests.rsindex 1ec224c032..67c89d34b1 100644--- a/crates/dbx-plugin-runtime/src/plugins/lifecycle_tests.rs+++ b/crates/dbx-plugin-runtime/src/plugins/lifecycle_tests.rs@@ -10,7 +10,7 @@ use zip::write::SimpleFileOptions;use super::{PluginHost, PluginInstallPolicy, PluginPackageInstaller, PluginRegistry, PluginTrustStore};-const ID: &str = "sample.lifecycle";+pub(super) const ID: &str = "sample.lifecycle";fn package(version: &str) -> Vec<u8> {#[cfg(windows)]@@ -27,6 +27,15 @@ while ($null -ne ($line = [Console]::ReadLine())) {continue}$result = @{protocolVersion=1; capabilities=@(); plugin=@{id=$env:DBX_PLUGIN_ID; version=$env:DBX_PLUGIN_VERSION}}+ } elseif ($r.method -eq 'closeJdbcSession') {+ if ($env:DBX_JDBC_CLOSE_LOG) { [IO.File]::AppendAllText($env:DBX_JDBC_CLOSE_LOG, $r.params.jdbcSessionId + "`n") }+ if ($r.params.jdbcSessionId -eq 'failed') {+ [Console]::WriteLine((@{jsonrpc='2.0'; id=$r.id; error=@{message='native_job_session_dispose_unknown'}} | ConvertTo-Json -Depth 8 -Compress))+ continue+ }+ $result = @{ok=$true}+ } elseif ($r.method -eq 'close') {+ $result = @{ok=($env:DBX_JDBC_ROOT_CLOSE -ne 'unconfirmed')}} elseif ($r.method -eq 'wait') {[IO.Directory]::CreateDirectory($env:DBX_PLUGIN_DATA_DIR) | Out-Null[IO.File]::WriteAllText((Join-Path $env:DBX_PLUGIN_DATA_DIR 'waiting'), 'ready')@@ -46,6 +55,18 @@ while IFS= read -r request; do*plugin/initialize*)if [ "$DBX_LIFECYCLE_STALL" = 1 ]; then mkdir -p "$DBX_PLUGIN_DATA_DIR"; touch "$DBX_PLUGIN_DATA_DIR/waiting"; continue; fiprintf '{"jsonrpc":"2.0","id":%s,"result":{"protocolVersion":1,"capabilities":[],"plugin":{"id":"%s","version":"%s"}}}\n' "$id" "$DBX_PLUGIN_ID" "$DBX_PLUGIN_VERSION" ;;+ *'"method":"closeJdbcSession"'*)+ case "$request" in+ *'"jdbcSessionId":"failed"'*)+ [ -z "$DBX_JDBC_CLOSE_LOG" ] || printf 'failed\n' >> "$DBX_JDBC_CLOSE_LOG"+ printf '{"jsonrpc":"2.0","id":%s,"error":{"message":"native_job_session_dispose_unknown"}}\n' "$id" ;;+ *)+ [ -z "$DBX_JDBC_CLOSE_LOG" ] || printf 'survivor\n' >> "$DBX_JDBC_CLOSE_LOG"+ printf '{"jsonrpc":"2.0","id":%s,"result":{"ok":true}}\n' "$id" ;;+ esac ;;+ *'"method":"close"'*)+ if [ "$DBX_JDBC_ROOT_CLOSE" = unconfirmed ]; then ok=false; else ok=true; fi+ printf '{"jsonrpc":"2.0","id":%s,"result":{"ok":%s}}\n' "$id" "$ok" ;;*'"method":"wait"'*) mkdir -p "$DBX_PLUGIN_DATA_DIR"; touch "$DBX_PLUGIN_DATA_DIR/waiting" ;;*) printf '{"jsonrpc":"2.0","id":%s,"result":"%s"}\n' "$id" "$DBX_PLUGIN_VERSION" ;;esac@@ -76,7 +97,7 @@ donezip.finish().unwrap().into_inner()}-fn registry(root: &Path) -> PluginRegistry {+pub(super) fn registry(root: &Path) -> PluginRegistry {PluginRegistry::new_with_app_version(root.to_path_buf(), "0.6.14")}@@ -85,7 +106,7 @@ fn installer(root: &Path) -> PluginPackageInstaller {.with_lifecycle(registry(root).lifecycle())}-fn install(root: &Path, version: &str) {+pub(super) fn install(root: &Path, version: &str) {installer(root).install_bytes(&package(version), PluginInstallPolicy::LocalDevelopment).unwrap();}diff --git a/crates/dbx-sql-core/src/object_source_sql.rs b/crates/dbx-sql-core/src/object_source_sql.rsindex ae610f26ff..295b9af730 100644--- a/crates/dbx-sql-core/src/object_source_sql.rs+++ b/crates/dbx-sql-core/src/object_source_sql.rs@@ -9,6 +9,11 @@ use crate::sql::{oracle_plsql_block_is_complete, split_sql_statements_for_databause crate::types::ObjectSourceKind;mod oracle_indexes;+mod oracle_trigger;+pub use oracle_trigger::{+ prepare_oracle_trigger_sql, OracleTriggerSqlBinding, OracleTriggerSqlHeader, OracleTriggerSqlInput,+ OracleTriggerSqlPurpose, PreparedOracleTriggerSql,+};mod oracle_routines;pub use oracle_indexes::{extract_oracle_table_triggers, oracle_index_ddl_sources, oracle_table_created_index_identities,@@ -617,6 +622,9 @@ fn build_executable_object_source_statements_with_mysql_validation_name(}pub fn validate_oracle_executable_object_source(input: OracleObjectSourceValidationInput) -> Result<(), String> {+ if input.object_type == ObjectSourceKind::Trigger {+ return oracle_trigger::validate(input);+ }if !matches!(input.database_type, DatabaseType::Oracle | DatabaseType::OceanbaseOracle)|| !matches!(input.object_type,diff --git a/crates/dbx-sql-core/src/object_source_sql/oracle_trigger.rs b/crates/dbx-sql-core/src/object_source_sql/oracle_trigger.rsnew file mode 100644index 0000000000..d82a5453ef--- /dev/null+++ b/crates/dbx-sql-core/src/object_source_sql/oracle_trigger.rs@@ -0,0 +1,1052 @@+//! Lossless trigger header edits, not a second PL/SQL parser. Dictionary identity,+//! privileges and concurrent changes are checked by the caller's execution plan.+use std::ops::Range;++use serde::{Deserialize, Serialize};+use sqlparser::tokenizer::TokenWithSpan;++use super::*;++#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]+#[serde(rename_all = "lowercase")]+pub enum OracleTriggerSqlPurpose {+ Inspect,+ Create,+ Replace,+}++#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct OracleTriggerSqlBinding {+ /// TABLE, VIEW, SCHEMA, DATABASE or TIMER, verified by the caller.+ pub scope: String,+ pub owner: Option<String>,+ pub name: Option<String>,+ #[serde(default)]+ pub pluggable: bool,+}++#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct OracleTriggerSqlHeader {+ /// RELATION needs a dictionary lookup to distinguish TABLE from VIEW.+ pub scope: String,+ pub owner: Option<String>,+ pub name: Option<String>,+ pub view_only: bool,+ pub pluggable: bool,+}++#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct OracleTriggerSqlInput {+ pub database_type: DatabaseType,+ pub owner: String,+ pub name: String,+ pub source: String,+ pub purpose: OracleTriggerSqlPurpose,+ pub binding: Option<OracleTriggerSqlBinding>,+ pub enabled: Option<bool>,+ /// Only a trusted metadata export may contain the same target's state DDL.+ #[serde(default)]+ pub allow_export_appendix: bool,+}++#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct PreparedOracleTriggerSql {+ pub definition: String,+ /// Whole source for readback comparison, with only the exported declaration+ /// wrapper canonicalized. Never execute this comparison form.+ pub comparison_source: String,+ pub header: OracleTriggerSqlHeader,+ pub inline_enabled: Option<bool>,+ pub export_enabled: Option<bool>,+ /// DM state restoration is a separately previewed and verified native step.+ pub requires_state_restore: bool,+ /// The complete header is representable by the timing/event/body form.+ pub structured_editable: bool,+}++struct TriggerTokens {+ source: String,+ lexical: String,+ tokens: Vec<TokenWithSpan>,+}++impl TriggerTokens {+ fn new(source: String, dm: bool) -> Result<Self, String> {+ let lexical = if dm { dm_lexical_view(&source) } else { source.clone() };+ let tokens = Tokenizer::new(&OracleDialect {}, &lexical)+ .tokenize_with_location()+ .map_err(|error| format!("Cannot tokenize trigger source: {error}"))?+ .into_iter()+ .filter(|token| !matches!(token.token, Token::Whitespace(_) | Token::EOF))+ .collect();+ Ok(Self { source, lexical, tokens })+ }++ fn token(&self, index: usize) -> Option<&Token> {+ self.tokens.get(index).map(|token| &token.token)+ }++ fn word(&self, index: usize, word: &str) -> bool {+ self.token(index).is_some_and(|token| token_unquoted_word_is(token, word))+ }++ fn range(&self, index: usize) -> Result<Range<usize>, String> {+ let token = self.tokens.get(index).ok_or("Incomplete trigger header")?;+ let start = routine_location_to_byte_offset(&self.source, token.span.start);+ let end = routine_location_to_byte_offset(&self.source, token.span.end);+ match (start, end) {+ (Some(start), Some(end)) if start < end && end <= self.source.len() => Ok(start..end),+ _ => Err("Cannot map trigger token positions to the source text".into()),+ }+ }++ fn identifier(&self, index: usize) -> Result<String, String> {+ match self.token(index) {+ Some(Token::Word(word)) if word.quote_style == Some('"') => Ok(word.value.clone()),+ // sqlparser's keyword set spans every dialect (including DATA).+ // Here the grammar already identifies an identifier position; a+ // write additionally binds this value to a dictionary target and+ // quotes it. Do not reject valid Oracle names using that union.+ Some(Token::Word(word)) if word.quote_style.is_none() && !word.value.contains('@') => {+ Ok(word.value.to_ascii_uppercase())+ }+ _ => Err("Trigger target must use a local Oracle identifier; quote reserved or special names".into()),+ }+ }++ fn qualified(&self, start: usize) -> Result<(Option<String>, String, usize), String> {+ let first = self.identifier(start)?;+ let result = if self.token(start + 1) == Some(&Token::Period) {+ (Some(first), self.identifier(start + 2)?, start + 3)+ } else {+ (None, first, start + 1)+ };+ if self.token(result.2) == Some(&Token::Period) {+ return Err("Three-part trigger targets are not supported".into());+ }+ Ok(result)+ }++ fn standalone_slash(&self, index: usize) -> Result<bool, String> {+ if self.token(index) != Some(&Token::Div) {+ return Ok(false);+ }+ let range = self.range(index)?;+ let start = self.source[..range.start].rfind('\n').map_or(0, |offset| offset + 1);+ let end = self.source[range.end..].find('\n').map_or(self.source.len(), |offset| range.end + offset);+ Ok(self.source[start..end].trim() == "/")+ }+}++struct Header {+ declaration: usize,+ declaration_end: usize,+ create_or_replace: Option<(usize, usize)>,+ parent: usize,+ parent_end: usize,+ state: Option<usize>,+ state_insert: usize,+ header: OracleTriggerSqlHeader,+ structured_editable: bool,+}++pub(super) fn validate(input: OracleObjectSourceValidationInput) -> Result<(), String> {+ // Validation without a selected owner must still check any explicit owner's+ // syntax, but cannot bind an omitted owner to the session schema.+ let mut source = normalized_source(input.database_type, input.source)?;+ strip_trailing_slash(&mut source, input.database_type)?;+ let tokens = TriggerTokens::new(source, input.database_type == DatabaseType::Dameng)?;+ analyze(&tokens, input.schema.as_deref(), &input.name, input.database_type)?;+ Ok(())+}++pub fn prepare_oracle_trigger_sql(input: OracleTriggerSqlInput) -> Result<PreparedOracleTriggerSql, String> {+ if input.owner.is_empty() || input.name.is_empty() {+ return Err("Select the exact trigger owner and name".into());+ }+ if input.allow_export_appendix && input.purpose != OracleTriggerSqlPurpose::Inspect {+ return Err("An editable trigger definition cannot contain export appendix statements".into());+ }+ let mut source = normalized_source(input.database_type, input.source)?;+ strip_trailing_slash(&mut source, input.database_type)?;+ let export_enabled = if input.allow_export_appendix {+ strip_export_appendix(&mut source, input.database_type, &input.owner, &input.name)?+ } else {+ None+ };+ let tokens = TriggerTokens::new(source, input.database_type == DatabaseType::Dameng)?;+ let parsed = analyze(&tokens, Some(&input.owner), &input.name, input.database_type)?;+ let inline_enabled = parsed.state.map(|index| tokens.word(index, "ENABLE"));+ let mut result = PreparedOracleTriggerSql {+ definition: tokens.source.clone(),+ comparison_source: String::new(),+ header: parsed.header.clone(),+ inline_enabled,+ export_enabled,+ requires_state_restore: false,+ structured_editable: parsed.structured_editable,+ };+ terminate_definition(&mut result.definition, input.database_type)?;+ result.comparison_source = comparison_source(&result.definition, input.database_type, &input.owner, &input.name)?;+ if let Some(binding) = &input.binding {+ verify_binding(&parsed.header, binding)?;+ }+ if input.purpose == OracleTriggerSqlPurpose::Inspect {+ return Ok(result);+ }++ let binding = input.binding.as_ref().ok_or("Verify the candidate's ON target before preparing trigger SQL")?;+ let enabled = input+ .enabled+ .or_else(|| (input.purpose == OracleTriggerSqlPurpose::Create).then_some(inline_enabled.unwrap_or(true)))+ .ok_or("Read the current enabled state before replacing a trigger")?;+ let mut edits = Vec::new();+ // Edit tokens separately to preserve comments between CREATE/OR/REPLACE or+ // between the owner, period and name. The PL/SQL body is never reconstructed.+ match (input.purpose, parsed.create_or_replace) {+ (OracleTriggerSqlPurpose::Create, Some((or, replace))) => {+ edits.push((tokens.range(or)?, String::new()));+ edits.push((tokens.range(replace)?, String::new()));+ }+ (OracleTriggerSqlPurpose::Replace, None) => {+ let end = tokens.range(0)?.end;+ edits.push((end..end, " OR REPLACE".into()));+ }+ _ => {}+ }+ qualify(&tokens, parsed.declaration, parsed.declaration_end, &input.owner, &input.name, &mut edits)?;+ match parsed.header.scope.as_str() {+ "RELATION" => qualify(+ &tokens,+ parsed.parent,+ parsed.parent_end,+ binding.owner.as_deref().unwrap(),+ binding.name.as_deref().unwrap(),+ &mut edits,+ )?,+ "SCHEMA" => {+ if parsed.header.owner.is_some() {+ edits+ .push((tokens.range(parsed.parent)?, quote_postgres_identifier(binding.owner.as_deref().unwrap())));+ } else {+ let start = tokens.range(parsed.parent)?.start;+ edits+ .push((start..start, format!("{}.", quote_postgres_identifier(binding.owner.as_deref().unwrap()))));+ }+ }+ _ => {}+ }+ if input.database_type == DatabaseType::Dameng {+ if let Some(state) = parsed.state {+ edits.push((tokens.range(state)?, String::new()));+ }+ result.requires_state_restore = !enabled;+ } else if let Some(state) = parsed.state {+ edits.push((tokens.range(state)?, if enabled { "ENABLE" } else { "DISABLE" }.into()));+ } else {+ let start = tokens.range(parsed.state_insert)?.start;+ edits.push((start..start, format!("{}\n", if enabled { "ENABLE" } else { "DISABLE" })));+ }+ edits.sort_by_key(|(range, _)| (range.start, range.end));+ for (range, replacement) in edits.into_iter().rev() {+ result.definition.replace_range(range, &replacement);+ }+ result.header.owner = binding.owner.clone();+ result.comparison_source = comparison_source(&result.definition, input.database_type, &input.owner, &input.name)?;+ Ok(result)+}++fn comparison_source(source: &str, database: DatabaseType, owner: &str, name: &str) -> Result<String, String> {+ let tokens = TriggerTokens::new(source.to_owned(), database == DatabaseType::Dameng)?;+ let parsed = analyze(&tokens, Some(owner), name, database)?;+ let end = tokens.range(parsed.declaration_end - 1)?.end;+ // GET_DDL reconstructs CREATE OR REPLACE and the declared owner/name;+ // ALL_SOURCE starts at TRIGGER. Ignore whitespace only in that wrapper,+ // retaining every comment and the complete header/body suffix verbatim.+ let mut comments = Vec::new();+ let mut previous = 0;+ for index in 0..parsed.declaration_end {+ let range = tokens.range(index)?;+ let gap = source[previous..range.start].trim();+ if !gap.is_empty() {+ comments.push(gap);+ }+ previous = range.end;+ }+ let edition = if (0..parsed.declaration).any(|index| tokens.word(index, "NONEDITIONABLE")) {+ " NONEDITIONABLE"+ } else if (0..parsed.declaration).any(|index| tokens.word(index, "EDITIONABLE")) {+ " EDITIONABLE"+ } else {+ ""+ };+ let comments = if comments.is_empty() { String::new() } else { format!("{}\n", comments.join("\n")) };+ Ok(format!(+ "{comments}CREATE OR REPLACE{edition} TRIGGER {}.{}{}",+ quote_postgres_identifier(owner),+ quote_postgres_identifier(name),+ &source[end..]+ ))+}++fn qualify(+ tokens: &TriggerTokens,+ start: usize,+ end: usize,+ owner: &str,+ name: &str,+ edits: &mut Vec<(Range<usize>, String)>,+) -> Result<(), String> {+ if end - start == 3 {+ edits.push((tokens.range(start)?, quote_postgres_identifier(owner)));+ edits.push((tokens.range(start + 2)?, quote_postgres_identifier(name)));+ } else {+ edits.push((+ tokens.range(start)?,+ format!("{}.{}", quote_postgres_identifier(owner), quote_postgres_identifier(name)),+ ));+ }+ Ok(())+}++fn verify_binding(header: &OracleTriggerSqlHeader, binding: &OracleTriggerSqlBinding) -> Result<(), String> {+ let matches = match header.scope.as_str() {+ "RELATION" => {+ matches!(binding.scope.as_str(), "TABLE" | "VIEW")+ && (!header.view_only || binding.scope == "VIEW")+ && binding.owner.as_ref().is_some_and(|owner| {+ !owner.is_empty() && header.owner.as_ref().is_none_or(|expected| expected == owner)+ })+ && binding.name.as_ref().is_some_and(|name| !name.is_empty() && header.name.as_ref() == Some(name))+ && !binding.pluggable+ }+ "SCHEMA" => {+ binding.scope == "SCHEMA"+ && binding.name.is_none()+ && !binding.pluggable+ && binding.owner.as_ref().is_some_and(|owner| {+ !owner.is_empty() && header.owner.as_ref().is_none_or(|expected| expected == owner)+ })+ }+ "DATABASE" | "TIMER" => {+ binding.scope == header.scope+ && binding.owner.is_none()+ && binding.name.is_none()+ && binding.pluggable == header.pluggable+ }+ _ => false,+ };+ if matches {+ Ok(())+ } else {+ Err("The candidate ON target does not match the verified owning object or scope; keep the draft and verify the selection".into())+ }+}++fn normalized_source(database: DatabaseType, source: String) -> Result<String, String> {+ if !matches!(database, DatabaseType::Oracle | DatabaseType::OceanbaseOracle | DatabaseType::Dameng) {+ return Err("Exact trigger source is supported only for Oracle, OceanBase Oracle and DM8".into());+ }+ let tokens = TriggerTokens::new(source, database == DatabaseType::Dameng)?;+ let mut source = tokens.source.clone();+ if tokens.word(0, "TRIGGER")+ || (tokens.word(0, "EDITIONABLE") || tokens.word(0, "NONEDITIONABLE")) && tokens.word(1, "TRIGGER")+ {+ let start = tokens.range(0)?.start;+ source.insert_str(start, "CREATE ");+ } else if !tokens.word(0, "CREATE") {+ return Err("A complete TRIGGER declaration is required, not only its body".into());+ }+ Ok(source)+}++fn strip_trailing_slash(source: &mut String, database: DatabaseType) -> Result<(), String> {+ let tokens = TriggerTokens::new(source.clone(), database == DatabaseType::Dameng)?;+ if let Some(last) = tokens.tokens.len().checked_sub(1) {+ if tokens.standalone_slash(last)? {+ source.replace_range(tokens.range(last)?, "");+ }+ }+ Ok(())+}++fn strip_export_appendix(+ source: &mut String,+ database: DatabaseType,+ owner: &str,+ name: &str,+) -> Result<Option<bool>, String> {+ let tokens = TriggerTokens::new(source.clone(), database == DatabaseType::Dameng)?;+ let Some(alter) = (0..tokens.tokens.len()).rev().find(|index| tokens.word(*index, "ALTER")) else {+ return Ok(None);+ };+ if !tokens.word(alter + 1, "TRIGGER") {+ return Ok(None);+ }+ let (declared_owner, declared_name, end) = tokens.qualified(alter + 2)?;+ if !(tokens.word(end, "ENABLE") || tokens.word(end, "DISABLE")) {+ return Ok(None);+ }+ let tail = if tokens.token(end + 1) == Some(&Token::SemiColon) { end + 2 } else { end + 1 };+ if tail != tokens.tokens.len() {+ return Err("Unexpected statements after the trigger export state".into());+ }+ if declared_owner.as_deref() != Some(owner) || declared_name != name {+ return Err("The trigger export appendix targets a different object".into());+ }+ let mut prefix = source[..tokens.range(alter)?.start].to_string();+ strip_trailing_slash(&mut prefix, database)?;+ let prefix_tokens = TriggerTokens::new(prefix.clone(), database == DatabaseType::Dameng)?;+ analyze(&prefix_tokens, Some(owner), name, database)?;+ *source = prefix;+ Ok(Some(tokens.word(end, "ENABLE")))+}++fn analyze(tokens: &TriggerTokens, owner: Option<&str>, name: &str, database: DatabaseType) -> Result<Header, String> {+ let mut index = 1;+ let create_or_replace = if tokens.word(index, "OR") && tokens.word(index + 1, "REPLACE") {+ index += 2;+ Some((1, 2))+ } else {+ None+ };+ if tokens.word(index, "EDITIONABLE") || tokens.word(index, "NONEDITIONABLE") {+ index += 1;+ }+ if !tokens.word(0, "CREATE") || !tokens.word(index, "TRIGGER") {+ return Err("The source must declare one TRIGGER".into());+ }+ let declaration = index + 1;+ let (declared_owner, declared_name, declaration_end) = tokens.qualified(declaration)?;+ if declared_name != name+ || declared_owner.as_deref().is_some_and(|declared| owner.is_some_and(|owner| owner != declared))+ {+ return Err("The trigger declaration does not match the selected exact owner and name".into());+ }+ let mut event = declaration_end;+ if database == DatabaseType::Dameng && tokens.word(event, "WITH") && tokens.word(event + 1, "ENCRYPTION") {+ event += 2;+ }+ if !["BEFORE", "AFTER", "INSTEAD", "FOR"].iter().any(|word| tokens.word(event, word)) {+ return Err("Cannot locate the trigger timing and event header".into());+ }+ let on = (event + 1..tokens.tokens.len())+ .find(|index| {+ tokens.word(*index, "ON")+ || tokens.word(*index, "BEGIN")+ || tokens.word(*index, "DECLARE")+ || tokens.word(*index, "CALL")+ || tokens.token(*index) == Some(&Token::SemiColon)+ })+ .filter(|index| tokens.word(*index, "ON"))+ .ok_or("Cannot locate the trigger header's ON target")?;+ let timer = database == DatabaseType::Dameng && (event..on).any(|index| tokens.word(index, "TIMER"));+ let mut parent = on + 1;+ let nested = tokens.word(parent, "NESTED") && tokens.word(parent + 1, "TABLE");+ if nested {+ tokens.identifier(parent + 2)?;+ if !tokens.word(parent + 3, "OF") {+ return Err("Incomplete NESTED TABLE trigger target".into());+ }+ parent += 4;+ }+ let (header, parent_end) = if tokens.word(parent, "SCHEMA") && tokens.token(parent + 1) != Some(&Token::Period) {+ (+ OracleTriggerSqlHeader {+ scope: "SCHEMA".into(),+ owner: None,+ name: None,+ view_only: false,+ pluggable: false,+ },+ parent + 1,+ )+ } else if tokens.word(parent, "DATABASE") && tokens.token(parent + 1) != Some(&Token::Period)+ || tokens.word(parent, "PLUGGABLE") && tokens.word(parent + 1, "DATABASE")+ {+ let pluggable = tokens.word(parent, "PLUGGABLE");+ if nested || timer && pluggable {+ return Err("Unsupported trigger scope header".into());+ }+ (+ OracleTriggerSqlHeader {+ scope: if timer { "TIMER" } else { "DATABASE" }.into(),+ owner: None,+ name: None,+ view_only: false,+ pluggable,+ },+ parent + if pluggable { 2 } else { 1 },+ )+ } else if tokens.token(parent + 1) == Some(&Token::Period) && tokens.word(parent + 2, "SCHEMA") {+ (+ OracleTriggerSqlHeader {+ scope: "SCHEMA".into(),+ owner: Some(tokens.identifier(parent)?),+ name: None,+ view_only: false,+ pluggable: false,+ },+ parent + 3,+ )+ } else {+ let (owner, name, end) = tokens.qualified(parent)?;+ if timer {+ return Err("A DM TIMER trigger must target DATABASE".into());+ }+ (+ OracleTriggerSqlHeader {+ scope: "RELATION".into(),+ owner,+ name: Some(name),+ view_only: nested || tokens.word(event, "INSTEAD"),+ pluggable: false,+ },+ end,+ )+ };+ if tokens.token(parent_end) == Some(&Token::Period) {+ return Err("The trigger ON target has an unexpected extra qualifier".into());+ }+ if nested && header.scope != "RELATION" {+ return Err("A nested-table trigger requires a verified view".into());+ }+ let mut depth = 0usize;+ let mut body = None;+ let mut state = None;+ let mut state_insert = None;+ for index in parent_end..tokens.tokens.len() {+ match tokens.token(index) {+ Some(Token::LParen) => depth += 1,+ Some(Token::RParen) => depth = depth.checked_sub(1).ok_or("Unbalanced trigger header parentheses")?,+ Some(Token::SemiColon) => return Err("Trigger header has no complete body".into()),+ _ => {}+ }+ if depth != 0 {+ continue;+ }+ if tokens.word(index, "ON") {+ return Err("Ambiguous extra ON target in the trigger header".into());+ }+ if tokens.word(index, "WHEN") {+ state_insert.get_or_insert(index);+ }+ if (tokens.word(index, "ENABLE") || tokens.word(index, "DISABLE")) && state.replace(index).is_some() {+ return Err("Duplicate top-level trigger state clauses".into());+ }+ if ["BEGIN", "DECLARE", "CALL"].iter().any(|word| tokens.word(index, word))+ || tokens.word(index, "COMPOUND") && tokens.word(index + 1, "TRIGGER")+ {+ body = Some(index);+ break;+ }+ }+ let body = body.ok_or("A complete trigger body is required")?;+ let last = tokens.tokens.len().checked_sub(1).ok_or("Empty trigger definition")?;+ let mut complete_source = tokens.lexical.clone();+ if tokens.token(last) != Some(&Token::SemiColon) {+ // ALL_SOURCE commonly omits the final terminator. Add it for analysis,+ // never by searching for END inside a string or comment.+ complete_source.insert(tokens.range(last)?.end, ';');+ }+ if tokens.word(body, "CALL") {+ validate_call(tokens, body)?;+ } else if !crate::sql::oracle_plsql_block_is_complete(&complete_source) {+ return Err("The trigger PL/SQL block is incomplete".into());+ }+ if split_sql_statements_for_database(&complete_source, database).len() != 1 {+ return Err("Trigger source must contain exactly one complete definition and no extra SQL".into());+ }+ let event_start = if tokens.word(event, "BEFORE") || tokens.word(event, "AFTER") {+ event + 1+ } else if tokens.word(event, "INSTEAD") && tokens.word(event + 1, "OF") {+ event + 2+ } else {+ on+ };+ let mut structured_editable = header.scope == "RELATION"+ && !nested+ && event == declaration_end+ && !(0..declaration).any(|index| tokens.word(index, "EDITIONABLE") || tokens.word(index, "NONEDITIONABLE"))+ && !tokens.word(body, "COMPOUND")+ && event_start < on+ && (on - event_start) % 2 == 1+ && (event_start..on).enumerate().all(|(offset, index)| {+ if offset % 2 == 1 {+ tokens.word(index, "OR")+ } else {+ ["INSERT", "UPDATE", "DELETE"].iter().any(|word| tokens.word(index, word))+ }+ });+ let mut index = parent_end;+ let mut row_clause = false;+ let mut referencing_clause = false;+ while structured_editable && index < body {+ if !row_clause && tokens.word(index, "FOR") && tokens.word(index + 1, "EACH") && tokens.word(index + 2, "ROW") {+ row_clause = true;+ index += 3;+ } else if tokens.word(index, "ENABLE") || tokens.word(index, "DISABLE") {+ index += 1;+ } else if !referencing_clause && tokens.word(index, "REFERENCING") {+ referencing_clause = true;+ index += 1;+ let mut aliases = 0u8;+ while tokens.word(index, "NEW") || tokens.word(index, "OLD") {+ let (word, bit) = if tokens.word(index, "NEW") { ("NEW", 1) } else { ("OLD", 2) };+ if aliases & bit != 0 || !tokens.word(index + 1, "AS") || !tokens.word(index + 2, word) {+ structured_editable = false;+ break;+ }+ aliases |= bit;+ index += 3;+ }+ structured_editable &= aliases != 0;+ } else {+ structured_editable = false;+ }+ }+ Ok(Header {+ declaration,+ declaration_end,+ create_or_replace,+ parent,+ parent_end,+ state,+ state_insert: state_insert.unwrap_or(body),+ header,+ structured_editable,+ })+}++fn terminate_definition(source: &mut String, database: DatabaseType) -> Result<(), String> {+ let tokens = TriggerTokens::new(source.clone(), database == DatabaseType::Dameng)?;+ if let Some(last) = tokens.tokens.len().checked_sub(1) {+ if tokens.token(last) != Some(&Token::SemiColon) {+ source.insert(tokens.range(last)?.end, ';');+ }+ }+ Ok(())+}++fn validate_call(tokens: &TriggerTokens, body: usize) -> Result<(), String> {+ // The CALL body is not the DDL target: packaged/remote routine references+ // keep their original semantics. Check its boundary, not local ownership.+ let mut end = body + 1;+ loop {+ if !matches!(tokens.token(end), Some(Token::Word(_))) {+ return Err("Incomplete trigger CALL routine reference".into());+ }+ end += 1;+ if tokens.token(end) != Some(&Token::Period) {+ break;+ }+ end += 1;+ }+ if tokens.token(end) != Some(&Token::LParen) {+ return Err("A trigger CALL body requires its complete argument list".into());+ }+ let mut depth = 0usize;+ for index in end..tokens.tokens.len() {+ match tokens.token(index) {+ Some(Token::LParen) => depth += 1,+ Some(Token::RParen) => {+ depth = depth.checked_sub(1).ok_or("Unbalanced CALL body")?;+ if depth == 0 {+ let tail = &tokens.tokens[index + 1..];+ return if tail.is_empty() || tail.len() == 1 && tail[0].token == Token::SemiColon {+ Ok(())+ } else {+ Err("Unexpected SQL after the trigger CALL body".into())+ };+ }+ }+ Some(Token::SemiColon) => return Err("Unexpected statement in the trigger CALL body".into()),+ _ => {}+ }+ }+ Err("The trigger CALL body is incomplete".into())+}++/// DM accepts // comments. Use the mature Oracle tokenizer/block detector on a+/// same-length lexical view, preserving all original source and token offsets.+fn dm_lexical_view(source: &str) -> String {+ let mut view = source.to_string();+ let mut index = 0;+ while index < source.len() {+ let end = if source[index..].starts_with('\'') && crate::sql::ends_with_oracle_q_quote_prefix(&source[..index])+ {+ Some(crate::sql::oracle_q_quote_end(source, index).unwrap_or(source.len()))+ } else {+ sql_single_quoted_literal_end(source, index)+ .or_else(|| read_quoted_sql_identifier(source, index).map(|(end, _)| end))+ .or_else(|| sql_line_comment_end(source, index))+ .or_else(|| sql_block_comment_end(source, index))+ };+ if let Some(end) = end {+ index = end;+ continue;+ }+ if source[index..].starts_with("//") {+ view.replace_range(index..index + 2, "--");+ index += source[index..].find('\n').unwrap_or(source.len() - index);+ continue;+ }+ index += source[index..].chars().next().unwrap().len_utf8();+ }+ view+}++#[cfg(test)]+mod tests {+ use super::*;++ fn input(source: &str) -> OracleTriggerSqlInput {+ OracleTriggerSqlInput {+ database_type: DatabaseType::Oracle,+ owner: "APP".into(),+ name: "T".into(),+ source: source.into(),+ purpose: OracleTriggerSqlPurpose::Inspect,+ binding: None,+ enabled: None,+ allow_export_appendix: false,+ }+ }++ fn relation(owner: &str, name: &str, view: bool) -> OracleTriggerSqlBinding {+ OracleTriggerSqlBinding {+ scope: if view { "VIEW" } else { "TABLE" }.into(),+ owner: Some(owner.into()),+ name: Some(name.into()),+ pluggable: false,+ }+ }++ fn scope(scope: &str, owner: Option<&str>) -> OracleTriggerSqlBinding {+ OracleTriggerSqlBinding { scope: scope.into(), owner: owner.map(str::to_string), name: None, pluggable: false }+ }++ const SIMPLE: &str = "CREATE TRIGGER APP.T BEFORE INSERT ON DATA.ORDERS FOR EACH ROW BEGIN NULL; END;";++ #[test]+ fn reports_whether_the_complete_definition_is_losslessly_structured() {+ for (source, expected) in [+ (SIMPLE, true),+ ("CREATE TRIGGER APP.T AFTER INSERT OR UPDATE ON DATA.ORDERS REFERENCING NEW AS NEW OLD AS OLD FOR EACH ROW DISABLE BEGIN NULL; END;", true),+ ("CREATE TRIGGER APP.T BEFORE INSERT ON DATA.ORDERS BEGIN pkg.run('FOLLOWS REFERENCING'); /* WHEN */ NULL; END;", true),+ ("CREATE TRIGGER APP.T BEFORE INSERT ON DATA.ORDERS FOR EACH ROW FOLLOWS OTHER_T BEGIN NULL; END;", false),+ ("CREATE TRIGGER APP.T BEFORE INSERT ON DATA.ORDERS REFERENCING NEW AS N FOR EACH ROW BEGIN NULL; END;", false),+ ("CREATE TRIGGER APP.T BEFORE UPDATE OF ID ON DATA.ORDERS FOR EACH ROW BEGIN NULL; END;", false),+ ("CREATE TRIGGER APP.T BEFORE INSERT ON DATA.ORDERS FOR EACH ROW WHEN (NEW.ID > 0) BEGIN NULL; END;", false),+ ("CREATE NONEDITIONABLE TRIGGER APP.T BEFORE INSERT ON DATA.ORDERS BEGIN NULL; END;", false),+ ("CREATE TRIGGER APP.T INSTEAD OF INSERT ON NESTED TABLE ITEMS OF DATA.V FOR EACH ROW BEGIN NULL; END;", false),+ ] {+ let prepared = serde_json::to_value(prepare_oracle_trigger_sql(input(source)).unwrap()).unwrap();+ assert_eq!(prepared.get("structuredEditable").and_then(serde_json::Value::as_bool), Some(expected), "{source}");+ }+ }++ #[test]+ fn strict_entry_accepts_oracle_family_triggers_without_changing_routines_or_default_trigger_building() {+ for (database, source) in [+ (DatabaseType::Oracle, SIMPLE),+ (DatabaseType::OceanbaseOracle, "CREATE OR REPLACE TRIGGER APP.T BEFORE UPDATE OF V ON DATA.ORDERS REFERENCING NEW AS N FOR EACH ROW DISABLE WHEN (N.V > 0) BEGIN NULL; END;"),+ (DatabaseType::Dameng, "CREATE OR REPLACE TRIGGER APP.T AFTER TIMER ON DATABASE FOR EACH 1 DAY FOR EACH 1 MINUTE BEGIN NULL; END;"),+ ] {+ validate_oracle_executable_object_source(OracleObjectSourceValidationInput { database_type: database, object_type: ObjectSourceKind::Trigger, schema: Some("APP".into()), name: "T".into(), source: source.into() }).unwrap();+ }+ validate_oracle_executable_object_source(OracleObjectSourceValidationInput {+ database_type: DatabaseType::Oracle,+ object_type: ObjectSourceKind::Procedure,+ schema: Some("APP".into()),+ name: "P".into(),+ source: "CREATE OR REPLACE PROCEDURE APP.P AS BEGIN NULL; END;".into(),+ })+ .unwrap();+ let legacy = build_executable_object_source_statements(EditableObjectSourceSqlInput {+ database_type: DatabaseType::Oracle,+ object_type: ObjectSourceKind::Trigger,+ schema: Some("APP".into()),+ name: "T".into(),+ source: "BEGIN NULL; END;".into(),+ })+ .unwrap();+ assert_eq!(legacy, ["BEGIN NULL; END;"]);+ }++ #[test]+ fn all_source_bare_declaration_and_missing_final_terminator_are_normalized_without_rebuilding_the_body() {+ let source = "-- 原始声明\nTRIGGER APP.T BEFORE INSERT ON DATA.ORDERS BEGIN NULL; END -- 尾注释\n";+ let prepared = prepare_oracle_trigger_sql(input(source)).unwrap();+ assert_eq!(+ prepared.definition,+ "-- 原始声明\nCREATE TRIGGER APP.T BEFORE INSERT ON DATA.ORDERS BEGIN NULL; END; -- 尾注释\n"+ );+ assert_eq!(prepared.header.owner.as_deref(), Some("DATA"));+ assert_eq!(prepared.header.name.as_deref(), Some("ORDERS"));+ let editioned =+ prepare_oracle_trigger_sql(input(&SIMPLE.replace("CREATE TRIGGER", "NONEDITIONABLE TRIGGER"))).unwrap();+ assert!(editioned.definition.starts_with("CREATE NONEDITIONABLE TRIGGER"));+ }++ #[test]+ fn export_same_target_state_is_separate_from_the_original_inline_state() {+ let source = format!("{SIMPLE}\n/\nALTER TRIGGER \"APP\".\"T\" DISABLE;\n/\n-- export tail\n");+ let mut request = input(&source);+ request.allow_export_appendix = true;+ let prepared = prepare_oracle_trigger_sql(request.clone()).unwrap();+ assert_eq!(prepared.export_enabled, Some(false));+ assert_eq!(prepared.inline_enabled, None);+ assert!(!prepared.definition.contains("ALTER TRIGGER"));+ assert!(!prepared.definition.lines().any(|line| line.trim() == "/"));+ request.purpose = OracleTriggerSqlPurpose::Replace;+ assert!(prepare_oracle_trigger_sql(request).is_err());+ }++ #[test]+ fn comparison_canonicalizes_only_the_known_declaration_wrapper_and_keeps_body_literals_and_comments() {+ let source = "CREATE TRIGGER APP.T BEFORE INSERT ON DATA.ORDERS BEGIN X := q'[a\r\nb]'; /* body */ NULL; END;";+ let plain = prepare_oracle_trigger_sql(input(source)).unwrap();+ let export = prepare_oracle_trigger_sql(input(+ &source.replace("CREATE TRIGGER APP.T", "\nCREATE OR REPLACE\nTRIGGER \"APP\" . \"T\""),+ ))+ .unwrap();+ assert_eq!(plain.definition, source);+ assert_eq!(plain.comparison_source, export.comparison_source);+ for changed in [+ source.replace("\r\n", "\n"),+ source.replace("/* body */", "/* changed */"),+ source.replace("CREATE TRIGGER", "CREATE /* wrapper comment */ TRIGGER"),+ source.replace("CREATE TRIGGER", "CREATE NONEDITIONABLE TRIGGER"),+ ] {+ let changed = prepare_oracle_trigger_sql(input(&changed)).unwrap();+ assert_ne!(plain.comparison_source, changed.comparison_source);+ }+ }++ #[test]+ fn export_cannot_strip_a_different_target_or_an_arbitrary_second_statement() {+ for tail in [+ "ALTER TRIGGER APP.OTHER DISABLE;",+ "ALTER TRIGGER OTHER.T DISABLE;",+ "DROP TABLE DATA.ORDERS;",+ "ALTER TRIGGER APP.T DISABLE; ALTER TRIGGER APP.T ENABLE;",+ ] {+ let mut request = input(&format!("{SIMPLE}\n{tail}"));+ request.allow_export_appendix = true;+ assert!(prepare_oracle_trigger_sql(request).is_err(), "{tail}");+ }+ assert!(prepare_oracle_trigger_sql(input(&format!("{SIMPLE}\nALTER TRIGGER APP.T DISABLE;"))).is_err());+ }++ #[test]+ fn slash_lines_in_q_and_nq_literals_and_comments_are_not_removed() {+ let source = "CREATE TRIGGER APP.T BEFORE INSERT ON DATA.ORDERS DECLARE V VARCHAR2(100); BEGIN V := q'[\n/\nON WRONG ENABLE END;]'; V := nq'!\n/\n中文😀!'; /*\n/\n*/ NULL; END;\n/\n";+ let prepared = prepare_oracle_trigger_sql(input(source)).unwrap();+ assert!(prepared.definition.contains("q'[\n/\nON WRONG ENABLE END;]'"));+ assert!(prepared.definition.contains("nq'!\n/\n中文😀!'"));+ assert!(prepared.definition.contains("/*\n/\n*/"));+ assert!(!prepared.definition.trim_end().ends_with('/'));+ }++ #[test]+ fn declaration_identity_is_exact_and_cannot_be_inferred_from_the_parent() {+ for source in [+ SIMPLE.replace("APP.T", "OTHER.T"),+ SIMPLE.replace("APP.T", "APP.OTHER"),+ SIMPLE.replace("APP.T", "APP.\"t\""),+ SIMPLE.replace("APP.T", "APP.T@REMOTE"),+ SIMPLE.replace("APP.T", "APP.DATA.T"),+ ] {+ assert!(prepare_oracle_trigger_sql(input(&source)).is_err(), "{source}");+ }+ let mut quoted =+ input("CREATE TRIGGER \" Owner \".\" Tr\"\"ig \" BEFORE INSERT ON \" Data \".\" A:b \" BEGIN NULL; END;");+ quoted.owner = " Owner ".into();+ quoted.name = " Tr\"ig ".into();+ let parsed = prepare_oracle_trigger_sql(quoted).unwrap();+ assert_eq!(parsed.header.name.as_deref(), Some(" A:b "));+ assert_eq!(parsed.header.owner.as_deref(), Some(" Data "));+ }++ #[test]+ fn explicit_on_target_must_match_the_verified_binding_before_any_rewrite() {+ let mut request = input(SIMPLE);+ request.purpose = OracleTriggerSqlPurpose::Replace;+ request.enabled = Some(false);+ for binding in+ [relation("OTHER", "ORDERS", false), relation("DATA", "OTHER", false), scope("SCHEMA", Some("DATA"))]+ {+ request.binding = Some(binding);+ assert!(prepare_oracle_trigger_sql(request.clone()).is_err());+ }+ request.binding = Some(relation("DATA", "ORDERS", false));+ let prepared = prepare_oracle_trigger_sql(request).unwrap();+ assert!(prepared.definition.contains("ON \"DATA\".\"ORDERS\""));+ assert!(prepared.definition.contains("DISABLE\nBEGIN NULL; END;"));+ }++ #[test]+ fn unqualified_parent_uses_verified_selection_not_trigger_owner_or_execution_schema() {+ let mut request = input("CREATE TRIGGER T BEFORE INSERT ON ORDERS BEGIN NULL; END;");+ request.purpose = OracleTriggerSqlPurpose::Create;+ request.binding = Some(relation(" Parent Owner ", "ORDERS", false));+ let prepared = prepare_oracle_trigger_sql(request).unwrap();+ assert!(prepared.definition.contains("TRIGGER \"APP\".\"T\""));+ assert!(prepared.definition.contains("ON \" Parent Owner \".\"ORDERS\""));+ assert_eq!(prepared.header.owner.as_deref(), Some(" Parent Owner "));+ }++ #[test]+ fn a_scope_word_used_as_an_owner_is_not_misread_as_a_scope() {+ for owner in ["SCHEMA", "DATABASE"] {+ let parsed = prepare_oracle_trigger_sql(input(&format!(+ "CREATE TRIGGER APP.T BEFORE INSERT ON {owner}.ORDERS BEGIN NULL; END;"+ )))+ .unwrap();+ assert_eq!(parsed.header.scope, "RELATION");+ assert_eq!(parsed.header.owner.as_deref(), Some(owner));+ assert_eq!(parsed.header.name.as_deref(), Some("ORDERS"));+ }+ assert!(prepare_oracle_trigger_sql(input(+ "CREATE TRIGGER APP.T AFTER CREATE ON APP.SCHEMA.EXTRA BEGIN NULL; END;"+ ))+ .is_err());+ }++ #[test]+ fn schema_scope_is_qualified_only_with_the_verified_scope_owner() {+ let mut request = input("CREATE TRIGGER APP.T AFTER CREATE ON SCHEMA BEGIN NULL; END;");+ request.purpose = OracleTriggerSqlPurpose::Create;+ request.binding = Some(scope("SCHEMA", Some(" Scope Owner ")));+ let prepared = prepare_oracle_trigger_sql(request.clone()).unwrap();+ assert!(prepared.definition.contains("ON \" Scope Owner \".SCHEMA"));+ request.source = request.source.replace("ON SCHEMA", "ON OTHER.SCHEMA");+ assert!(prepare_oracle_trigger_sql(request).is_err());+ }++ #[test]+ fn database_scope_is_not_prefixed_with_a_schema_and_pluggable_is_bound() {+ let mut request = input("CREATE TRIGGER APP.T AFTER LOGON ON DATABASE BEGIN NULL; END;");+ request.purpose = OracleTriggerSqlPurpose::Create;+ request.binding = Some(scope("DATABASE", None));+ assert!(prepare_oracle_trigger_sql(request.clone()).unwrap().definition.contains("ON DATABASE"));+ request.source = request.source.replace("ON DATABASE", "ON PLUGGABLE DATABASE");+ assert!(prepare_oracle_trigger_sql(request.clone()).is_err());+ request.binding.as_mut().unwrap().pluggable = true;+ assert!(prepare_oracle_trigger_sql(request).unwrap().header.pluggable);+ }++ #[test]+ fn nested_table_instead_of_requires_a_view_and_edits_only_its_reference() {+ let mut request = input("CREATE TRIGGER APP.T INSTEAD OF INSERT ON NESTED TABLE \"Items\" OF ORDERS REFERENCING NEW AS N FOR EACH ROW BEGIN NULL; END;");+ request.purpose = OracleTriggerSqlPurpose::Replace;+ request.enabled = Some(true);+ request.binding = Some(relation("DATA", "ORDERS", false));+ assert!(prepare_oracle_trigger_sql(request.clone()).is_err());+ request.binding = Some(relation("DATA", "ORDERS", true));+ let prepared = prepare_oracle_trigger_sql(request).unwrap();+ assert!(prepared.definition.contains("ON NESTED TABLE \"Items\" OF \"DATA\".\"ORDERS\" REFERENCING NEW AS N"));+ }++ #[test]+ fn compound_crossedition_when_and_ordering_clauses_are_preserved_and_state_is_top_level_only() {+ for source in [+ "CREATE OR REPLACE EDITIONABLE TRIGGER APP.T FOR UPDATE OF V ON DATA.ORDERS REFERENCING NEW AS N FOLLOWS APP.EARLIER DISABLE WHEN (N.V > 0) COMPOUND TRIGGER BEFORE EACH ROW IS BEGIN NULL; END BEFORE EACH ROW; END T;",+ "CREATE OR REPLACE EDITIONABLE TRIGGER APP.T BEFORE UPDATE OF V ON DATA.ORDERS REFERENCING NEW AS N FOR EACH ROW FORWARD CROSSEDITION FOLLOWS APP.EARLIER DISABLE WHEN (N.V > 0) DECLARE \"ENABLE\" NUMBER; BEGIN NULL; END;",+ ] {+ let mut request = input(source);+ request.purpose = OracleTriggerSqlPurpose::Replace; request.enabled = Some(false);+ request.binding = Some(relation("DATA", "ORDERS", false));+ let prepared = prepare_oracle_trigger_sql(request).unwrap();+ assert!(prepared.definition.contains("REFERENCING NEW AS N"));+ assert!(prepared.definition.contains("FOLLOWS APP.EARLIER DISABLE WHEN (N.V > 0)"));+ assert!(prepared.definition.ends_with(if source.contains("COMPOUND") { "END T;" } else { "END;" }));+ }+ }++ #[test]+ fn create_removes_replace_without_losing_comments_and_replace_preserves_inline_disabled_in_one_statement() {+ let source = "CREATE /*a*/ OR /*b*/ REPLACE /*c*/ TRIGGER APP /*d*/ . /*e*/ T BEFORE INSERT ON DATA /*f*/ . /*g*/ ORDERS BEGIN DBMS_OUTPUT.PUT_LINE('ENABLE ON OTHER'); END;";+ let mut request = input(source);+ request.purpose = OracleTriggerSqlPurpose::Create;+ request.binding = Some(relation("DATA", "ORDERS", false));+ request.enabled = Some(false);+ let prepared = prepare_oracle_trigger_sql(request.clone()).unwrap();+ for comment in ["/*a*/", "/*b*/", "/*c*/", "/*d*/", "/*e*/", "/*f*/", "/*g*/"] {+ assert!(prepared.definition.contains(comment));+ }+ assert!(!prepared.definition.contains("REPLACE"));+ assert!(prepared.definition.contains("DISABLE\nBEGIN DBMS_OUTPUT.PUT_LINE('ENABLE ON OTHER'); END;"));+ request.purpose = OracleTriggerSqlPurpose::Replace;+ let prepared = prepare_oracle_trigger_sql(request.clone()).unwrap();+ assert!(prepared.definition.contains("OR /*b*/ REPLACE"));+ assert!(!prepared.requires_state_restore);+ request.enabled = None;+ assert!(prepare_oracle_trigger_sql(request).is_err());+ }++ #[test]+ fn dm_timer_and_double_slash_comments_keep_native_text_and_require_explicit_state_restoration() {+ let source = "// ' ON WRONG BEGIN\nCREATE TRIGGER APP.T AFTER TIMER ON DATABASE FOR EACH 1 DAY FOR EACH 1 MINUTE BEGIN DBMS_OUTPUT.PUT_LINE(q'[// ON WRONG DISABLE]'); // ' END;\n NULL; END;";+ let mut request = input(source);+ request.database_type = DatabaseType::Dameng;+ request.purpose = OracleTriggerSqlPurpose::Replace;+ request.enabled = Some(false);+ request.binding = Some(scope("TIMER", None));+ let prepared = prepare_oracle_trigger_sql(request).unwrap();+ assert_eq!(prepared.header.scope, "TIMER");+ assert!(prepared.requires_state_restore);+ assert!(prepared.definition.contains("AFTER TIMER ON DATABASE FOR EACH 1 DAY FOR EACH 1 MINUTE"));+ assert!(prepared.definition.starts_with("// ' ON WRONG BEGIN\nCREATE OR REPLACE TRIGGER"));+ assert!(prepared.definition.contains("q'[// ON WRONG DISABLE]'"));+ assert!(prepared.definition.contains("// ' END;\n NULL; END;"));+ }++ #[test]+ fn call_body_is_complete_but_does_not_admit_a_second_statement() {+ let source = "CREATE TRIGGER APP.T AFTER INSERT ON DATA.ORDERS CALL APP.P(:NEW.V, f('ON'));";+ assert!(prepare_oracle_trigger_sql(input(source)).is_ok());+ for routine in ["APP.PKG.P", "APP.P@REMOTE"] {+ assert!(prepare_oracle_trigger_sql(input(&source.replace("APP.P(", &format!("{routine}(")))).is_ok());+ }+ for source in [+ source.replace("f('ON'));", "f('ON');"),+ format!("{source} DROP TABLE DATA.ORDERS;"),+ source.replace("CALL APP.P", "CALL APP.P SELECT EXTRA"),+ ] {+ assert!(prepare_oracle_trigger_sql(input(&source)).is_err(), "{source}");+ }+ }++ #[test]+ fn partial_body_extra_sql_and_ambiguous_headers_cannot_be_promoted_to_complete_sources() {+ for source in [+ "BEGIN NULL; END;",+ "TRIGGER APP.T BEFORE INSERT ON DATA.ORDERS BEGIN NULL;",+ "TRIGGER APP.T BEFORE INSERT ON DATA.ORDERS BEGIN IF 1=1 THEN NULL; END IF;",+ "TRIGGER APP.T BEFORE INSERT ON DATA.ORDERS ENABLE DISABLE BEGIN NULL; END;",+ "TRIGGER APP.T BEFORE INSERT ON DATA.ORDERS ON OTHER BEGIN NULL; END;",+ "TRIGGER APP.T BEFORE INSERT ON DATA.ORDERS BEGIN NULL; END; SELECT 1 FROM DUAL;",+ "CREATE PROCEDURE APP.T AS BEGIN NULL; END;",+ ] {+ assert!(prepare_oracle_trigger_sql(input(source)).is_err(), "{source}");+ }+ }++ #[test]+ fn long_unicode_crlf_source_keeps_comments_and_body_bytes_through_header_edits() {+ let body = format!("BEGIN\r\n/* {} */\r\nNULL; END; -- 尾注释\r\n", "中文😀 ON ENABLE DISABLE ".repeat(8_000));+ let mut request = input(&format!("-- 😀\r\nCREATE TRIGGER APP.T BEFORE INSERT ON DATA.ORDERS\r\n{body}"));+ request.purpose = OracleTriggerSqlPurpose::Replace;+ request.enabled = Some(false);+ request.binding = Some(relation("DATA", "ORDERS", false));+ let prepared = prepare_oracle_trigger_sql(request).unwrap();+ assert!(prepared.definition.ends_with(&body));+ assert!(prepared.definition.contains("ON \"DATA\".\"ORDERS\"\r\nDISABLE\nBEGIN\r\n"));+ }+}diff --git a/crates/dbx-sql-core/src/sql.rs b/crates/dbx-sql-core/src/sql.rsindex 9a9f45f1c2..54e3ab9c2b 100644--- a/crates/dbx-sql-core/src/sql.rs+++ b/crates/dbx-sql-core/src/sql.rs@@ -1144,7 +1144,7 @@ fn is_identifier_continue_char(ch: char) -> bool {}/// Whether the text before a quote ends in an Oracle `q`/`nq` introducer token.-fn ends_with_oracle_q_quote_prefix(text: &str) -> bool {+pub(crate) fn ends_with_oracle_q_quote_prefix(text: &str) -> bool {let mut chars = text.chars().rev();if !matches!(chars.next(), Some('q' | 'Q')) {return false;@@ -1172,7 +1172,7 @@ fn oracle_q_quote_closer(opening: char) -> Option<char> {/// Byte index just past the closing quote of the `q'...'` literal whose opening/// quote sits at `quote_index`, or `None` when the literal is not well formed.-fn oracle_q_quote_end(sql: &str, quote_index: usize) -> Option<usize> {+pub(crate) fn oracle_q_quote_end(sql: &str, quote_index: usize) -> Option<usize> {let opening = next_char_at(sql, quote_index + 1)?;let closer = oracle_q_quote_closer(opening)?;let content_start = quote_index + 1 + opening.len_utf8();diff --git a/crates/dbx-sql-schema/src/db_admin_sql.rs b/crates/dbx-sql-schema/src/db_admin_sql.rsindex 7956135795..1981f5d550 100644--- a/crates/dbx-sql-schema/src/db_admin_sql.rs+++ b/crates/dbx-sql-schema/src/db_admin_sql.rs@@ -15,6 +15,7 @@ pub enum DatabaseObjectType {Procedure,Function,Event,+ Trigger,Type,TypeBody,}@@ -1034,6 +1035,9 @@ pub fn build_copy_table_data_sql(options: CopyTableDataSqlOptions) -> String {}pub fn supports_object_rename(database_type: Option<DatabaseType>, object_type: DatabaseObjectType) -> bool {+ if object_type == DatabaseObjectType::Trigger {+ return false;+ }let Some(database_type) = database_type else {return false;};@@ -1365,6 +1369,7 @@ fn object_type_keyword(object_type: DatabaseObjectType) -> &'static str {DatabaseObjectType::Procedure => "PROCEDURE",DatabaseObjectType::Function => "FUNCTION",DatabaseObjectType::Event => "EVENT",+ DatabaseObjectType::Trigger => "TRIGGER",DatabaseObjectType::Type => "TYPE",DatabaseObjectType::TypeBody => "TYPE BODY",}@@ -2292,6 +2297,27 @@ mod tests {}}+ #[test]+ fn trigger_drop_transport_preserves_exact_identity_without_enabling_rename() {+ for database_type in ["oracle", "oceanbase-oracle", "dameng"] {+ let options: DropObjectSqlOptions = serde_json::from_value(serde_json::json!({+ "databaseType": database_type,+ "objectType": "TRIGGER",+ "schema": " Owner ",+ "name": " Tr\"igger ",+ "signature": "must_not_be_appended"+ }))+ .unwrap();+ let object_type = options.object_type;+ assert_eq!(build_drop_object_sql(options), "DROP TRIGGER \" Owner \".\" Tr\"\"igger \";");+ for rename_database in+ [DatabaseType::Oracle, DatabaseType::OceanbaseOracle, DatabaseType::Dameng, DatabaseType::SqlServer]+ {+ assert!(!supports_object_rename(Some(rename_database), object_type));+ }+ }+ }+#[test]fn kingbase_drop_object_sql_preserves_routine_signature() {for (object_type, keyword) indiff --git a/crates/dbx-sql-schema/src/lib.rs b/crates/dbx-sql-schema/src/lib.rsindex c364c8138f..af7361144c 100644--- a/crates/dbx-sql-schema/src/lib.rs+++ b/crates/dbx-sql-schema/src/lib.rs@@ -5,6 +5,9 @@ pub use dbx_sql_dialect::sql_dialect;pub use dbx_types::{database_manifest, models, types};pub mod db_admin_sql;+pub mod native_job_arguments;+pub mod native_job_changes;+pub mod native_jobs;pub mod schema_diff;pub mod sql_parser;pub mod table_structure_sql;diff --git a/crates/dbx-sql-schema/src/native_job_arguments.rs b/crates/dbx-sql-schema/src/native_job_arguments.rsnew file mode 100644index 0000000000..c8c1303961--- /dev/null+++ b/crates/dbx-sql-schema/src/native_job_arguments.rs@@ -0,0 +1,677 @@+//! Lossless Oracle Scheduler argument values. This codec is separate from general SQL values.++use dbx_types::native_jobs::{NativeJobArgumentValue, NativeJobRow};+use serde_json::{json, Value};++mod characters;+mod civil;+mod identity;+mod scalars;+pub use civil::{civil_date_query, editable_argument, normalize_civil_date};+pub use identity::{anydata_join, anydata_query_prefix, ScalarType};++/// Fixed catalog columns only; no identifier or accessor is supplied by a client.+#[derive(Clone, Copy)]+pub enum AnydataColumn {+ JobArgument,+ ProgramDefault,+}++pub fn anydata_projection(column: AnydataColumn) -> String {+ let column = column.sql();+ let type_name = format!("{column}.GetTypeName()");+ let null_access = ScalarType::ALL+ .into_iter()+ .map(|kind| {+ format!("WHEN '{}' THEN CASE WHEN {column}.{}() IS NULL THEN 1 ELSE 0 END", kind.token(), kind.access())+ })+ .collect::<Vec<_>>()+ .join(" ");+ let values = scalars::projection(column);+ format!(+ "CASE WHEN {column} IS NOT NULL THEN 1 ELSE 0 END AS DBX_ANYDATA_PRESENT, \+ CASE WHEN {column} IS NOT NULL THEN {type_name} END AS DBX_ANYDATA_TYPE, \+ DBX_AT.CODEC AS DBX_ANYDATA_CODEC, DBX_AT.TYPE_NAME AS DBX_ANYDATA_CONSTRUCTOR_TYPE, \+ CASE WHEN {column} IS NOT NULL THEN CASE DBX_AT.CODEC {null_access} ELSE NULL END END AS DBX_ANYDATA_IS_NULL, \+ CASE WHEN {column} IS NOT NULL THEN CASE DBX_AT.CODEC \+ WHEN 'number' THEN TO_CHAR({column}.AccessNumber(), 'TM9', 'NLS_NUMERIC_CHARACTERS=''.,''') \+ WHEN 'interval-ym' THEN TO_CHAR(EXTRACT(YEAR FROM {column}.AccessIntervalYM()) * 12 + EXTRACT(MONTH FROM {column}.AccessIntervalYM()), 'TM9', 'NLS_NUMERIC_CHARACTERS=''.,''') \+ WHEN 'interval-ds' THEN TO_CHAR((EXTRACT(DAY FROM {column}.AccessIntervalDS()) * 86400 + EXTRACT(HOUR FROM {column}.AccessIntervalDS()) * 3600 + EXTRACT(MINUTE FROM {column}.AccessIntervalDS()) * 60 + EXTRACT(SECOND FROM {column}.AccessIntervalDS())) * 1000000000, 'TM9', 'NLS_NUMERIC_CHARACTERS=''.,''') \+ WHEN 'urowid' THEN ROWIDTOCHAR({column}.AccessURowid()) ELSE NULL END END AS DBX_ANYDATA_TEXT, {values}"+ )+}++pub fn scalar_envelope(value: &Value) -> Result<ArgumentExpectation, &'static str> {+ let object = value.as_object().ok_or("native_job_argument_value_invalid")?;+ if object.len() != 3 || object.get("$dbx").and_then(Value::as_str) != Some("oracle-anydata-v1") {+ return Err("native_job_argument_value_invalid");+ }+ let kind = match (object.get("typeName"), object.get("scalarType")) {+ (Some(Value::String(name)), None) if name == "SYS.NUMBER" => ScalarType::Number,+ (None, Some(Value::String(token))) => {+ ScalarType::from_token(token).ok_or("native_job_argument_value_invalid")?+ }+ _ => return Err("native_job_argument_value_invalid"),+ };+ let value = object.get("value").ok_or("native_job_argument_value_invalid")?;+ let value = if object.contains_key("scalarType") && value.is_null() {+ None+ } else {+ Some(scalars::normalize(kind, value)?)+ };+ Ok(ArgumentExpectation { scalar_type: kind, value })+}++pub fn scalar_anydata_expression(value: &Value) -> Result<(String, ArgumentExpectation), &'static str> {+ let expected = scalar_envelope(value)?;+ Ok((scalars::expression(&expected)?, expected))+}++/// The optional setter is generated by the Job builder; a missing setter performs no writes.+pub fn scalar_value_block(value: &Value, setter: Option<&str>) -> Result<(String, ArgumentExpectation), &'static str> {+ let expected = scalar_envelope(value)?;+ let character = expected.value.is_some()+ && matches!(+ expected.scalar_type,+ ScalarType::Varchar2 | ScalarType::Char | ScalarType::Nvarchar2 | ScalarType::Nchar+ );+ let extra = if character { characters::declarations() } else { "" };+ let construction = if character {+ characters::construction(&expected)?+ } else {+ format!("l_anydata := {}; ", scalars::expression(&expected)?)+ };+ let validation = scalars::validation(&expected)?;+ let kind = expected.scalar_type.token();+ let prefix = anydata_query_prefix();+ let sql = format!("DECLARE l_anydata SYS.ANYDATA; l_type_name VARCHAR2(4000); l_match_count PLS_INTEGER; {extra} BEGIN {construction} IF l_anydata IS NULL THEN RAISE_APPLICATION_ERROR(-20001, 'native_job_argument_conversion_loss'); END IF; l_type_name := l_anydata.GetTypeName(); {prefix}SELECT COUNT(*) INTO l_match_count FROM DBX_ANYDATA_UNIQUE WHERE CODEC = '{kind}' AND SYS.UTL_RAW.CAST_TO_RAW(TYPE_NAME) = SYS.UTL_RAW.CAST_TO_RAW(l_type_name); IF l_match_count <> 1 THEN RAISE_APPLICATION_ERROR(-20001, 'native_job_argument_type_unverified'); END IF; {validation}{} END;", setter.unwrap_or(""));+ Ok((sql, expected))+}++/// Parse an explicit envelope only. JSON-looking strings retain their original string contract.+pub fn number_envelope(value: &Value) -> Result<ArgumentExpectation, &'static str> {+ let object = value.as_object().ok_or("native_job_argument_value_invalid")?;+ if object.len() != 3+ || object.get("$dbx").and_then(Value::as_str) != Some("oracle-anydata-v1")+ || object.get("typeName").and_then(Value::as_str) != Some("SYS.NUMBER")+ {+ return Err("native_job_argument_value_invalid");+ }+ let value = object.get("value").and_then(Value::as_str).ok_or("native_job_argument_value_invalid")?;+ Ok(ArgumentExpectation { scalar_type: ScalarType::Number, value: Some(Value::String(normalize_number(value)?)) })+}++pub fn number_anydata_expression(value: &Value) -> Result<(String, NativeJobArgumentValue), &'static str> {+ let scalar = number_envelope(value)?;+ let Some(Value::String(number)) = &scalar.value else { unreachable!() };+ Ok((format!("SYS.ANYDATA.ConvertNumber({number})"), scalar.editable_value()))+}++pub fn null_anydata_expression(data_type: &str) -> Result<(String, ArgumentExpectation), &'static str> {+ let kind = match data_type.to_ascii_uppercase().as_str() {+ "VARCHAR2" | "VARCHAR" | "CHAR" => ScalarType::Varchar2,+ "NUMBER" | "INTEGER" => ScalarType::Number,+ "DATE" => ScalarType::Date,+ "TIMESTAMP" => ScalarType::Timestamp,+ "TIMESTAMP WITH TIME ZONE" => ScalarType::TimestampTz,+ "TIMESTAMP WITH LOCAL TIME ZONE" => ScalarType::TimestampLtz,+ "NVARCHAR2" => ScalarType::Nvarchar2,+ "NCHAR" => ScalarType::Nchar,+ "INTERVAL YEAR TO MONTH" => ScalarType::IntervalYm,+ "INTERVAL DAY TO SECOND" => ScalarType::IntervalDs,+ "RAW" => ScalarType::Raw,+ "BINARY_FLOAT" => ScalarType::BinaryFloat,+ "BINARY_DOUBLE" => ScalarType::BinaryDouble,+ "UROWID" => ScalarType::Urowid,+ _ => return Err("native_job_argument_type_required_for_null"),+ };+ Ok((kind.null_expression(), ArgumentExpectation { scalar_type: kind, value: None }))+}++pub fn oracle_argument_matches(row: &NativeJobRow, desired: &NativeJobArgumentValue, data_type: &str) -> bool {+ let expected = match desired {+ NativeJobArgumentValue::Null => null_anydata_expression(data_type).map(|(_, storage)| storage),+ NativeJobArgumentValue::Value { value: Value::String(text) } if text.is_empty() => {+ null_anydata_expression(data_type).map(|(_, storage)| storage)+ }+ NativeJobArgumentValue::Value { value: Value::String(text) } => {+ return decode_argument(row, false) == ArgumentStorage::Text(text.clone())+ }+ NativeJobArgumentValue::Value { value } => scalar_envelope(value),+ _ => return false,+ };+ expected.is_ok_and(|expected| expected.matches(&decode_argument(row, false)))+}++pub fn canonical_argument_row(row: &NativeJobRow, default_value: bool) -> NativeJobRow {+ let storage = decode_argument(row, default_value);+ if matches!(storage, ArgumentStorage::Opaque(_)) {+ return row.clone();+ }+ let mut canonical = row.clone();+ canonical.retain(|key, _| {+ !matches!(+ key.as_str(),+ "DBX_ANYDATA_PRESENT"+ | "DBX_ANYDATA_TYPE"+ | "DBX_ANYDATA_IS_NULL"+ | "DBX_ANYDATA_TEXT"+ | "DBX_ANYDATA_CODEC"+ | "DBX_ANYDATA_CONSTRUCTOR_TYPE"+ | "DBX_ANYDATA_DAY"+ | "DBX_ANYDATA_SECONDS"+ | "DBX_ANYDATA_TZ_REGION"+ | "DBX_ANYDATA_TZ_OFFSET"+ | "DBX_ANYDATA_TZ_ABBR"+ | "DBX_ANYDATA_HEX"+ | "DBX_ANYDATA_LENGTH"+ | "DBX_ARGUMENT_DEFAULT"+ | "DBX_ANYDATA_CIVIL_DATE"+ ) && if default_value {+ !matches!(key.as_str(), "DEFAULT_VALUE" | "DEFAULT_ANYDATA_VALUE")+ } else {+ !matches!(key.as_str(), "VALUE" | "ANYDATA_VALUE")+ }+ });+ canonical.insert("DBX_ARGUMENT_CANONICAL".into(), storage.canonical_value());+ canonical+}++pub fn validate_lightweight_argument(style: Option<&str>, value: &NativeJobArgumentValue) -> Result<(), &'static str> {+ let string_setter_or_reset = match value {+ NativeJobArgumentValue::Unset | NativeJobArgumentValue::Inherit => true,+ NativeJobArgumentValue::Value { value: Value::String(text) } => !text.is_empty(),+ _ => false,+ };+ if style.is_some_and(|style| style.eq_ignore_ascii_case("LIGHTWEIGHT")) && !string_setter_or_reset {+ return Err("native_job_lightweight_anydata_unsupported");+ }+ Ok(())+}++/// Storage identity is part of equality: a VARCHAR override and ANYDATA VARCHAR2 are not interchangeable.+#[derive(Clone, PartialEq)]+pub enum ArgumentStorage {+ Text(String),+ TypedNull { type_name: String, scalar_type: ScalarType },+ Scalar { type_name: String, scalar_type: ScalarType, value: Value },+ Opaque(NativeJobRow),+}++impl ArgumentStorage {+ pub fn editable_value(&self) -> NativeJobArgumentValue {+ match self {+ Self::Text(value) => NativeJobArgumentValue::Value { value: Value::String(value.clone()) },+ Self::TypedNull { scalar_type, .. } => {+ ArgumentExpectation { scalar_type: *scalar_type, value: None }.editable_value()+ }+ Self::Scalar { scalar_type, value, .. } => {+ ArgumentExpectation { scalar_type: *scalar_type, value: Some(value.clone()) }.editable_value()+ }+ Self::Opaque(row) => NativeJobArgumentValue::Opaque { value: json!(row) },+ }+ }++ /// Excludes driver-specific locator text only after a complete value has been decoded.+ pub fn canonical_value(&self) -> Value {+ match self {+ Self::Text(value) => json!({"storage": "varchar", "value": value}),+ Self::TypedNull { type_name, scalar_type } => {+ json!({"storage": "anydata", "typeName": type_name, "scalarType": scalar_type.token(), "isNull": true})+ }+ Self::Scalar { type_name, scalar_type, value } => {+ json!({"storage": "anydata", "typeName": type_name, "scalarType": scalar_type.token(), "isNull": false, "value": value})+ }+ Self::Opaque(row) => json!({"storage": "opaque", "row": row}),+ }+ }+}++#[derive(Clone)]+pub struct ArgumentExpectation {+ pub scalar_type: ScalarType,+ pub value: Option<Value>,+}++impl ArgumentExpectation {+ pub fn editable_value(&self) -> NativeJobArgumentValue {+ match &self.value {+ None => NativeJobArgumentValue::Value {+ value: json!({"$dbx":"oracle-anydata-v1", "scalarType":self.scalar_type.token(), "value":null}),+ },+ Some(value) => NativeJobArgumentValue::Value {+ value: if self.scalar_type == ScalarType::Number {+ json!({"$dbx":"oracle-anydata-v1", "typeName":"SYS.NUMBER", "value":value})+ } else {+ json!({"$dbx":"oracle-anydata-v1", "scalarType":self.scalar_type.token(), "value":value})+ },+ },+ }+ }++ pub fn matches(&self, actual: &ArgumentStorage) -> bool {+ match (actual, &self.value) {+ (ArgumentStorage::TypedNull { scalar_type, .. }, None) => *scalar_type == self.scalar_type,+ (ArgumentStorage::Scalar { scalar_type, value, .. }, Some(expected)) => {+ *scalar_type == self.scalar_type && value == expected+ }+ _ => false,+ }+ }+}++fn projected_boolean(value: Option<&Value>) -> Option<bool> {+ match value? {+ Value::Bool(value) => Some(*value),+ Value::Number(value) if value.as_u64() == Some(0) => Some(false),+ Value::Number(value) if value.as_u64() == Some(1) => Some(true),+ Value::String(value) if value == "0" || value.eq_ignore_ascii_case("false") => Some(false),+ Value::String(value) if value == "1" || value.eq_ignore_ascii_case("true") => Some(true),+ _ => None,+ }+}++/// Decode only proven native values. Presence never falls back to a misleading VALUE column.+/// `default_value` selects the Program-default column; projected evidence uses the same aliases.+pub fn decode_argument(row: &NativeJobRow, default_value: bool) -> ArgumentStorage {+ let opaque = || ArgumentStorage::Opaque(row.clone());+ if row.get("OUT_ARGUMENT").is_some_and(|value| projected_boolean(Some(value)) != Some(false)) {+ return opaque();+ }+ match projected_boolean(row.get("DBX_ANYDATA_PRESENT")) {+ Some(false) => {+ let column = if default_value { "DEFAULT_VALUE" } else { "VALUE" };+ row.get(column)+ .and_then(Value::as_str)+ .map(|value| ArgumentStorage::Text(value.into()))+ .unwrap_or_else(opaque)+ }+ Some(true) => {+ let Some(type_name) = row.get("DBX_ANYDATA_TYPE").and_then(Value::as_str) else { return opaque() };+ let Some(scalar_type) = identity::proven_type(row, type_name) else {+ return opaque();+ };+ match projected_boolean(row.get("DBX_ANYDATA_IS_NULL")) {+ Some(true) => ArgumentStorage::TypedNull { type_name: type_name.into(), scalar_type },+ Some(false) => {+ let Ok(value) = scalars::projected_value(scalar_type, row) else {+ return opaque();+ };+ ArgumentStorage::Scalar { type_name: type_name.into(), scalar_type, value }+ }+ None => opaque(),+ }+ }+ None => opaque(),+ }+}++/// Canonicalize an exactly representable Oracle NUMBER without floating-point conversion.+pub fn normalize_number(value: &str) -> Result<String, &'static str> {+ const INVALID: &str = "native_job_argument_value_invalid";+ let mut parts = value.split(['e', 'E']);+ let mantissa = parts.next().ok_or(INVALID)?;+ let exponent = match parts.next() {+ Some(value) => value.parse::<i64>().map_err(|_| INVALID)?,+ None => 0,+ };+ if parts.next().is_some() {+ return Err(INVALID);+ }+ let negative = mantissa.starts_with('-');+ let unsigned = mantissa.strip_prefix(['+', '-']).unwrap_or(mantissa);+ let mut decimal_seen = false;+ let mut fractional_digits = 0_i64;+ let mut digits = String::with_capacity(unsigned.len());+ for byte in unsigned.bytes() {+ match byte {+ b'.' if !decimal_seen => decimal_seen = true,+ b'0'..=b'9' => {+ digits.push(char::from(byte));+ if decimal_seen {+ fractional_digits = fractional_digits.checked_add(1).ok_or(INVALID)?;+ }+ }+ _ => return Err(INVALID),+ }+ }+ if digits.is_empty() {+ return Err(INVALID);+ }+ let significant = digits.trim_start_matches('0');+ if significant.is_empty() {+ return Ok("0".into());+ }+ let coefficient = significant.trim_end_matches('0');+ let trailing_zeros = i64::try_from(significant.len() - coefficient.len()).map_err(|_| INVALID)?;+ let low = exponent.checked_sub(fractional_digits).and_then(|n| n.checked_add(trailing_zeros)).ok_or(INVALID)?;+ let high = low.checked_add(i64::try_from(coefficient.len() - 1).map_err(|_| INVALID)?).ok_or(INVALID)?;+ // Each base-100 digit spans powers 2n and 2n+1, also for negative powers.+ // Removing decimal trailing zeroes does not remove a partial base-100 digit.+ if !(-130..=125).contains(&high) || high.div_euclid(2) - low.div_euclid(2) + 1 > 20 {+ return Err(INVALID);+ }+ let sign = if negative { "-" } else { "" };+ let fraction = if coefficient.len() > 1 { format!(".{}", &coefficient[1..]) } else { String::new() };+ Ok(format!("{sign}{}{fraction}E{high}", &coefficient[..1]))+}++#[cfg(test)]+mod tests {+ use super::*;++ fn number_row(value: Value) -> NativeJobRow {+ serde_json::from_value(json!({+ "DBX_ANYDATA_PRESENT": 1, "DBX_ANYDATA_TYPE": "SYS.NUMBER",+ "DBX_ANYDATA_IS_NULL": 0, "DBX_ANYDATA_TEXT": value,+ "ANYDATA_VALUE": "driver locator", "VALUE": "misleading fallback"+ }))+ .unwrap()+ }++ #[test]+ fn explicit_number_envelope_is_canonical_and_safe_to_construct() {+ let input = json!({"$dbx": "oracle-anydata-v1", "typeName": "SYS.NUMBER", "value": "9007199254740993.123"});+ let (expression, expected) = number_anydata_expression(&input).unwrap();+ assert_eq!(expression, "SYS.ANYDATA.ConvertNumber(9.007199254740993123E15)");+ assert!(expected == decode_argument(&number_row(json!("9007199254740993.123")), false).editable_value());+ for input in [+ json!(input.to_string()),+ json!({"$dbx": "oracle-anydata-v1", "typeName": "SYS.NUMBER", "value": null}),+ json!({"$dbx": "oracle-anydata-v1", "typeName": "SYS.NUMBER", "value": 123}),+ json!({"$dbx": "oracle-anydata-v1", "typeName": "SYS.NUMBER", "value": "1); END;--"}),+ json!({"$dbx": "oracle-anydata-v1", "typeName": "APP.NUMBER", "value": "1"}),+ json!({"$dbx": "oracle-anydata-v1", "typeName": "SYS.NUMBER", "value": "1", "sql": "ignored?"}),+ ] {+ assert!(number_anydata_expression(&input).is_err());+ }+ }++ #[test]+ fn every_null_scalar_uses_a_closed_constructor_and_proven_native_identity() {+ for kind in ScalarType::ALL {+ let native_name = kind.fixed_name().unwrap_or("native-name-from-this-constructor");+ let row: NativeJobRow = serde_json::from_value(json!({+ "DBX_ANYDATA_PRESENT":1, "DBX_ANYDATA_TYPE":native_name,+ "DBX_ANYDATA_CODEC":kind.token(), "DBX_ANYDATA_CONSTRUCTOR_TYPE":native_name,+ "DBX_ANYDATA_IS_NULL":1, "VALUE":"misleading fallback"+ }))+ .unwrap();+ let expected = ArgumentExpectation { scalar_type: kind, value: None };+ assert!(expected.matches(&decode_argument(&row, false)), "{}", kind.token());+ let mut changed_name = row.clone();+ changed_name.insert("DBX_ANYDATA_TYPE".into(), json!("other-name"));+ assert!(matches!(decode_argument(&changed_name, false), ArgumentStorage::Opaque(_)));+ for key in ["DBX_ANYDATA_CODEC", "DBX_ANYDATA_CONSTRUCTOR_TYPE"] {+ let mut incomplete = row.clone();+ incomplete.remove(key);+ assert!(matches!(decode_argument(&incomplete, false), ArgumentStorage::Opaque(_)));+ }+ let different = ArgumentExpectation {+ scalar_type: if kind == ScalarType::Date { ScalarType::Number } else { ScalarType::Date },+ value: None,+ };+ assert!(!different.matches(&decode_argument(&row, false)));+ }+ let prefix = anydata_query_prefix();+ for kind in ScalarType::ALL {+ assert!(prefix.contains(&format!("SELECT '{}' AS CODEC", kind.token())));+ }+ assert!(prefix.contains("P0.T2.GetTypeName()"));+ assert!(prefix.contains("GROUP BY SYS.UTL_RAW.CAST_TO_RAW(TYPE_NAME) HAVING COUNT(*) = 1"));+ assert!(!prefix.contains("SYS.NVARCHAR2'"));+ assert!(!prefix.contains("SYS.INTERVALYM'"));+ }++ #[test]+ fn collided_or_incomplete_constructor_evidence_never_turns_a_mismatched_accessor_into_null() {+ for name in ["SYS.CHAR", "SYS.VARCHAR2"] {+ let mut row: NativeJobRow = serde_json::from_value(json!({+ "DBX_ANYDATA_PRESENT":1, "DBX_ANYDATA_TYPE":name,+ "DBX_ANYDATA_CODEC":null, "DBX_ANYDATA_CONSTRUCTOR_TYPE":null,+ "DBX_ANYDATA_IS_NULL":1, "VALUE":"fallback must not be used"+ }))+ .unwrap();+ assert!(matches!(decode_argument(&row, false), ArgumentStorage::Opaque(_)));+ row.insert("DBX_ANYDATA_CODEC".into(), json!("nvarchar2"));+ assert!(matches!(decode_argument(&row, false), ArgumentStorage::Opaque(_)));+ }+ for data_type in [+ "NVARCHAR2",+ "NCHAR",+ "TIMESTAMP WITH LOCAL TIME ZONE",+ "INTERVAL YEAR TO MONTH",+ "INTERVAL DAY TO SECOND",+ "RAW",+ "BINARY_FLOAT",+ "BINARY_DOUBLE",+ "UROWID",+ ] {+ let (sql, expected) = null_anydata_expression(data_type).unwrap();+ assert!(sql.starts_with("SYS.ANYDATA.Convert"));+ assert!(expected.value.is_none());+ }+ assert!(null_anydata_expression("NUMBER); DELETE FROM t;--").is_err());+ }++ #[test]+ fn temporal_envelopes_preserve_days_nine_digits_and_region_identity() {+ let envelope = |kind, value| json!({"$dbx":"oracle-anydata-v1","scalarType":kind,"value":value});+ let date = envelope("date", json!({"day":"0000001","seconds":"00001"}));+ let (sql, expected) = scalar_anydata_expression(&date).unwrap();+ assert_eq!(expected.value, Some(json!({"day":"1","seconds":"1"})));+ assert!(sql.contains("TO_DATE('1', 'J')"));+ assert!(sql.contains("ConvertDate"));+ let ts = envelope("timestamp", json!({"day":"2458849","seconds":"86399.123456789"}));+ let (sql, expected) = scalar_anydata_expression(&ts).unwrap();+ assert!(sql.contains("TIMESTAMP(9)"));+ assert!(sql.contains("86399.123456789"));+ let row: NativeJobRow = serde_json::from_value(json!({"DBX_ANYDATA_PRESENT":1,"DBX_ANYDATA_TYPE":"SYS.TIMESTAMP","DBX_ANYDATA_IS_NULL":0,"DBX_ANYDATA_DAY":"2458849","DBX_ANYDATA_SECONDS":"86399.123456789"})).unwrap();+ assert!(expected.matches(&decode_argument(&row, false)));+ let tz = envelope(+ "timestamp-tz",+ json!({"day":"2459526","seconds":"5400.123456789","region":"America/New_York","offset":"-04:00","abbreviation":"EDT"}),+ );+ let (sql, expected) = scalar_anydata_expression(&tz).unwrap();+ assert!(sql.contains("FROM_TZ("));+ assert!(sql.contains(", '-04:00') AT TIME ZONE 'America/New_York'"));+ let mut other_region = tz;+ other_region["value"]["region"] = json!("US/Eastern");+ assert_ne!(expected.value, scalar_envelope(&other_region).unwrap().value);+ for value in [+ json!({"day":"0","seconds":"0"}),+ json!({"day":"5373485","seconds":"0"}),+ json!({"day":"1","seconds":"86400"}),+ json!({"day":"1","seconds":"1.1234567890"}),+ ] {+ assert!(scalar_envelope(&envelope("timestamp", value)).is_err());+ }+ assert!(scalar_envelope(&envelope("date", json!({"day":"1","seconds":"1.1"}))).is_err());+ let (ltz, _) =+ scalar_anydata_expression(&envelope("timestamp-ltz", json!({"day":"2458849","seconds":"123.000000001"})))+ .unwrap();+ assert!(ltz.contains("'+00:00'"));+ assert!(ltz.contains("TIMESTAMP(9) WITH LOCAL TIME ZONE"));+ }++ #[test]+ fn explicit_typed_null_retains_constructor_identity_without_changing_legacy_nulls() {+ let row: NativeJobRow = serde_json::from_value(json!({"DBX_ANYDATA_PRESENT":1,"DBX_ANYDATA_TYPE":"SYS.CHAR","DBX_ANYDATA_CODEC":"char","DBX_ANYDATA_CONSTRUCTOR_TYPE":"SYS.CHAR","DBX_ANYDATA_IS_NULL":1})).unwrap();+ let NativeJobArgumentValue::Value { value } = decode_argument(&row, false).editable_value() else {+ panic!("typed NULL must retain its constructor")+ };+ assert_eq!(value, json!({"$dbx":"oracle-anydata-v1","scalarType":"char","value":null}));+ let (sql, expected) = scalar_value_block(&value, None).unwrap();+ assert_eq!(expected.scalar_type, ScalarType::Char);+ assert!(expected.value.is_none());+ assert!(expected.matches(&decode_argument(&row, false)));+ assert!(sql.contains("ConvertChar(CAST(NULL AS CHAR(1)))"));+ assert!(sql.contains("l_anydata.AccessChar() IS NOT NULL"));+ assert!(!sql.contains("EXECUTE IMMEDIATE"));+ let mut wrong = row;+ wrong.insert("DBX_ANYDATA_TYPE".into(), json!("SYS.VARCHAR2"));+ wrong.insert("DBX_ANYDATA_CONSTRUCTOR_TYPE".into(), json!("SYS.VARCHAR2"));+ wrong.insert("DBX_ANYDATA_CODEC".into(), json!("varchar2"));+ assert!(!expected.matches(&decode_argument(&wrong, false)));+ assert_eq!(null_anydata_expression("CHAR").unwrap().1.scalar_type, ScalarType::Varchar2);+ assert!(scalar_envelope(&json!({"$dbx":"oracle-anydata-v1","typeName":"SYS.NUMBER","value":null})).is_err());+ }++ #[test]+ fn raw_intervals_and_binary_bits_have_exact_closed_values() {+ let envelope = |kind, value| json!({"$dbx":"oracle-anydata-v1","scalarType":kind,"value":value});+ let (sql, expected) = scalar_anydata_expression(&envelope("raw", json!("00ff"))).unwrap();+ assert_eq!(expected.value, Some(json!("00FF")));+ assert!(sql.contains("HEXTORAW('00FF')"));+ let long = "AB".repeat(5_000);+ let (sql, _) = scalar_anydata_expression(&envelope("raw", json!(long))).unwrap();+ assert_eq!(sql.matches("HEXTORAW(").count(), 3);+ assert!(sql.contains("UTL_RAW.CONCAT"));+ for (kind, value) in [+ ("raw", ""),+ ("raw", "F"),+ ("raw", "01');END;--"),+ ("binary-float", "80000000"),+ ("binary-float", "7FC00001"),+ ("binary-double", "8000000000000000"),+ ("binary-double", "7FF0000000000001"),+ ] {+ assert!(scalar_anydata_expression(&envelope(kind, json!(value))).is_err(), "{kind}/{value}");+ }+ for (kind, value) in+ [("binary-float", "7F800000"), ("binary-double", "FFF0000000000000"), ("binary-float", "00000000")]+ {+ assert!(scalar_anydata_expression(&envelope(kind, json!(value))).unwrap().0.contains("UTL_RAW.BIG_ENDIAN"));+ }+ let (sql, expected) = scalar_anydata_expression(&envelope("interval-ds", json!("-86400123456789"))).unwrap();+ assert!(sql.contains("NUMTODSINTERVAL(-86400.123456789, 'SECOND')"));+ assert_eq!(expected.value, Some(json!("-86400123456789")));+ assert!(scalar_anydata_expression(&envelope("interval-ym", json!("-11999999999"))).is_ok());+ assert!(scalar_anydata_expression(&envelope("interval-ym", json!("12000000000"))).is_err());+ let mut bad = envelope("raw", json!("00"));+ bad["typeName"] = json!("SYS.RAW");+ assert!(scalar_envelope(&bad).is_err());+ }++ #[test]+ fn complete_hex_projection_retains_unicode_spaces_and_unreplayable_binary_values() {+ let mut row: NativeJobRow = serde_json::from_value(json!({"DBX_ANYDATA_PRESENT":1,"DBX_ANYDATA_TYPE":"native-national-type","DBX_ANYDATA_CODEC":"nvarchar2","DBX_ANYDATA_CONSTRUCTOR_TYPE":"native-national-type","DBX_ANYDATA_IS_NULL":0,"DBX_ANYDATA_HEX":"0041005CD83DDE000020","DBX_ANYDATA_LENGTH":"4"})).unwrap();+ let decoded = decode_argument(&row, false);+ assert!(matches!(&decoded, ArgumentStorage::Scalar { value, .. } if *value == json!("A\\😀 ")));+ row.insert("DBX_ANYDATA_LENGTH".into(), json!("5"));+ assert!(matches!(decode_argument(&row, false), ArgumentStorage::Opaque(_)));+ row.insert("DBX_ANYDATA_LENGTH".into(), json!("4"));+ row.insert("DBX_ANYDATA_HEX".into(), json!("D800"));+ assert!(matches!(decode_argument(&row, false), ArgumentStorage::Opaque(_)));+ row.extend(serde_json::from_value::<NativeJobRow>(json!({"DBX_ANYDATA_TYPE":"native-binary-type","DBX_ANYDATA_CODEC":"binary-double","DBX_ANYDATA_CONSTRUCTOR_TYPE":"native-binary-type","DBX_ANYDATA_HEX":"8000000000000000"})).unwrap());+ assert!(matches!(decode_argument(&row, false), ArgumentStorage::Opaque(_)));+ }++ #[test]+ fn anydata_presence_and_native_null_require_complete_evidence() {+ let row = number_row(json!("9007199254740993"));+ assert!(matches!(decode_argument(&row, false), ArgumentStorage::Scalar { .. }));+ for key in ["DBX_ANYDATA_PRESENT", "DBX_ANYDATA_TYPE", "DBX_ANYDATA_IS_NULL", "DBX_ANYDATA_TEXT"] {+ let mut incomplete = row.clone();+ incomplete.remove(key);+ assert!(matches!(decode_argument(&incomplete, false), ArgumentStorage::Opaque(_)), "{key}");+ }+ let mut unknown = row.clone();+ unknown.insert("DBX_ANYDATA_TYPE".into(), json!("APP.OBJECT"));+ assert!(matches!(decode_argument(&unknown, false), ArgumentStorage::Opaque(_)));+ let mut typed_null = row;+ typed_null.insert("DBX_ANYDATA_IS_NULL".into(), json!(1));+ let number_null = decode_argument(&typed_null, false);+ typed_null.insert("DBX_ANYDATA_TYPE".into(), json!("SYS.DATE"));+ assert!(number_null != decode_argument(&typed_null, false));+ assert!(+ matches!(number_null.editable_value(), NativeJobArgumentValue::Value { value } if value == json!({"$dbx":"oracle-anydata-v1","scalarType":"number","value":null}))+ );+ }++ #[test]+ fn canonical_anydata_ignores_locators_but_preserves_type_and_exact_value() {+ let original = number_row(json!("123.4500"));+ let mut changed = number_row(json!("1.2345e2"));+ changed.insert("ANYDATA_VALUE".into(), json!("another locator"));+ assert_eq!(+ decode_argument(&original, false).canonical_value(),+ decode_argument(&changed, false).canonical_value()+ );+ changed.insert("DBX_ANYDATA_TEXT".into(), json!("123.450000000000000000000000000000000001"));+ assert_ne!(+ decode_argument(&original, false).canonical_value(),+ decode_argument(&changed, false).canonical_value()+ );+ }++ #[test]+ fn defaults_prioritize_anydata_and_plain_strings_keep_their_contents() {+ let mut row = number_row(json!("1"));+ row.insert("DEFAULT_VALUE".into(), json!("wrong"));+ assert!(matches!(decode_argument(&row, true), ArgumentStorage::Scalar { .. }));+ row.insert("DBX_ANYDATA_PRESENT".into(), json!(0));+ let text = " {\"$dbx\":\"oracle-anydata-v1\"} ";+ row.insert("DEFAULT_VALUE".into(), json!(text));+ assert!(matches!(decode_argument(&row, true), ArgumentStorage::Text(value) if value == text));+ row.insert("DEFAULT_VALUE".into(), Value::Null);+ assert!(matches!(decode_argument(&row, true), ArgumentStorage::Opaque(_)));+ row.insert("OUT_ARGUMENT".into(), json!(true));+ assert!(matches!(decode_argument(&row, false), ArgumentStorage::Opaque(_)));+ }++ #[test]+ fn number_preserves_decimal_digits_and_normalizes_equivalent_spellings() {+ for (input, expected) in [+ ("9007199254740993.123456789", "9.007199254740993123456789E15"),+ ("+00123.45000e-2", "1.2345E0"),+ (".00100", "1E-3"),+ ("-100.", "-1E2"),+ ("-0.000e125", "0"),+ ("1e-130", "1E-130"),+ ("9.99e125", "9.99E125"),+ ] {+ assert_eq!(normalize_number(input), Ok(expected.into()), "{input}");+ }+ }++ #[test]+ fn number_precision_counts_base_100_digits_instead_of_decimal_digits() {+ let digits39 = "123456789012345678901234567890123456789";+ let digits40 = "1234567890123456789012345678901234567891";+ assert!(normalize_number(digits39).is_ok());+ assert!(normalize_number(digits40).is_ok());+ assert!(normalize_number(&format!("{digits39}e-1")).is_ok());+ assert!(normalize_number(&format!("{digits40}e-1")).is_err());+ assert!(normalize_number(&format!("{digits40}e1")).is_err());+ assert!(normalize_number(&format!("{digits40}00")).is_ok());+ assert!(normalize_number(&format!("{digits40}1")).is_err());+ }++ #[test]+ fn number_rejects_rounding_underflow_overflow_and_sql_fragments() {+ for value in [+ "1e-131",+ "9e-131",+ "1e126",+ "-1e126",+ "NaN",+ "Infinity",+ "",+ ".",+ "e1",+ "1e",+ "--1",+ "1e1e1",+ "1.2.3",+ " 1",+ "1 ",+ "1,2",+ "1);NULL;--",+ "1",+ "1e9223372036854775808",+ ] {+ assert!(normalize_number(value).is_err(), "{value}");+ }+ }+}diff --git a/crates/dbx-sql-schema/src/native_job_arguments/characters.rs b/crates/dbx-sql-schema/src/native_job_arguments/characters.rsnew file mode 100644index 0000000000..88cbfcdaa7--- /dev/null+++ b/crates/dbx-sql-schema/src/native_job_arguments/characters.rs@@ -0,0 +1,96 @@+use super::{ArgumentExpectation, ScalarType};++fn chunks(value: &str) -> Vec<(String, String, usize)> {+ let mut result = Vec::new();+ let mut encoded = String::new();+ let mut hex = String::new();+ let mut length = 0;+ for character in value.chars() {+ let mut units = [0; 2];+ for unit in character.encode_utf16(&mut units) {+ hex.push_str(&format!("{unit:04X}"));+ if *unit == 0x005C {+ encoded.push_str("\\\\");+ } else {+ encoded.push_str(&format!("\\{unit:04X}"));+ }+ }+ length += 1;+ if length == 256 {+ result.push((std::mem::take(&mut encoded), std::mem::take(&mut hex), length));+ length = 0;+ }+ }+ if length != 0 {+ result.push((encoded, hex, length));+ }+ result+}++fn check_piece(value: &str, hex: &str) -> String {+ format!("l_actual := SYS.UTL_I18N.STRING_TO_RAW({value}, 'AL16UTF16'); l_expected := HEXTORAW('{hex}'); IF l_actual IS NULL OR SYS.UTL_RAW.LENGTH(l_actual) <> SYS.UTL_RAW.LENGTH(l_expected) OR SYS.UTL_RAW.COMPARE(l_actual, l_expected) <> 0 THEN RAISE_APPLICATION_ERROR(-20001, 'native_job_argument_character_loss'); END IF; ")+}++pub(super) fn declarations() -> &'static str {+ "l_value_v VARCHAR2(32767 BYTE); l_value_n NVARCHAR2(32767); l_piece_v VARCHAR2(32767 BYTE); l_piece_n NVARCHAR2(32767); l_read_v VARCHAR2(32767 BYTE); l_read_n NVARCHAR2(32767); l_actual RAW(32767); l_expected RAW(32767); l_size PLS_INTEGER; "+}++pub(super) fn construction(expected: &ArgumentExpectation) -> Result<String, &'static str> {+ let value = expected+ .value+ .as_ref()+ .and_then(serde_json::Value::as_str)+ .filter(|value| !value.is_empty())+ .ok_or("native_job_argument_value_invalid")?;+ // A scalar needs at least one target byte; reject values exceeding even that native hard bound.+ if value.chars().count() > 32_767 {+ return Err("native_job_argument_character_capacity");+ }+ let pieces = chunks(value);+ let national = matches!(expected.scalar_type, ScalarType::Nvarchar2 | ScalarType::Nchar);+ let (buffer, read, piece) =+ if national { ("l_value_n", "l_read_n", "l_piece_n") } else { ("l_value_v", "l_read_v", "l_piece_v") };+ let mut body = String::new();+ for (encoded, hex, _) in &pieces {+ body.push_str(&format!("l_piece_n := UNISTR('{encoded}'); "));+ if !national {+ body.push_str("l_piece_v := TO_CHAR(l_piece_n); ");+ }+ body.push_str(&check_piece(piece, hex));+ body.push_str(&format!("IF NVL(LENGTHB({buffer}), 0) + LENGTHB({piece}) > 32767 THEN RAISE_APPLICATION_ERROR(-20001, 'native_job_argument_character_capacity'); END IF; {buffer} := {buffer} || {piece}; "));+ }+ match expected.scalar_type {+ ScalarType::Char | ScalarType::Nchar => {+ let (length, suffix) = if national { ("LENGTH", "") } else { ("LENGTHB", " BYTE") };+ let datatype = if national { "NCHAR" } else { "CHAR" };+ body.push_str(&format!("l_size := {length}({buffer}); IF l_size NOT BETWEEN 1 AND 32767 THEN RAISE_APPLICATION_ERROR(-20001, 'native_job_argument_character_capacity'); END IF; EXECUTE IMMEDIATE 'DECLARE c {datatype}(' || TO_CHAR(l_size, 'FM99990', 'NLS_NUMERIC_CHARACTERS=''.,''') || ' {suffix}); BEGIN c := :v; :a := SYS.ANYDATA.{}(c); END;' USING IN {buffer}, OUT l_anydata; ", expected.scalar_type.convert()));+ }+ ScalarType::Varchar2 | ScalarType::Nvarchar2 => {+ body.push_str(&format!("l_anydata := SYS.ANYDATA.{}({buffer}); ", expected.scalar_type.convert()))+ }+ _ => return Err("native_job_argument_value_invalid"),+ }+ body.push_str(&format!("{read} := l_anydata.{}(); IF {read} IS NULL OR LENGTH4({read}) <> {} THEN RAISE_APPLICATION_ERROR(-20001, 'native_job_argument_character_loss'); END IF; ", expected.scalar_type.access(), value.chars().count()));+ let mut start = 1;+ for (_, hex, length) in &pieces {+ body.push_str(&check_piece(&format!("SUBSTR4({read}, {start}, {length})"), hex));+ start += length;+ }+ Ok(body)+}++#[cfg(test)]+mod tests {+ use super::*;+ #[test]+ fn unicode_chunks_keep_surrogate_pairs_backslashes_and_trailing_spaces_without_literal_collisions() {+ let parts = chunks(&format!("{}\\😀' ", "中".repeat(255)));+ assert_eq!(parts.len(), 2);+ assert_eq!(parts[0].2, 256);+ assert!(parts[0].0.ends_with("\\\\"));+ assert_eq!(parts[1], ("\\D83D\\DE00\\0027\\0020".into(), "D83DDE0000270020".into(), 3));+ let literal = chunks("\\0041");+ assert_ne!(literal[0].0, chunks("A")[0].0);+ assert_eq!(literal[0].1, "005C0030003000340031");+ }+}diff --git a/crates/dbx-sql-schema/src/native_job_arguments/civil.rs b/crates/dbx-sql-schema/src/native_job_arguments/civil.rsnew file mode 100644index 0000000000..e4d4e4afc6--- /dev/null+++ b/crates/dbx-sql-schema/src/native_job_arguments/civil.rs@@ -0,0 +1,146 @@+use super::{scalar_envelope, NativeJobArgumentValue, NativeJobRow, ScalarType};+use dbx_sql_core::value_literals::quote_string_literal;+use serde_json::{json, Value};++const INVALID: &str = "native_job_argument_date_invalid";++fn valid_civil(value: &str) -> bool {+ let (negative, date) = value.strip_prefix('-').map_or((false, value), |date| (true, date));+ let bytes = date.as_bytes();+ if bytes.len() != 10+ || bytes[4] != b'-'+ || bytes[7] != b'-'+ || !bytes.iter().enumerate().all(|(index, byte)| matches!(index, 4 | 7) || byte.is_ascii_digit())+ {+ return false;+ }+ let year = date[..4].parse::<u16>().unwrap();+ let month = date[5..7].parse::<u8>().unwrap();+ let day = date[8..].parse::<u8>().unwrap();+ year != 0 && (!negative || year <= 4712) && (1..=12).contains(&month) && (1..=31).contains(&day)+}++fn input(value: &Value) -> Result<Option<&str>, &'static str> {+ let Some(payload) = value.get("value").and_then(Value::as_object) else { return Ok(None) };+ let Some(civil) = payload.get("civilDate") else { return Ok(None) };+ let kind = value.get("scalarType").and_then(Value::as_str).and_then(ScalarType::from_token).ok_or(INVALID)?;+ if !matches!(kind, ScalarType::Date | ScalarType::Timestamp | ScalarType::TimestampTz | ScalarType::TimestampLtz)+ || payload.contains_key("day")+ {+ return Err(INVALID);+ }+ let civil = civil.as_str().filter(|civil| valid_civil(civil)).ok_or(INVALID)?;+ let mut probe = value.clone();+ let payload = probe["value"].as_object_mut().unwrap();+ payload.remove("civilDate");+ payload.insert("day".into(), json!("1"));+ scalar_envelope(&probe)?;+ Ok(Some(civil))+}++pub fn civil_date_query(value: &Value) -> Result<Option<String>, &'static str> {+ let Some(civil) = input(value)? else { return Ok(None) };+ let text = if civil.starts_with('-') { civil.to_string() } else { format!(" {civil}") };+ let text = quote_string_literal(&text);+ Ok(Some(format!("SELECT TO_CHAR(X.D, 'J') AS DBX_DAY, TRIM(TO_CHAR(X.D, 'SYYYY-MM-DD', 'NLS_CALENDAR=GREGORIAN')) AS DBX_CIVIL, TRIM(TO_CHAR(TO_DATE(TO_CHAR(X.D, 'J'), 'J'), 'SYYYY-MM-DD', 'NLS_CALENDAR=GREGORIAN')) AS DBX_REBUILT FROM (SELECT TO_DATE({text}, 'SYYYY-MM-DD', 'NLS_CALENDAR=GREGORIAN') AS D FROM DUAL) X")))+}++pub fn normalize_civil_date(value: &Value, row: &NativeJobRow) -> Result<Value, &'static str> {+ let civil = input(value)?.ok_or(INVALID)?;+ if row.get("DBX_CIVIL").and_then(Value::as_str) != Some(civil)+ || row.get("DBX_REBUILT").and_then(Value::as_str) != Some(civil)+ {+ return Err(INVALID);+ }+ let day = row.get("DBX_DAY").and_then(Value::as_str).ok_or(INVALID)?;+ let mut normalized = value.clone();+ let payload = normalized["value"].as_object_mut().unwrap();+ payload.remove("civilDate");+ payload.insert("day".into(), json!(day));+ let NativeJobArgumentValue::Value { value } = scalar_envelope(&normalized)?.editable_value() else {+ unreachable!()+ };+ Ok(value)+}++pub fn editable_argument(row: &NativeJobRow, default_value: bool) -> NativeJobArgumentValue {+ let mut result = super::decode_argument(row, default_value).editable_value();+ if let NativeJobArgumentValue::Value { value } = &mut result {+ let kind = value.get("scalarType").and_then(Value::as_str).and_then(ScalarType::from_token);+ if matches!(+ kind,+ Some(ScalarType::Date | ScalarType::Timestamp | ScalarType::TimestampTz | ScalarType::TimestampLtz)+ ) {+ if let Some(civil) =+ row.get("DBX_ANYDATA_CIVIL_DATE").and_then(Value::as_str).filter(|civil| valid_civil(civil))+ {+ if let Some(payload) = value["value"].as_object_mut() {+ payload.remove("day");+ payload.insert("civilDate".into(), json!(civil));+ }+ }+ }+ }+ result+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn civil_dates_use_fixed_native_calendar_roundtrips_without_client_epoch_arithmetic() {+ for civil in ["-4712-01-01", "-0001-12-31", "0001-01-01", "1582-10-05", "9999-12-31"] {+ let value = json!({"$dbx":"oracle-anydata-v1","scalarType":"timestamp","value":{"civilDate":civil,"seconds":"86399.123456789"}});+ let sql = civil_date_query(&value).unwrap().unwrap();+ assert!(sql.contains("'NLS_CALENDAR=GREGORIAN'"));+ assert!(!sql.contains("ALTER SESSION"));+ assert!(!sql.contains("TO_TIMESTAMP"));+ let row =+ serde_json::from_value(json!({"DBX_DAY":"1234567","DBX_CIVIL":civil,"DBX_REBUILT":civil})).unwrap();+ assert_eq!(+ normalize_civil_date(&value, &row).unwrap()["value"],+ json!({"day":"1234567","seconds":"86399.123456789"})+ );+ let wrong =+ serde_json::from_value(json!({"DBX_DAY":"1234567","DBX_CIVIL":civil,"DBX_REBUILT":"2000-01-01"}))+ .unwrap();+ assert!(normalize_civil_date(&value, &wrong).is_err());+ }+ for civil in [+ "0000-01-01",+ "-0000-01-01",+ "-4713-01-01",+ "10000-01-01",+ "2026-13-01",+ "2026-01-00",+ "2026-01-01');END;--",+ ] {+ assert!(civil_date_query(+ &json!({"$dbx":"oracle-anydata-v1","scalarType":"date","value":{"civilDate":civil,"seconds":"0"}})+ )+ .is_err());+ }+ assert!(civil_date_query(&json!({"$dbx":"oracle-anydata-v1","scalarType":"date","value":{"civilDate":"2026-01-01","day":"1","seconds":"0"}})).is_err());+ assert!(civil_date_query(&json!("{\"value\":{\"civilDate\":\"2026-01-01\"}}")).unwrap().is_none());+ assert!(civil_date_query(+ &json!({"$dbx":"oracle-anydata-v1","scalarType":"date","value":{"day":"1","seconds":"0"}})+ )+ .unwrap()+ .is_none());+ }++ #[test]+ fn auxiliary_civil_dates_only_affect_edit_display_not_storage_fingerprints() {+ let mut row: NativeJobRow = serde_json::from_value(json!({"DBX_ANYDATA_PRESENT":1,"DBX_ANYDATA_TYPE":"SYS.TIMESTAMP","DBX_ANYDATA_IS_NULL":0,"DBX_ANYDATA_DAY":"1234567","DBX_ANYDATA_SECONDS":"1.123456789"})).unwrap();+ let baseline = super::super::canonical_argument_row(&row, false);+ row.insert("DBX_ANYDATA_CIVIL_DATE".into(), json!("-0001-12-31"));+ assert_eq!(baseline, super::super::canonical_argument_row(&row, false));+ let NativeJobArgumentValue::Value { value } = editable_argument(&row, false) else { panic!("value required") };+ assert_eq!(value["value"], json!({"civilDate":"-0001-12-31","seconds":"1.123456789"}));+ row.insert("DBX_ANYDATA_IS_NULL".into(), json!(1));+ assert!(+ matches!(editable_argument(&row, false), NativeJobArgumentValue::Value { value } if value["value"].is_null())+ );+ }+}diff --git a/crates/dbx-sql-schema/src/native_job_arguments/identity.rs b/crates/dbx-sql-schema/src/native_job_arguments/identity.rsnew file mode 100644index 0000000000..298c0bd43b--- /dev/null+++ b/crates/dbx-sql-schema/src/native_job_arguments/identity.rs@@ -0,0 +1,194 @@+use super::{AnydataColumn, NativeJobRow};+use serde_json::Value;++#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum ScalarType {+ Varchar2,+ Char,+ Nvarchar2,+ Nchar,+ Number,+ Date,+ Timestamp,+ TimestampTz,+ TimestampLtz,+ IntervalYm,+ IntervalDs,+ Raw,+ BinaryFloat,+ BinaryDouble,+ Urowid,+}++impl ScalarType {+ pub const ALL: [Self; 15] = [+ Self::Varchar2,+ Self::Char,+ Self::Nvarchar2,+ Self::Nchar,+ Self::Number,+ Self::Date,+ Self::Timestamp,+ Self::TimestampTz,+ Self::TimestampLtz,+ Self::IntervalYm,+ Self::IntervalDs,+ Self::Raw,+ Self::BinaryFloat,+ Self::BinaryDouble,+ Self::Urowid,+ ];++ pub fn token(self) -> &'static str {+ match self {+ Self::Varchar2 => "varchar2",+ Self::Char => "char",+ Self::Nvarchar2 => "nvarchar2",+ Self::Nchar => "nchar",+ Self::Number => "number",+ Self::Date => "date",+ Self::Timestamp => "timestamp",+ Self::TimestampTz => "timestamp-tz",+ Self::TimestampLtz => "timestamp-ltz",+ Self::IntervalYm => "interval-ym",+ Self::IntervalDs => "interval-ds",+ Self::Raw => "raw",+ Self::BinaryFloat => "binary-float",+ Self::BinaryDouble => "binary-double",+ Self::Urowid => "urowid",+ }+ }++ pub fn from_token(token: &str) -> Option<Self> {+ Self::ALL.into_iter().find(|kind| kind.token() == token)+ }++ pub fn fixed_name(self) -> Option<&'static str> {+ Some(match self {+ Self::Varchar2 => "SYS.VARCHAR2",+ Self::Char => "SYS.CHAR",+ Self::Number => "SYS.NUMBER",+ Self::Date => "SYS.DATE",+ Self::Timestamp => "SYS.TIMESTAMP",+ Self::TimestampTz => "SYS.TIMESTAMPTZ",+ Self::TimestampLtz => "SYS.TIMESTAMPLTZ",+ Self::Raw => "SYS.RAW",+ _ => return None,+ })+ }++ pub fn from_fixed_name(name: &str) -> Option<Self> {+ Self::ALL.into_iter().find(|kind| kind.fixed_name() == Some(name))+ }++ pub fn convert(self) -> &'static str {+ match self {+ Self::Varchar2 => "ConvertVarchar2",+ Self::Char => "ConvertChar",+ Self::Nvarchar2 => "ConvertNVarchar2",+ Self::Nchar => "ConvertNchar",+ Self::Number => "ConvertNumber",+ Self::Date => "ConvertDate",+ Self::Timestamp => "ConvertTimestamp",+ Self::TimestampTz => "ConvertTimestampTZ",+ Self::TimestampLtz => "ConvertTimestampLTZ",+ Self::IntervalYm => "ConvertIntervalYM",+ Self::IntervalDs => "ConvertIntervalDS",+ Self::Raw => "ConvertRaw",+ Self::BinaryFloat => "ConvertBFloat",+ Self::BinaryDouble => "ConvertBDouble",+ Self::Urowid => "ConvertURowid",+ }+ }++ pub fn access(self) -> &'static str {+ match self {+ Self::Varchar2 => "AccessVarchar2",+ Self::Char => "AccessChar",+ Self::Nvarchar2 => "AccessNVarchar2",+ Self::Nchar => "AccessNchar",+ Self::Number => "AccessNumber",+ Self::Date => "AccessDate",+ Self::Timestamp => "AccessTimestamp",+ Self::TimestampTz => "AccessTimestampTZ",+ Self::TimestampLtz => "AccessTimestampLTZ",+ Self::IntervalYm => "AccessIntervalYM",+ Self::IntervalDs => "AccessIntervalDS",+ Self::Raw => "AccessRaw",+ Self::BinaryFloat => "AccessBFloat",+ Self::BinaryDouble => "AccessBDouble",+ Self::Urowid => "AccessURowid",+ }+ }++ pub fn null_cast(self) -> &'static str {+ match self {+ Self::Varchar2 => "VARCHAR2(4000)",+ Self::Char => "CHAR(1)",+ Self::Nvarchar2 => "NVARCHAR2(1)",+ Self::Nchar => "NCHAR(1)",+ Self::Number => "NUMBER",+ Self::Date => "DATE",+ Self::Timestamp => "TIMESTAMP(9)",+ Self::TimestampTz => "TIMESTAMP(9) WITH TIME ZONE",+ Self::TimestampLtz => "TIMESTAMP(9) WITH LOCAL TIME ZONE",+ Self::IntervalYm => "INTERVAL YEAR(9) TO MONTH",+ Self::IntervalDs => "INTERVAL DAY(9) TO SECOND(9)",+ Self::Raw => "RAW(1)",+ Self::BinaryFloat => "BINARY_FLOAT",+ Self::BinaryDouble => "BINARY_DOUBLE",+ Self::Urowid => "UROWID",+ }+ }++ pub fn null_expression(self) -> String {+ format!("SYS.ANYDATA.{}(CAST(NULL AS {}))", self.convert(), self.null_cast())+ }+}++impl AnydataColumn {+ pub(super) fn sql(self) -> &'static str {+ match self {+ Self::JobArgument => "J.ANYDATA_VALUE",+ Self::ProgramDefault => "J.DEFAULT_ANYDATA_VALUE",+ }+ }+}++pub fn anydata_query_prefix() -> String {+ let prototypes = ScalarType::ALL+ .into_iter()+ .enumerate()+ .filter(|(_, kind)| kind.fixed_name().is_none())+ .map(|(index, kind)| format!("{} AS T{index}", kind.null_expression()))+ .collect::<Vec<_>>()+ .join(", ");+ let names = ScalarType::ALL.into_iter().enumerate().map(|(index, kind)| {+ if let Some(name) = kind.fixed_name() {+ format!("SELECT '{}' AS CODEC, '{name}' AS TYPE_NAME FROM DUAL", kind.token())+ } else {+ format!("SELECT '{}' AS CODEC, CASE WHEN P0.T{index} IS NOT NULL THEN P0.T{index}.GetTypeName() END AS TYPE_NAME FROM DBX_ANYDATA_PROTOTYPES P0", kind.token())+ }+ }).collect::<Vec<_>>().join(" UNION ALL ");+ format!("WITH DBX_ANYDATA_PROTOTYPES AS (SELECT {prototypes} FROM DUAL), DBX_ANYDATA_TYPES AS ({names}), DBX_ANYDATA_UNIQUE AS (SELECT MIN(CODEC) AS CODEC, MIN(TYPE_NAME) AS TYPE_NAME FROM DBX_ANYDATA_TYPES WHERE TYPE_NAME IS NOT NULL GROUP BY SYS.UTL_RAW.CAST_TO_RAW(TYPE_NAME) HAVING COUNT(*) = 1) ")+}++pub fn anydata_join(column: AnydataColumn) -> String {+ let column = column.sql();+ format!(" LEFT JOIN DBX_ANYDATA_UNIQUE DBX_AT ON SYS.UTL_RAW.CAST_TO_RAW(CASE WHEN {column} IS NOT NULL THEN {column}.GetTypeName() END) = SYS.UTL_RAW.CAST_TO_RAW(DBX_AT.TYPE_NAME)")+}++pub(super) fn proven_type(row: &NativeJobRow, type_name: &str) -> Option<ScalarType> {+ if row.contains_key("DBX_ANYDATA_CODEC") || row.contains_key("DBX_ANYDATA_CONSTRUCTOR_TYPE") {+ let kind = ScalarType::from_token(row.get("DBX_ANYDATA_CODEC")?.as_str()?)?;+ if row.get("DBX_ANYDATA_CONSTRUCTOR_TYPE").and_then(Value::as_str) != Some(type_name)+ || kind.fixed_name().is_some_and(|name| name != type_name)+ {+ return None;+ }+ Some(kind)+ } else {+ // Existing proven fixed-type projections remain readable without a new global prerequisite.+ ScalarType::from_fixed_name(type_name)+ }+}diff --git a/crates/dbx-sql-schema/src/native_job_arguments/scalars.rs b/crates/dbx-sql-schema/src/native_job_arguments/scalars.rsnew file mode 100644index 0000000000..4e0180670c--- /dev/null+++ b/crates/dbx-sql-schema/src/native_job_arguments/scalars.rs@@ -0,0 +1,349 @@+use super::{ArgumentExpectation, ScalarType};+use dbx_sql_core::value_literals::quote_string_literal;+use serde_json::{json, Value};++const INVALID: &str = "native_job_argument_value_invalid";+const NANOS: i128 = 1_000_000_000;+const DAY_NANOS: i128 = 86_400 * NANOS;++fn integer(value: &str) -> Result<i128, &'static str> {+ let unsigned = value.strip_prefix(['-', '+']).unwrap_or(value);+ if unsigned.is_empty() || !unsigned.bytes().all(|byte| byte.is_ascii_digit()) {+ return Err(INVALID);+ }+ value.parse().map_err(|_| INVALID)+}++fn decimal_nanos(value: &str) -> Result<i128, &'static str> {+ let negative = value.starts_with('-');+ let unsigned = value.strip_prefix(['-', '+']).unwrap_or(value);+ let mut pieces = unsigned.split('.');+ let whole = pieces.next().ok_or(INVALID)?;+ let fraction = pieces.next().unwrap_or("");+ if pieces.next().is_some()+ || whole.is_empty()+ || !whole.bytes().all(|byte| byte.is_ascii_digit())+ || fraction.len() > 9+ || !fraction.bytes().all(|byte| byte.is_ascii_digit())+ {+ return Err(INVALID);+ }+ let whole = integer(whole)?;+ let fraction = if fraction.is_empty() { 0 } else { integer(fraction)? * 10_i128.pow(9 - fraction.len() as u32) };+ let nanos = whole.checked_mul(NANOS).and_then(|whole| whole.checked_add(fraction)).ok_or(INVALID)?;+ Ok(if negative { -nanos } else { nanos })+}++fn seconds(nanos: i128) -> String {+ let sign = if nanos < 0 { "-" } else { "" };+ let nanos = nanos.abs();+ if nanos % NANOS == 0 {+ return format!("{sign}{}", nanos / NANOS);+ }+ format!("{sign}{}.{:09}", nanos / NANOS, nanos % NANOS).trim_end_matches('0').into()+}++fn normalized_hex(value: &str, bytes: Option<usize>) -> Result<String, &'static str> {+ if value.is_empty()+ || !value.len().is_multiple_of(2)+ || value.len() > 65_534+ || !value.bytes().all(|byte| byte.is_ascii_hexdigit())+ || bytes.is_some_and(|bytes| value.len() != bytes * 2)+ {+ return Err(INVALID);+ }+ Ok(value.to_ascii_uppercase())+}++fn raw_expression(hex: &str) -> String {+ let mut chunks = hex+ .as_bytes()+ .chunks(4_000)+ .map(|chunk| format!("HEXTORAW('{}')", std::str::from_utf8(chunk).expect("validated ASCII hex")));+ let first = chunks.next().expect("nonempty RAW");+ chunks.fold(first, |value, chunk| format!("SYS.UTL_RAW.CONCAT({value}, {chunk})"))+}++fn date_value(kind: ScalarType, value: &Value) -> Result<Value, &'static str> {+ let object = value.as_object().ok_or(INVALID)?;+ if object.len() != if kind == ScalarType::TimestampTz { 5 } else { 2 } {+ return Err(INVALID);+ }+ let day = integer(object.get("day").and_then(Value::as_str).ok_or(INVALID)?)?;+ let nanos = decimal_nanos(object.get("seconds").and_then(Value::as_str).ok_or(INVALID)?)?;+ if !(1..=5_373_484).contains(&day)+ || !(0..DAY_NANOS).contains(&nanos)+ || (kind == ScalarType::Date && nanos % NANOS != 0)+ {+ return Err(INVALID);+ }+ let mut result = json!({"day":day.to_string(), "seconds":seconds(nanos)});+ if kind == ScalarType::TimestampTz {+ let offset = object.get("offset").and_then(Value::as_str).ok_or(INVALID)?;+ let bytes = offset.as_bytes();+ if bytes.len() != 6+ || !matches!(bytes[0], b'+' | b'-')+ || bytes[3] != b':'+ || ![bytes[1], bytes[2], bytes[4], bytes[5]].iter().all(u8::is_ascii_digit)+ {+ return Err(INVALID);+ }+ let hours = i32::from(bytes[1] - b'0') * 10 + i32::from(bytes[2] - b'0');+ let minutes = i32::from(bytes[4] - b'0') * 10 + i32::from(bytes[5] - b'0');+ if minutes > 59 || hours * 60 + minutes > if bytes[0] == b'-' { 720 } else { 840 } {+ return Err(INVALID);+ }+ let region = object.get("region").and_then(Value::as_str).ok_or(INVALID)?;+ if region.is_empty()+ || region.len() > 128+ || !region.bytes().all(|byte| byte.is_ascii_alphanumeric() || b"_/-+.:".contains(&byte))+ {+ return Err(INVALID);+ }+ let abbreviation = object.get("abbreviation").ok_or(INVALID)?;+ if !abbreviation.is_null()+ && !abbreviation.as_str().is_some_and(|text| {+ !text.is_empty()+ && text.len() <= 64+ && text.bytes().all(|byte| byte.is_ascii_alphanumeric() || b"_+-".contains(&byte))+ })+ {+ return Err(INVALID);+ }+ result["region"] = json!(region);+ result["offset"] = json!(offset);+ result["abbreviation"] = abbreviation.clone();+ }+ Ok(result)+}++pub(super) fn normalize(kind: ScalarType, value: &Value) -> Result<Value, &'static str> {+ Ok(match kind {+ ScalarType::Number => json!(super::normalize_number(value.as_str().ok_or(INVALID)?)?),+ ScalarType::Date | ScalarType::Timestamp | ScalarType::TimestampTz | ScalarType::TimestampLtz => {+ date_value(kind, value)?+ }+ ScalarType::IntervalYm | ScalarType::IntervalDs => {+ let total = integer(value.as_str().ok_or(INVALID)?)?;+ let max = if kind == ScalarType::IntervalYm { 11_999_999_999 } else { 1_000_000_000 * DAY_NANOS - 1 };+ if !(-max..=max).contains(&total) {+ return Err(INVALID);+ }+ json!(total.to_string())+ }+ ScalarType::Raw => json!(normalized_hex(value.as_str().ok_or(INVALID)?, None)?),+ ScalarType::BinaryFloat | ScalarType::BinaryDouble => {+ let text = normalized_hex(+ value.as_str().ok_or(INVALID)?,+ Some(if kind == ScalarType::BinaryFloat { 4 } else { 8 }),+ )?;+ let bits = u64::from_str_radix(&text, 16).map_err(|_| INVALID)?;+ let (sign, exponent, fraction) = if kind == ScalarType::BinaryFloat {+ (0x8000_0000, 0x7F80_0000, 0x007F_FFFF)+ } else {+ (0x8000_0000_0000_0000, 0x7FF0_0000_0000_0000, 0x000F_FFFF_FFFF_FFFF)+ };+ if bits == sign || (bits & exponent == exponent && bits & fraction != 0) {+ return Err(INVALID);+ }+ json!(text)+ }+ ScalarType::Urowid => {+ let text = value.as_str().ok_or(INVALID)?;+ if text.is_empty() || text.len() > 4_000 || !text.bytes().all(|byte| byte.is_ascii_graphic()) {+ return Err(INVALID);+ }+ json!(text)+ }+ ScalarType::Varchar2 | ScalarType::Char | ScalarType::Nvarchar2 | ScalarType::Nchar => {+ let text = value.as_str().filter(|text| !text.is_empty()).ok_or(INVALID)?;+ json!(text)+ }+ })+}++pub(super) fn expression(expected: &ArgumentExpectation) -> Result<String, &'static str> {+ let kind = expected.scalar_type;+ let Some(value) = &expected.value else {+ return Ok(kind.null_expression());+ };+ let input = match kind {+ ScalarType::Number => value.as_str().ok_or(INVALID)?.into(),+ ScalarType::Date | ScalarType::Timestamp | ScalarType::TimestampTz | ScalarType::TimestampLtz => {+ let day = value["day"].as_str().ok_or(INVALID)?;+ let seconds = value["seconds"].as_str().ok_or(INVALID)?;+ let timestamp =+ format!("(CAST(TO_DATE('{day}', 'J') AS TIMESTAMP(9)) + NUMTODSINTERVAL({seconds}, 'SECOND'))");+ match kind {+ ScalarType::Date => format!("CAST({timestamp} AS DATE)"),+ ScalarType::Timestamp => timestamp,+ ScalarType::TimestampLtz => {+ format!("CAST(FROM_TZ({timestamp}, '+00:00') AS TIMESTAMP(9) WITH LOCAL TIME ZONE)")+ }+ _ => format!(+ "(FROM_TZ({timestamp}, {}) AT TIME ZONE {})",+ quote_string_literal(value["offset"].as_str().ok_or(INVALID)?),+ quote_string_literal(value["region"].as_str().ok_or(INVALID)?)+ ),+ }+ }+ ScalarType::IntervalYm => format!("NUMTOYMINTERVAL({}, 'MONTH')", value.as_str().ok_or(INVALID)?),+ ScalarType::IntervalDs => {+ format!("NUMTODSINTERVAL({}, 'SECOND')", seconds(integer(value.as_str().ok_or(INVALID)?)?))+ }+ ScalarType::Raw => raw_expression(value.as_str().ok_or(INVALID)?),+ ScalarType::BinaryFloat | ScalarType::BinaryDouble => format!(+ "SYS.UTL_RAW.{}({}, SYS.UTL_RAW.BIG_ENDIAN)",+ if kind == ScalarType::BinaryFloat { "CAST_TO_BINARY_FLOAT" } else { "CAST_TO_BINARY_DOUBLE" },+ raw_expression(value.as_str().ok_or(INVALID)?)+ ),+ ScalarType::Urowid => format!("CAST({} AS UROWID)", quote_string_literal(value.as_str().ok_or(INVALID)?)),+ _ => return Err("native_job_argument_character_constructor_required"),+ };+ Ok(format!("SYS.ANYDATA.{}({input})", kind.convert()))+}++pub(super) fn validation(expected: &ArgumentExpectation) -> Result<String, &'static str> {+ let kind = expected.scalar_type;+ let actual = format!("l_anydata.{}()", kind.access());+ let Some(value) = expected.value.as_ref() else {+ return Ok(format!("IF {actual} IS NOT NULL THEN RAISE_APPLICATION_ERROR(-20001, 'native_job_argument_conversion_loss'); END IF; "));+ };+ let exact_text = |actual: &str, expected: &str| {+ format!("SYS.UTL_RAW.CAST_TO_RAW({actual}) = SYS.UTL_RAW.CAST_TO_RAW({})", quote_string_literal(expected))+ };+ let equal = match kind {+ ScalarType::Number => format!("{actual} = {}", value.as_str().ok_or(INVALID)?),+ ScalarType::Date | ScalarType::Timestamp | ScalarType::TimestampTz | ScalarType::TimestampLtz => {+ let timestamp = if kind == ScalarType::TimestampLtz { format!("CAST(({actual} AT TIME ZONE '+00:00') AS TIMESTAMP(9))") }+ else { format!("CAST({actual} AS TIMESTAMP(9))") };+ let mut check = format!("{} AND (EXTRACT(HOUR FROM {timestamp}) * 3600 + EXTRACT(MINUTE FROM {timestamp}) * 60 + EXTRACT(SECOND FROM {timestamp})) = {}", exact_text(&format!("TO_CHAR({timestamp}, 'J')"), value["day"].as_str().ok_or(INVALID)?), value["seconds"].as_str().ok_or(INVALID)?);+ if kind == ScalarType::TimestampTz {+ for (field, format) in [("region", "TZR"), ("offset", "TZH:TZM")] {+ check.push_str(&format!(" AND {}", exact_text(&format!("TO_CHAR({actual}, '{format}')"), value[field].as_str().ok_or(INVALID)?)));+ }+ check.push_str(&match value.get("abbreviation").ok_or(INVALID)? {+ Value::Null => format!(" AND TO_CHAR({actual}, 'TZD') IS NULL"),+ Value::String(abbreviation) => format!(" AND {}", exact_text(&format!("TO_CHAR({actual}, 'TZD')"), abbreviation)),+ _ => return Err(INVALID),+ });+ }+ check+ }+ ScalarType::IntervalYm => format!("(EXTRACT(YEAR FROM {actual}) * 12 + EXTRACT(MONTH FROM {actual})) = {}", value.as_str().ok_or(INVALID)?),+ ScalarType::IntervalDs => format!("(EXTRACT(DAY FROM {actual}) * 86400 + EXTRACT(HOUR FROM {actual}) * 3600 + EXTRACT(MINUTE FROM {actual}) * 60 + EXTRACT(SECOND FROM {actual})) * 1000000000 = {}", value.as_str().ok_or(INVALID)?),+ ScalarType::Raw | ScalarType::BinaryFloat | ScalarType::BinaryDouble => {+ let actual = match kind {+ ScalarType::BinaryFloat => format!("SYS.UTL_RAW.CAST_FROM_BINARY_FLOAT({actual}, SYS.UTL_RAW.BIG_ENDIAN)"),+ ScalarType::BinaryDouble => format!("SYS.UTL_RAW.CAST_FROM_BINARY_DOUBLE({actual}, SYS.UTL_RAW.BIG_ENDIAN)"),+ _ => actual.clone(),+ };+ let hex = value.as_str().ok_or(INVALID)?;+ format!("SYS.UTL_RAW.LENGTH({actual}) = {} AND SYS.UTL_RAW.COMPARE({actual}, {}) = 0", hex.len() / 2, raw_expression(hex))+ }+ ScalarType::Urowid => exact_text(&format!("ROWIDTOCHAR({actual})"), value.as_str().ok_or(INVALID)?),+ _ => return Ok(String::new()),+ };+ Ok(format!("IF {actual} IS NOT NULL AND ({equal}) THEN NULL; ELSE RAISE_APPLICATION_ERROR(-20001, 'native_job_argument_conversion_loss'); END IF; "))+}++pub(super) fn projected_value(kind: ScalarType, row: &super::NativeJobRow) -> Result<Value, &'static str> {+ let text = |key: &str| row.get(key).and_then(Value::as_str).ok_or(INVALID);+ let value = match kind {+ ScalarType::Date | ScalarType::Timestamp | ScalarType::TimestampLtz | ScalarType::TimestampTz => {+ let mut date = json!({"day":text("DBX_ANYDATA_DAY")?, "seconds":text("DBX_ANYDATA_SECONDS")?});+ if kind == ScalarType::TimestampTz {+ date["region"] = json!(text("DBX_ANYDATA_TZ_REGION")?);+ date["offset"] = json!(text("DBX_ANYDATA_TZ_OFFSET")?);+ date["abbreviation"] = row.get("DBX_ANYDATA_TZ_ABBR").cloned().ok_or(INVALID)?;+ }+ date+ }+ ScalarType::Raw | ScalarType::BinaryFloat | ScalarType::BinaryDouble => {+ let hex = text("DBX_ANYDATA_HEX")?;+ if kind == ScalarType::Raw && integer(text("DBX_ANYDATA_LENGTH")?)? * 2 != hex.len() as i128 {+ return Err(INVALID);+ }+ json!(hex)+ }+ ScalarType::Varchar2 | ScalarType::Char | ScalarType::Nvarchar2 | ScalarType::Nchar => {+ if !row.contains_key("DBX_ANYDATA_CODEC") && !row.contains_key("DBX_ANYDATA_HEX") {+ return normalize(kind, &json!(text("DBX_ANYDATA_TEXT")?));+ }+ let hex = text("DBX_ANYDATA_HEX")?;+ if hex.is_empty()+ || hex.len() > 131_068+ || hex.len() % 4 != 0+ || !hex.bytes().all(|byte| byte.is_ascii_hexdigit())+ {+ return Err(INVALID);+ }+ let units = hex+ .as_bytes()+ .chunks(4)+ .map(|bytes| {+ u16::from_str_radix(std::str::from_utf8(bytes).map_err(|_| INVALID)?, 16).map_err(|_| INVALID)+ })+ .collect::<Result<Vec<_>, _>>()?;+ let string = String::from_utf16(&units).map_err(|_| INVALID)?;+ if integer(text("DBX_ANYDATA_LENGTH")?)? != string.chars().count() as i128 {+ return Err(INVALID);+ }+ json!(string)+ }+ _ => json!(text("DBX_ANYDATA_TEXT")?),+ };+ normalize(kind, &value)+}++fn clob_chunks(value: &str, unicode: bool) -> String {+ let size = if unicode { 256 } else { 1_000 };+ let maximum = 32_767;+ (0..maximum).step_by(size).map(|offset| {+ let start = offset + 1;+ if unicode {+ format!("CASE WHEN LENGTH4({value}) >= {start} THEN TO_CLOB(RAWTOHEX(SYS.UTL_I18N.STRING_TO_RAW(SUBSTR4({value}, {start}, {size}), 'AL16UTF16'))) END")+ } else {+ format!("CASE WHEN SYS.UTL_RAW.LENGTH({value}) >= {start} THEN TO_CLOB(RAWTOHEX(SYS.UTL_RAW.SUBSTR({value}, {start}, {size}))) END")+ }+ }).collect::<Vec<_>>().join(" || ")+}++pub(super) fn projection(column: &str) -> String {+ let utc_ltz = format!("CAST(({column}.AccessTimestampLTZ() AT TIME ZONE '+00:00') AS TIMESTAMP(9))");+ let mut day = Vec::new();+ let mut seconds = Vec::new();+ let mut civil = Vec::new();+ for kind in [ScalarType::Date, ScalarType::Timestamp, ScalarType::TimestampTz, ScalarType::TimestampLtz] {+ let value =+ if kind == ScalarType::TimestampLtz { utc_ltz.clone() } else { format!("{column}.{}()", kind.access()) };+ day.push(format!("WHEN '{}' THEN TO_CHAR({value}, 'J')", kind.token()));+ civil.push(format!(+ "WHEN '{}' THEN TRIM(TO_CHAR({value}, 'SYYYY-MM-DD', 'NLS_CALENDAR=GREGORIAN'))",+ kind.token()+ ));+ seconds.push(format!(+ "WHEN '{}' THEN TO_CHAR({value}, '{}', 'NLS_NUMERIC_CHARACTERS=''.,''')",+ kind.token(),+ if kind == ScalarType::Date { "SSSSS" } else { "SSSSS.FF9" }+ ));+ }+ let mut hex = Vec::new();+ let mut lengths = Vec::new();+ for kind in [ScalarType::Varchar2, ScalarType::Char, ScalarType::Nvarchar2, ScalarType::Nchar] {+ let value = format!("{column}.{}()", kind.access());+ hex.push(format!("WHEN '{}' THEN ({})", kind.token(), clob_chunks(&value, true)));+ lengths.push(format!("WHEN '{}' THEN TO_CHAR(LENGTH4({value}), 'TM9')", kind.token()));+ }+ hex.push(format!("WHEN 'raw' THEN ({})", clob_chunks(&format!("{column}.AccessRaw()"), false)));+ lengths.push(format!("WHEN 'raw' THEN TO_CHAR(SYS.UTL_RAW.LENGTH({column}.AccessRaw()), 'TM9')"));+ for (token, access, method) in [+ ("binary-float", "AccessBFloat", "CAST_FROM_BINARY_FLOAT"),+ ("binary-double", "AccessBDouble", "CAST_FROM_BINARY_DOUBLE"),+ ] {+ hex.push(format!(+ "WHEN '{token}' THEN TO_CLOB(RAWTOHEX(SYS.UTL_RAW.{method}({column}.{access}(), SYS.UTL_RAW.BIG_ENDIAN)))"+ ));+ }+ format!("CASE DBX_AT.CODEC {} END AS DBX_ANYDATA_DAY, CASE DBX_AT.CODEC {} END AS DBX_ANYDATA_SECONDS, CASE DBX_AT.CODEC WHEN 'timestamp-tz' THEN TO_CHAR({column}.AccessTimestampTZ(), 'TZR') END AS DBX_ANYDATA_TZ_REGION, CASE DBX_AT.CODEC WHEN 'timestamp-tz' THEN TO_CHAR({column}.AccessTimestampTZ(), 'TZH:TZM') END AS DBX_ANYDATA_TZ_OFFSET, CASE DBX_AT.CODEC WHEN 'timestamp-tz' THEN TO_CHAR({column}.AccessTimestampTZ(), 'TZD') END AS DBX_ANYDATA_TZ_ABBR, CASE DBX_AT.CODEC {} END AS DBX_ANYDATA_HEX, CASE DBX_AT.CODEC {} END AS DBX_ANYDATA_LENGTH, CASE DBX_AT.CODEC {} END AS DBX_ANYDATA_CIVIL_DATE", day.join(" "), seconds.join(" "), hex.join(" "), lengths.join(" "), civil.join(" "))+}diff --git a/crates/dbx-sql-schema/src/native_job_changes.rs b/crates/dbx-sql-schema/src/native_job_changes.rsnew file mode 100644index 0000000000..fb63d4ecbe--- /dev/null+++ b/crates/dbx-sql-schema/src/native_job_changes.rs@@ -0,0 +1,781 @@+use crate::native_jobs::NativeJobCatalogDialect;+use dbx_sql_core::value_literals::quote_string_literal;+use dbx_types::native_jobs::*;+use serde_json::Value;+use std::collections::HashSet;++mod creation;+mod dameng;+mod references;+mod transitions;+pub use creation::{native_job_scheduler_create_plan, NativeJobSchedulerSqlPlan};+pub use dameng::{+ native_job_dameng_catalog_id, native_job_dameng_child_id, native_job_dameng_child_key,+ native_job_dameng_civil_time, native_job_dameng_create_plan, native_job_dameng_date_query,+ native_job_dameng_identity_queries, native_job_dameng_legacy_time, native_job_dameng_name_queries,+ native_job_dameng_what_query, resolve_native_job_dameng_child_step, NativeJobDamengChildAction,+ NativeJobDamengChildEffect, NativeJobDamengChildReference, NativeJobDamengConfigPlan, NativeJobDamengCreatePlan,+ NativeJobDamengOperator, NativeJobDamengOperatorSelector, NativeJobDamengPart,+};+pub use references::{native_job_scheduler_reference_target, NativeJobSchedulerReferenceTarget};+pub use transitions::{+ native_job_scheduler_edit_plan, NativeJobSchedulerDefinitionEffect, NativeJobSchedulerEditPlan,+ NativeJobSchedulerReferenceBinding,+};++#[derive(Clone)]+pub enum NativeJobStepEffect {+ Created,+ Fields(Vec<NativeJobAttributeChange>),+ SchedulerDefinition(NativeJobSchedulerDefinitionEffect),+ DamengDefinition(Vec<NativeJobAttributeChange>),+ DamengLegacyInterval { expected_seconds: Option<String> },+ DamengLegacyWhat { expected: String },+ DamengLegacyNextDate { expected: String },+ DamengRenamed { old_name: String, new_name: String },+ DamengConfigurationStarted,+ DamengConfigurationCommitted,+ DamengChild(NativeJobDamengChildEffect),+ Argument(NativeJobArgumentChange, Option<crate::native_job_arguments::ArgumentExpectation>),+ Enabled(bool),+ Deleted,+ Accepted,+ Completed,+ ArgumentValidated,+ HistoryCleared,+}++// Plans contain reviewed SQL bodies and parameter values, not diagnostic material.+#[derive(Clone)]+pub struct NativeJobSqlStep {+ pub id: String,+ pub label: String,+ pub sql: String,+ pub effect: NativeJobStepEffect,+}++#[derive(Clone)]+pub struct NativeJobSqlPlan {+ pub steps: Vec<NativeJobSqlStep>,+ pub required_partitions: Vec<String>,+ pub compare_next_date: bool,+ pub dameng_configuration: Option<NativeJobDamengConfigPlan>,+}++fn text(value: &str) -> String {+ // PL/SQL accepts concatenated literals; do not cut a UTF-8 character or silently truncate a body.+ let mut chunks = Vec::new();+ let mut start = 0;+ for (index, _) in value.char_indices() {+ if index - start >= 2_000 {+ chunks.push(quote_string_literal(&value[start..index]));+ start = index;+ }+ }+ chunks.push(quote_string_literal(&value[start..]));+ chunks.join(" || ")+}++fn quoted_name(owner: &str, name: &str) -> String {+ format!("\"{}\".\"{}\"", owner.replace('"', "\"\""), name.replace('"', "\"\""))+}++fn definition(details: &NativeJobDetails) -> Result<&NativeJobRow, &'static str> {+ match &details.snapshot.definition {+ NativeJobMetadata::Available { value } => Ok(value),+ _ => Err("native_job_definition_unavailable"),+ }+}++fn string_field<'a>(row: &'a NativeJobRow, name: &str) -> Result<&'a str, &'static str> {+ row.get(name).and_then(Value::as_str).ok_or("native_job_metadata_incomplete")+}++fn target_name(+ engine: NativeJobCatalogDialect,+ target: &NativeJobRef,+ details: &NativeJobDetails,+) -> Result<String, &'static str> {+ Ok(match target {+ NativeJobRef::Scheduler { owner, name, .. } if engine != NativeJobCatalogDialect::OceanbaseOracle => {+ quoted_name(owner, name)+ }+ NativeJobRef::Scheduler { name, .. } | NativeJobRef::DamengNative { name, .. } => name.clone(),+ NativeJobRef::Legacy { .. } if engine == NativeJobCatalogDialect::Dameng => {+ string_field(definition(details)?, "NAME")?.into()+ }+ _ => return Err("native_job_kind_invalid"),+ })+}++fn wrap(+ engine: NativeJobCatalogDialect,+ target: &NativeJobRef,+ details: &NativeJobDetails,+ calls: &str,+) -> Result<String, &'static str> {+ if matches!(target, NativeJobRef::Scheduler { .. }) {+ let identity = match &details.native_identity {+ NativeJobMetadata::Available { value } => Some(value),+ _ if engine == NativeJobCatalogDialect::OceanbaseOracle => {+ return Err("native_job_identity_unverified");+ }+ _ => None,+ };+ return wrap_scheduler(engine, target, identity, calls);+ }+ if engine == NativeJobCatalogDialect::Dameng {+ return dameng::guarded_call(target, details, calls);+ }+ Ok(format!("BEGIN {calls} END;"))+}++fn scheduler_name(engine: NativeJobCatalogDialect, target: &NativeJobRef) -> Result<String, &'static str> {+ let NativeJobRef::Scheduler { owner, name, .. } = target else { return Err("native_job_kind_invalid") };+ Ok(if engine == NativeJobCatalogDialect::OceanbaseOracle { name.clone() } else { quoted_name(owner, name) })+}++// A missing identity is used only for a new job's preview. Apply regenerates the guard from the+// observed identity; it never substitutes text inside user bodies or accepts client-provided SQL.+fn wrap_scheduler(+ engine: NativeJobCatalogDialect,+ target: &NativeJobRef,+ identity: Option<&NativeJobRow>,+ calls: &str,+) -> Result<String, &'static str> {+ if let NativeJobRef::Scheduler { owner, name, .. } = target {+ if engine == NativeJobCatalogDialect::OceanbaseOracle {+ let id = if let Some(identity) = identity {+ let id = string_field(identity, "DBX_JOB_ID")?;+ if id.starts_with('0') || id.is_empty() || !id.bytes().all(|byte| byte.is_ascii_digit()) {+ return Err("native_job_identity_unverified");+ }+ id+ } else {+ ":dbx_created_job_id"+ };+ return Ok(format!("DECLARE n INTEGER; expected INTEGER; BEGIN SELECT COUNT(DISTINCT JOB), COUNT(DISTINCT CASE WHEN POWNER = {} AND JOB = {id} THEN JOB END) INTO n, expected FROM SYS.ALL_VIRTUAL_TENANT_SCHEDULER_JOB_REAL_AGENT WHERE JOB_NAME = {} AND JOB > 0; IF n <> 1 OR expected <> 1 THEN RAISE_APPLICATION_ERROR(-20001, 'DBX_JOB_TARGET_CHANGED'); END IF; {calls} END;", text(owner), text(name)));+ }+ }+ Ok(format!("BEGIN {calls} END;"))+}++fn bool_sql(value: bool) -> &'static str {+ if value {+ "TRUE"+ } else {+ "FALSE"+ }+}++pub fn native_job_legacy_create_preview(+ engine: NativeJobCatalogDialect,+ definition: &NativeJobLegacyCreate,+) -> Result<Vec<NativeJobStepPreview>, &'static str> {+ if !matches!(engine, NativeJobCatalogDialect::Oracle | NativeJobCatalogDialect::OceanbaseOracle) {+ return Err("native_job_legacy_protocol_unavailable");+ }+ if definition.what.trim().is_empty()+ || definition.what.contains('\0')+ || definition.interval.contains('\0')+ || definition.schema.contains('\0')+ || match engine {+ NativeJobCatalogDialect::Oracle => {+ !(0..=i64::from(i32::MAX)).contains(&definition.instance) || definition.zone.is_some()+ }+ NativeJobCatalogDialect::OceanbaseOracle => {+ definition.instance != 0+ || definition.zone.as_ref().is_some_and(|zone| zone.is_empty() || zone.contains('\0'))+ }+ _ => unreachable!(),+ }+ {+ return Err("native_job_request_invalid");+ }+ let schema = if definition.schema.is_empty() {+ String::new()+ } else {+ format!("ALTER SESSION SET CURRENT_SCHEMA = \"{}\";\n", definition.schema.replace('"', "\"\""))+ };+ let read = "SELECT TO_CHAR(JOB) AS DBX_JOB_ID, WHAT, TO_CHAR(NEXT_DATE, 'YYYY-MM-DD HH24:MI:SS') AS NEXT_DATE, INTERVAL, BROKEN, INSTANCE, LOG_USER, PRIV_USER, SCHEMA_USER FROM SYS.USER_JOBS WHERE JOB = TO_NUMBER(:dbx_job_id);";+ let placement = if engine == NativeJobCatalogDialect::OceanbaseOracle {+ format!("zone => {}", definition.zone.as_deref().map(text).unwrap_or_else(|| "NULL".into()))+ } else {+ format!("instance => {}", definition.instance)+ };+ let restore_date = if engine == NativeJobCatalogDialect::OceanbaseOracle {+ format!(+ "BEGIN SYS.DBMS_JOB.NEXT_DATE(TO_NUMBER(:dbx_job_id), TO_DATE({}, 'YYYY-MM-DD HH24:MI:SS')); END;\n",+ text(&definition.next_date)+ )+ } else {+ String::new()+ };+ Ok(vec![+ NativeJobStepPreview {+ id: "legacy_prepare".into(), label: "native_job_step_legacy_prepare".into(),+ sql: format!("{schema}DECLARE native_id BINARY_INTEGER; BEGIN SYS.DBMS_JOB.SUBMIT(job => native_id, what => {}, next_date => TO_DATE({}, 'YYYY-MM-DD HH24:MI:SS'), interval => {}, no_parse => FALSE, {placement}, force => FALSE); :dbx_job_id := TO_CHAR(native_id); END;\nBEGIN SYS.DBMS_JOB.BROKEN(TO_NUMBER(:dbx_job_id), {}, TO_DATE({}, 'YYYY-MM-DD HH24:MI:SS')); END;\n{restore_date}{read}",+ text(&definition.what), text(&definition.next_date), text(&definition.interval),+ bool_sql(!definition.enabled), text(&definition.next_date)),+ },+ NativeJobStepPreview { id: "legacy_commit".into(), label: "native_job_step_legacy_commit".into(), sql: "COMMIT;".into() },+ NativeJobStepPreview { id: "legacy_readback".into(), label: "native_job_step_legacy_readback".into(), sql: read.into() },+ ])+}++fn scheduler_package(engine: NativeJobCatalogDialect) -> &'static str {+ match engine {+ NativeJobCatalogDialect::Oracle | NativeJobCatalogDialect::OceanbaseOracle => "SYS.DBMS_SCHEDULER",+ NativeJobCatalogDialect::Dameng => "DBMS_SCHEDULER",+ }+}++pub fn native_job_mutation_plan(+ engine: NativeJobCatalogDialect,+ request: &NativeJobMutation,+ details: &NativeJobDetails,+) -> Result<NativeJobSqlPlan, &'static str> {+ request.target.validate()?;+ if details.snapshot.job_ref != request.target {+ return Err("native_job_identity_mismatch");+ }+ let scheduler = matches!(request.target, NativeJobRef::Scheduler { .. });+ if engine == NativeJobCatalogDialect::Dameng && !scheduler {+ if let Some(plan) = dameng::rename_changes(request, details)? {+ return Ok(plan);+ }+ }+ if matches!(+ &request.change,+ NativeJobChange::Update { final_enabled: Some(_), .. }+ | NativeJobChange::Update { argument_target: Some(_), .. }+ ) {+ return Err(if scheduler {+ "native_job_scheduler_transition_required"+ } else {+ "native_job_final_enabled_not_applicable"+ });+ }+ let package = scheduler_package(engine);+ let dm = engine == NativeJobCatalogDialect::Dameng && !scheduler;+ let mut plan = NativeJobSqlPlan {+ steps: Vec::new(),+ required_partitions: Vec::new(),+ compare_next_date: false,+ dameng_configuration: None,+ };+ match &request.change {+ NativeJobChange::ConfigureDameng { configuration }+ if dm && matches!(request.target, NativeJobRef::DamengNative { .. }) =>+ {+ dameng::configuration_changes(request, details, configuration, &mut plan)?;+ }+ NativeJobChange::Update { attributes, arguments, .. } if scheduler => {+ scheduler_changes(engine, request, details, attributes, arguments, &mut plan)?;+ }+ NativeJobChange::Update { attributes, arguments, .. } if !dm => {+ if !arguments.is_empty() {+ return Err("native_job_arguments_not_applicable");+ }+ legacy_changes(engine, request, attributes, &mut plan)?;+ }+ NativeJobChange::Update { attributes, arguments, .. } => {+ if !arguments.is_empty() {+ return Err("native_job_arguments_not_applicable");+ }+ dameng::metadata_changes(request, details, attributes, &mut plan)?;+ }+ action => {+ let name = if scheduler || dm { Some(text(&target_name(engine, &request.target, details)?)) } else { None };+ let id = match &request.target {+ NativeJobRef::Legacy { job_id, .. } | NativeJobRef::DamengNative { job_id, .. } => job_id.as_str(),+ _ => "",+ };+ let (label, calls, effect) = match action {+ NativeJobChange::Enable | NativeJobChange::Disable => {+ let enabled = matches!(action, NativeJobChange::Enable);+ let label = if enabled { "enable" } else { "disable" };+ let call = if scheduler {+ format!("{package}.{}({});", if enabled { "ENABLE" } else { "DISABLE" }, name.as_ref().unwrap())+ } else if dm {+ format!("SP_ENABLE_JOB({}, {});", name.as_ref().unwrap(), if enabled { 1 } else { 0 })+ } else {+ // Read the current date in this call; OB BROKEN(TRUE) ignores its date argument.+ let source = match details.sources.get("definition").and_then(|source| source.source.as_deref())+ {+ Some("SYS.DBA_JOBS") => "SYS.DBA_JOBS",+ _ => "SYS.USER_JOBS",+ };+ let restore_date = if engine == NativeJobCatalogDialect::OceanbaseOracle {+ format!(" SYS.DBMS_JOB.NEXT_DATE({id}, next_at);")+ } else {+ String::new()+ };+ format!("DECLARE next_at DATE; BEGIN SELECT NEXT_DATE INTO next_at FROM {source} WHERE JOB = {id}; SYS.DBMS_JOB.BROKEN({id}, {}, next_at);{restore_date} COMMIT; END;", bool_sql(!enabled))+ };+ (label, call, NativeJobStepEffect::Enabled(enabled))+ }+ NativeJobChange::Run => {+ let calls = if scheduler {+ format!(+ "{package}.RUN_JOB(job_name => {}, {} => FALSE);",+ name.as_ref().unwrap(),+ if engine == NativeJobCatalogDialect::OceanbaseOracle {+ "force"+ } else {+ "use_current_session"+ }+ )+ } else if dm {+ format!("SP_DBMS_JOB_RUN_ASYNC({id});")+ } else {+ format!("SYS.DBMS_JOB.RUN({id}, FALSE);")+ };+ (+ "run",+ calls,+ if !scheduler && !dm { NativeJobStepEffect::Completed } else { NativeJobStepEffect::Accepted },+ )+ }+ NativeJobChange::Stop { force } => {+ if *force && engine != NativeJobCatalogDialect::Oracle {+ return Err("native_job_force_stop_not_supported");+ }+ let calls = if scheduler {+ format!(+ "{package}.STOP_JOB(job_name => {}, force => {});",+ name.as_ref().unwrap(),+ bool_sql(*force)+ )+ } else if dm {+ format!("SP_STOP_RUNNING_JOB({id});")+ } else {+ return Err("native_job_dbms_job_has_no_stop");+ };+ ("stop", calls, NativeJobStepEffect::Accepted)+ }+ NativeJobChange::Drop { force } => {+ let calls = if scheduler {+ format!(+ "{package}.DROP_JOB(job_name => {}, force => {});",+ name.as_ref().unwrap(),+ bool_sql(*force)+ )+ } else if dm {+ if *force {+ return Err("native_job_force_drop_not_applicable");+ }+ format!("SP_DROP_JOB({});", name.as_ref().unwrap())+ } else {+ if *force {+ return Err("native_job_force_drop_not_applicable");+ }+ format!("SYS.DBMS_JOB.REMOVE({id}); COMMIT;")+ };+ ("drop", calls, NativeJobStepEffect::Deleted)+ }+ NativeJobChange::ClearHistory if dm => (+ "clear_history",+ format!("SP_JOB_CLEAR_HISTORIES({});", name.as_ref().unwrap()),+ NativeJobStepEffect::HistoryCleared,+ ),+ _ => return Err("native_job_action_not_applicable"),+ };+ let sql = wrap(engine, &request.target, details, &calls)?;+ plan.steps.push(NativeJobSqlStep {+ id: label.into(),+ label: format!("native_job_step_{label}"),+ sql,+ effect,+ });+ plan.required_partitions.push("definition".into());+ }+ }+ if plan.steps.is_empty() {+ return Err("native_job_no_changes");+ }+ Ok(plan)+}++fn legacy_changes(+ engine: NativeJobCatalogDialect,+ request: &NativeJobMutation,+ attributes: &[NativeJobAttributeChange],+ plan: &mut NativeJobSqlPlan,+) -> Result<(), &'static str> {+ let NativeJobRef::Legacy { job_id, .. } = &request.target else {+ return Err("native_job_kind_invalid");+ };+ let mut calls = String::new();+ let mut changed = Vec::new();+ let mut seen = HashSet::new();+ for attribute in attributes.iter().filter(|attribute| attribute.change != NativeJobFieldChange::Keep) {+ let name = attribute.name.to_ascii_uppercase();+ if !seen.insert(name.clone()) {+ return Err("native_job_duplicate_attribute");+ }+ if name == "ZONE" && engine == NativeJobCatalogDialect::OceanbaseOracle {+ let zone = match &attribute.change {+ NativeJobFieldChange::Set { value: Value::String(value) }+ if !value.is_empty() && !value.contains('\0') =>+ {+ text(value)+ }+ NativeJobFieldChange::Clear => "NULL".into(),+ _ => return Err("native_job_attribute_type_invalid"),+ };+ calls.push_str(&format!("SYS.DBMS_JOB.ZONE(job => {job_id}, zone => {zone}, force => FALSE);"));+ // The native view calls this VARCHAR2/NULL column INSTANCE; keep that raw projection.+ changed.push(NativeJobAttributeChange { name: "INSTANCE".into(), change: attribute.change.clone() });+ continue;+ }+ let value = match &attribute.change {+ NativeJobFieldChange::Set { value } => value,+ _ => return Err("native_job_legacy_clear_requires_value"),+ };+ let sql = match name.as_str() {+ "WHAT" | "INTERVAL" => {+ let value = value.as_str().ok_or("native_job_attribute_type_invalid")?;+ format!("SYS.DBMS_JOB.{}({job_id}, {});", name, text(value))+ }+ "NEXT_DATE" => {+ plan.compare_next_date = true;+ format!(+ "SYS.DBMS_JOB.NEXT_DATE({job_id}, TO_DATE({}, 'YYYY-MM-DD HH24:MI:SS'));",+ text(value.as_str().ok_or("native_job_attribute_type_invalid")?)+ )+ }+ "INSTANCE" if engine == NativeJobCatalogDialect::Oracle => {+ format!(+ "SYS.DBMS_JOB.INSTANCE({job_id}, {});",+ value.as_u64().ok_or("native_job_attribute_type_invalid")?+ )+ }+ _ => return Err("native_job_attribute_not_editable"),+ };+ calls.push_str(&sql);+ changed.push(NativeJobAttributeChange { name, change: attribute.change.clone() });+ }+ if !changed.is_empty() {+ plan.required_partitions.push("definition".into());+ plan.steps.push(NativeJobSqlStep {+ id: "definition".into(),+ label: "native_job_step_definition".into(),+ sql: format!("BEGIN {calls} COMMIT; END;"),+ effect: NativeJobStepEffect::Fields(changed),+ });+ }+ Ok(())+}++fn scheduler_changes(+ engine: NativeJobCatalogDialect,+ request: &NativeJobMutation,+ details: &NativeJobDetails,+ attributes: &[NativeJobAttributeChange],+ arguments: &[NativeJobArgumentChange],+ plan: &mut NativeJobSqlPlan,+) -> Result<(), &'static str> {+ let before = definition(details)?;+ let identity = match &details.native_identity {+ NativeJobMetadata::Available { value } => Some(value),+ _ if engine == NativeJobCatalogDialect::OceanbaseOracle => return Err("native_job_identity_unverified"),+ _ => None,+ };+ scheduler_attribute_steps(engine, &request.target, identity, Some(before), attributes, plan)?;+ let original = match &details.snapshot.arguments {+ NativeJobMetadata::Available { value } => value,+ _ if arguments.is_empty() => return Ok(()),+ _ => return Err("native_job_arguments_unavailable"),+ };+ let mut positions = HashSet::new();+ if !arguments.is_empty() && !plan.required_partitions.iter().any(|part| part == "definition") {+ plan.required_partitions.push("definition".into());+ }+ for change in arguments {+ if engine == NativeJobCatalogDialect::Oracle {+ crate::native_job_arguments::validate_lightweight_argument(+ before.get("JOB_STYLE").and_then(Value::as_str),+ &change.value,+ )?;+ }+ if change.position == 0 || !positions.insert(change.position) {+ return Err("native_job_argument_position_invalid");+ }+ let argument = original+ .iter()+ .find(|argument| argument.position == change.position)+ .ok_or("native_job_argument_missing")?;+ if !argument.editable || matches!(change.value, NativeJobArgumentValue::Opaque { .. }) {+ return Err("native_job_argument_not_editable");+ }+ plan.required_partitions.push(format!("argument:{}", change.position));+ plan.steps.push(scheduler_argument_step(engine, &request.target, identity, change, &argument.data_type)?);+ }+ Ok(())+}++fn scheduler_attribute_steps(+ engine: NativeJobCatalogDialect,+ target: &NativeJobRef,+ identity: Option<&NativeJobRow>,+ before: Option<&NativeJobRow>,+ attributes: &[NativeJobAttributeChange],+ plan: &mut NativeJobSqlPlan,+) -> Result<(), &'static str> {+ let name = text(&scheduler_name(engine, target)?);+ let package = scheduler_package(engine);+ let mut seen = HashSet::new();+ let mut batch = Vec::new();+ let mut changes = Vec::new();+ for attribute in attributes.iter().filter(|attribute| attribute.change != NativeJobFieldChange::Keep) {+ let key = attribute.name.to_ascii_uppercase();+ if !seen.insert(key.clone()) {+ return Err("native_job_duplicate_attribute");+ }+ // DM exposes Oracle compatibility columns whose values have no scheduling effect.+ if engine == NativeJobCatalogDialect::Dameng+ && !matches!(+ key.as_str(),+ "AUTO_DROP"+ | "JOB_TYPE"+ | "JOB_ACTION"+ | "NUMBER_OF_ARGUMENTS"+ | "START_DATE"+ | "END_DATE"+ | "REPEAT_INTERVAL"+ | "PROGRAM_NAME"+ | "SCHEDULE_NAME"+ | "COMMENTS"+ | "MAX_RUN_DURATION"+ )+ {+ return Err("native_job_attribute_not_editable");+ }+ // The OB adapter follows the V4.2.5 setter contract, not CREATE_JOB's broader inputs.+ if engine == NativeJobCatalogDialect::OceanbaseOracle+ && !matches!(key.as_str(), "JOB_CLASS" | "MAX_FAILURES" | "MAX_RUN_DURATION" | "INSTANCE_ID")+ {+ return Err("native_job_attribute_not_editable");+ }+ let kind = match key.as_str() {+ "INSTANCE_ID" if engine == NativeJobCatalogDialect::OceanbaseOracle => "text",+ "AUTO_DROP"+ | "RESTARTABLE"+ | "STOP_ON_WINDOW_CLOSE"+ | "STORE_OUTPUT"+ | "ALLOW_RUNS_IN_RESTRICTED_MODE"+ | "INSTANCE_STICKINESS"+ | "FOLLOW_DEFAULT_TIMEZONE" => "boolean",+ "NUMBER_OF_ARGUMENTS"+ | "JOB_PRIORITY"+ | "MAX_RUNS"+ | "MAX_FAILURES"+ | "RAISE_EVENTS"+ | "INSTANCE_ID"+ | "JOB_WEIGHT" => "number",+ "START_DATE" | "END_DATE" => "timestamp",+ "SCHEDULE_LIMIT" | "MAX_RUN_DURATION" => "interval",+ "JOB_ACTION"+ | "JOB_TYPE"+ | "COMMENTS"+ | "REPEAT_INTERVAL"+ | "JOB_CLASS"+ | "CONNECT_CREDENTIAL_NAME"+ | "CREDENTIAL_NAME"+ | "DESTINATION"+ | "DESTINATION_NAME"+ | "PROGRAM_NAME"+ | "SCHEDULE_NAME" => "text",+ "LOGGING_LEVEL" if engine == NativeJobCatalogDialect::Oracle => "logging",+ _ => return Err("native_job_attribute_not_editable"),+ };+ // A missing field is not an empty attribute; keep it available for correction rather than overwrite it.+ if before.is_some_and(|before| !before.contains_key(&key)) {+ return Err("native_job_metadata_incomplete");+ }+ let value = match &attribute.change {+ NativeJobFieldChange::Set { value } => value,+ NativeJobFieldChange::Clear => &Value::Null,+ NativeJobFieldChange::Keep => unreachable!(),+ };+ if key == "DESTINATION"+ && !value.is_null()+ && !value.as_str().is_some_and(|value| !value.is_empty() && !value.contains('\0'))+ {+ return Err("native_job_attribute_value_invalid");+ }+ let value_sql = match (kind, value) {+ (_, Value::Null) if engine == NativeJobCatalogDialect::OceanbaseOracle => {+ return Err("native_job_attribute_null_unsupported");+ }+ (_, Value::Null) => None,+ ("boolean", Value::Bool(value)) => Some(bool_sql(*value).into()),+ ("number", Value::Number(value)) if value.as_u64().is_some() => Some(value.to_string()),+ ("text", Value::String(value)) => Some(text(value)),+ ("logging", Value::String(value)) => Some(match value.as_str() {+ "OFF" => "SYS.DBMS_SCHEDULER.LOGGING_OFF".into(),+ "RUNS" => "SYS.DBMS_SCHEDULER.LOGGING_RUNS".into(),+ "FAILED RUNS" => "SYS.DBMS_SCHEDULER.LOGGING_FAILED_RUNS".into(),+ "FULL" => "SYS.DBMS_SCHEDULER.LOGGING_FULL".into(),+ _ => return Err("native_job_attribute_value_invalid"),+ }),+ ("timestamp", Value::String(value)) => Some(scheduler_timestamp(value)?),+ ("interval", Value::String(value)) if engine == NativeJobCatalogDialect::OceanbaseOracle => {+ Some(text(&ob_duration_seconds(value)?.to_string()))+ }+ ("interval", Value::String(value)) => Some(format!("TO_DSINTERVAL({})", text(value))),+ _ => return Err("native_job_attribute_type_invalid"),+ };+ let attr = text(&key.to_ascii_lowercase());+ let calls = match &value_sql {+ Some(value) => format!("{package}.SET_ATTRIBUTE(name => {name}, attribute => {attr}, value => {value});"),+ None if engine == NativeJobCatalogDialect::Oracle => {+ format!("{package}.SET_ATTRIBUTE_NULL(name => {name}, attribute => {attr});")+ }+ None => format!(+ "{package}.SET_ATTRIBUTE(name => {name}, attribute => {attr}, value => CAST(NULL AS VARCHAR2(4000)));"+ ),+ };+ let changed = NativeJobAttributeChange { name: key.clone(), change: attribute.change.clone() };+ if engine == NativeJobCatalogDialect::Oracle+ && key != "DESTINATION"+ && value.as_str().is_none_or(|value| value.len() <= 4_000)+ {+ batch.push(match value_sql {+ Some(value) => format!("SYS.JOBATTR({name}, {attr}, {value})"),+ None => format!("SYS.JOBATTR({name}, {attr})"),+ });+ changes.push(changed);+ } else {+ plan.steps.push(NativeJobSqlStep {+ id: format!("attribute:{key}"),+ label: "native_job_step_attribute".into(),+ sql: wrap_scheduler(engine, target, identity, &calls)?,+ effect: NativeJobStepEffect::Fields(vec![changed]),+ });+ }+ }+ if !batch.is_empty() {+ plan.steps.insert(+ 0,+ NativeJobSqlStep {+ id: "attributes".into(),+ label: "native_job_step_attributes".into(),+ sql: format!(+ "BEGIN SYS.DBMS_SCHEDULER.SET_JOB_ATTRIBUTES(SYS.JOBATTR_ARRAY({}), 'TRANSACTIONAL'); END;",+ batch.join(", ")+ ),+ effect: NativeJobStepEffect::Fields(changes),+ },+ );+ }+ if !attributes.is_empty() {+ plan.required_partitions.push("definition".into());+ }+ Ok(())+}++fn ob_duration_seconds(value: &str) -> Result<u64, &'static str> {+ let invalid = "native_job_duration_requires_whole_seconds";+ let pattern = regex::Regex::new(r"^\+?(\d+) (\d{1,2}):(\d{2}):(\d{2})(?:\.(0{1,9}))?$").unwrap();+ let captures = pattern.captures(value.trim()).ok_or(invalid)?;+ let component = |index: usize| captures[index].parse::<u64>().map_err(|_| invalid);+ let (days, hours, minutes, seconds) = (component(1)?, component(2)?, component(3)?, component(4)?);+ if hours > 23 || minutes > 59 || seconds > 59 {+ return Err(invalid);+ }+ days.checked_mul(24)+ .and_then(|value| value.checked_add(hours))+ .and_then(|value| value.checked_mul(60))+ .and_then(|value| value.checked_add(minutes))+ .and_then(|value| value.checked_mul(60))+ .and_then(|value| value.checked_add(seconds))+ .filter(|value| *value <= i64::MAX as u64)+ .ok_or(invalid)+}++fn scheduler_timestamp(value: &str) -> Result<String, &'static str> {+ let pattern =+ regex::Regex::new(r"^(\d{4}-\d{2}-\d{2}[T ]\d{2}:\d{2}:\d{2}(?:\.\d{1,9})?) ?([+-]\d{2}:\d{2}|Z)$").unwrap();+ let captures = pattern.captures(value).ok_or("native_job_timestamp_requires_offset")?;+ let offset = if &captures[2] == "Z" { "+00:00" } else { &captures[2] };+ let normalized = format!("{} {offset}", captures[1].replace('T', " "));+ let format =+ if captures[1].contains('.') { "YYYY-MM-DD HH24:MI:SS.FF TZH:TZM" } else { "YYYY-MM-DD HH24:MI:SS TZH:TZM" };+ Ok(format!("TO_TIMESTAMP_TZ({}, '{}')", text(&normalized), format))+}++pub fn scheduler_argument_step(+ engine: NativeJobCatalogDialect,+ target: &NativeJobRef,+ identity: Option<&NativeJobRow>,+ change: &NativeJobArgumentChange,+ data_type: &str,+) -> Result<NativeJobSqlStep, &'static str> {+ let name = text(&scheduler_name(engine, target)?);+ let package = scheduler_package(engine);+ let mut expected = change.clone();+ let mut expected_storage = None;+ let calls = match &change.value {+ NativeJobArgumentValue::Unset | NativeJobArgumentValue::Inherit => {+ if engine == NativeJobCatalogDialect::Dameng {+ return Err("native_job_argument_reset_mapping_unverified");+ }+ format!("{package}.RESET_JOB_ARGUMENT_VALUE(job_name => {name}, argument_position => {});", change.position)+ }+ NativeJobArgumentValue::Value { value: Value::String(value) } if !value.is_empty() => format!(+ "{package}.SET_JOB_ARGUMENT_VALUE(job_name => {name}, argument_position => {}, argument_value => {});",+ change.position,+ text(value)+ ),+ NativeJobArgumentValue::Value { value: Value::Object(_) } if engine == NativeJobCatalogDialect::Oracle => {+ let NativeJobArgumentValue::Value { value } = &change.value else { unreachable!() };+ let setter = format!("{package}.SET_JOB_ANYDATA_VALUE(job_name => {name}, argument_position => {}, argument_value => l_anydata);", change.position);+ let (block, storage) = crate::native_job_arguments::scalar_value_block(value, Some(&setter))?;+ expected.value = storage.editable_value();+ expected_storage = Some(storage);+ block+ }+ NativeJobArgumentValue::Null | NativeJobArgumentValue::Value { value: Value::String(_) }+ if engine == NativeJobCatalogDialect::Oracle =>+ {+ let (expression, storage) = crate::native_job_arguments::null_anydata_expression(data_type)?;+ expected_storage = Some(storage);+ format!("{package}.SET_JOB_ANYDATA_VALUE(job_name => {name}, argument_position => {}, argument_value => {expression});", change.position)+ }+ NativeJobArgumentValue::Null => return Err("native_job_argument_null_mapping_unverified"),+ _ => return Err("native_job_argument_value_invalid"),+ };+ Ok(NativeJobSqlStep {+ id: format!("argument:{}", change.position),+ label: "native_job_step_argument".into(),+ sql: wrap_scheduler(engine, target, identity, &calls)?,+ effect: NativeJobStepEffect::Argument(expected, expected_storage),+ })+}++pub fn scheduler_argument_validation_steps<'a>(+ engine: NativeJobCatalogDialect,+ values: impl IntoIterator<Item = (usize, &'a NativeJobArgumentValue)>,+) -> Result<Vec<NativeJobSqlStep>, &'static str> {+ if engine != NativeJobCatalogDialect::Oracle {+ return Ok(Vec::new());+ }+ values+ .into_iter()+ .filter_map(|(position, value)| match value {+ NativeJobArgumentValue::Value { value: Value::Object(_) } => Some((position, value)),+ _ => None,+ })+ .map(|(position, value)| {+ let NativeJobArgumentValue::Value { value } = value else { unreachable!() };+ Ok(NativeJobSqlStep {+ id: format!("validate-argument:{position}"),+ label: "native_job_step_validate_arguments".into(),+ sql: crate::native_job_arguments::scalar_value_block(value, None)?.0,+ effect: NativeJobStepEffect::ArgumentValidated,+ })+ })+ .collect()+}diff --git a/crates/dbx-sql-schema/src/native_job_changes/creation.rs b/crates/dbx-sql-schema/src/native_job_changes/creation.rsnew file mode 100644index 0000000000..27b8f5ab88--- /dev/null+++ b/crates/dbx-sql-schema/src/native_job_changes/creation.rs@@ -0,0 +1,263 @@+use super::*;++#[derive(Clone)]+pub struct NativeJobSchedulerSqlPlan {+ pub target: NativeJobRef,+ pub steps: Vec<NativeJobSqlStep>,+}++fn nonempty(value: &str) -> Result<(), &'static str> {+ if value.is_empty() || value.contains('\0') {+ Err("native_job_request_invalid")+ } else {+ Ok(())+ }+}++fn reference_name(+ engine: NativeJobCatalogDialect,+ reference: &NativeJobObjectReference,+) -> Result<String, &'static str> {+ nonempty(&reference.owner)?;+ nonempty(&reference.name)?;+ Ok(if engine == NativeJobCatalogDialect::OceanbaseOracle {+ reference.name.clone()+ } else {+ quoted_name(&reference.owner, &reference.name)+ })+}++/// Input-only validation precedes disabled creation. Extra attributes/arguments precede the optional+/// final ENABLE. None is a preview-only generation; apply supplies the identity read after CREATE.+pub fn native_job_scheduler_create_plan(+ engine: NativeJobCatalogDialect,+ scope: &NativeJobScope,+ definition: &NativeJobSchedulerCreate,+ identity: Option<&NativeJobRow>,+) -> Result<NativeJobSchedulerSqlPlan, &'static str> {+ let target = NativeJobRef::Scheduler {+ scope: scope.clone(),+ owner: definition.owner.clone(),+ name: definition.name.clone(),+ };+ target.validate()?;+ if engine == NativeJobCatalogDialect::OceanbaseOracle {+ if definition.schedule.is_some() {+ return Err("native_job_schedule_mapping_unverified");+ }+ if definition.credential_name.is_some() || definition.destination_name.is_some() {+ return Err("native_job_reference_not_supported");+ }+ if definition.job_type.as_deref().is_some_and(|kind| {+ !kind.eq_ignore_ascii_case("STORED_PROCEDURE") && !kind.eq_ignore_ascii_case("PLSQL_BLOCK")+ }) {+ return Err("native_job_type_not_supported");+ }+ }+ let package = scheduler_package(engine);+ let mut parameters = vec![format!("job_name => {}", text(&scheduler_name(engine, &target)?))];+ if let Some(program) = &definition.program {+ if definition.job_type.is_some() || definition.job_action.is_some() || definition.number_of_arguments != 0 {+ return Err("native_job_program_conflicts_with_inline_definition");+ }+ parameters.push(format!("program_name => {}", text(&reference_name(engine, program)?)));+ } else {+ let job_type = definition.job_type.as_deref().ok_or("native_job_type_required")?;+ let action = definition.job_action.as_deref().ok_or("native_job_action_required")?;+ nonempty(job_type)?;+ nonempty(action)?;+ if definition.number_of_arguments > 255+ || (job_type.eq_ignore_ascii_case("PLSQL_BLOCK") && definition.number_of_arguments != 0)+ {+ return Err("native_job_argument_count_invalid");+ }+ parameters.push(format!("job_type => {}", text(job_type)));+ parameters.push(format!("job_action => {}", text(action)));+ parameters.push(format!(+ "{} => {}",+ if engine == NativeJobCatalogDialect::OceanbaseOracle {+ "number_of_argument"+ } else {+ "number_of_arguments"+ },+ definition.number_of_arguments+ ));+ }+ if let Some(style) = &definition.job_style {+ if definition.program.is_none() {+ return Err("native_job_style_requires_program");+ }+ if definition.event_source.is_some() {+ return Err("native_job_style_not_applicable_to_event");+ }+ nonempty(style)?;+ parameters.push(format!("job_style => {}", text(style)));+ }+ if let Some(schedule) = &definition.schedule {+ if definition.start_date.is_some()+ || definition.end_date.is_some()+ || definition.repeat_interval.is_some()+ || definition.event_condition.is_some()+ || definition.event_source.is_some()+ {+ return Err("native_job_schedule_conflicts_with_inline_definition");+ }+ parameters.push(format!("schedule_name => {}", text(&reference_name(engine, schedule)?)));+ } else {+ if let Some(date) = &definition.start_date {+ parameters.push(format!("start_date => {}", create_timestamp(engine, date)?));+ }+ if let Some(date) = &definition.end_date {+ parameters.push(format!("end_date => {}", create_timestamp(engine, date)?));+ }+ if let Some(event) = &definition.event_source {+ if engine != NativeJobCatalogDialect::Oracle {+ return Err("native_job_event_mapping_unverified");+ }+ if definition.repeat_interval.is_some() {+ return Err("native_job_event_conflicts_with_calendar");+ }+ let queue = match event {+ NativeJobEventSource::Queue { owner, name, agent } => {+ let mut queue =+ reference_name(engine, &NativeJobObjectReference { owner: owner.clone(), name: name.clone() })?;+ if let Some(agent) = agent {+ nonempty(agent)?;+ queue.push_str(&format!(",\"{}\"", agent.replace('"', "\"\"")));+ }+ queue+ }+ NativeJobEventSource::FileWatcher { reference } => reference_name(engine, reference)?,+ };+ parameters.push(format!("queue_spec => {}", text(&queue)));+ if let Some(condition) = &definition.event_condition {+ parameters.push(format!("event_condition => {}", text(condition)));+ } else if definition.program.is_some() {+ parameters.push("event_condition => NULL".into());+ }+ if definition.program.is_some() {+ if definition.start_date.is_none() {+ parameters.push("start_date => NULL".into());+ }+ if definition.end_date.is_none() {+ parameters.push("end_date => NULL".into());+ }+ }+ } else {+ if definition.event_condition.is_some() {+ return Err("native_job_event_queue_required");+ }+ if let Some(repeat) = &definition.repeat_interval {+ parameters.push(format!("repeat_interval => {}", text(repeat)));+ }+ }+ }+ for (key, value) in [+ ("job_class", &definition.job_class),+ ("comments", &definition.comments),+ ("credential_name", &definition.credential_name),+ ("destination_name", &definition.destination_name),+ ] {+ if let Some(value) = value {+ if value.contains('\0') {+ return Err("native_job_request_invalid");+ }+ parameters.push(format!("{key} => {}", text(value)));+ }+ }+ parameters.push("enabled => FALSE".into());+ parameters.push(format!("auto_drop => {}", bool_sql(definition.auto_drop)));+ let create = NativeJobSqlStep {+ id: "create".into(),+ label: "native_job_step_create_disabled".into(),+ sql: format!("BEGIN {package}.CREATE_JOB({}); END;", parameters.join(", ")),+ effect: NativeJobStepEffect::Created,+ };+ // Creation inputs each have one owner. Advanced settings cannot silently override a base field+ // or activate a job before all configuration has been verified.+ for attribute in &definition.attributes {+ if matches!(+ attribute.name.to_ascii_uppercase().as_str(),+ "JOB_TYPE"+ | "JOB_ACTION"+ | "NUMBER_OF_ARGUMENTS"+ | "PROGRAM_NAME"+ | "SCHEDULE_NAME"+ | "START_DATE"+ | "END_DATE"+ | "REPEAT_INTERVAL"+ | "AUTO_DROP"+ | "COMMENTS"+ | "JOB_CLASS"+ | "ENABLED"+ | "CREDENTIAL_NAME"+ | "DESTINATION_NAME"+ ) {+ return Err("native_job_duplicate_attribute");+ }+ }+ let mut configured = NativeJobSqlPlan {+ steps: Vec::new(),+ required_partitions: Vec::new(),+ compare_next_date: false,+ dameng_configuration: None,+ };+ scheduler_attribute_steps(engine, &target, identity, None, &definition.attributes, &mut configured)?;+ let mut positions = HashSet::new();+ for argument in &definition.arguments {+ if engine == NativeJobCatalogDialect::Oracle {+ crate::native_job_arguments::validate_lightweight_argument(+ definition.job_style.as_deref(),+ &argument.value,+ )?;+ }+ if argument.position == 0+ || !positions.insert(argument.position)+ || (definition.program.is_none() && argument.position > definition.number_of_arguments)+ {+ return Err("native_job_argument_position_invalid");+ }+ if matches!(argument.value, NativeJobArgumentValue::Unset | NativeJobArgumentValue::Inherit) {+ continue;+ }+ configured.steps.push(scheduler_argument_step(+ engine,+ &target,+ identity,+ &NativeJobArgumentChange { position: argument.position, value: argument.value.clone() },+ &argument.data_type,+ )?);+ }+ if definition.enabled {+ let name = text(&scheduler_name(engine, &target)?);+ configured.steps.push(NativeJobSqlStep {+ id: "enable".into(),+ label: "native_job_step_enable".into(),+ sql: wrap_scheduler(engine, &target, identity, &format!("{package}.ENABLE({name});"))?,+ effect: NativeJobStepEffect::Enabled(true),+ });+ }+ let mut steps = scheduler_argument_validation_steps(+ engine,+ definition.arguments.iter().map(|argument| (argument.position, &argument.value)),+ )?;+ steps.push(create);+ steps.extend(configured.steps);+ Ok(NativeJobSchedulerSqlPlan { target, steps })+}++fn create_timestamp(engine: NativeJobCatalogDialect, value: &str) -> Result<String, &'static str> {+ let timestamp = scheduler_timestamp(value)?;+ if engine == NativeJobCatalogDialect::OceanbaseOracle+ && value.split_once('.').is_some_and(|(_, fraction)| {+ fraction.bytes().take_while(u8::is_ascii_digit).skip(6).any(|digit| digit != b'0')+ })+ {+ return Err("native_job_timestamp_precision_microseconds");+ }+ Ok(if engine == NativeJobCatalogDialect::OceanbaseOracle {+ format!("CAST({timestamp} AT TIME ZONE SESSIONTIMEZONE AS TIMESTAMP(9))")+ } else {+ timestamp+ })+}diff --git a/crates/dbx-sql-schema/src/native_job_changes/dameng.rs b/crates/dbx-sql-schema/src/native_job_changes/dameng.rsnew file mode 100644index 0000000000..5996266e16--- /dev/null+++ b/crates/dbx-sql-schema/src/native_job_changes/dameng.rs@@ -0,0 +1,614 @@+use super::*;+use crate::native_jobs::{NativeJobCatalogCoverage, NativeJobCatalogQuery};+use std::collections::BTreeMap;++mod creation;+mod legacy;+pub use legacy::{native_job_dameng_civil_time, native_job_dameng_date_query, native_job_dameng_legacy_time};+mod parts;+pub use creation::{native_job_dameng_create_plan, native_job_dameng_name_queries, NativeJobDamengCreatePlan};++pub fn native_job_dameng_identity_queries(target: &NativeJobRef) -> Result<Vec<NativeJobCatalogQuery>, &'static str> {+ target.validate()?;+ let (NativeJobRef::DamengNative { job_id, .. } | NativeJobRef::Legacy { job_id, .. }) = target else {+ return Err("native_job_kind_invalid");+ };+ Ok([("SYSJOB.SYSJOBS", NativeJobCatalogCoverage::Database), ("SYSJOB.USER_JOBS_VIEW", NativeJobCatalogCoverage::CurrentUser)].into_iter().map(|(source, coverage)| NativeJobCatalogQuery {+ source, coverage, limit: 1,+ sql: format!("SELECT CAST(ID AS VARCHAR(40)) AS DBX_JOB_ID, CREATETIME AS DBX_CREATED_AT, NAME, USERNAME, SYS_FLAG FROM {source} WHERE ID = {job_id}"),+ }).collect())+}++pub fn native_job_dameng_what_query(body: &str) -> NativeJobCatalogQuery {+ NativeJobCatalogQuery {+ source: "DUAL",+ coverage: NativeJobCatalogCoverage::Accessible,+ sql: format!("SELECT CAST({} AS VARCHAR2(32767)) AS DBX_WHAT FROM DUAL", text(body)),+ limit: 1,+ }+}++pub(super) fn rename_changes(+ request: &NativeJobMutation,+ details: &NativeJobDetails,+) -> Result<Option<NativeJobSqlPlan>, &'static str> {+ let attributes = match &request.change {+ NativeJobChange::Update { attributes, .. } => attributes,+ NativeJobChange::ConfigureDameng { configuration } => &configuration.attributes,+ _ => return Ok(None),+ };+ let names = attributes+ .iter()+ .filter(|attribute| {+ attribute.name.eq_ignore_ascii_case("NAME") && attribute.change != NativeJobFieldChange::Keep+ })+ .collect::<Vec<_>>();+ if names.len() > 1 {+ return Err("native_job_duplicate_attribute");+ }+ let Some(change) = names.first() else {+ return Ok(None);+ };+ let NativeJobFieldChange::Set { value: Value::String(new_name) } = &change.change else {+ return Err("native_job_attribute_type_invalid");+ };+ // Parent Job names use the documented ASCII name domain too; catalog names remain unmodified.+ parts::valid_name(new_name).map_err(|_| "native_job_name_invalid")?;+ let old_name = target_name(NativeJobCatalogDialect::Dameng, &request.target, details)?;+ let mut base = request.clone();+ let attributes = match &mut base.change {+ NativeJobChange::Update { attributes, .. } => attributes,+ NativeJobChange::ConfigureDameng { configuration } => &mut configuration.attributes,+ _ => unreachable!(),+ };+ attributes.retain(|attribute| !attribute.name.eq_ignore_ascii_case("NAME"));+ let mut plan = match native_job_mutation_plan(NativeJobCatalogDialect::Dameng, &base, details) {+ Ok(plan) => plan,+ Err("native_job_no_changes") => NativeJobSqlPlan {+ steps: Vec::new(),+ required_partitions: vec!["definition".into()],+ compare_next_date: false,+ dameng_configuration: Some(NativeJobDamengConfigPlan { operators: Vec::new() }),+ },+ Err(reason) => return Err(reason),+ };+ if new_name == &old_name {+ return if plan.steps.is_empty() { Err("native_job_no_changes") } else { Ok(Some(plan)) };+ }+ flag(current(definition(details)?, "ENABLE")?)?;+ let at = plan+ .steps+ .iter()+ .position(|step| matches!(step.effect, NativeJobStepEffect::Enabled(true)))+ .unwrap_or(plan.steps.len());+ plan.steps.insert(+ at,+ NativeJobSqlStep {+ id: "rename".into(),+ label: "native_job_step_attribute".into(),+ sql: guarded_call(+ &request.target,+ details,+ &format!("SP_RENAME_JOB({}, {}); COMMIT;", text(&old_name), text(new_name)),+ )?,+ effect: NativeJobStepEffect::DamengRenamed { old_name, new_name: new_name.clone() },+ },+ );+ let mut rebound = details.clone();+ if let NativeJobRef::DamengNative { name, .. } = &mut rebound.snapshot.job_ref {+ *name = new_name.clone();+ }+ if let NativeJobMetadata::Available { value } = &mut rebound.snapshot.definition {+ value.insert("NAME".into(), Value::String(new_name.clone()));+ }+ for step in &mut plan.steps[at + 1..] {+ if let NativeJobStepEffect::Enabled(enabled) = step.effect {+ step.sql = guarded_call(+ &rebound.snapshot.job_ref,+ &rebound,+ &format!("SP_ENABLE_JOB({}, {});", text(new_name), u8::from(enabled)),+ )?;+ }+ }+ Ok(Some(plan))+}+pub use parts::{+ native_job_dameng_catalog_id, native_job_dameng_child_id, native_job_dameng_child_key,+ resolve_native_job_dameng_child_step, NativeJobDamengChildAction, NativeJobDamengChildEffect,+ NativeJobDamengChildReference, NativeJobDamengPart,+};++#[derive(Clone)]+pub enum NativeJobDamengOperatorSelector {+ Unassigned,+ Id(i64),+ Name(String),+}++#[derive(Clone)]+pub struct NativeJobDamengOperator {+ pub column: &'static str,+ pub selector: NativeJobDamengOperatorSelector,+}++#[derive(Clone)]+pub struct NativeJobDamengConfigPlan {+ pub operators: Vec<NativeJobDamengOperator>,+}++impl NativeJobDamengConfigPlan {+ /// Resolve only this definition's references before pausing or changing the native job.+ pub fn operator_query(&self) -> Option<NativeJobCatalogQuery> {+ let selectors = self+ .operators+ .iter()+ .map(|operator| {+ (+ operator.column,+ match &operator.selector {+ NativeJobDamengOperatorSelector::Unassigned => None,+ NativeJobDamengOperatorSelector::Id(id) => Some(format!("ID = {id}")),+ NativeJobDamengOperatorSelector::Name(name) => {+ Some(format!("UPPER(NAME) = UPPER({})", text(name)))+ }+ },+ )+ })+ .collect::<Vec<_>>();+ let predicates = selectors.iter().filter_map(|(_, predicate)| predicate.as_deref()).collect::<Vec<_>>();+ let matches = selectors+ .iter()+ .map(|(column, predicate)| match predicate {+ Some(predicate) => format!("CASE WHEN {predicate} THEN 1 ELSE 0 END AS DBX_MATCH_{column}"),+ None => format!("0 AS DBX_MATCH_{column}"),+ })+ .collect::<Vec<_>>()+ .join(", ");+ (!predicates.is_empty()).then(|| NativeJobCatalogQuery {+ source: "SYSJOB.SYSOPERATORS",+ coverage: NativeJobCatalogCoverage::Database,+ sql: format!(+ "SELECT CAST(ID AS VARCHAR(40)) AS DBX_OPERATOR_ID, NAME, {matches} FROM SYSJOB.SYSOPERATORS WHERE {} ORDER BY ID",+ predicates.join(" OR ")+ ),+ limit: 4,+ })+ }+}++fn integer(value: &Value) -> Result<i64, &'static str> {+ value.as_i64().or_else(|| value.as_str()?.parse().ok()).ok_or("native_job_attribute_type_invalid")+}++fn flag(value: &Value) -> Result<bool, &'static str> {+ match value {+ Value::Bool(value) => Ok(*value),+ _ => match integer(value)? {+ 0 => Ok(false),+ 1 => Ok(true),+ _ => Err("native_job_attribute_value_invalid"),+ },+ }+}++fn scalar(value: &Value) -> Result<String, &'static str> {+ match value {+ Value::Null => Ok("NULL".into()),+ Value::String(value) if !value.contains('\0') => Ok(text(value)),+ _ => Err("native_job_attribute_type_invalid"),+ }+}++fn current<'a>(row: &'a NativeJobRow, key: &str) -> Result<&'a Value, &'static str> {+ row.get(key).ok_or("native_job_metadata_incomplete")+}++fn desired(+ row: &NativeJobRow,+ changes: &BTreeMap<String, NativeJobFieldChange>,+ key: &str,+) -> Result<Value, &'static str> {+ match changes.get(key) {+ Some(NativeJobFieldChange::Set { value }) => Ok(value.clone()),+ Some(NativeJobFieldChange::Clear) => Ok(Value::Null),+ _ => Ok(current(row, key)?.clone()),+ }+}++fn operator(+ row: &NativeJobRow,+ changes: &BTreeMap<String, NativeJobFieldChange>,+ input: &str,+ column: &'static str,+) -> Result<NativeJobDamengOperator, &'static str> {+ let selector = match changes.get(input) {+ Some(NativeJobFieldChange::Clear) => NativeJobDamengOperatorSelector::Unassigned,+ Some(NativeJobFieldChange::Set { value: Value::String(name) }) if !name.is_empty() && !name.contains('\0') => {+ NativeJobDamengOperatorSelector::Name(name.clone())+ }+ Some(NativeJobFieldChange::Set { .. }) => return Err("native_job_attribute_type_invalid"),+ _ => match current(row, column)? {+ Value::Null => NativeJobDamengOperatorSelector::Unassigned,+ value => {+ let id = integer(value)?;+ if id > 0 {+ NativeJobDamengOperatorSelector::Id(id)+ } else {+ NativeJobDamengOperatorSelector::Unassigned+ }+ }+ },+ };+ Ok(NativeJobDamengOperator { column, selector })+}++fn operator_sql(operator: &NativeJobDamengOperator, variable: &str) -> (String, String) {+ let predicate = match &operator.selector {+ NativeJobDamengOperatorSelector::Unassigned => return (String::new(), "NULL".into()),+ NativeJobDamengOperatorSelector::Id(id) => format!("ID = {id}"),+ NativeJobDamengOperatorSelector::Name(name) => format!("UPPER(NAME) = UPPER({})", text(name)),+ };+ (format!("SELECT NAME INTO {variable} FROM SYSJOB.SYSOPERATORS WHERE {predicate}; "), variable.into())+}++pub(super) fn guarded_call(+ target: &NativeJobRef,+ details: &NativeJobDetails,+ calls: &str,+) -> Result<String, &'static str> {+ let name = target_name(NativeJobCatalogDialect::Dameng, target, details)?;+ let id = match target {+ NativeJobRef::DamengNative { job_id, .. } | NativeJobRef::Legacy { job_id, .. } => job_id,+ _ => return Err("native_job_kind_invalid"),+ };+ let source = match details+ .sources+ .get("identity")+ .and_then(|source| source.source.as_deref())+ .or_else(|| details.sources.get("definition").and_then(|source| source.source.as_deref()))+ {+ Some("SYSJOB.SYSJOBS") => "SYSJOB.SYSJOBS",+ Some("SYSJOB.USER_JOBS_VIEW") => "SYSJOB.USER_JOBS_VIEW",+ _ => return Err("native_job_catalog_source_unverified"),+ };+ let NativeJobMetadata::Available { value: identity } = &details.native_identity else {+ return Err("native_job_identity_unverified");+ };+ if identity.get("DBX_JOB_ID").and_then(Value::as_str) != Some(id) {+ return Err("native_job_identity_unverified");+ }+ let created = string_field(identity, "DBX_CREATED_AT")?;+ Ok(format!("DECLARE dbx_target_count INT; dbx_target_changed EXCEPTION; dbx_email_operator VARCHAR(128); dbx_netsend_operator VARCHAR(128); BEGIN SELECT COUNT(*) INTO dbx_target_count FROM {source} WHERE ID = {id} AND NAME = {} AND CREATETIME = {}; IF dbx_target_count <> 1 THEN RAISE dbx_target_changed; END IF; {calls} END;", text(&name), text(created)))+}++pub(super) fn metadata_changes(+ request: &NativeJobMutation,+ details: &NativeJobDetails,+ attributes: &[NativeJobAttributeChange],+ plan: &mut NativeJobSqlPlan,+) -> Result<(), &'static str> {+ if !matches!(request.target, NativeJobRef::Legacy { .. }) {+ return native_metadata_changes(request, details, attributes, plan);+ }+ let interval = attributes+ .iter()+ .filter(|attribute| {+ attribute.name.eq_ignore_ascii_case("INTERVAL") && attribute.change != NativeJobFieldChange::Keep+ })+ .collect::<Vec<_>>();+ if interval.len() > 1 {+ return Err("native_job_duplicate_attribute");+ }+ let what = attributes+ .iter()+ .filter(|attribute| {+ attribute.name.eq_ignore_ascii_case("WHAT") && attribute.change != NativeJobFieldChange::Keep+ })+ .collect::<Vec<_>>();+ if what.len() > 1 {+ return Err("native_job_duplicate_attribute");+ }+ let dates = attributes+ .iter()+ .filter(|attribute| {+ attribute.name.eq_ignore_ascii_case("NEXT_DATE") && attribute.change != NativeJobFieldChange::Keep+ })+ .collect::<Vec<_>>();+ if dates.len() > 1 {+ return Err("native_job_duplicate_attribute");+ }+ if interval.is_empty() && what.is_empty() && dates.is_empty() {+ return native_metadata_changes(request, details, attributes, plan);+ }+ let Some(NativeJobMetadata::Available { value: legacy }) = &details.legacy_definition else {+ return Err("native_job_legacy_definition_unavailable");+ };+ for column in ["WHAT", "NEXT_DATE", "INTERVAL", "INSTANCE"] {+ current(legacy, column)?;+ }+ let legacy_value = |attribute: &&NativeJobAttributeChange| -> Result<String, &'static str> {+ let NativeJobFieldChange::Set { value: Value::String(input) } = &attribute.change else {+ return Err("native_job_attribute_type_invalid");+ };+ if input.is_empty() || input.contains('\0') {+ return Err("native_job_attribute_value_invalid");+ }+ Ok(input.clone())+ };+ let body = what.first().map(legacy_value).transpose()?;+ let interval = interval.first().map(legacy_value).transpose()?;+ let date =+ dates.first().map(legacy_value).transpose()?.map(|value| native_job_dameng_civil_time(&value)).transpose()?;+ if date.is_some() {+ native_job_dameng_legacy_time(legacy)?;+ plan.compare_next_date = true;+ }+ let native = attributes+ .iter()+ .filter(|attribute| {+ !["INTERVAL", "WHAT", "NEXT_DATE"].iter().any(|name| attribute.name.eq_ignore_ascii_case(name))+ })+ .cloned()+ .collect::<Vec<_>>();+ native_metadata_changes(request, details, &native, plan)?;+ let name = target_name(NativeJobCatalogDialect::Dameng, &request.target, details)?;+ let guard = |calls: &str| guarded_call(&request.target, details, calls);+ if plan.steps.is_empty() {+ plan.steps.push(NativeJobSqlStep {+ id: "pause".into(),+ label: "native_job_step_pause_scheduling".into(),+ sql: guard(&format!("SP_ENABLE_JOB({}, 0);", text(&name)))?,+ effect: NativeJobStepEffect::Enabled(false),+ });+ if flag(current(definition(details)?, "ENABLE")?)? {+ plan.steps.push(NativeJobSqlStep {+ id: "enable".into(),+ label: "native_job_step_enable".into(),+ sql: guard(&format!("SP_ENABLE_JOB({}, 1);", text(&name)))?,+ effect: NativeJobStepEffect::Enabled(true),+ });+ }+ plan.required_partitions.push("definition".into());+ plan.dameng_configuration = Some(NativeJobDamengConfigPlan { operators: Vec::new() });+ }+ let NativeJobRef::Legacy { job_id, .. } = &request.target else { unreachable!() };+ let at = plan+ .steps+ .iter()+ .position(|step| matches!(step.effect, NativeJobStepEffect::Enabled(true)))+ .unwrap_or(plan.steps.len());+ let mut setters = Vec::new();+ if let Some(body) = body {+ setters.push(NativeJobSqlStep {+ id: "legacy_what".into(),+ label: "native_job_step_attribute".into(),+ sql: guard(&format!("DECLARE dbx_what VARCHAR2(32767); BEGIN dbx_what := {}; DBMS_JOB.WHAT({job_id}, dbx_what); COMMIT; END;", text(&body)))?,+ effect: NativeJobStepEffect::DamengLegacyWhat { expected: body },+ });+ }+ if let Some(input) = interval {+ let digits = input.trim_start_matches('0');+ let expected_seconds =+ (!digits.is_empty() && input.bytes().all(|byte| byte.is_ascii_digit())).then(|| digits.to_string());+ let expression =+ expected_seconds.as_ref().map_or_else(|| input.clone(), |seconds| format!("SYSDATE+{seconds}/86400"));+ setters.push(NativeJobSqlStep {+ id: "legacy_interval".into(),+ label: "native_job_step_attribute".into(),+ sql: guard(&format!("DBMS_JOB.\"INTERVAL\"({job_id}, {}); COMMIT;", text(&expression)))?,+ effect: NativeJobStepEffect::DamengLegacyInterval { expected_seconds },+ });+ }+ if let Some(expected) = date {+ setters.push(NativeJobSqlStep {+ id: "legacy_next_date".into(),+ label: "native_job_step_attribute".into(),+ sql: guard(&format!(+ "DBMS_JOB.NEXT_DATE({job_id}, CAST(TIMESTAMP {} AS DATETIME(6))); COMMIT;",+ text(&expected)+ ))?,+ effect: NativeJobStepEffect::DamengLegacyNextDate { expected },+ });+ }+ plan.steps.splice(at..at, setters);+ plan.required_partitions.extend(["legacyDefinition", "steps", "schedules"].map(str::to_string));+ Ok(())+}++fn native_metadata_changes(+ request: &NativeJobMutation,+ details: &NativeJobDetails,+ attributes: &[NativeJobAttributeChange],+ plan: &mut NativeJobSqlPlan,+) -> Result<(), &'static str> {+ let row = definition(details)?;+ let name = target_name(NativeJobCatalogDialect::Dameng, &request.target, details)?;+ let changes = metadata_patches(attributes)?;+ if changes.is_empty() {+ return Ok(());+ }+ let enabled = flag(&desired(row, &changes, "ENABLE")?)?;+ let basic = changes.keys().any(|key| !matches!(key.as_str(), "ENABLE" | "EP_SEQNO" | "RAFT_NAME"));+ let mut configuration = NativeJobDamengConfigPlan { operators: Vec::new() };+ let guard = |calls: &str| guarded_call(&request.target, details, calls);+ let mut steps = vec![NativeJobSqlStep {+ id: "pause".into(),+ label: "native_job_step_pause_scheduling".into(),+ sql: guard(&format!("SP_ENABLE_JOB({}, 0);", text(&name)))?,+ effect: NativeJobStepEffect::Enabled(false),+ }];+ if basic {+ let (calls, fields, operators) = basic_definition(row, &changes, &name, "SP_ALTER_JOB")?;+ steps.push(NativeJobSqlStep {+ id: "definition".into(),+ label: "native_job_step_definition".into(),+ sql: guard(&calls)?,+ effect: NativeJobStepEffect::DamengDefinition(fields),+ });+ configuration.operators = operators;+ }+ steps.push(NativeJobSqlStep {+ id: "config_start".into(),+ label: "native_job_step_config_start".into(),+ sql: guard(&format!("SP_JOB_CONFIG_START({});", text(&name)))?,+ effect: NativeJobStepEffect::DamengConfigurationStarted,+ });+ for key in ["EP_SEQNO", "RAFT_NAME"] {+ if !changes.contains_key(key) {+ continue;+ }+ current(row, key)?;+ let value = desired(row, &changes, key)?;+ steps.push(NativeJobSqlStep {+ id: format!("attribute:{key}"),+ label: "native_job_step_attribute".into(),+ sql: guard(&node_call(&name, key, &value)?)?,+ effect: NativeJobStepEffect::Fields(vec![NativeJobAttributeChange {+ name: key.into(),+ change: NativeJobFieldChange::Set { value },+ }]),+ });+ }+ steps.push(NativeJobSqlStep {+ id: "config_commit".into(),+ label: "native_job_step_config_commit".into(),+ sql: guard(&format!("SP_JOB_CONFIG_COMMIT({});", text(&name)))?,+ effect: NativeJobStepEffect::DamengConfigurationCommitted,+ });+ if enabled {+ steps.push(NativeJobSqlStep {+ id: "enable".into(),+ label: "native_job_step_enable".into(),+ sql: guard(&format!("SP_ENABLE_JOB({}, 1);", text(&name)))?,+ effect: NativeJobStepEffect::Enabled(true),+ });+ }+ plan.steps = steps;+ plan.required_partitions.push("definition".into());+ plan.dameng_configuration = Some(configuration);+ Ok(())+}++fn metadata_patches(+ attributes: &[NativeJobAttributeChange],+) -> Result<BTreeMap<String, NativeJobFieldChange>, &'static str> {+ let mut changes = BTreeMap::new();+ for attribute in attributes.iter().filter(|attribute| attribute.change != NativeJobFieldChange::Keep) {+ let key = attribute.name.to_ascii_uppercase();+ if !matches!(+ key.as_str(),+ "ENABLE"+ | "DESCRIBE"+ | "ENABLE_EMAIL"+ | "EMAIL_OPERATOR_NAME"+ | "EMAIL_TYPE"+ | "ENABLE_NETSEND"+ | "NETSEND_OPERATOR_NAME"+ | "NETSEND_TYPE"+ | "EP_SEQNO"+ | "RAFT_NAME"+ ) {+ return Err("native_job_attribute_not_editable");+ }+ if changes.insert(key, attribute.change.clone()).is_some() {+ return Err("native_job_duplicate_attribute");+ }+ }+ Ok(changes)+}++fn basic_definition(+ row: &NativeJobRow,+ changes: &BTreeMap<String, NativeJobFieldChange>,+ name: &str,+ procedure: &str,+) -> Result<(String, Vec<NativeJobAttributeChange>, Vec<NativeJobDamengOperator>), &'static str> {+ let email = flag(&desired(row, changes, "ENABLE_EMAIL")?)?;+ let netsend = flag(&desired(row, changes, "ENABLE_NETSEND")?)?;+ let email_type = desired(row, changes, "EMAIL_TYPE")?;+ let netsend_type = desired(row, changes, "NETSEND_TYPE")?;+ if !(0..=2).contains(&integer(&email_type)?) || !(0..=2).contains(&integer(&netsend_type)?) {+ return Err("native_job_attribute_value_invalid");+ }+ let email_operator = operator(row, changes, "EMAIL_OPERATOR_NAME", "EMAIL_OPERID")?;+ let netsend_operator = operator(row, changes, "NETSEND_OPERATOR_NAME", "NETSEND_OPERID")?;+ if (email && matches!(email_operator.selector, NativeJobDamengOperatorSelector::Unassigned))+ || (netsend && matches!(netsend_operator.selector, NativeJobDamengOperatorSelector::Unassigned))+ {+ return Err("native_job_notification_operator_required");+ }+ let description = desired(row, changes, "DESCRIBE")?;+ let (email_lookup, email_name) = operator_sql(&email_operator, "dbx_email_operator");+ let (netsend_lookup, netsend_name) = operator_sql(&netsend_operator, "dbx_netsend_operator");+ let calls = format!(+ "{email_lookup}{netsend_lookup}{procedure}({}, 0, {}, {email_name}, {}, {}, {netsend_name}, {}, {});",+ text(name),+ u8::from(email),+ integer(&email_type)?,+ u8::from(netsend),+ integer(&netsend_type)?,+ scalar(&description)?+ );+ let fields = [+ ("ENABLE_EMAIL", Value::Bool(email)),+ ("EMAIL_TYPE", email_type),+ ("ENABLE_NETSEND", Value::Bool(netsend)),+ ("NETSEND_TYPE", netsend_type),+ ("DESCRIBE", description),+ ]+ .into_iter()+ .map(|(name, value)| NativeJobAttributeChange { name: name.into(), change: NativeJobFieldChange::Set { value } })+ .collect();+ Ok((calls, fields, vec![email_operator, netsend_operator]))+}++fn node_call(name: &str, key: &str, value: &Value) -> Result<String, &'static str> {+ let (procedure, value_sql) = if key == "EP_SEQNO" {+ let value = integer(value)?;+ if !(0..=15).contains(&value) {+ return Err("native_job_attribute_value_invalid");+ }+ ("SP_JOB_SET_EP_SEQNO", value.to_string())+ } else {+ ("SP_JOB_SET_RAFT_NAME", scalar(value)?)+ };+ Ok(format!("{procedure}({}, {value_sql});", text(name)))+}++pub(super) fn configuration_changes(+ request: &NativeJobMutation,+ details: &NativeJobDetails,+ configuration: &NativeJobDamengConfiguration,+ plan: &mut NativeJobSqlPlan,+) -> Result<(), &'static str> {+ let mut children = parts::part_steps(NativeJobDamengPart::Steps, &configuration.steps, &request.target, details)?;+ let schedules =+ parts::part_steps(NativeJobDamengPart::Schedules, &configuration.schedules, &request.target, details)?;+ let has_steps = !children.is_empty();+ let has_schedules = !schedules.is_empty();+ children.extend(schedules);+ let mut attributes = configuration.attributes.clone();+ if attributes.iter().all(|attribute| attribute.change == NativeJobFieldChange::Keep) {+ if children.is_empty() {+ return Ok(());+ }+ attributes.push(NativeJobAttributeChange {+ name: "ENABLE".into(),+ change: NativeJobFieldChange::Set { value: current(definition(details)?, "ENABLE")?.clone() },+ });+ }+ metadata_changes(request, details, &attributes, plan)?;+ let commit = plan+ .steps+ .iter()+ .position(|step| matches!(step.effect, NativeJobStepEffect::DamengConfigurationCommitted))+ .expect("configuration commit");+ plan.steps.splice(commit..commit, children);+ if has_steps {+ plan.required_partitions.push("steps".into());+ }+ if has_schedules {+ plan.required_partitions.push("schedules".into());+ }+ Ok(())+}diff --git a/crates/dbx-sql-schema/src/native_job_changes/dameng/creation.rs b/crates/dbx-sql-schema/src/native_job_changes/dameng/creation.rsnew file mode 100644index 0000000000..325cff20f6--- /dev/null+++ b/crates/dbx-sql-schema/src/native_job_changes/dameng/creation.rs@@ -0,0 +1,120 @@+use super::*;++#[derive(Clone)]+pub struct NativeJobDamengCreatePlan {+ pub steps: Vec<NativeJobSqlStep>,+ pub configuration: NativeJobDamengConfigPlan,+ pub definition_fields: Vec<NativeJobAttributeChange>,+ pub remaining: NativeJobDamengConfiguration,+}++/// Name lookup is only for absence checks and an acknowledged CREATE receipt, never OUT-ID guessing.+pub fn native_job_dameng_name_queries(name: &str) -> Result<Vec<NativeJobCatalogQuery>, &'static str> {+ parts::valid_name(name).map_err(|_| "native_job_name_invalid")?;+ Ok([+ ("SYSJOB.SYSJOBS", NativeJobCatalogCoverage::Database),+ ("SYSJOB.USER_JOBS_VIEW", NativeJobCatalogCoverage::CurrentUser),+ ]+ .into_iter()+ .map(|(source, coverage)| NativeJobCatalogQuery {+ source,+ coverage,+ sql: format!(+ "SELECT CAST(ID AS VARCHAR(40)) AS DBX_JOB_ID, NAME, USERNAME FROM {source} WHERE UPPER(NAME) = UPPER({})",+ text(name)+ ),+ limit: 1,+ })+ .collect())+}++/// No fabricated target or generation enters the preview. Apply rebuilds configuration guards after+/// the disabled CREATE is acknowledged and its exact native identity is read on the owned session.+pub fn native_job_dameng_create_plan(+ definition: &NativeJobDamengCreate,+) -> Result<NativeJobDamengCreatePlan, &'static str> {+ parts::valid_name(&definition.name).map_err(|_| "native_job_name_invalid")?;+ let changes = metadata_patches(&definition.configuration.attributes)?;+ if changes.contains_key("ENABLE") {+ return Err("native_job_duplicate_attribute");+ }+ let defaults: NativeJobRow = serde_json::from_value(serde_json::json!({+ "ENABLE_EMAIL":0, "EMAIL_OPERID":-1, "EMAIL_TYPE":0,+ "ENABLE_NETSEND":0, "NETSEND_OPERID":-1, "NETSEND_TYPE":0, "DESCRIBE":""+ }))+ .expect("native job creation defaults");+ let (call, definition_fields, operators) =+ basic_definition(&defaults, &changes, &definition.name, "SP_CREATE_JOB")?;+ let mut steps = vec![NativeJobSqlStep {+ id: "create".into(),+ label: "native_job_step_create_disabled".into(),+ sql: format!("DECLARE dbx_email_operator VARCHAR(128); dbx_netsend_operator VARCHAR(128); BEGIN {call} END;"),+ effect: NativeJobStepEffect::Created,+ }];+ let mut push = |id: &str, label: &str, call: String, effect| {+ steps.push(NativeJobSqlStep { id: id.into(), label: label.into(), sql: format!("BEGIN {call} END;"), effect })+ };+ push(+ "pause",+ "native_job_step_pause_scheduling",+ format!("SP_ENABLE_JOB({}, 0);", text(&definition.name)),+ NativeJobStepEffect::Enabled(false),+ );+ push(+ "config_start",+ "native_job_step_config_start",+ format!("SP_JOB_CONFIG_START({});", text(&definition.name)),+ NativeJobStepEffect::DamengConfigurationStarted,+ );+ let mut remaining = NativeJobDamengConfiguration {+ attributes: vec![NativeJobAttributeChange {+ name: "ENABLE".into(),+ change: NativeJobFieldChange::Set { value: Value::Bool(definition.enabled) },+ }],+ steps: definition.configuration.steps.clone(),+ schedules: definition.configuration.schedules.clone(),+ };+ for key in ["EP_SEQNO", "RAFT_NAME"] {+ let Some(change) = changes.get(key) else { continue };+ let value = match change {+ NativeJobFieldChange::Set { value } => value.clone(),+ NativeJobFieldChange::Clear => Value::Null,+ NativeJobFieldChange::Keep => unreachable!(),+ };+ let attribute =+ NativeJobAttributeChange { name: key.into(), change: NativeJobFieldChange::Set { value: value.clone() } };+ push(+ &format!("attribute:{key}"),+ "native_job_step_attribute",+ node_call(&definition.name, key, &value)?,+ NativeJobStepEffect::Fields(vec![attribute.clone()]),+ );+ remaining.attributes.push(attribute);+ }+ steps.extend(parts::new_part_steps(NativeJobDamengPart::Steps, &definition.configuration.steps, &definition.name)?);+ steps.extend(parts::new_part_steps(+ NativeJobDamengPart::Schedules,+ &definition.configuration.schedules,+ &definition.name,+ )?);+ steps.push(NativeJobSqlStep {+ id: "config_commit".into(),+ label: "native_job_step_config_commit".into(),+ sql: format!("BEGIN SP_JOB_CONFIG_COMMIT({}); END;", text(&definition.name)),+ effect: NativeJobStepEffect::DamengConfigurationCommitted,+ });+ if definition.enabled {+ steps.push(NativeJobSqlStep {+ id: "enable".into(),+ label: "native_job_step_enable".into(),+ sql: format!("BEGIN SP_ENABLE_JOB({}, 1); END;", text(&definition.name)),+ effect: NativeJobStepEffect::Enabled(true),+ });+ }+ Ok(NativeJobDamengCreatePlan {+ steps,+ configuration: NativeJobDamengConfigPlan { operators },+ definition_fields,+ remaining,+ })+}diff --git a/crates/dbx-sql-schema/src/native_job_changes/dameng/legacy.rs b/crates/dbx-sql-schema/src/native_job_changes/dameng/legacy.rsnew file mode 100644index 0000000000..42819d516b--- /dev/null+++ b/crates/dbx-sql-schema/src/native_job_changes/dameng/legacy.rs@@ -0,0 +1,84 @@+use super::*;++pub fn native_job_dameng_civil_time(input: &str) -> Result<String, &'static str> {+ let invalid = "native_job_attribute_value_invalid";+ let bytes = input.as_bytes();+ if bytes.len() < 19+ || !bytes.is_ascii()+ || bytes[4] != b'-'+ || bytes[7] != b'-'+ || !matches!(bytes[10], b' ' | b'T')+ || bytes[13] != b':'+ || bytes[16] != b':'+ {+ return Err(invalid);+ }+ let number = |start: usize, end: usize| -> Result<u32, &'static str> {+ let part = &input[start..end];+ if !part.bytes().all(|byte| byte.is_ascii_digit()) {+ return Err(invalid);+ }+ part.parse().map_err(|_| invalid)+ };+ if number(0, 4)? == 0+ || !(1..=12).contains(&number(5, 7)?)+ || !(1..=31).contains(&number(8, 10)?)+ || number(11, 13)? > 23+ || number(14, 16)? > 59+ || number(17, 19)? > 59+ {+ return Err(invalid);+ }+ let fraction = if bytes.len() == 19 {+ ""+ } else {+ if bytes[19] != b'.' {+ return Err(invalid);+ }+ let fraction = &input[20..];+ if fraction.is_empty()+ || fraction.len() > 9+ || !fraction.bytes().all(|byte| byte.is_ascii_digit())+ || (fraction.len() > 6 && !fraction[6..].bytes().all(|byte| byte == b'0'))+ {+ return Err(invalid);+ }+ &fraction[..fraction.len().min(6)]+ };+ Ok(format!("{} {}.{:0<6}", &input[..10], &input[11..19], fraction))+}++pub fn native_job_dameng_legacy_time(row: &NativeJobRow) -> Result<String, &'static str> {+ let invalid = "native_job_metadata_incomplete";+ let date = row.get("NEXT_DATE").and_then(Value::as_str).ok_or(invalid)?;+ let seconds = row.get("NEXT_SEC").ok_or(invalid)?;+ let seconds = if seconds.is_null() || seconds.as_str() == Some("") {+ None+ } else {+ let text = seconds.as_str().ok_or(invalid)?;+ if text.len() != 8 || native_job_dameng_civil_time(&format!("2000-01-01 {text}")).is_err() {+ return Err(invalid);+ }+ Some(text)+ };+ let civil = if date.len() == 10 {+ let seconds = seconds.ok_or(invalid)?;+ native_job_dameng_civil_time(&format!("{date} {seconds}"))+ } else {+ native_job_dameng_civil_time(date)+ }+ .map_err(|_| invalid)?;+ if let Some(seconds) = seconds {+ if &civil[11..19] != seconds {+ return Err(invalid);+ }+ }+ Ok(civil)+}++pub fn native_job_dameng_date_query(civil: &str) -> NativeJobCatalogQuery {+ NativeJobCatalogQuery {+ source: "DUAL", coverage: NativeJobCatalogCoverage::Accessible, limit: 1,+ sql: format!("SELECT TO_CHAR(CAST(TIMESTAMP {} AS DATETIME(6)), 'SYYYY-MM-DD HH24:MI:SS.FF6') AS DBX_NEXT_DATE FROM DUAL", text(civil)),+ }+}diff --git a/crates/dbx-sql-schema/src/native_job_changes/dameng/parts.rs b/crates/dbx-sql-schema/src/native_job_changes/dameng/parts.rsnew file mode 100644index 0000000000..94aa156f85--- /dev/null+++ b/crates/dbx-sql-schema/src/native_job_changes/dameng/parts.rs@@ -0,0 +1,777 @@+use super::*;+use std::borrow::Cow;++#[derive(Clone, Copy, PartialEq, Eq)]+pub enum NativeJobDamengPart {+ Steps,+ Schedules,+}++impl NativeJobDamengPart {+ pub fn key(self) -> &'static str {+ match self {+ Self::Steps => "steps",+ Self::Schedules => "schedules",+ }+ }+ fn singular(self) -> &'static str {+ match self {+ Self::Steps => "STEP",+ Self::Schedules => "SCHEDULE",+ }+ }+ fn source(self, details: &NativeJobDetails) -> Result<&'static str, &'static str> {+ match (self, details.sources.get(self.key()).and_then(|source| source.source.as_deref())) {+ (Self::Steps, Some("SYSJOB.SYSJOBSTEPS")) => Ok("SYSJOB.SYSJOBSTEPS"),+ (Self::Steps, Some("SYSJOB.USER_JOBSTEPS_VIEW")) => Ok("SYSJOB.USER_JOBSTEPS_VIEW"),+ (Self::Schedules, Some("SYSJOB.SYSJOBSCHEDULES")) => Ok("SYSJOB.SYSJOBSCHEDULES"),+ (Self::Schedules, Some("SYSJOB.USER_JOBSCHEDULES_VIEW")) => Ok("SYSJOB.USER_JOBSCHEDULES_VIEW"),+ _ => Err("native_job_catalog_source_unverified"),+ }+ }+}++#[derive(Clone, PartialEq, Eq)]+pub enum NativeJobDamengChildAction {+ Added,+ Changed,+ Dropped,+ Renamed(String),+}++#[derive(Clone)]+pub struct NativeJobDamengChildReference {+ pub name: String,+ pub native_id: Option<String>,+}++#[derive(Clone)]+pub struct NativeJobDamengChildEffect {+ pub part: NativeJobDamengPart,+ pub action: NativeJobDamengChildAction,+ pub name: String,+ pub native_id: Option<String>,+ pub fields: NativeJobRow,+ pub acknowledged_fields: Vec<String>,+ pub references: Vec<NativeJobDamengChildReference>,+ pub requires_acknowledgement: bool,+ native_call: String,+}++pub fn native_job_dameng_child_key(part: NativeJobDamengPart, name: &str) -> String {+ format!("{}:{}", part.key(), name.to_ascii_uppercase())+}++pub fn native_job_dameng_catalog_id(value: &Value) -> Option<String> {+ let id = match value {+ Value::Number(value) => value.as_u64().filter(|value| *value > 0)?.to_string(),+ Value::String(value)+ if !value.is_empty() && !value.starts_with('0') && value.bytes().all(|byte| byte.is_ascii_digit()) =>+ {+ value.clone()+ }+ _ => return None,+ };+ Some(id)+}++pub fn native_job_dameng_child_id(row: &NativeJobRow) -> Option<String> {+ native_job_dameng_catalog_id(row.get("ID")?)+}++fn name_key(name: &str) -> String {+ name.to_ascii_uppercase()+}++pub(super) fn valid_name(name: &str) -> Result<(), &'static str> {+ if name.is_empty()+ || name.len() > 128+ || name.as_bytes()[0].is_ascii_digit()+ || !name.bytes().all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'-' | b'$'))+ {+ return Err("native_job_child_name_invalid");+ }+ Ok(())+}++fn row_name(row: &NativeJobRow) -> Result<&str, &'static str> {+ row.get("NAME").and_then(Value::as_str).filter(|name| !name.is_empty()).ok_or("native_job_metadata_incomplete")+}++fn links(row: &NativeJobRow, key: &str) -> Result<Option<String>, &'static str> {+ match current(row, key)? {+ Value::Null => Ok(None),+ Value::String(value) if value.is_empty() => Ok(None),+ Value::String(value) if !value.contains('\0') => Ok(Some(value.clone())),+ _ => Err("native_job_attribute_type_invalid"),+ }+}++fn patches(+ attributes: &[NativeJobAttributeChange],+ part: NativeJobDamengPart,+) -> Result<BTreeMap<String, NativeJobFieldChange>, &'static str> {+ let allowed: &[&str] = match part {+ NativeJobDamengPart::Steps => &[+ "NAME",+ "TYPE",+ "COMMAND_INPUT",+ "SUCC_ACTION",+ "FAIL_ACTION",+ "RETRY_ATTEMPTS",+ "RETRY_INTERVAL",+ "OUTPUT_FILE_PATH",+ "APPEND_FLAG",+ "DESCRIBE",+ "SUCC_NEXT_STEP",+ "FAIL_NEXT_STEP",+ ],+ NativeJobDamengPart::Schedules => &[+ "NAME",+ "ENABLE",+ "TYPE",+ "FREQ_INTERVAL",+ "FREQ_SUB_INTERVAL",+ "FREQ_MINUTE_INTERVAL",+ "STARTTIME",+ "ENDTIME",+ "DURING_START_DATE",+ "DURING_END_DATE",+ "DESCRIBE",+ ],+ };+ let mut result = BTreeMap::new();+ for attribute in attributes.iter().filter(|attribute| attribute.change != NativeJobFieldChange::Keep) {+ let key = attribute.name.to_ascii_uppercase();+ if !allowed.contains(&key.as_str()) {+ return Err("native_job_attribute_not_editable");+ }+ if result.insert(key, attribute.change.clone()).is_some() {+ return Err("native_job_duplicate_attribute");+ }+ }+ Ok(result)+}++fn defaults(part: NativeJobDamengPart, name: &str) -> NativeJobRow {+ let value = match part {+ NativeJobDamengPart::Steps => {+ serde_json::json!({"NAME":name,"TYPE":0,"SUCC_ACTION":1,"FAIL_ACTION":1,"RETRY_ATTEMPTS":0,"RETRY_INTERVAL":0,"OUTPUT_FILE_PATH":null,"APPEND_FLAG":0,"DESCRIBE":null,"SUCC_NEXT_STEP":null,"FAIL_NEXT_STEP":null})+ }+ NativeJobDamengPart::Schedules => {+ serde_json::json!({"NAME":name,"ENABLE":1,"TYPE":1,"FREQ_INTERVAL":1,"FREQ_SUB_INTERVAL":0,"FREQ_MINUTE_INTERVAL":0,"STARTTIME":"00:00:00","ENDTIME":null,"DURING_START_DATE":"CURDATE","DURING_END_DATE":null,"DESCRIBE":null})+ }+ };+ serde_json::from_value(value).expect("native child defaults")+}++struct Entry<'a> {+ original: Option<&'a NativeJobRow>,+ original_name: String,+ name: String,+ id: Option<String>,+ row: Cow<'a, NativeJobRow>,+ patch: BTreeMap<String, NativeJobFieldChange>,+ added: bool,+ dropped: bool,+}++fn entries<'a>(+ part: NativeJobDamengPart,+ details: &'a NativeJobDetails,+ changes: &[NativeJobDamengChildChange],+ target: &NativeJobRef,+) -> Result<Vec<Entry<'a>>, &'static str> {+ let data = match part {+ NativeJobDamengPart::Steps => &details.steps,+ NativeJobDamengPart::Schedules => &details.schedules,+ };+ let rows = match data {+ NativeJobMetadata::Available { value } => value.as_slice(),+ NativeJobMetadata::Empty => &[],+ _ => return Err("native_job_metadata_incomplete"),+ };+ part.source(details)?;+ let parent = match target {+ NativeJobRef::DamengNative { job_id, .. } | NativeJobRef::Legacy { job_id, .. } => job_id,+ _ => return Err("native_job_kind_invalid"),+ };+ let mut names = HashSet::new();+ let mut ids = HashSet::new();+ let mut result = Vec::new();+ for row in rows {+ let name = row_name(row)?;+ let id = native_job_dameng_child_id(row).ok_or("native_job_child_identity_unverified")?;+ if row.get("JOBID").and_then(native_job_dameng_catalog_id).as_ref() != Some(parent) {+ return Err("native_job_child_identity_unverified");+ }+ if !names.insert(name_key(name)) || !ids.insert(id.clone()) {+ return Err("native_job_child_identity_ambiguous");+ }+ result.push(Entry {+ original: Some(row),+ original_name: name.into(),+ name: name.into(),+ id: Some(id),+ row: Cow::Borrowed(row),+ patch: BTreeMap::new(),+ added: false,+ dropped: false,+ });+ }+ apply_changes(part, result, changes)+}++fn apply_changes<'a>(+ part: NativeJobDamengPart,+ mut result: Vec<Entry<'a>>,+ changes: &[NativeJobDamengChildChange],+) -> Result<Vec<Entry<'a>>, &'static str> {+ let names = result.iter().map(|entry| name_key(&entry.original_name)).collect::<HashSet<_>>();+ let original_indices = result+ .iter()+ .enumerate()+ .map(|(index, entry)| (name_key(&entry.original_name), index))+ .collect::<BTreeMap<_, _>>();+ let mut changed = HashSet::new();+ for change in changes {+ let (name, attributes, add, drop) = match change {+ NativeJobDamengChildChange::Add { name, attributes } => (name, attributes.as_slice(), true, false),+ NativeJobDamengChildChange::Update { name, attributes } => (name, attributes.as_slice(), false, false),+ NativeJobDamengChildChange::Drop { name } => (name, &[][..], false, true),+ };+ if name.is_empty() || name.contains('\0') {+ return Err("native_job_child_name_invalid");+ }+ if !changed.insert(name_key(name)) {+ return Err("native_job_duplicate_child_change");+ }+ let patch = patches(attributes, part)?;+ if add {+ valid_name(name)?;+ if patch.contains_key("NAME") {+ return Err("native_job_duplicate_attribute");+ }+ // A drop/add of the same native name is a replacement, not a lossless edit.+ if names.contains(&name_key(name)) {+ return Err("native_job_child_name_collision");+ }+ result.push(Entry {+ original: None,+ original_name: name.clone(),+ name: name.clone(),+ id: None,+ row: Cow::Owned(defaults(part, name)),+ patch,+ added: true,+ dropped: false,+ });+ } else {+ let index = *original_indices.get(&name_key(name)).ok_or("native_job_child_missing")?;+ let entry = &mut result[index];+ if part == NativeJobDamengPart::Schedules && integer(current(&entry.row, "TYPE")?)? == 9 {+ return Err("native_job_legacy_schedule_requires_dbms_job");+ }+ entry.patch = patch;+ entry.dropped = drop;+ }+ }+ for entry in &mut result {+ if entry.dropped {+ continue;+ }+ for (key, change) in &entry.patch {+ if matches!(key.as_str(), "NAME" | "COMMAND_INPUT") {+ continue;+ }+ let value = match change {+ NativeJobFieldChange::Set { value } => value.clone(),+ NativeJobFieldChange::Clear => Value::Null,+ NativeJobFieldChange::Keep => unreachable!(),+ };+ entry.row.to_mut().insert(key.clone(), value);+ }+ if let Some(change) = entry.patch.get("NAME") {+ let NativeJobFieldChange::Set { value: Value::String(name) } = change else {+ return Err("native_job_child_name_invalid");+ };+ valid_name(name)?;+ if name_key(name) == name_key(&entry.name) {+ return Err("native_job_child_name_case_unchanged");+ }+ entry.name = name.clone();+ }+ }+ let mut final_names = HashSet::new();+ for entry in result.iter().filter(|entry| !entry.dropped) {+ if !final_names.insert(name_key(&entry.name)) {+ return Err("native_job_child_name_collision");+ }+ }+ Ok(result)+}++fn effect(+ part: NativeJobDamengPart,+ entry: &Entry<'_>,+ action: NativeJobDamengChildAction,+ fields: NativeJobRow,+ call: String,+) -> NativeJobDamengChildEffect {+ let requires_acknowledgement = action == NativeJobDamengChildAction::Added;+ NativeJobDamengChildEffect {+ part,+ action,+ name: entry.name.clone(),+ native_id: entry.id.clone(),+ fields,+ acknowledged_fields: Vec::new(),+ references: Vec::new(),+ requires_acknowledgement,+ native_call: call,+ }+}++struct ChildPlanContext<'a> {+ job: &'a str,+ existing: Option<(&'a NativeJobRef, &'a NativeJobDetails)>,+}++fn make_step(+ context: &ChildPlanContext<'_>,+ effect: NativeJobDamengChildEffect,+ index: usize,+) -> Result<NativeJobSqlStep, &'static str> {+ let action = match effect.action {+ NativeJobDamengChildAction::Added => "add",+ NativeJobDamengChildAction::Dropped => "drop",+ NativeJobDamengChildAction::Renamed(_) => "rename",+ NativeJobDamengChildAction::Changed => "edit",+ };+ let id = format!("{}:{action}:{index}", effect.part.key());+ let sql = match context.existing {+ Some((target, details)) => render_child_call(target, details, &effect)?,+ // Preview for an absent job. Apply rebuilds guards from its acknowledged native identity.+ None => format!("BEGIN {} END;", effect.native_call),+ };+ Ok(NativeJobSqlStep {+ id,+ label: format!("native_job_step_{}_{}", effect.part.key(), action),+ sql,+ effect: NativeJobStepEffect::DamengChild(effect),+ })+}++fn rename_steps(+ part: NativeJobDamengPart,+ entries: &[Entry<'_>],+ context: &ChildPlanContext<'_>,+ output: &mut Vec<NativeJobSqlStep>,+) -> Result<(), &'static str> {+ let job = context.job;+ let mut current =+ entries.iter().filter(|entry| !entry.added).map(|entry| name_key(&entry.original_name)).collect::<HashSet<_>>();+ let mut remaining = entries+ .iter()+ .filter(|entry| !entry.added && !entry.dropped && entry.name != entry.original_name)+ .collect::<Vec<_>>();+ while !remaining.is_empty() {+ let index = remaining+ .iter()+ .position(|entry| !current.contains(&name_key(&entry.name)))+ .ok_or("native_job_child_rename_requires_correction")?;+ let entry = remaining.remove(index);+ if part == NativeJobDamengPart::Schedules && job.len() + entry.name.len() >= 253 {+ return Err("native_job_child_name_invalid");+ }+ let call = format!(+ "SP_RENAME_JOB_{}({}, {}, {});",+ part.singular(),+ text(job),+ text(&entry.original_name),+ text(&entry.name)+ );+ let mut change =+ effect(part, entry, NativeJobDamengChildAction::Renamed(entry.name.clone()), NativeJobRow::new(), call);+ change.name = entry.original_name.clone();+ output.push(make_step(context, change, output.len())?);+ current.remove(&name_key(&entry.original_name));+ current.insert(name_key(&entry.name));+ }+ Ok(())+}++fn step_definition(entry: &Entry<'_>, job: &str) -> Result<(NativeJobRow, Vec<String>, String), &'static str> {+ let row = &entry.row;+ let kind = integer(current(row, "TYPE")?)?;+ if !(0..=6).contains(&kind) {+ return Err("native_job_attribute_value_invalid");+ }+ let command = match entry.patch.get("COMMAND_INPUT") {+ Some(NativeJobFieldChange::Set { value: Value::String(value) }) if !value.contains('\0') => {+ Value::String(value.clone())+ }+ Some(NativeJobFieldChange::Clear) => Value::Null,+ Some(_) => return Err("native_job_attribute_type_invalid"),+ None if kind == 0+ && entry.original.is_some_and(|row| row.get("TYPE").and_then(|value| integer(value).ok()) == Some(0)) =>+ {+ current(row, "COMMAND")?.clone()+ }+ None if matches!(kind, 2 | 3) => Value::Null,+ None => return Err("native_job_step_command_input_required"),+ };+ if matches!(kind, 2 | 3) && command.as_str().is_some_and(|value| !value.is_empty()) {+ return Err("native_job_step_command_not_applicable");+ }+ if !matches!(kind, 2 | 3) && !command.as_str().is_some_and(|value| !value.trim().is_empty()) {+ return Err("native_job_step_command_input_required");+ }+ if kind != 0 && command.as_str().is_some_and(|value| value.chars().count() > 3_600) {+ return Err("native_job_attribute_value_invalid");+ }+ let mut fields = NativeJobRow::new();+ for (key, min, max) in [+ ("TYPE", 0, 6),+ ("SUCC_ACTION", 0, 3),+ ("FAIL_ACTION", 0, 3),+ ("RETRY_ATTEMPTS", 0, 99_999),+ ("RETRY_INTERVAL", 0, i64::from(i32::MAX)),+ ] {+ let value = integer(current(row, key)?)?;+ if !(min..=max).contains(&value) {+ return Err("native_job_attribute_value_invalid");+ }+ fields.insert(key.into(), serde_json::json!(value));+ }+ let append = flag(current(row, "APPEND_FLAG")?)?;+ fields.insert("APPEND_FLAG".into(), Value::Bool(append));+ for key in ["OUTPUT_FILE_PATH", "DESCRIBE"] {+ scalar(current(row, key)?)?;+ fields.insert(key.into(), current(row, key)?.clone());+ }+ if kind == 0 {+ fields.insert("COMMAND".into(), command.clone());+ }+ let call = format!(+ "SP_{}_JOB_STEP_EX({}, {}, {kind}, {}, {}, {}, {}, {}, {}, {}, {});",+ if entry.added { "ADD" } else { "ALTER" },+ text(job),+ text(&entry.name),+ scalar(&command)?,+ fields["SUCC_ACTION"],+ fields["FAIL_ACTION"],+ fields["RETRY_ATTEMPTS"],+ fields["RETRY_INTERVAL"],+ scalar(&fields["OUTPUT_FILE_PATH"])?,+ u8::from(append),+ scalar(&fields["DESCRIBE"])?+ );+ Ok((fields, if kind == 0 { vec![] } else { vec!["COMMAND".into()] }, call))+}++fn calendar_sql(value: &Value, key: &str) -> Result<(String, bool), &'static str> {+ if let Some(value) = value.as_str() {+ if ((key == "DURING_START_DATE" || key == "DURING_END_DATE") && value.eq_ignore_ascii_case("CURDATE"))+ || ((key == "STARTTIME" || key == "ENDTIME") && value.eq_ignore_ascii_case("CURTIME"))+ {+ return Ok((value.to_ascii_uppercase(), true));+ }+ }+ Ok((scalar(value)?, false))+}++fn schedule_definition(entry: &Entry<'_>, job: &str) -> Result<(NativeJobRow, Vec<String>, String), &'static str> {+ let row = &entry.row;+ let kind = integer(current(row, "TYPE")?)?;+ if kind == 9 {+ return Err("native_job_legacy_schedule_requires_dbms_job");+ }+ if !(0..=8).contains(&kind) {+ return Err("native_job_attribute_value_invalid");+ }+ let interval = integer(current(row, "FREQ_INTERVAL")?)?;+ let sub = integer(current(row, "FREQ_SUB_INTERVAL")?)?;+ let minute = integer(current(row, "FREQ_MINUTE_INTERVAL")?)?;+ if interval < 0+ || interval > i64::from(i32::MAX)+ || sub < 0+ || sub > i64::from(i32::MAX)+ || !(0..=1439).contains(&minute)+ || (kind > 0 && interval == 0)+ || (kind == 1 && interval > 100)+ || (kind == 2 && !(1..=127).contains(&sub))+ || (kind == 3 && !(1..=31).contains(&sub))+ || ((4..=8).contains(&kind) && !(1..=7).contains(&sub))+ {+ return Err("native_job_attribute_value_invalid");+ }+ for key in if kind == 0 { &["DURING_START_DATE"][..] } else { &["STARTTIME", "DURING_START_DATE"][..] } {+ if !current(row, key)?.as_str().is_some_and(|value| !value.is_empty()) {+ return Err("native_job_attribute_value_invalid");+ }+ }+ let enabled = flag(current(row, "ENABLE")?)?;+ let mut fields: NativeJobRow = serde_json::from_value(serde_json::json!({"ENABLE":enabled,"TYPE":kind,"FREQ_INTERVAL":interval,"FREQ_SUB_INTERVAL":sub,"FREQ_MINUTE_INTERVAL":minute})).expect("native schedule fields");+ let mut acknowledged = Vec::new();+ let mut dates = Vec::new();+ for key in ["STARTTIME", "ENDTIME", "DURING_START_DATE", "DURING_END_DATE"] {+ let value = current(row, key)?;+ let (sql, dynamic) = calendar_sql(value, key)?;+ if dynamic {+ acknowledged.push(key.into());+ } else {+ fields.insert(key.into(), value.clone());+ }+ dates.push(sql);+ }+ fields.insert("DESCRIBE".into(), current(row, "DESCRIBE")?.clone());+ let call = format!(+ "SP_{}_JOB_SCHEDULE({}, {}, {}, {kind}, {interval}, {sub}, {minute}, {}, {}, {}, {}, {});",+ if entry.added { "ADD" } else { "ALTER" },+ text(job),+ text(&entry.name),+ u8::from(enabled),+ dates[0],+ dates[1],+ dates[2],+ dates[3],+ scalar(&fields["DESCRIBE"])?+ );+ Ok((fields, acknowledged, call))+}++pub(super) fn part_steps(+ part: NativeJobDamengPart,+ changes: &[NativeJobDamengChildChange],+ target: &NativeJobRef,+ details: &NativeJobDetails,+) -> Result<Vec<NativeJobSqlStep>, &'static str> {+ if changes.is_empty() {+ return Ok(Vec::new());+ }+ let entries = entries(part, details, changes, target)?;+ let job = target_name(NativeJobCatalogDialect::Dameng, target, details)?;+ plan_entries(part, entries, &ChildPlanContext { job: &job, existing: Some((target, details)) })+}++pub(super) fn new_part_steps(+ part: NativeJobDamengPart,+ changes: &[NativeJobDamengChildChange],+ job: &str,+) -> Result<Vec<NativeJobSqlStep>, &'static str> {+ if changes.iter().any(|change| !matches!(change, NativeJobDamengChildChange::Add { .. })) {+ return Err("native_job_creation_children_must_be_new");+ }+ let entries = apply_changes(part, Vec::new(), changes)?;+ plan_entries(part, entries, &ChildPlanContext { job, existing: None })+}++fn plan_entries(+ part: NativeJobDamengPart,+ mut entries: Vec<Entry<'_>>,+ context: &ChildPlanContext<'_>,+) -> Result<Vec<NativeJobSqlStep>, &'static str> {+ let job = context.job;+ let renames = entries+ .iter()+ .filter(|entry| !entry.added && !entry.dropped)+ .map(|entry| (name_key(&entry.original_name), entry.name.clone()))+ .collect::<BTreeMap<_, _>>();+ // Retarget existing references by original identity once, not by cascading text replacements.+ if part == NativeJobDamengPart::Steps {+ for entry in entries.iter_mut().filter(|entry| !entry.added && !entry.dropped) {+ for key in ["SUCC_NEXT_STEP", "FAIL_NEXT_STEP"] {+ if entry.patch.contains_key(key) {+ continue;+ }+ if let Some(old) = links(&entry.row, key)? {+ if let Some(new) = renames.get(&name_key(&old)).filter(|new| **new != old) {+ entry.row.to_mut().insert(key.into(), Value::String(new.clone()));+ }+ }+ }+ }+ let survivors =+ entries.iter().filter(|entry| !entry.dropped).map(|entry| name_key(&entry.name)).collect::<HashSet<_>>();+ for entry in entries.iter().filter(|entry| !entry.dropped) {+ for (action, next) in [("SUCC_ACTION", "SUCC_NEXT_STEP"), ("FAIL_ACTION", "FAIL_NEXT_STEP")] {+ let value = links(&entry.row, next)?;+ if integer(current(&entry.row, action)?)? >= 2+ && value.as_deref().is_some_and(|name| !survivors.contains(&name_key(name)))+ {+ return Err("native_job_step_dependency_requires_correction");+ }+ if entry.patch.contains_key(next)+ && value.as_deref().is_some_and(|name| !survivors.contains(&name_key(name)))+ {+ return Err("native_job_step_dependency_requires_correction");+ }+ }+ }+ }+ let mut output = Vec::new();+ rename_steps(part, &entries, context, &mut output)?;+ for entry in entries.iter().filter(|entry| !entry.dropped) {+ if part == NativeJobDamengPart::Schedules && job.len() + entry.name.len() > 253 {+ return Err("native_job_child_name_invalid");+ }+ let definition_changed = entry.added+ || entry.patch.keys().any(|key| match part {+ NativeJobDamengPart::Steps => !matches!(key.as_str(), "NAME" | "SUCC_NEXT_STEP" | "FAIL_NEXT_STEP"),+ NativeJobDamengPart::Schedules => key != "NAME",+ });+ if !definition_changed {+ continue;+ }+ let (fields, acknowledged, call) = match part {+ NativeJobDamengPart::Steps => step_definition(entry, job)?,+ NativeJobDamengPart::Schedules => schedule_definition(entry, job)?,+ };+ let mut change = effect(+ part,+ entry,+ if entry.added { NativeJobDamengChildAction::Added } else { NativeJobDamengChildAction::Changed },+ fields,+ call,+ );+ change.requires_acknowledgement |= !acknowledged.is_empty();+ change.acknowledged_fields = acknowledged;+ output.push(make_step(context, change, output.len())?);+ }+ if part == NativeJobDamengPart::Steps {+ let references = entries+ .iter()+ .filter(|entry| !entry.dropped)+ .map(|entry| {+ (+ name_key(&entry.name),+ NativeJobDamengChildReference { name: entry.name.clone(), native_id: entry.id.clone() },+ )+ })+ .collect::<BTreeMap<_, _>>();+ for entry in &entries {+ let mut wanted = NativeJobRow::new();+ let mut reference_names = Vec::new();+ let mut changed = entry.added;+ for key in ["SUCC_NEXT_STEP", "FAIL_NEXT_STEP"] {+ let next = if entry.dropped { None } else { links(&entry.row, key)? };+ let original = entry.original.map(|row| links(row, key)).transpose()?.flatten();+ changed |= entry.patch.contains_key(key) || next != original;+ if let Some(name) = &next {+ reference_names.push(name.clone());+ }+ wanted.insert(key.into(), next.map_or(Value::Null, Value::String));+ }+ if !changed {+ continue;+ }+ if entry.added+ && reference_names.is_empty()+ && !entry.patch.keys().any(|key| matches!(key.as_str(), "SUCC_NEXT_STEP" | "FAIL_NEXT_STEP"))+ {+ continue;+ }+ let call = format!(+ "SP_JOB_STEP_SET_NEXT_STEP({}, {}, {}, {});",+ text(job),+ text(&entry.name),+ scalar(&wanted["SUCC_NEXT_STEP"])?,+ scalar(&wanted["FAIL_NEXT_STEP"])?+ );+ let mut change = effect(part, entry, NativeJobDamengChildAction::Changed, wanted, call);+ for name in reference_names {+ change.references.push(+ references+ .get(&name_key(&name))+ .cloned()+ .ok_or("native_job_step_dependency_requires_correction")?,+ );+ }+ output.push(make_step(context, change, output.len())?);+ }+ }+ for entry in entries.iter().filter(|entry| entry.dropped) {+ let call = format!("SP_DROP_JOB_{}({}, {});", part.singular(), text(job), text(&entry.name));+ output.push(make_step(+ context,+ effect(part, entry, NativeJobDamengChildAction::Dropped, NativeJobRow::new(), call),+ output.len(),+ )?);+ }+ Ok(output)+}++fn render_child_call(+ target: &NativeJobRef,+ details: &NativeJobDetails,+ effect: &NativeJobDamengChildEffect,+) -> Result<String, &'static str> {+ let source = effect.part.source(details)?;+ let job_id = match target {+ NativeJobRef::DamengNative { job_id, .. } | NativeJobRef::Legacy { job_id, .. } => job_id,+ _ => return Err("native_job_kind_invalid"),+ };+ let mut calls = String::new();+ let mut check = |source: &str, name: &str, id: Option<&str>, absent: bool, placeholder: &str| {+ let identity = if absent { String::new() } else { format!(" AND ID = {}", id.unwrap_or(placeholder)) };+ calls.push_str(&format!("SELECT COUNT(*) INTO dbx_target_count FROM {source} WHERE JOBID = {job_id} AND UPPER(NAME) = UPPER({}){identity}; IF dbx_target_count <> {} THEN RAISE dbx_target_changed; END IF; ", text(name), if absent { 0 } else { 1 }));+ };+ check(+ source,+ &effect.name,+ effect.native_id.as_deref(),+ effect.action == NativeJobDamengChildAction::Added,+ ":dbx_created_step_id",+ );+ if let NativeJobDamengChildAction::Renamed(name) = &effect.action {+ check(source, name, None, true, "");+ }+ for (index, reference) in effect.references.iter().enumerate() {+ check(+ source,+ &reference.name,+ reference.native_id.as_deref(),+ false,+ &format!(":dbx_created_reference_id_{index}"),+ );+ }+ calls.push_str(&effect.native_call);+ guarded_call(target, details, &calls)+}++/// Resolve only IDs captured after this operation's acknowledged adds; never replace text in a body.+pub fn resolve_native_job_dameng_child_step(+ step: &NativeJobSqlStep,+ target: &NativeJobRef,+ details: &NativeJobDetails,+ created: &BTreeMap<String, String>,+) -> Result<NativeJobSqlStep, &'static str> {+ let NativeJobStepEffect::DamengChild(effect) = &step.effect else { return Ok(step.clone()) };+ let mut effect = effect.clone();+ if effect.native_id.is_none() && effect.action != NativeJobDamengChildAction::Added {+ effect.native_id = Some(+ created+ .get(&native_job_dameng_child_key(effect.part, &effect.name))+ .cloned()+ .ok_or("native_job_child_identity_unverified")?,+ );+ }+ for reference in &mut effect.references {+ if reference.native_id.is_none() {+ reference.native_id = Some(+ created+ .get(&native_job_dameng_child_key(NativeJobDamengPart::Steps, &reference.name))+ .cloned()+ .ok_or("native_job_child_identity_unverified")?,+ );+ }+ }+ let sql = render_child_call(target, details, &effect)?;+ Ok(NativeJobSqlStep {+ id: step.id.clone(),+ label: step.label.clone(),+ sql,+ effect: NativeJobStepEffect::DamengChild(effect),+ })+}diff --git a/crates/dbx-sql-schema/src/native_job_changes/references.rs b/crates/dbx-sql-schema/src/native_job_changes/references.rsnew file mode 100644index 0000000000..d611f2e122--- /dev/null+++ b/crates/dbx-sql-schema/src/native_job_changes/references.rs@@ -0,0 +1,88 @@+use super::*;+use sqlparser::dialect::OracleDialect;+use sqlparser::tokenizer::{Token, Tokenizer, Word};++#[derive(Clone, PartialEq)]+pub struct NativeJobSchedulerReferenceTarget {+ pub kind: NativeJobReferenceKind,+ pub reference: NativeJobObjectReference,+}++/// Normalize one reference without treating dots or commas inside quoted names as separators.+/// Ordinary action bodies are not references. NULL means an explicit detach, with no new target.+pub fn native_job_scheduler_reference_target(+ attribute: &str,+ value: &Value,+ job_owner: &str,+ job_type: &str,+) -> Result<Option<NativeJobSchedulerReferenceTarget>, &'static str> {+ let default_kind = match attribute.to_ascii_uppercase().as_str() {+ "PROGRAM_NAME" => NativeJobReferenceKind::Program,+ "SCHEDULE_NAME" => NativeJobReferenceKind::Schedule,+ "CREDENTIAL_NAME" | "CONNECT_CREDENTIAL_NAME" => NativeJobReferenceKind::Credential,+ "DESTINATION_NAME" => NativeJobReferenceKind::Destination,+ "JOB_ACTION" if job_type.eq_ignore_ascii_case("CHAIN") => NativeJobReferenceKind::Chain,+ _ => return Ok(None),+ };+ if value.is_null() {+ return Ok(None);+ }+ let invalid = "native_job_reference_input_invalid";+ let (kind, reference) = match value {+ Value::Object(object) => {+ let reference: NativeJobObjectReference = serde_json::from_value(value.clone()).map_err(|_| invalid)?;+ let kind = object+ .get("kind")+ .map(|kind| serde_json::from_value(kind.clone()).map_err(|_| invalid))+ .transpose()?+ .unwrap_or(default_kind);+ (kind, reference)+ }+ Value::String(name) => (default_kind, legacy_reference(name, job_owner)?),+ _ => return Err(invalid),+ };+ let compatible = kind == default_kind+ || matches!(+ (default_kind, kind),+ (NativeJobReferenceKind::Schedule, NativeJobReferenceKind::Window | NativeJobReferenceKind::WindowGroup)+ | (NativeJobReferenceKind::Destination, NativeJobReferenceKind::DestinationGroup)+ );+ if !compatible || [&reference.owner, &reference.name].iter().any(|value| value.is_empty() || value.contains('\0')) {+ return Err(invalid);+ }+ Ok(Some(NativeJobSchedulerReferenceTarget { kind, reference }))+}++fn legacy_reference(value: &str, job_owner: &str) -> Result<NativeJobObjectReference, &'static str> {+ let invalid = "native_job_reference_input_invalid";+ if value.contains('\0') {+ return Err(invalid);+ }+ let tokens = Tokenizer::new(&OracleDialect {}, value).tokenize().map_err(|_| invalid)?;+ // Skip spacing, not comments: a native object-name value is not a SQL statement.+ let tokens: Vec<_> = tokens+ .into_iter()+ .filter(|token| {+ !matches!(+ token,+ Token::Whitespace(+ sqlparser::tokenizer::Whitespace::Space+ | sqlparser::tokenizer::Whitespace::Newline+ | sqlparser::tokenizer::Whitespace::Tab+ )+ )+ })+ .collect();+ let identifier = |word: &Word| match word.quote_style {+ Some('"') => Ok(word.value.clone()),+ None => Ok(word.value.to_uppercase()),+ _ => Err(invalid),+ };+ match tokens.as_slice() {+ [Token::Word(name)] => Ok(NativeJobObjectReference { owner: job_owner.into(), name: identifier(name)? }),+ [Token::Word(owner), Token::Period, Token::Word(name)] => {+ Ok(NativeJobObjectReference { owner: identifier(owner)?, name: identifier(name)? })+ }+ _ => Err(invalid),+ }+}diff --git a/crates/dbx-sql-schema/src/native_job_changes/transitions.rs b/crates/dbx-sql-schema/src/native_job_changes/transitions.rsnew file mode 100644index 0000000000..286b8477bf--- /dev/null+++ b/crates/dbx-sql-schema/src/native_job_changes/transitions.rs@@ -0,0 +1,705 @@+use super::*;+use std::collections::BTreeMap;++#[derive(Clone)]+pub struct NativeJobSchedulerReferenceBinding {+ pub attribute: String,+ pub target: NativeJobSchedulerReferenceTarget,+}++#[derive(Clone)]+pub struct NativeJobSchedulerDefinitionEffect {+ pub columns: Vec<NativeJobAttributeChange>,+ pub references: Vec<NativeJobSchedulerReferenceBinding>,+}++#[derive(Clone)]+pub struct NativeJobSchedulerEditPlan {+ pub sql: NativeJobSqlPlan,+ pub transition: bool,+ pub context_changed: bool,+ pub references: Vec<NativeJobSchedulerReferenceBinding>,+ pub definition: NativeJobRow,+ pub argument_target: Option<NativeJobArgumentTarget>,+ pub final_enabled: bool,+ pub event_changed: bool,+}++fn enabled(value: Option<&Value>) -> Option<bool> {+ match value? {+ Value::Bool(value) => Some(*value),+ Value::String(value) if value.eq_ignore_ascii_case("true") || value == "1" => Some(true),+ Value::String(value) if value.eq_ignore_ascii_case("false") || value == "0" => Some(false),+ Value::Number(value) if value.as_i64() == Some(1) => Some(true),+ Value::Number(value) if value.as_i64() == Some(0) => Some(false),+ _ => None,+ }+}++fn native_reference(+ row: &NativeJobRow,+ slot: &str,+ owner: &str,+ job_type: &str,+) -> Result<Option<NativeJobSchedulerReferenceTarget>, &'static str> {+ if slot == "JOB_ACTION" {+ return native_job_scheduler_reference_target(slot, row.get(slot).unwrap_or(&Value::Null), owner, job_type);+ }+ let (owner_column, name_column) = match slot {+ "PROGRAM_NAME" => ("PROGRAM_OWNER", "PROGRAM_NAME"),+ "SCHEDULE_NAME" => ("SCHEDULE_OWNER", "SCHEDULE_NAME"),+ "CREDENTIAL_NAME" => ("CREDENTIAL_OWNER", "CREDENTIAL_NAME"),+ "CONNECT_CREDENTIAL_NAME" => ("CONNECT_CREDENTIAL_OWNER", "CONNECT_CREDENTIAL_NAME"),+ "DESTINATION_NAME" => ("DESTINATION_OWNER", "DESTINATION"),+ _ => return Ok(None),+ };+ let Some(name) = row.get(name_column).filter(|value| !value.is_null()) else { return Ok(None) };+ let name = name.as_str().filter(|name| !name.is_empty()).ok_or("native_job_reference_identity_unavailable")?;+ let owner = row+ .get(owner_column)+ .and_then(Value::as_str)+ .filter(|owner| !owner.is_empty())+ .ok_or("native_job_reference_identity_unavailable")?;+ let kind = match (slot, row.get("SCHEDULE_TYPE").and_then(Value::as_str)) {+ ("SCHEDULE_NAME", Some("WINDOW")) => Some("window"),+ ("SCHEDULE_NAME", Some("WINDOW_GROUP")) => Some("window-group"),+ _ => None,+ };+ let mut value = serde_json::json!({"owner":owner,"name":name});+ if let Some(kind) = kind {+ value["kind"] = Value::String(kind.into());+ }+ native_job_scheduler_reference_target(slot, &value, owner, job_type)+}++fn changed(name: &str, value: Value) -> NativeJobAttributeChange {+ NativeJobAttributeChange {+ name: name.into(),+ change: if value.is_null() { NativeJobFieldChange::Clear } else { NativeJobFieldChange::Set { value } },+ }+}++fn patch_value(change: &NativeJobFieldChange) -> Value {+ match change {+ NativeJobFieldChange::Set { value } => value.clone(),+ _ => Value::Null,+ }+}++fn inline_schedule_kind(before: &NativeJobRow, patches: &BTreeMap<String, NativeJobFieldChange>) -> &'static str {+ let value =+ |name: &str| patches.get(name).map(patch_value).or_else(|| before.get(name).cloned()).unwrap_or(Value::Null);+ if !value("EVENT_SPEC").is_null() {+ return "EVENT";+ }+ if !patches.contains_key("EVENT_SPEC")+ && before.get("SCHEDULE_TYPE").and_then(Value::as_str) == Some("EVENT")+ && !patches.get("REPEAT_INTERVAL").is_some_and(|change| !patch_value(change).is_null())+ {+ return "EVENT";+ }+ if let Some(repeat) = value("REPEAT_INTERVAL").as_str() {+ if !repeat.is_empty() {+ return if repeat.trim_start().to_ascii_uppercase().starts_with("FREQ") { "CALENDAR" } else { "PLSQL" };+ }+ }+ if value("START_DATE").is_null() {+ "IMMEDIATE"+ } else {+ "ONCE"+ }+}++fn project_reference(slot: &str, target: Option<&NativeJobSchedulerReferenceTarget>) -> Vec<NativeJobAttributeChange> {+ let (owner_column, name_column) = match slot {+ "PROGRAM_NAME" => ("PROGRAM_OWNER", "PROGRAM_NAME"),+ "SCHEDULE_NAME" => ("SCHEDULE_OWNER", "SCHEDULE_NAME"),+ "CREDENTIAL_NAME" => ("CREDENTIAL_OWNER", "CREDENTIAL_NAME"),+ "CONNECT_CREDENTIAL_NAME" => ("CONNECT_CREDENTIAL_OWNER", "CONNECT_CREDENTIAL_NAME"),+ "DESTINATION_NAME" => ("DESTINATION_OWNER", "DESTINATION"),+ _ => return Vec::new(),+ };+ vec![+ changed(owner_column, target.map_or(Value::Null, |target| Value::String(target.reference.owner.clone()))),+ changed(name_column, target.map_or(Value::Null, |target| Value::String(target.reference.name.clone()))),+ ]+}++/// Compile definitions and conditional argument candidates, not a second execution language.+/// Core binds the referenced metadata and decides which already-previewed SET/RESETs are needed.+pub fn native_job_scheduler_edit_plan(+ engine: NativeJobCatalogDialect,+ request: &NativeJobMutation,+ details: &NativeJobDetails,+) -> Result<NativeJobSchedulerEditPlan, &'static str> {+ let NativeJobRef::Scheduler { owner, .. } = &request.target else { return Err("native_job_not_scheduler") };+ request.target.validate()?;+ if details.snapshot.job_ref != request.target {+ return Err("native_job_identity_mismatch");+ }+ let NativeJobChange::Update { attributes, arguments, argument_target, final_enabled } = &request.change else {+ return Err("native_job_action_not_applicable");+ };+ if argument_target.is_some() && !arguments.is_empty() {+ return Err("native_job_argument_contract_conflict");+ }+ let before = definition(details)?;+ if engine == NativeJobCatalogDialect::Oracle {+ let style = before.get("JOB_STYLE").and_then(Value::as_str);+ for value in arguments+ .iter()+ .map(|argument| &argument.value)+ .chain(argument_target.iter().flat_map(|target| target.arguments.iter().map(|argument| &argument.value)))+ {+ crate::native_job_arguments::validate_lightweight_argument(style, value)?;+ }+ }+ let mut patches = BTreeMap::new();+ for attribute in attributes.iter().filter(|attribute| attribute.change != NativeJobFieldChange::Keep) {+ let key = attribute.name.to_ascii_uppercase();+ if patches.insert(key, attribute.change.clone()).is_some() {+ return Err("native_job_duplicate_attribute");+ }+ }+ if patches.contains_key("DESTINATION") && patches.contains_key("DESTINATION_NAME") {+ return Err("native_job_destination_contract_conflict");+ }+ let old_type = before.get("JOB_TYPE").and_then(Value::as_str).unwrap_or("");+ let job_type = patches+ .get("JOB_TYPE")+ .and_then(|change| match change {+ NativeJobFieldChange::Set { value } => value.as_str(),+ _ => None,+ })+ .unwrap_or(old_type)+ .to_ascii_uppercase();+ let mut normalized = Vec::new();+ let mut references = Vec::new();+ let mut reference_projections = BTreeMap::new();+ let mut reference_changed = false;+ let mut program_changed = false;+ for (slot, change) in &patches {+ if slot == "DESTINATION" {+ if engine != NativeJobCatalogDialect::Oracle {+ return Err("native_job_attribute_not_editable");+ }+ let value = patch_value(change);+ if !before.contains_key("DESTINATION") || !before.contains_key("DESTINATION_OWNER") {+ return Err("native_job_metadata_incomplete");+ }+ if before.get("DESTINATION_OWNER") == Some(&Value::Null) && before.get("DESTINATION") == Some(&value) {+ continue;+ }+ reference_changed = true;+ normalized.push(changed(slot, value.clone()));+ reference_projections+ .insert(slot.clone(), vec![changed("DESTINATION_OWNER", Value::Null), changed("DESTINATION", value)]);+ continue;+ }+ let reference_slot = matches!(+ slot.as_str(),+ "PROGRAM_NAME" | "SCHEDULE_NAME" | "CREDENTIAL_NAME" | "CONNECT_CREDENTIAL_NAME" | "DESTINATION_NAME"+ ) || (slot == "JOB_ACTION" && job_type == "CHAIN");+ if !reference_slot {+ normalized.push(NativeJobAttributeChange { name: slot.clone(), change: change.clone() });+ continue;+ }+ let target = native_job_scheduler_reference_target(slot, &patch_value(change), owner, &job_type)?;+ let old_host = slot == "DESTINATION_NAME"+ && before.get("DESTINATION_OWNER") == Some(&Value::Null)+ && before.get("DESTINATION").is_some_and(|value| !value.is_null());+ let previous = if old_host { None } else { native_reference(before, slot, owner, old_type)? };+ if previous == target && !old_host {+ continue;+ }+ if engine == NativeJobCatalogDialect::Dameng && matches!(slot.as_str(), "PROGRAM_NAME" | "SCHEDULE_NAME") {+ if previous.is_none() {+ return Err("native_job_reference_attach_mapping_unverified");+ }+ if target.is_none() {+ return Err("native_job_reference_detach_mapping_unverified");+ }+ }+ if old_host && target.is_none() {+ return Err("native_job_legacy_destination_clear_mapping_unverified");+ }+ reference_changed = true;+ program_changed |= slot == "PROGRAM_NAME";+ let native_value = target+ .as_ref()+ .map_or(Value::Null, |target| Value::String(quoted_name(&target.reference.owner, &target.reference.name)));+ normalized.push(changed(slot, native_value));+ let mut projections = project_reference(slot, target.as_ref());+ if slot == "JOB_ACTION" {+ projections.push(changed(+ "JOB_ACTION",+ target.as_ref().map_or(Value::Null, |target| {+ Value::String(quoted_name(&target.reference.owner, &target.reference.name))+ }),+ ));+ }+ if slot == "SCHEDULE_NAME" && engine != NativeJobCatalogDialect::Dameng {+ projections.push(changed(+ "SCHEDULE_TYPE",+ Value::String(+ match target.as_ref().map(|target| target.kind) {+ Some(NativeJobReferenceKind::Window) => "WINDOW",+ Some(NativeJobReferenceKind::WindowGroup) => "WINDOW_GROUP",+ Some(_) => "NAMED",+ None => inline_schedule_kind(before, &patches),+ }+ .into(),+ ),+ ));+ }+ if let Some(target) = target {+ references.push(NativeJobSchedulerReferenceBinding { attribute: slot.clone(), target });+ }+ reference_projections.insert(slot.clone(), projections);+ }+ let context_changed = program_changed+ || patches.get("JOB_TYPE").is_some_and(|change| {+ !patch_value(change).as_str().is_some_and(|value| value.eq_ignore_ascii_case(old_type))+ })+ || patches.get("NUMBER_OF_ARGUMENTS").is_some_and(|change| {+ let previous = before+ .get("NUMBER_OF_ARGUMENTS")+ .and_then(|value| value.as_u64().or_else(|| value.as_str()?.parse().ok()));+ previous.is_none() || previous != patch_value(change).as_u64()+ });+ if engine == NativeJobCatalogDialect::OceanbaseOracle+ && (reference_changed || context_changed || patches.contains_key("EVENT_SPEC"))+ {+ return Err("native_job_attribute_not_editable");+ }+ if context_changed && argument_target.is_none() {+ return Err("native_job_argument_target_required");+ }+ let inline_schedule_changed =+ ["START_DATE", "END_DATE", "REPEAT_INTERVAL"].iter().any(|key| patches.contains_key(*key));+ let transition = reference_changed+ || context_changed+ || argument_target.is_some()+ || patches.contains_key("EVENT_SPEC")+ || (engine == NativeJobCatalogDialect::Oracle && inline_schedule_changed);+ if !transition {+ let ordinary = NativeJobMutation {+ target: request.target.clone(),+ baseline: request.baseline.clone(),+ change: NativeJobChange::Update {+ final_enabled: None,+ argument_target: None,+ attributes: normalized,+ arguments: arguments.clone(),+ },+ };+ let mut sql = match native_job_mutation_plan(engine, &ordinary, details) {+ Ok(sql) => sql,+ Err("native_job_no_changes") if final_enabled.is_some() => NativeJobSqlPlan {+ steps: Vec::new(),+ required_partitions: vec!["definition".into()],+ compare_next_date: false,+ dameng_configuration: None,+ },+ Err(reason) => return Err(reason),+ };+ let mut definition = before.clone();+ if let Some(enabled) = final_enabled {+ for step in &mut sql.steps {+ if let NativeJobStepEffect::Fields(changes) = &step.effect {+ for change in changes {+ definition.insert(change.name.clone(), patch_value(&change.change));+ }+ step.effect = NativeJobStepEffect::SchedulerDefinition(NativeJobSchedulerDefinitionEffect {+ columns: changes.clone(),+ references: Vec::new(),+ });+ }+ }+ activation_steps(engine, &request.target, details, &mut sql, *enabled)?;+ }+ return Ok(NativeJobSchedulerEditPlan {+ sql,+ transition: final_enabled.is_some(),+ context_changed: false,+ references: Vec::new(),+ definition,+ argument_target: None,+ final_enabled: final_enabled.unwrap_or(false),+ event_changed: false,+ });+ }+ let final_program = if let Some(change) = patches.get("PROGRAM_NAME") {+ native_job_scheduler_reference_target("PROGRAM_NAME", &patch_value(change), owner, &job_type)?+ } else if context_changed || argument_target.is_some() {+ native_reference(before, "PROGRAM_NAME", owner, old_type)?+ } else {+ None+ };+ let has_program = if program_changed {+ final_program.is_some()+ } else {+ before.get("PROGRAM_NAME").and_then(Value::as_str).is_some_and(|name| !name.is_empty())+ };+ if has_program+ && !program_changed+ && ["JOB_TYPE", "JOB_ACTION", "NUMBER_OF_ARGUMENTS"].iter().any(|key| patches.contains_key(*key))+ {+ return Err("native_job_program_conflicts_with_inline_definition");+ }+ if engine == NativeJobCatalogDialect::Dameng && program_changed && final_program.is_none() {+ return Err("native_job_reference_detach_mapping_unverified");+ }+ if let Some(target) = argument_target {+ if target.program != final_program.as_ref().map(|target| target.reference.clone()) {+ return Err("native_job_argument_target_mismatch");+ }+ if let Some(program) = &final_program {+ if !references.iter().any(|reference| reference.attribute == "PROGRAM_NAME") {+ references.push(NativeJobSchedulerReferenceBinding {+ attribute: "PROGRAM_NAME".into(),+ target: program.clone(),+ });+ }+ }+ }+ let final_enabled =+ final_enabled.or_else(|| enabled(before.get("ENABLED"))).ok_or("native_job_enabled_state_unavailable")?;+ let event_changed = reference_projections.contains_key("SCHEDULE_NAME")+ || patches.contains_key("EVENT_SPEC")+ || inline_schedule_changed;+ let mut force = |key: &str, value: Value| {+ normalized.retain(|attribute| attribute.name != key);+ normalized.push(changed(key, value));+ };+ if program_changed {+ if final_program.is_some() {+ if engine == NativeJobCatalogDialect::Oracle {+ for key in ["JOB_TYPE", "JOB_ACTION", "NUMBER_OF_ARGUMENTS"] {+ force(key, Value::Null);+ }+ }+ } else {+ for key in ["JOB_TYPE", "JOB_ACTION", "NUMBER_OF_ARGUMENTS"] {+ if !patches+ .get(key)+ .is_some_and(|change| matches!(change, NativeJobFieldChange::Set { value } if !value.is_null()))+ {+ return Err("native_job_inline_definition_required");+ }+ }+ }+ }+ if engine != NativeJobCatalogDialect::Dameng+ && patches.contains_key("SCHEDULE_NAME")+ && reference_projections.contains_key("SCHEDULE_NAME")+ {+ let named = references.iter().any(|reference| reference.attribute == "SCHEDULE_NAME");+ if named {+ for key in ["START_DATE", "END_DATE", "REPEAT_INTERVAL", "EVENT_SPEC"] {+ force(key, Value::Null);+ }+ } else if !patches.contains_key("EVENT_SPEC") {+ force("EVENT_SPEC", Value::Null);+ }+ }+ if patches.get("EVENT_SPEC").is_some_and(|change| !patch_value(change).is_null()) {+ if engine != NativeJobCatalogDialect::Oracle {+ return Err("native_job_event_mapping_unverified");+ }+ if final_program.is_some() && patches.contains_key("JOB_TYPE") {+ return Err("native_job_program_conflicts_with_inline_definition");+ }+ force("REPEAT_INTERVAL", Value::Null);+ if !reference_projections.contains_key("SCHEDULE_NAME") {+ force("SCHEDULE_NAME", Value::Null);+ let mut columns = project_reference("SCHEDULE_NAME", None);+ columns.push(changed("SCHEDULE_TYPE", Value::String("EVENT".into())));+ reference_projections.insert("SCHEDULE_NAME".into(), columns);+ }+ }+ if engine == NativeJobCatalogDialect::Oracle+ && patches.get("REPEAT_INTERVAL").is_some_and(|change| !patch_value(change).is_null())+ && before.get("SCHEDULE_TYPE").and_then(Value::as_str) == Some("EVENT")+ && !patches.contains_key("EVENT_SPEC")+ {+ force("EVENT_SPEC", Value::Null);+ }+ let final_schedule_named = if let Some(change) = patches.get("SCHEDULE_NAME") {+ !patch_value(change).is_null()+ } else {+ before.get("SCHEDULE_NAME").is_some_and(|value| !value.is_null())+ };+ if inline_schedule_changed && final_schedule_named && !reference_projections.contains_key("SCHEDULE_NAME") {+ return Err("native_job_schedule_conflicts_with_inline_definition");+ }+ let mut definition = before.clone();+ let mut columns_by_attribute = BTreeMap::new();+ let mut ordinary_attributes = Vec::new();+ let mut event = None;+ for attribute in normalized {+ let mut columns = reference_projections.remove(&attribute.name).unwrap_or_else(|| vec![attribute.clone()]);+ if attribute.name == "EVENT_SPEC" {+ let value = patch_value(&attribute.change);+ let mut columns = [+ "EVENT_CONDITION",+ "EVENT_QUEUE_OWNER",+ "EVENT_QUEUE_NAME",+ "EVENT_QUEUE_AGENT",+ "FILE_WATCHER_OWNER",+ "FILE_WATCHER_NAME",+ ]+ .into_iter()+ .map(|key| changed(key, Value::Null))+ .collect::<Vec<_>>();+ let (condition, queue) = if value.is_null() {+ (Value::Null, Value::Null)+ } else {+ let source: NativeJobEventSource =+ serde_json::from_value(value.get("source").cloned().ok_or("native_job_event_queue_required")?)+ .map_err(|_| "native_job_event_queue_required")?;+ let condition = value.get("condition").cloned().unwrap_or(Value::Null);+ if !condition.is_null() && !condition.is_string() {+ return Err("native_job_attribute_type_invalid");+ }+ columns[0] = changed("EVENT_CONDITION", condition.clone());+ let queue = match source {+ NativeJobEventSource::Queue { owner, name, agent } => {+ if owner.is_empty()+ || name.is_empty()+ || owner.contains('\0')+ || name.contains('\0')+ || agent.as_ref().is_some_and(|agent| agent.is_empty() || agent.contains('\0'))+ {+ return Err("native_job_reference_input_invalid");+ }+ columns[1] = changed("EVENT_QUEUE_OWNER", Value::String(owner.clone()));+ columns[2] = changed("EVENT_QUEUE_NAME", Value::String(name.clone()));+ columns[3] = changed("EVENT_QUEUE_AGENT", agent.clone().map_or(Value::Null, Value::String));+ let mut queue = quoted_name(&owner, &name);+ if let Some(agent) = agent {+ queue.push_str(&format!(",\"{}\"", agent.replace('"', "\"\"")));+ }+ queue+ }+ NativeJobEventSource::FileWatcher { reference } => {+ if reference.owner.is_empty()+ || reference.name.is_empty()+ || reference.owner.contains('\0')+ || reference.name.contains('\0')+ {+ return Err("native_job_reference_input_invalid");+ }+ columns[4] = changed("FILE_WATCHER_OWNER", Value::String(reference.owner.clone()));+ columns[5] = changed("FILE_WATCHER_NAME", Value::String(reference.name.clone()));+ let queue = quoted_name(&reference.owner, &reference.name);+ references.push(NativeJobSchedulerReferenceBinding {+ attribute: "EVENT_SPEC".into(),+ target: NativeJobSchedulerReferenceTarget {+ kind: NativeJobReferenceKind::FileWatcher,+ reference,+ },+ });+ queue+ }+ };+ (condition, Value::String(queue))+ };+ for column in &columns {+ definition.insert(column.name.clone(), patch_value(&column.change));+ }+ if !final_schedule_named {+ let kind = if value.is_null() { inline_schedule_kind(before, &patches) } else { "EVENT" };+ definition.insert("SCHEDULE_TYPE".into(), Value::String(kind.into()));+ columns.push(changed("SCHEDULE_TYPE", Value::String(kind.into())));+ }+ event = Some((condition, queue, columns));+ continue;+ }+ if engine == NativeJobCatalogDialect::Oracle+ && inline_schedule_changed+ && !final_schedule_named+ && matches!(attribute.name.as_str(), "START_DATE" | "END_DATE" | "REPEAT_INTERVAL")+ {+ columns.push(changed("SCHEDULE_TYPE", Value::String(inline_schedule_kind(before, &patches).into())));+ }+ for column in &columns {+ definition.insert(column.name.clone(), patch_value(&column.change));+ }+ columns_by_attribute.insert(attribute.name.clone(), columns);+ ordinary_attributes.push(attribute);+ }+ if !has_program && (context_changed || argument_target.is_some()) {+ let count = definition+ .get("NUMBER_OF_ARGUMENTS")+ .and_then(Value::as_u64)+ .filter(|count| *count <= 255)+ .ok_or("native_job_argument_count_invalid")?;+ if matches!(job_type.as_str(), "PLSQL_BLOCK" | "CHAIN") && count != 0 {+ return Err("native_job_argument_count_invalid");+ }+ if let Some(target) = argument_target {+ if target.arguments.len() != count as usize {+ return Err("native_job_argument_target_incomplete");+ }+ }+ }+ let identity = match &details.native_identity {+ NativeJobMetadata::Available { value } => Some(value),+ _ => return Err("native_job_identity_unverified"),+ };+ let mut sql = NativeJobSqlPlan {+ steps: Vec::new(),+ required_partitions: vec!["definition".into()],+ compare_next_date: false,+ dameng_configuration: None,+ };+ // No caller-supplied SQL and no broad field exemption: each native projection is explicit.+ scheduler_attribute_steps(engine, &request.target, identity, None, &ordinary_attributes, &mut sql)?;+ for step in &mut sql.steps {+ let NativeJobStepEffect::Fields(changes) = &step.effect else { continue };+ let columns = changes+ .iter()+ .flat_map(|change| columns_by_attribute.get(&change.name).cloned().unwrap_or_default())+ .collect();+ let changed_slots: HashSet<_> = changes.iter().map(|change| change.name.as_str()).collect();+ step.effect = NativeJobStepEffect::SchedulerDefinition(NativeJobSchedulerDefinitionEffect {+ columns,+ references: references+ .iter()+ .filter(|reference| changed_slots.contains(reference.attribute.as_str()))+ .cloned()+ .collect(),+ });+ }+ if let Some((condition, queue, columns)) = event {+ let value = |value: &Value| value.as_str().map(text).unwrap_or_else(|| "CAST(NULL AS VARCHAR2(4000))".into());+ let name = text(&scheduler_name(engine, &request.target)?);+ let constructor = if condition.is_null() && queue.is_null() {+ format!("SYS.JOBATTR({name}, 'event_spec')")+ } else {+ format!("SYS.JOBATTR({name}, 'event_spec', {}, {})", value(&condition), value(&queue))+ };+ if let Some(step) = sql.steps.iter_mut().find(|step| step.id == "attributes") {+ step.sql = step.sql.replacen("SYS.JOBATTR_ARRAY(", &format!("SYS.JOBATTR_ARRAY({constructor}, "), 1);+ let NativeJobStepEffect::SchedulerDefinition(effect) = &mut step.effect else { unreachable!() };+ effect.columns.extend(columns);+ } else {+ sql.steps.insert(0, NativeJobSqlStep { id: "attributes".into(), label: "native_job_step_attributes".into(), sql: format!("BEGIN SYS.DBMS_SCHEDULER.SET_JOB_ATTRIBUTES(SYS.JOBATTR_ARRAY({constructor}), 'TRANSACTIONAL'); END;"), effect: NativeJobStepEffect::SchedulerDefinition(NativeJobSchedulerDefinitionEffect { columns, references: Vec::new() }) });+ }+ }+ activation_steps(engine, &request.target, details, &mut sql, false)?;+ if let Some(target) = argument_target {+ sql.required_partitions.push("argument-inventory".into());+ let mut positions = HashSet::new();+ for argument in &target.arguments {+ if argument.position == 0+ || !positions.insert(argument.position)+ || argument.position > target.arguments.len()+ {+ return Err("native_job_argument_target_incomplete");+ }+ if engine == NativeJobCatalogDialect::Dameng+ && matches!(argument.value, NativeJobArgumentValue::Unset | NativeJobArgumentValue::Inherit)+ {+ if !program_changed {+ let inventory = match &details.parameter_metadata {+ NativeJobMetadata::Available { value } => value.as_slice(),+ NativeJobMetadata::Empty => &[],+ _ => return Err("native_job_arguments_unavailable"),+ };+ for row in inventory {+ let position = row+ .get("ARGUMENT_POSITION")+ .and_then(|value| value.as_u64().or_else(|| value.as_str()?.parse().ok()))+ .filter(|position| *position > 0)+ .ok_or("native_job_arguments_invalid")?;+ if position == argument.position as u64 {+ return Err("native_job_argument_reset_mapping_unverified");+ }+ }+ }+ continue;+ }+ sql.steps.push(scheduler_argument_step(+ engine,+ &request.target,+ identity,+ &NativeJobArgumentChange { position: argument.position, value: argument.value.clone() },+ &argument.data_type,+ )?);+ }+ } else {+ // Reference-only changes retain the original delta semantics for unchanged argument contexts.+ let mut delta = NativeJobSqlPlan {+ steps: Vec::new(),+ required_partitions: Vec::new(),+ compare_next_date: false,+ dameng_configuration: None,+ };+ scheduler_changes(engine, request, details, &[], arguments, &mut delta)?;+ sql.steps.extend(delta.steps);+ sql.required_partitions.extend(delta.required_partitions);+ }+ if final_enabled {+ let name = text(&scheduler_name(engine, &request.target)?);+ let package = scheduler_package(engine);+ sql.steps.push(NativeJobSqlStep {+ id: "enable".into(),+ label: "native_job_step_enable".into(),+ sql: wrap_scheduler(engine, &request.target, identity, &format!("{package}.ENABLE({name});"))?,+ effect: NativeJobStepEffect::Enabled(true),+ });+ }+ let validations = if let Some(target) = argument_target {+ scheduler_argument_validation_steps(+ engine,+ target.arguments.iter().map(|argument| (argument.position, &argument.value)),+ )?+ } else {+ scheduler_argument_validation_steps(+ engine,+ arguments.iter().map(|argument| (argument.position, &argument.value)),+ )?+ };+ sql.steps.splice(0..0, validations);+ Ok(NativeJobSchedulerEditPlan {+ sql,+ transition,+ context_changed,+ references,+ definition,+ argument_target: argument_target.clone(),+ final_enabled,+ event_changed,+ })+}++fn activation_steps(+ engine: NativeJobCatalogDialect,+ target: &NativeJobRef,+ details: &NativeJobDetails,+ sql: &mut NativeJobSqlPlan,+ final_enabled: bool,+) -> Result<(), &'static str> {+ let name = text(&scheduler_name(engine, target)?);+ let package = scheduler_package(engine);+ sql.steps.insert(+ 0,+ NativeJobSqlStep {+ id: "pause".into(),+ label: "native_job_step_disable".into(),+ sql: wrap(engine, target, details, &format!("{package}.DISABLE({name});"))?,+ effect: NativeJobStepEffect::Enabled(false),+ },+ );+ if final_enabled {+ sql.steps.push(NativeJobSqlStep {+ id: "enable".into(),+ label: "native_job_step_enable".into(),+ sql: wrap(engine, target, details, &format!("{package}.ENABLE({name});"))?,+ effect: NativeJobStepEffect::Enabled(true),+ });+ }+ Ok(())+}diff --git a/crates/dbx-sql-schema/src/native_jobs.rs b/crates/dbx-sql-schema/src/native_jobs.rsnew file mode 100644index 0000000000..65ec610619--- /dev/null+++ b/crates/dbx-sql-schema/src/native_jobs.rs@@ -0,0 +1,253 @@+use dbx_sql_core::value_literals::quote_string_literal;+pub use dbx_types::native_jobs::{NativeJobCatalogCoverage, NativeJobEngine as NativeJobCatalogDialect};+use dbx_types::native_jobs::{NativeJobKind, NativeJobRef};++mod references;+pub use references::native_job_reference_queries;++#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum NativeJobCatalogPart {+ Definition,+ Generation,+ NativeAttributes,+ Arguments,+ Steps,+ Schedules,+ Running,+ History,+}++#[derive(Debug, Clone, PartialEq, Eq)]+pub struct NativeJobCatalogQuery {+ pub source: &'static str,+ pub coverage: NativeJobCatalogCoverage,+ pub sql: String,+ pub limit: usize,+}++fn scheduler_sources(+ dialect: NativeJobCatalogDialect,+ part: NativeJobCatalogPart,+) -> Vec<(&'static str, NativeJobCatalogCoverage)> {+ use NativeJobCatalogCoverage::{Accessible, CurrentUser, Database};+ use NativeJobCatalogPart::{Arguments, Definition, Generation, History, Running};+ // OB documents these compatibility views as always empty, even for jobs with actual arguments.+ // An empty placeholder is not evidence of an unset argument or permission to overwrite it.+ if dialect == NativeJobCatalogDialect::OceanbaseOracle && part == Arguments {+ return Vec::new();+ }+ let sources = match part {+ Definition => ["SYS.DBA_SCHEDULER_JOBS", "SYS.ALL_SCHEDULER_JOBS", "SYS.USER_SCHEDULER_JOBS"],+ Arguments => ["SYS.DBA_SCHEDULER_JOB_ARGS", "SYS.ALL_SCHEDULER_JOB_ARGS", "SYS.USER_SCHEDULER_JOB_ARGS"],+ Running => {+ ["SYS.DBA_SCHEDULER_RUNNING_JOBS", "SYS.ALL_SCHEDULER_RUNNING_JOBS", "SYS.USER_SCHEDULER_RUNNING_JOBS"]+ }+ History => [+ "SYS.DBA_SCHEDULER_JOB_RUN_DETAILS",+ "SYS.ALL_SCHEDULER_JOB_RUN_DETAILS",+ "SYS.USER_SCHEDULER_JOB_RUN_DETAILS",+ ],+ Generation => ["SYS.DBA_OBJECTS", "SYS.ALL_OBJECTS", "SYS.USER_OBJECTS"],+ _ => return Vec::new(),+ };+ match dialect {+ NativeJobCatalogDialect::Oracle => {+ vec![(sources[0], Database), (sources[1], Accessible), (sources[2], CurrentUser)]+ }+ NativeJobCatalogDialect::OceanbaseOracle => vec![(sources[0], Database), (sources[2], CurrentUser)],+ NativeJobCatalogDialect::Dameng => vec![+ (sources[0].strip_prefix("SYS.").unwrap(), Database),+ (sources[2].strip_prefix("SYS.").unwrap(), CurrentUser),+ ],+ }+}++fn dameng_native_sources() -> Vec<(&'static str, NativeJobCatalogCoverage)> {+ vec![+ ("SYSJOB.SYSJOBS", NativeJobCatalogCoverage::Database),+ ("SYSJOB.USER_JOBS_VIEW", NativeJobCatalogCoverage::CurrentUser),+ ]+}++/// Alternative catalog sources, not a license to reinterpret an empty or failed read.+pub fn native_job_definition_queries(+ dialect: NativeJobCatalogDialect,+ target: &NativeJobRef,+) -> Result<Vec<NativeJobCatalogQuery>, &'static str> {+ native_job_catalog_queries(dialect, target, NativeJobCatalogPart::Definition)+}++pub fn native_job_catalog_queries(+ dialect: NativeJobCatalogDialect,+ target: &NativeJobRef,+ part: NativeJobCatalogPart,+) -> Result<Vec<NativeJobCatalogQuery>, &'static str> {+ target.validate()?;+ let limit = match part {+ NativeJobCatalogPart::Definition+ | NativeJobCatalogPart::Generation+ | NativeJobCatalogPart::NativeAttributes => 1,+ NativeJobCatalogPart::Running => 1_000,+ NativeJobCatalogPart::History => 200,+ _ => 10_000,+ };+ match target {+ NativeJobRef::Scheduler { owner, name, .. }+ if part == NativeJobCatalogPart::Generation && dialect == NativeJobCatalogDialect::OceanbaseOracle =>+ {+ Ok(vec![NativeJobCatalogQuery {+ source: "SYS.ALL_VIRTUAL_TENANT_SCHEDULER_JOB_REAL_AGENT",+ coverage: NativeJobCatalogCoverage::Accessible,+ sql: format!(+ "SELECT DISTINCT TO_CHAR(JOB) AS DBX_JOB_ID, TO_CHAR(GMT_CREATE, 'YYYY-MM-DD HH24:MI:SS.FF6') AS DBX_CREATED_AT FROM SYS.ALL_VIRTUAL_TENANT_SCHEDULER_JOB_REAL_AGENT WHERE POWNER = {} AND JOB_NAME = {} AND JOB > 0",+ quote_string_literal(owner), quote_string_literal(name)+ ),+ limit,+ }])+ }+ NativeJobRef::Scheduler { owner, name, .. }+ if part == NativeJobCatalogPart::NativeAttributes && dialect == NativeJobCatalogDialect::OceanbaseOracle =>+ {+ Ok(vec![NativeJobCatalogQuery {+ source: "SYS.ALL_VIRTUAL_TENANT_SCHEDULER_JOB_REAL_AGENT",+ coverage: NativeJobCatalogCoverage::Accessible,+ sql: format!(+ "SELECT DISTINCT TO_CHAR(JOB) AS DBX_JOB_ID, TO_CHAR(GMT_CREATE, 'YYYY-MM-DD HH24:MI:SS.FF6') AS DBX_CREATED_AT, POWNER AS DBX_OWNER, JOB_NAME, MAX_FAILURES FROM SYS.ALL_VIRTUAL_TENANT_SCHEDULER_JOB_REAL_AGENT WHERE POWNER = {} AND JOB_NAME = {} AND JOB > 0",+ quote_string_literal(owner), quote_string_literal(name)+ ),+ limit,+ }])+ }+ NativeJobRef::Scheduler { owner, name, .. } => Ok(scheduler_sources(dialect, part)+ .into_iter()+ .map(|(source, coverage)| {+ let current_user = coverage == NativeJobCatalogCoverage::CurrentUser;+ let owner_column = if current_user { "USER" } else { "J.OWNER" };+ let extra = if current_user { ", USER AS DBX_OWNER" } else { "" };+ let (projection, name_column, filter) = if part == NativeJobCatalogPart::Generation {+ ("TO_CHAR(J.OBJECT_ID) AS DBX_JOB_ID, TO_CHAR(J.CREATED, 'YYYY-MM-DD HH24:MI:SS') AS DBX_CREATED_AT".to_string(), "J.OBJECT_NAME", " AND J.OBJECT_TYPE = 'JOB'")+ } else if part == NativeJobCatalogPart::Arguments && dialect == NativeJobCatalogDialect::Oracle {+ let evidence = crate::native_job_arguments::anydata_projection(crate::native_job_arguments::AnydataColumn::JobArgument);+ (format!("J.*, {evidence}"), "J.JOB_NAME", "")+ } else {+ ("J.*".to_string(), "J.JOB_NAME", "")+ };+ let order = match part {+ NativeJobCatalogPart::History => " ORDER BY J.LOG_DATE DESC, J.LOG_ID DESC",+ _ => "",+ };+ let (prefix, join) = if part == NativeJobCatalogPart::Arguments && dialect == NativeJobCatalogDialect::Oracle {+ (crate::native_job_arguments::anydata_query_prefix(), crate::native_job_arguments::anydata_join(crate::native_job_arguments::AnydataColumn::JobArgument))+ } else { (String::new(), String::new()) };+ NativeJobCatalogQuery {+ source,+ coverage,+ sql: format!(+ "{prefix}SELECT {projection}{extra} FROM {source} J{join} WHERE {owner_column} = {} AND {name_column} = {}{filter}{order}",+ quote_string_literal(owner),+ quote_string_literal(name)+ ),+ limit,+ }+ })+ .collect()),+ NativeJobRef::Legacy { job_id, .. } if dialect != NativeJobCatalogDialect::Dameng => {+ let sources = match part {+ NativeJobCatalogPart::Definition | NativeJobCatalogPart::Generation => vec![+ ("SYS.DBA_JOBS", NativeJobCatalogCoverage::Database),+ ("SYS.USER_JOBS", NativeJobCatalogCoverage::CurrentUser),+ ],+ NativeJobCatalogPart::Running => vec![("SYS.DBA_JOBS_RUNNING", NativeJobCatalogCoverage::Database)],+ _ => Vec::new(),+ };+ Ok(sources.into_iter().map(|(source, coverage)| {+ let projection = if part == NativeJobCatalogPart::Generation { "TO_CHAR(J.JOB) AS DBX_JOB_ID" } else { "J.*, TO_CHAR(J.JOB) AS DBX_JOB_ID" };+ NativeJobCatalogQuery { source, coverage, sql: format!("SELECT {projection} FROM {source} J WHERE J.JOB = {job_id}"), limit }+ }).collect())+ }+ NativeJobRef::Legacy { job_id, .. } | NativeJobRef::DamengNative { job_id, .. }+ if dialect == NativeJobCatalogDialect::Dameng =>+ {+ let identity_filter = match target {+ NativeJobRef::DamengNative { name, .. } => format!(" AND J.NAME = {}", quote_string_literal(name)),+ _ => " AND J.SYS_FLAG = 2".into(),+ };+ let (sources, projection, predicate, order) = match part {+ NativeJobCatalogPart::Definition => (dameng_native_sources(), "J.*, CAST(J.ID AS VARCHAR(40)) AS DBX_JOB_ID", format!("J.ID = {job_id}{identity_filter}"), ""),+ NativeJobCatalogPart::Generation => (dameng_native_sources(), "CAST(J.ID AS VARCHAR(40)) AS DBX_JOB_ID, J.CREATETIME AS DBX_CREATED_AT", format!("J.ID = {job_id}{identity_filter}"), ""),+ NativeJobCatalogPart::Steps => (vec![("SYSJOB.SYSJOBSTEPS", NativeJobCatalogCoverage::Database), ("SYSJOB.USER_JOBSTEPS_VIEW", NativeJobCatalogCoverage::CurrentUser)], "J.*, CAST(J.ID AS VARCHAR(40)) AS DBX_CHILD_ID", format!("J.JOBID = {job_id}"), " ORDER BY J.SEQNO, J.NAME"),+ NativeJobCatalogPart::Schedules => (vec![("SYSJOB.SYSJOBSCHEDULES", NativeJobCatalogCoverage::Database), ("SYSJOB.USER_JOBSCHEDULES_VIEW", NativeJobCatalogCoverage::CurrentUser)], "J.*, CAST(J.ID AS VARCHAR(40)) AS DBX_CHILD_ID", format!("J.JOBID = {job_id}"), " ORDER BY J.NAME"),+ NativeJobCatalogPart::Running => (vec![("SYSJOB.DBA_JOBS_RUNNING", NativeJobCatalogCoverage::Database)], "J.*", format!("J.JOB = {job_id}"), ""),+ NativeJobCatalogPart::History => (vec![("SYSJOB.SYSJOBHISTORIES2", NativeJobCatalogCoverage::Database), ("SYSJOB.USER_JOBHISTORIES_VIEW", NativeJobCatalogCoverage::CurrentUser)], "J.*", format!("J.JOBID = {job_id}"), " ORDER BY J.EXEC_ID DESC"),+ NativeJobCatalogPart::NativeAttributes if matches!(target, NativeJobRef::Legacy { .. }) => (+ vec![("SYSJOB.DBA_JOBS", NativeJobCatalogCoverage::Database), ("SYSJOB.USER_JOBS", NativeJobCatalogCoverage::CurrentUser)],+ "J.*, CAST(J.JOB AS VARCHAR(40)) AS DBX_JOB_ID", format!("J.JOB = {job_id}"), ""+ ),+ NativeJobCatalogPart::Arguments | NativeJobCatalogPart::NativeAttributes => return Ok(Vec::new()),+ };+ Ok(sources.into_iter().map(|(source, coverage)| NativeJobCatalogQuery {+ source, coverage, sql: format!("SELECT {projection} FROM {source} J WHERE {predicate}{order}"), limit+ }).collect())+ }+ _ => Err("native_job_kind_invalid"),+ }+}++/// Lightweight, deterministically ordered pages. Selected definitions are fetched separately.+pub fn native_job_list_queries(+ dialect: NativeJobCatalogDialect,+ kind: NativeJobKind,+ schema: Option<&str>,+ filter: &str,+ offset: usize,+ limit: usize,+) -> Result<Vec<NativeJobCatalogQuery>, &'static str> {+ if limit == 0+ || limit > 500+ || schema.is_some_and(|schema| schema.is_empty() || schema.contains('\0'))+ || filter.contains('\0')+ {+ return Err("native_job_list_input_invalid");+ }+ let end = offset+ .checked_add(limit)+ .and_then(|end| end.checked_add(1))+ .filter(|end| *end <= i32::MAX as usize)+ .ok_or("native_job_list_input_invalid")?;+ let scheduler = kind == NativeJobKind::Scheduler;+ let dm_native = dialect == NativeJobCatalogDialect::Dameng && !scheduler;+ let sources = match kind {+ NativeJobKind::Scheduler => scheduler_sources(dialect, NativeJobCatalogPart::Definition),+ NativeJobKind::Legacy if !dm_native => vec![+ ("SYS.DBA_JOBS", NativeJobCatalogCoverage::Database),+ ("SYS.USER_JOBS", NativeJobCatalogCoverage::CurrentUser),+ ],+ NativeJobKind::Legacy | NativeJobKind::DamengNative if dm_native => dameng_native_sources(),+ _ => return Err("native_job_kind_invalid"),+ };+ let search =+ quote_string_literal(&format!("%{}%", filter.replace('!', "!!").replace('%', "!%").replace('_', "!_")));+ Ok(sources.into_iter().map(|(source, coverage)| {+ let owner = if coverage == NativeJobCatalogCoverage::CurrentUser { "USER" } else { "J.OWNER" };+ let (projection, name, schema_column, order) = if scheduler {+ (format!("J.JOB_NAME, {owner} AS DBX_OWNER, J.JOB_TYPE, J.ENABLED, J.STATE, J.NEXT_RUN_DATE, J.COMMENTS"), "J.JOB_NAME", owner, format!("{owner}, J.JOB_NAME"))+ } else if dm_native {+ ("CAST(J.ID AS VARCHAR(40)) AS DBX_JOB_ID, J.NAME, J.ENABLE, J.USERNAME, J.DESCRIBE, J.SYS_FLAG".into(), "J.NAME", "J.USERNAME", "J.NAME, J.ID".into())+ } else {+ ("TO_CHAR(J.JOB) AS DBX_JOB_ID, J.LOG_USER, J.PRIV_USER, J.SCHEMA_USER, J.BROKEN, J.NEXT_DATE, J.FAILURES".into(), "TO_CHAR(J.JOB)", "J.SCHEMA_USER", "J.JOB".into())+ };+ let mut predicates = Vec::new();+ if let Some(schema) = schema { predicates.push(format!("{schema_column} = {}", quote_string_literal(schema))); }+ if !filter.is_empty() {+ let columns = if dm_native {vec![name, "J.USERNAME", "J.DESCRIBE"]} else {vec![name]};+ let matches = columns.into_iter().map(|column| format!("UPPER({column}) LIKE UPPER({search}) ESCAPE '!'")).collect::<Vec<_>>().join(" OR ");+ predicates.push(if dm_native {format!("({matches})")} else {matches});+ }+ if dm_native && kind == NativeJobKind::Legacy { predicates.push("J.SYS_FLAG = 2".into()); }+ let condition = if predicates.is_empty() { String::new() } else { format!(" WHERE {}", predicates.join(" AND ")) };+ NativeJobCatalogQuery {+ source, coverage, limit,+ sql: format!("SELECT * FROM (SELECT {projection}, ROW_NUMBER() OVER (ORDER BY {order}) AS DBX_ROW_NUM FROM {source} J{condition}) WHERE DBX_ROW_NUM > {offset} AND DBX_ROW_NUM <= {end} ORDER BY DBX_ROW_NUM"),+ }+ }).collect())+}diff --git a/crates/dbx-sql-schema/src/native_jobs/references.rs b/crates/dbx-sql-schema/src/native_jobs/references.rsnew file mode 100644index 0000000000..b33b4e2956--- /dev/null+++ b/crates/dbx-sql-schema/src/native_jobs/references.rs@@ -0,0 +1,184 @@+use super::*;+use dbx_types::native_jobs::{NativeJobReferenceKind, NativeJobReferenceListRequest};++/// Reference browsing uses the same typed source fallback and authenticated scope as Job reads.+pub fn native_job_reference_queries(+ dialect: NativeJobCatalogDialect,+ request: &NativeJobReferenceListRequest,+) -> Result<Vec<NativeJobCatalogQuery>, &'static str> {+ let args = request.kind == NativeJobReferenceKind::ProgramArguments;+ let members = request.kind == NativeJobReferenceKind::DestinationGroupMembers;+ let inventory = args || members;+ if request.limit == 0+ || request.limit > if inventory { 10_000 } else { 500 }+ || request.schema.as_ref().is_some_and(|value| value.is_empty() || value.contains('\0'))+ || request.name.as_ref().is_some_and(|value| value.is_empty() || value.contains('\0'))+ || request.filter.contains('\0')+ || request.name.is_some() && request.schema.is_none()+ || inventory && request.name.is_none()+ {+ return Err("native_job_reference_input_invalid");+ }+ let end = request+ .offset+ .checked_add(request.limit)+ .and_then(|end| end.checked_add(1))+ .filter(|end| *end <= i32::MAX as usize)+ .ok_or("native_job_reference_input_invalid")?;+ let (catalog, name_column) = match request.kind {+ NativeJobReferenceKind::Program => ("SCHEDULER_PROGRAMS", "PROGRAM_NAME"),+ NativeJobReferenceKind::ProgramArguments => ("SCHEDULER_PROGRAM_ARGS", "PROGRAM_NAME"),+ NativeJobReferenceKind::Schedule => ("SCHEDULER_SCHEDULES", "SCHEDULE_NAME"),+ NativeJobReferenceKind::Chain => ("SCHEDULER_CHAINS", "CHAIN_NAME"),+ NativeJobReferenceKind::Credential => ("CREDENTIALS", "CREDENTIAL_NAME"),+ NativeJobReferenceKind::Destination => ("SCHEDULER_DESTS", "DESTINATION_NAME"),+ NativeJobReferenceKind::Window => ("SCHEDULER_WINDOWS", "WINDOW_NAME"),+ NativeJobReferenceKind::WindowGroup | NativeJobReferenceKind::DestinationGroup => {+ ("SCHEDULER_GROUPS", "GROUP_NAME")+ }+ NativeJobReferenceKind::FileWatcher => ("SCHEDULER_FILE_WATCHERS", "FILE_WATCHER_NAME"),+ NativeJobReferenceKind::DestinationGroupMembers => ("SCHEDULER_GROUP_MEMBERS", "GROUP_NAME"),+ };+ if dialect != NativeJobCatalogDialect::Oracle+ && matches!(+ request.kind,+ NativeJobReferenceKind::Window+ | NativeJobReferenceKind::WindowGroup+ | NativeJobReferenceKind::FileWatcher+ | NativeJobReferenceKind::DestinationGroup+ | NativeJobReferenceKind::DestinationGroupMembers+ )+ {+ return Ok(Vec::new());+ }+ // V4.2.5's documented Program argument views are compatibility placeholders (WHERE 1=0).+ if dialect == NativeJobCatalogDialect::OceanbaseOracle && args {+ return Ok(Vec::new());+ }+ // DM documents these job attributes as compatibility-only and does not implement CHAIN.+ if dialect == NativeJobCatalogDialect::Dameng+ && matches!(+ request.kind,+ NativeJobReferenceKind::Chain | NativeJobReferenceKind::Credential | NativeJobReferenceKind::Destination+ )+ {+ return Ok(Vec::new());+ }+ let sources = match (dialect, catalog) {+ (NativeJobCatalogDialect::Oracle, "SCHEDULER_PROGRAMS") => {+ vec!["SYS.DBA_SCHEDULER_PROGRAMS", "SYS.ALL_SCHEDULER_PROGRAMS", "SYS.USER_SCHEDULER_PROGRAMS"]+ }+ (NativeJobCatalogDialect::Oracle, "SCHEDULER_PROGRAM_ARGS") => {+ vec!["SYS.DBA_SCHEDULER_PROGRAM_ARGS", "SYS.ALL_SCHEDULER_PROGRAM_ARGS", "SYS.USER_SCHEDULER_PROGRAM_ARGS"]+ }+ (NativeJobCatalogDialect::Oracle, "SCHEDULER_SCHEDULES") => {+ vec!["SYS.DBA_SCHEDULER_SCHEDULES", "SYS.ALL_SCHEDULER_SCHEDULES", "SYS.USER_SCHEDULER_SCHEDULES"]+ }+ (NativeJobCatalogDialect::Oracle, "SCHEDULER_CHAINS") => {+ vec!["SYS.DBA_SCHEDULER_CHAINS", "SYS.ALL_SCHEDULER_CHAINS", "SYS.USER_SCHEDULER_CHAINS"]+ }+ (NativeJobCatalogDialect::Oracle, "CREDENTIALS") => vec![+ "SYS.DBA_CREDENTIALS",+ "SYS.ALL_CREDENTIALS",+ "SYS.USER_CREDENTIALS",+ "SYS.DBA_SCHEDULER_CREDENTIALS",+ "SYS.ALL_SCHEDULER_CREDENTIALS",+ "SYS.USER_SCHEDULER_CREDENTIALS",+ ],+ (NativeJobCatalogDialect::Oracle, "SCHEDULER_DESTS") => {+ vec!["SYS.DBA_SCHEDULER_DESTS", "SYS.ALL_SCHEDULER_DESTS", "SYS.USER_SCHEDULER_DESTS"]+ }+ (NativeJobCatalogDialect::Oracle, "SCHEDULER_WINDOWS") => {+ // Oracle documents DBA/ALL windows, not a USER_SCHEDULER_WINDOWS view.+ vec!["SYS.DBA_SCHEDULER_WINDOWS", "SYS.ALL_SCHEDULER_WINDOWS"]+ }+ (NativeJobCatalogDialect::Oracle, "SCHEDULER_GROUPS") => {+ vec!["SYS.DBA_SCHEDULER_GROUPS", "SYS.ALL_SCHEDULER_GROUPS", "SYS.USER_SCHEDULER_GROUPS"]+ }+ (NativeJobCatalogDialect::Oracle, "SCHEDULER_FILE_WATCHERS") => {+ vec![+ "SYS.DBA_SCHEDULER_FILE_WATCHERS",+ "SYS.ALL_SCHEDULER_FILE_WATCHERS",+ "SYS.USER_SCHEDULER_FILE_WATCHERS",+ ]+ }+ (NativeJobCatalogDialect::Oracle, "SCHEDULER_GROUP_MEMBERS") => vec![+ "SYS.DBA_SCHEDULER_GROUP_MEMBERS",+ "SYS.ALL_SCHEDULER_GROUP_MEMBERS",+ "SYS.USER_SCHEDULER_GROUP_MEMBERS",+ ],+ (NativeJobCatalogDialect::OceanbaseOracle, "SCHEDULER_PROGRAMS") => {+ vec!["SYS.DBA_SCHEDULER_PROGRAM"]+ }+ (NativeJobCatalogDialect::OceanbaseOracle, "SCHEDULER_SCHEDULES") => {+ vec!["SYS.DBA_SCHEDULER_SCHEDULES", "SYS.USER_SCHEDULER_SCHEDULES"]+ }+ (NativeJobCatalogDialect::OceanbaseOracle, "SCHEDULER_CHAINS") => {+ vec!["SYS.DBA_SCHEDULER_CHAINS", "SYS.USER_SCHEDULER_CHAINS"]+ }+ (NativeJobCatalogDialect::OceanbaseOracle, "CREDENTIALS") => {+ vec!["SYS.DBA_CREDENTIALS", "SYS.USER_CREDENTIALS"]+ }+ (NativeJobCatalogDialect::OceanbaseOracle, "SCHEDULER_DESTS") => {+ vec!["SYS.DBA_SCHEDULER_DESTS", "SYS.USER_SCHEDULER_DESTS"]+ }+ (NativeJobCatalogDialect::Dameng, "SCHEDULER_PROGRAMS") => {+ vec!["DBA_SCHEDULER_PROGRAMS", "USER_SCHEDULER_PROGRAMS"]+ }+ (NativeJobCatalogDialect::Dameng, "SCHEDULER_PROGRAM_ARGS") => {+ vec!["DBA_SCHEDULER_PROGRAM_ARGS", "USER_SCHEDULER_PROGRAM_ARGS"]+ }+ (NativeJobCatalogDialect::Dameng, "SCHEDULER_SCHEDULES") => {+ vec!["DBA_SCHEDULER_SCHEDULES", "USER_SCHEDULER_SCHEDULES"]+ }+ _ => unreachable!("closed reference kind"),+ };+ let search =+ quote_string_literal(&format!("%{}%", request.filter.replace('!', "!!").replace('%', "!%").replace('_', "!_")));+ let queries = sources.into_iter().map(|source| {+ let current = source.starts_with("SYS.USER_") || source.starts_with("USER_");+ let accessible = source.starts_with("SYS.ALL_");+ let owner = if current { "USER" } else { "J.OWNER" };+ let mut conditions = Vec::new();+ match request.kind {+ NativeJobReferenceKind::WindowGroup => conditions.push("J.GROUP_TYPE = 'WINDOW'".into()),+ NativeJobReferenceKind::DestinationGroup => conditions.push("J.GROUP_TYPE IN ('DB_DEST', 'EXTERNAL_DEST')".into()),+ _ => {}+ }+ if let Some(schema) = &request.schema {+ conditions.push(format!("{owner} = {}", quote_string_literal(schema)));+ }+ if let Some(name) = &request.name {+ conditions.push(format!("J.{name_column} = {}", quote_string_literal(name)));+ }+ if !request.filter.is_empty() {+ conditions.push(format!("(UPPER(J.{name_column}) LIKE UPPER({search}) ESCAPE '!' OR UPPER({owner}) LIKE UPPER({search}) ESCAPE '!')"));+ }+ let condition = if conditions.is_empty() {+ String::new()+ } else {+ format!(" WHERE {}", conditions.join(" AND "))+ };+ let raw = if args && dialect == NativeJobCatalogDialect::Oracle {+ format!("J.*, {}, ", crate::native_job_arguments::anydata_projection(crate::native_job_arguments::AnydataColumn::ProgramDefault))+ } else if request.kind == NativeJobReferenceKind::Credential { String::new() } else if members { "J.MEMBER_NAME, ".into() } else { "J.*, ".into() };+ let order = format!("{owner}, J.{name_column}{}", if args { ", J.ARGUMENT_POSITION" } else if members { ", J.MEMBER_NAME" } else { "" });+ let (prefix, join) = if args && dialect == NativeJobCatalogDialect::Oracle {+ (crate::native_job_arguments::anydata_query_prefix(), crate::native_job_arguments::anydata_join(crate::native_job_arguments::AnydataColumn::ProgramDefault))+ } else { (String::new(), String::new()) };+ let coverage = if current {+ NativeJobCatalogCoverage::CurrentUser+ } else if accessible {+ NativeJobCatalogCoverage::Accessible+ } else {+ NativeJobCatalogCoverage::Database+ };+ NativeJobCatalogQuery {+ source,+ coverage,+ limit: request.limit,+ sql: format!("{prefix}SELECT * FROM (SELECT {raw}{owner} AS DBX_OWNER, J.{name_column} AS DBX_NAME, ROW_NUMBER() OVER (ORDER BY {order}) AS DBX_ROW_NUM FROM {source} J{join}{condition}) WHERE DBX_ROW_NUM > {} AND DBX_ROW_NUM <= {end} ORDER BY DBX_ROW_NUM", request.offset),+ }+ }).collect();+ Ok(queries)+}diff --git a/crates/dbx-sql-schema/src/schema_diff.rs b/crates/dbx-sql-schema/src/schema_diff.rsindex b8481d6176..03cc270358 100644--- a/crates/dbx-sql-schema/src/schema_diff.rs+++ b/crates/dbx-sql-schema/src/schema_diff.rs@@ -8908,6 +8908,7 @@ mod tests {}];let trigger = TriggerInfo {name: "trg_events_insert".into(),+ oracle_metadata: None,event: "INSERT".into(),timing: "AFTER".into(),level: None,@@ -11690,6 +11691,7 @@ mod tests {valid: None,comment: None,created_at: None,+ oracle_metadata: None,statement: None,}],ddl: None,diff --git a/crates/dbx-sql-schema/src/table_structure_sql.rs b/crates/dbx-sql-schema/src/table_structure_sql.rsindex be07d8285b..629da963b7 100644--- a/crates/dbx-sql-schema/src/table_structure_sql.rs+++ b/crates/dbx-sql-schema/src/table_structure_sql.rs@@ -32,7 +32,8 @@ mod tests;pub use column_alter::build_single_column_alter_sql;pub use create_options::*;pub use create_table::{- build_create_table_sql, build_create_table_sql_for_version, build_create_table_sql_with_dialect_options,+ build_create_table_sql, build_create_table_sql_for_version, build_create_table_sql_plan_with_dialect_options,+ build_create_table_sql_with_dialect_options,};pub use mysql_table_charset::{build_mysql_table_charset_change_sql, MysqlTableCharsetChange};pub use owner::build_table_owner_change_sql;@@ -53,7 +54,7 @@ use comments::build_table_comment_sql;use foreign_keys::build_foreign_key_sql;use indexes::build_index_sql;use mysql_engine::{build_mysql_engine_change_sql, validate_mysql_engine};-use triggers::build_trigger_sql;+use triggers::{build_trigger_sql, build_trigger_sql_with_operations};use validation::validate_concurrent_index_scope;pub use validation::validate_draft;@@ -62,24 +63,31 @@ pub fn build_table_structure_change_sql(options: TableStructureSqlOptions) -> Ta}pub fn build_table_structure_change_sql_with_context(- mut options: TableStructureSqlOptions,+ options: TableStructureSqlOptions,starrocks: Option<StarRocksAlterOptions>,) -> TableStructureSqlResult {+ build_table_structure_change_sql_plan(options, starrocks).sql+}++pub fn build_table_structure_change_sql_plan(+ mut options: TableStructureSqlOptions,+ starrocks: Option<StarRocksAlterOptions>,+) -> TableStructureSqlPlan {if options.oracle_constraint_changes.is_some() {- return oracle_constraints::build_changes(options);+ return oracle_constraints::build_changes(options).into();}if options.oracle_foreign_key_changes.is_some() {- return oracle_foreign_keys::build_changes(options);+ return oracle_foreign_keys::build_changes(options).into();}if options.primary_key_change.is_some() {- return existing_primary_key::build_existing_primary_key_change(options);+ return existing_primary_key::build_existing_primary_key_change(options).into();}if alter_dialect::is_starrocks(&options) {- return alter_dialect::build(&options, starrocks);+ return alter_dialect::build(&options, starrocks).into();}let mysql_engine_errors = validate_mysql_engine(&options);if !mysql_engine_errors.is_empty() {- return TableStructureSqlResult { statements: Vec::new(), warnings: mysql_engine_errors };+ return TableStructureSqlResult { statements: Vec::new(), warnings: mysql_engine_errors }.into();}// GaussDB M-mode uses MySQL-compatible SQL dialect with backtick quoting.// Map to StructureDialect::Mysql so DDL is generated correctly.@@ -89,23 +97,40 @@ pub fn build_table_structure_change_sql_with_context(strip_inherited_mysql_column_charsets(&mut options);let primary_key_errors = validate_primary_key_change_scope(&options);if !primary_key_errors.is_empty() {- return TableStructureSqlResult { statements: Vec::new(), warnings: primary_key_errors };+ return TableStructureSqlResult { statements: Vec::new(), warnings: primary_key_errors }.into();}// Fail closed: an unsupported concurrent-index request (existing index, or// partitioned parent table) must never degrade into blocking index DDL// behind the caller's back, so the whole plan is refused up front.let concurrent_errors = validate_concurrent_index_scope(&options);if !concurrent_errors.is_empty() {- return TableStructureSqlResult { statements: Vec::new(), warnings: concurrent_errors };+ return TableStructureSqlResult { statements: Vec::new(), warnings: concurrent_errors }.into();}let mut warnings = validate_draft(&options);let mut statements = build_column_sql(&options, &mut warnings);statements.extend(build_index_sql(&options, &mut warnings));statements.extend(build_foreign_key_sql(&options, &mut warnings));- statements.extend(build_trigger_sql(&options, &mut warnings));+ let mut trigger_operations = Vec::new();+ let oracle_trigger_contract = options.triggers.iter().any(|trigger| trigger.oracle_exact.is_some()).then_some(1);+ let trigger_sql = if oracle_trigger_contract.is_some() {+ build_trigger_sql_with_operations(+ &options,+ &mut warnings,+ false,+ statements.len(),+ Some(&mut trigger_operations),+ )+ } else {+ build_trigger_sql(&options, &mut warnings)+ };+ statements.extend(trigger_sql);statements.extend(build_table_comment_sql(&options, &mut warnings));statements.extend(build_mysql_engine_change_sql(&options));- TableStructureSqlResult { statements, warnings }+ TableStructureSqlPlan {+ sql: TableStructureSqlResult { statements, warnings },+ trigger_operations,+ oracle_trigger_contract,+ }}/// Whether this engine's structure editor can generate `COMMENT ON`/inlinediff --git a/crates/dbx-sql-schema/src/table_structure_sql/create_table.rs b/crates/dbx-sql-schema/src/table_structure_sql/create_table.rsindex ada6434e34..23407f2974 100644--- a/crates/dbx-sql-schema/src/table_structure_sql/create_table.rs+++ b/crates/dbx-sql-schema/src/table_structure_sql/create_table.rs@@ -11,8 +11,8 @@ use super::foreign_keys::build_foreign_key_sql_for_new_table;use super::indexes::{build_create_index_statements, mysql_inline_index_definition, normalized_index_type};use super::mysql_engine::{append_mysql_table_option, validate_mysql_engine};use super::transwarp;-use super::triggers::build_trigger_sql_for_new_table;-use super::types::{TableStructureSqlOptions, TableStructureSqlResult};+use super::triggers::{build_trigger_sql_for_new_table, build_trigger_sql_with_operations};+use super::types::{TableStructureSqlOptions, TableStructureSqlPlan, TableStructureSqlResult};use super::util::{clean, format_default_for_sql, normalize_default, qualified_new_table, quote_ident, quote_new_ident, quote_string,};@@ -45,6 +45,14 @@ pub fn build_create_table_sql_with_dialect_options(server_version: Option<&str>,dialect_options: CreateTableDialectOptions,) -> TableStructureSqlResult {+ build_create_table_sql_plan_with_dialect_options(options, server_version, dialect_options).sql+}++pub fn build_create_table_sql_plan_with_dialect_options(+ options: TableStructureSqlOptions,+ server_version: Option<&str>,+ dialect_options: CreateTableDialectOptions,+) -> TableStructureSqlPlan {build_create_table_sql_impl(options, None, server_version, dialect_options)}@@ -58,7 +66,7 @@ pub(super) fn build_create_table_sql_with_partition_clause(options: TableStructureSqlOptions,partition_clause: Option<String>,) -> TableStructureSqlResult {- build_create_table_sql_impl(options, partition_clause, None, CreateTableDialectOptions::default())+ build_create_table_sql_impl(options, partition_clause, None, CreateTableDialectOptions::default()).sql}fn build_create_table_sql_impl(@@ -66,7 +74,7 @@ fn build_create_table_sql_impl(partition_clause: Option<String>,server_version: Option<&str>,dialect_options: CreateTableDialectOptions,-) -> TableStructureSqlResult {+) -> TableStructureSqlPlan {let create_dialect = create_table_dialect(&options, server_version, dialect_options);let capabilities;let dialect;@@ -84,7 +92,9 @@ fn build_create_table_sql_impl(strip_inherited_mysql_column_charsets(&mut options);let ordered_foreign_keys = match super::oracle_foreign_keys::build_new_table_keys(&options) {Ok(statements) => statements,- Err(message) => return TableStructureSqlResult { statements: Vec::new(), warnings: vec![message.into()] },+ Err(message) => {+ return TableStructureSqlResult { statements: Vec::new(), warnings: vec![message.into()] }.into()+ }};let mut warnings = Vec::new();warnings.extend(validate_mysql_engine(&options));@@ -179,7 +189,7 @@ fn build_create_table_sql_impl(transwarp::validate_create_options(&options, &active_columns, &mut warnings);create_dialect.validate(&options, &active_columns, &mut warnings);if !warnings.is_empty() {- return TableStructureSqlResult { statements: Vec::new(), warnings };+ return TableStructureSqlResult { statements: Vec::new(), warnings }.into();}let table = qualified_new_table(options.database_type, dialect, options.schema.as_deref(), &options.table_name);if dialect == StructureDialect::Dameng {@@ -192,7 +202,7 @@ fn build_create_table_sql_impl(}}if !warnings.is_empty() {- return TableStructureSqlResult { statements: Vec::new(), warnings };+ return TableStructureSqlResult { statements: Vec::new(), warnings }.into();}}if dialect == StructureDialect::Sqlite {@@ -213,7 +223,7 @@ fn build_create_table_sql_impl(}}if !warnings.is_empty() {- return TableStructureSqlResult { statements: Vec::new(), warnings };+ return TableStructureSqlResult { statements: Vec::new(), warnings }.into();}}let mut statements = Vec::new();@@ -466,7 +476,24 @@ fn build_create_table_sql_impl(} else {statements.extend(build_foreign_key_sql_for_new_table(&options, &mut warnings));}- statements.extend(build_trigger_sql_for_new_table(&options, &mut warnings));+ let mut trigger_operations = Vec::new();+ let oracle_trigger_contract = options.triggers.iter().any(|trigger| trigger.oracle_exact.is_some()).then_some(1);+ let trigger_sql = if oracle_trigger_contract.is_some() {+ build_trigger_sql_with_operations(+ &options,+ &mut warnings,+ true,+ statements.len(),+ Some(&mut trigger_operations),+ )+ } else {+ build_trigger_sql_for_new_table(&options, &mut warnings)+ };+ statements.extend(trigger_sql);- TableStructureSqlResult { statements, warnings }+ TableStructureSqlPlan {+ sql: TableStructureSqlResult { statements, warnings },+ trigger_operations,+ oracle_trigger_contract,+ }}diff --git a/crates/dbx-sql-schema/src/table_structure_sql/tests.rs b/crates/dbx-sql-schema/src/table_structure_sql/tests.rsindex afc0cdb885..f1e5a8bc34 100644--- a/crates/dbx-sql-schema/src/table_structure_sql/tests.rs+++ b/crates/dbx-sql-schema/src/table_structure_sql/tests.rs@@ -693,6 +693,7 @@ fn trigger(name: &str, timing: &str, event: &str, statement: &str) -> EditableStEditableStructureTrigger {id: name.to_string(),name: name.to_string(),+ oracle_exact: None,timing: timing.to_string(),event: event.to_string(),statement: statement.to_string(),diff --git a/crates/dbx-sql-schema/src/table_structure_sql/triggers.rs b/crates/dbx-sql-schema/src/table_structure_sql/triggers.rsindex 4d2ce86b8b..d37addce82 100644--- a/crates/dbx-sql-schema/src/table_structure_sql/triggers.rs+++ b/crates/dbx-sql-schema/src/table_structure_sql/triggers.rs@@ -1,22 +1,28 @@use super::dialect::{database_label, StructureDialect};-use super::types::{EditableStructureTrigger, TableStructureSqlOptions, TriggerInfo};-use super::util::{clean, qualified_new_table, qualified_table, quote_ident, quote_new_ident};+use super::types::{EditableStructureTrigger, OracleTriggerStructureOperation, TableStructureSqlOptions, TriggerInfo};+use super::util::{clean, created_identifier_name, qualified_new_table, qualified_table, quote_ident, quote_new_ident};+use crate::models::connection::DatabaseType;+use dbx_sql_core::object_source_sql::{+ prepare_oracle_trigger_sql, OracleTriggerSqlBinding, OracleTriggerSqlInput, OracleTriggerSqlPurpose,+};pub(super) fn build_trigger_sql(options: &TableStructureSqlOptions, warnings: &mut Vec<String>) -> Vec<String> {- build_trigger_sql_with_mode(options, warnings, false)+ build_trigger_sql_with_operations(options, warnings, false, 0, None)}pub(super) fn build_trigger_sql_for_new_table(options: &TableStructureSqlOptions,warnings: &mut Vec<String>,) -> Vec<String> {- build_trigger_sql_with_mode(options, warnings, true)+ build_trigger_sql_with_operations(options, warnings, true, 0, None)}-fn build_trigger_sql_with_mode(+pub(super) fn build_trigger_sql_with_operations(options: &TableStructureSqlOptions,warnings: &mut Vec<String>,for_new_table: bool,+ statement_offset: usize,+ mut operations: Option<&mut Vec<OracleTriggerStructureOperation>>,) -> Vec<String> {if options.triggers.is_empty() {return Vec::new();@@ -42,6 +48,22 @@ fn build_trigger_sql_with_mode(let mut statements = Vec::new();for trigger in &options.triggers {+ if trigger.oracle_exact.is_some() {+ match build_exact_trigger_operations(options, dialect, &table, trigger, for_new_table) {+ Ok(groups) => {+ for (mut operation, sql) in groups {+ operation.statement_index = statement_offset + statements.len();+ operation.statement_count = sql.len();+ if let Some(operations) = operations.as_deref_mut() {+ operations.push(operation);+ }+ statements.extend(sql);+ }+ }+ Err(error) => warnings.push(error),+ }+ continue;+ }if trigger.marked_for_drop {if let Some(original) = &trigger.original {statements.push(drop_trigger_sql(dialect, options.schema.as_deref(), &original.name));@@ -133,6 +155,142 @@ fn build_trigger_sql_with_mode(statements}+fn build_exact_trigger_operations(+ options: &TableStructureSqlOptions,+ dialect: StructureDialect,+ table: &str,+ trigger: &EditableStructureTrigger,+ for_new_table: bool,+) -> Result<Vec<(OracleTriggerStructureOperation, Vec<String>)>, String> {+ let context = trigger.oracle_exact.as_ref().unwrap();+ let database_type = options.database_type.ok_or("Select the trigger engine")?;+ if !matches!(database_type, DatabaseType::Oracle | DatabaseType::OceanbaseOracle | DatabaseType::Dameng)+ || context.owner.is_empty()+ || !matches!(context.parent_type.as_str(), "TABLE" | "VIEW")+ {+ return Err("Verify the exact trigger owner and parent type before generating structured SQL".into());+ }+ let operation = |action: &str, name: &str, enabled: Option<bool>| OracleTriggerStructureOperation {+ draft_id: trigger.id.clone(),+ action: action.into(),+ owner: context.owner.clone(),+ name: name.into(),+ statement_index: 0,+ statement_count: 0,+ enabled,+ };+ let original = trigger.original.as_ref();+ if trigger.marked_for_drop {+ return Ok(original+ .map(|original| {+ vec![(+ operation("delete", &original.name, None),+ vec![drop_trigger_sql(dialect, Some(&context.owner), &original.name)],+ )]+ })+ .unwrap_or_default());+ }+ let body_changed = original.is_none_or(|original| {+ trigger.name != original.name+ || normalize_keyword(&trigger.timing) != normalize_keyword(&original.timing)+ || normalize_keyword(&trigger.event) != normalize_keyword(&original.event)+ || normalize_statement(&trigger.statement)+ != normalize_statement(original.statement.as_deref().unwrap_or(""))+ });+ if !body_changed {+ if let (Some(original), Some(enabled)) = (original, trigger.enabled) {+ if original.enabled != Some(enabled) {+ let state = if enabled { "ENABLE" } else { "DISABLE" };+ return Ok(vec![(+ operation(if enabled { "enable" } else { "disable" }, &original.name, Some(enabled)),+ vec![format!(+ "ALTER TRIGGER {} {state};",+ qualified_trigger_object_name(dialect, Some(&context.owner), &original.name)+ )],+ )]);+ }+ }+ return Ok(Vec::new());+ }+ if original+ .is_some_and(|original| !is_structured_oracle_trigger_source(original) || has_trigger_condition(original))+ {+ return Err(format!(+ "Editing existing trigger \"{}\" requires its complete source definition.",+ original.unwrap().name+ ));+ }+ let requested_name = if let Some(original) = original.filter(|original| original.name == trigger.name) {+ original.name.clone()+ } else {+ clean(&trigger.name)+ };+ if requested_name.is_empty() {+ return Err("Trigger name is required".into());+ }+ let name = if for_new_table {+ created_identifier_name(options.database_type, dialect, &requested_name)+ } else {+ requested_name+ };+ let parent_owner =+ options.schema.as_ref().filter(|owner| !owner.is_empty()).ok_or("Select the exact parent owner")?;+ let parent_name = if for_new_table {+ created_identifier_name(options.database_type, dialect, &options.table_name)+ } else {+ options.table_name.clone()+ };+ let mut warnings = Vec::new();+ let source = create_oracle_trigger_sql(+ options.database_type,+ dialect,+ Some(&context.owner),+ table,+ &name,+ &normalize_keyword(&trigger.timing),+ &clean(&trigger.event),+ &clean(&trigger.statement),+ &mut warnings,+ for_new_table,+ )+ .ok_or_else(|| warnings.join("\n"))?;+ let renamed = original.is_some_and(|original| original.name != name);+ let replacing = original.is_some() && !renamed;+ let enabled = trigger.enabled.or_else(|| original.and_then(|original| original.enabled));+ let prepared = prepare_oracle_trigger_sql(OracleTriggerSqlInput {+ database_type,+ owner: context.owner.clone(),+ name: name.clone(),+ source,+ purpose: if replacing { OracleTriggerSqlPurpose::Replace } else { OracleTriggerSqlPurpose::Create },+ binding: Some(OracleTriggerSqlBinding {+ scope: context.parent_type.clone(),+ owner: Some(parent_owner.clone()),+ name: Some(parent_name),+ pluggable: false,+ }),+ enabled,+ allow_export_appendix: false,+ })?;+ let mut groups = Vec::new();+ if renamed {+ let original_name = &original.unwrap().name;+ groups.push((+ operation("delete", original_name, None),+ vec![drop_trigger_sql(dialect, Some(&context.owner), original_name)],+ ));+ }+ let mut statements = vec![prepared.definition];+ if prepared.requires_state_restore {+ statements.push(format!(+ "ALTER TRIGGER {} DISABLE;",+ qualified_trigger_object_name(dialect, Some(&context.owner), &name)+ ));+ }+ groups.push((operation(if replacing { "replace" } else { "create" }, &name, enabled.or(Some(true))), statements));+ Ok(groups)+}+fn qualified_trigger_object_name(dialect: StructureDialect, schema: Option<&str>, name: &str) -> String {if schema.is_some_and(|schema| !schema.trim().is_empty()) {format!("{}.{}", quote_ident(dialect, schema.unwrap()), quote_ident(dialect, name))diff --git a/crates/dbx-sql-schema/src/table_structure_sql/types.rs b/crates/dbx-sql-schema/src/table_structure_sql/types.rsindex 2fadd335ab..61093a2c03 100644--- a/crates/dbx-sql-schema/src/table_structure_sql/types.rs+++ b/crates/dbx-sql-schema/src/table_structure_sql/types.rs@@ -224,12 +224,35 @@ pub struct EditableStructureTrigger {pub statement: String,#[serde(default, skip_serializing_if = "Option::is_none")]pub enabled: Option<bool>,+ /// Explicit exact workflow; absence preserves the legacy structured SQL contract.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub oracle_exact: Option<OracleStructureTriggerContext>,#[serde(default, skip_serializing_if = "Option::is_none")]pub original: Option<TriggerInfo>,#[serde(default)]pub marked_for_drop: bool,}+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct OracleStructureTriggerContext {+ pub owner: String,+ pub parent_type: String,+}++#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct OracleTriggerStructureOperation {+ pub draft_id: String,+ pub action: String,+ pub owner: String,+ pub name: String,+ pub statement_index: usize,+ pub statement_count: usize,+ #[serde(skip_serializing_if = "Option::is_none")]+ pub enabled: Option<bool>,+}+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]pub struct TriggerInfo {pub name: String,@@ -544,6 +567,23 @@ pub struct TableStructureSqlResult {pub warnings: Vec<String>,}+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct TableStructureSqlPlan {+ #[serde(flatten)]+ pub sql: TableStructureSqlResult,+ #[serde(default, skip_serializing_if = "Vec::is_empty")]+ pub trigger_operations: Vec<OracleTriggerStructureOperation>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub oracle_trigger_contract: Option<u8>,+}++impl From<TableStructureSqlResult> for TableStructureSqlPlan {+ fn from(sql: TableStructureSqlResult) -> Self {+ Self { sql, trigger_operations: Vec::new(), oracle_trigger_contract: None }+ }+}+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]#[serde(rename_all = "camelCase")]pub struct TableOwnerChangeSqlOptions {diff --git a/crates/dbx-sql-schema/src/table_structure_sql/util.rs b/crates/dbx-sql-schema/src/table_structure_sql/util.rsindex bf622651f7..86b6212b46 100644--- a/crates/dbx-sql-schema/src/table_structure_sql/util.rs+++ b/crates/dbx-sql-schema/src/table_structure_sql/util.rs@@ -84,6 +84,23 @@ pub(super) fn quote_new_ident(database_type: Option<DatabaseType>, dialect: Stru}}+/// The stored name corresponding to the same creation rule as `quote_new_ident`.+pub(super) fn created_identifier_name(+ database_type: Option<DatabaseType>,+ dialect: StructureDialect,+ name: &str,+) -> String {+ if database_type == Some(DatabaseType::Oracle)+ && dialect == StructureDialect::Oracle+ && is_simple_oracle_identifier(name)+ && !is_oracle_reserved_identifier(name)+ {+ name.to_ascii_uppercase()+ } else {+ name.to_owned()+ }+}+/// Reference spelling that resolves to an object created through [`quote_new_ident`]'s Oracle path.////// Plain Oracle identifiers are created unquoted and are therefore stored uppercase-folded; adiff --git a/crates/dbx-sql-schema/tests/native_job_changes.rs b/crates/dbx-sql-schema/tests/native_job_changes.rsnew file mode 100644index 0000000000..0d7afe6aa7--- /dev/null+++ b/crates/dbx-sql-schema/tests/native_job_changes.rs@@ -0,0 +1,494 @@+use dbx_sql_schema::native_job_changes::{+ native_job_legacy_create_preview, native_job_mutation_plan, NativeJobStepEffect,+};+use dbx_types::native_jobs::*;+use serde_json::json;++fn details() -> NativeJobDetails {+ serde_json::from_value(json!({+ "snapshot": { "ref": {"kind":"scheduler", "owner":"Owner", "name":"Job", "scope":{"connectionId":"c","database":"","contextId":"ctx"}}, "revision":"baseline",+ "definition":{"status":"available","value":{"OWNER":"Owner","JOB_NAME":"Job","JOB_ACTION":"kept","COMMENTS":"old","AUTO_DROP":"FALSE","ENABLED":"FALSE"}},+ "arguments":{"status":"available","value":[{"position":1,"dataType":"VARCHAR2","value":{"kind":"value","value":"old"},"editable":true},{"position":2,"dataType":"OBJECT","value":{"kind":"opaque","value":{"unparsed":true}},"editable":false}]} },+ "nativeIdentity":{"status":"available","value":{"DBX_JOB_ID":"9007199254740993","DBX_CREATED_AT":"creation"}},"consistency":{"status":"available","value":null},+ "parameterMetadata":{"status":"empty"},"steps":{"status":"empty"},"schedules":{"status":"empty"},"running":{"status":"unknown","reason":"not visible"},"history":{"status":"empty"},"sources":{}+ })).unwrap()+}++fn request(details: &NativeJobDetails, change: NativeJobChange) -> NativeJobMutation {+ NativeJobMutation { target: details.snapshot.job_ref.clone(), baseline: "baseline".into(), change }+}++#[test]+fn legacy_creation_preview_keeps_initial_state_before_commit_and_does_not_guess_an_id() {+ let mut definition = NativeJobLegacyCreate {+ what: "my_proc('private');".into(),+ next_date: "2026-10-21 10:20:30".into(),+ interval: "NULL".into(),+ enabled: false,+ instance: 0,+ schema: "Ow\"ner".into(),+ zone: None,+ };+ let steps = native_job_legacy_create_preview(NativeJobEngine::Oracle, &definition).unwrap();+ assert_eq!(steps.len(), 3);+ assert!(steps[0].sql.starts_with("ALTER SESSION SET CURRENT_SCHEMA = \"Ow\"\"ner\";"));+ assert!(steps[0].sql.contains("what => 'my_proc(''private'');'"));+ assert!(steps[0].sql.contains("BROKEN(TO_NUMBER(:dbx_job_id), TRUE, TO_DATE('2026-10-21 10:20:30'"));+ assert!(!steps[0].sql.contains("DBMS_JOB.NEXT_DATE"));+ assert!(!steps[0].sql.contains("COMMIT"));+ assert_eq!(steps[1].sql, "COMMIT;");+ assert!(steps[2].sql.contains("JOB = TO_NUMBER(:dbx_job_id)"));+ definition.instance = -1;+ assert!(native_job_legacy_create_preview(NativeJobEngine::Oracle, &definition).is_err());+ definition.instance = 0;+ definition.zone = Some("zone1".into());+ assert!(native_job_legacy_create_preview(NativeJobEngine::Oracle, &definition).is_err());+}++#[test]+fn ob_legacy_creation_uses_nullable_zone_and_keeps_the_initial_state_before_commit() {+ let mut definition = NativeJobLegacyCreate {+ what: "my_proc();".into(),+ next_date: "2026-10-21 10:20:30".into(),+ interval: "NULL".into(),+ enabled: false,+ instance: 0,+ schema: "Owner".into(),+ zone: Some("zone's name".into()),+ };+ let steps = native_job_legacy_create_preview(NativeJobEngine::OceanbaseOracle, &definition).unwrap();+ assert_eq!(steps.len(), 3);+ assert!(steps[0].sql.contains("zone => 'zone''s name', force => FALSE"));+ assert!(!steps[0].sql.contains("instance =>"));+ assert!(!steps[0].sql.contains("COMMIT"));+ assert!(steps[0].sql.contains("BROKEN(TO_NUMBER(:dbx_job_id), TRUE"));+ let broken = steps[0].sql.find("DBMS_JOB.BROKEN").unwrap();+ let restore_date =+ steps[0].sql.find("DBMS_JOB.NEXT_DATE(TO_NUMBER(:dbx_job_id), TO_DATE('2026-10-21 10:20:30'").unwrap();+ let read = steps[0].sql.find("SELECT TO_CHAR(JOB)").unwrap();+ assert!(broken < restore_date && restore_date < read);+ assert!(steps[0].sql.contains("BROKEN, INSTANCE, LOG_USER, PRIV_USER, SCHEMA_USER"));+ definition.zone = None;+ assert!(native_job_legacy_create_preview(NativeJobEngine::OceanbaseOracle, &definition).unwrap()[0]+ .sql+ .contains("zone => NULL"));+ definition.instance = 2;+ assert!(native_job_legacy_create_preview(NativeJobEngine::OceanbaseOracle, &definition).is_err());+}++#[test]+fn ob_legacy_zone_patch_preserves_raw_instance_projection_and_accepts_explicit_clear() {+ let mut data = details();+ data.snapshot.job_ref = NativeJobRef::Legacy { scope: data.snapshot.job_ref.scope().clone(), job_id: "41".into() };+ for change in [NativeJobFieldChange::Set { value: json!("zone1") }, NativeJobFieldChange::Clear] {+ let update = NativeJobChange::Update {+ final_enabled: None,+ argument_target: None,+ attributes: vec![NativeJobAttributeChange { name: "ZONE".into(), change: change.clone() }],+ arguments: vec![],+ };+ let plan = native_job_mutation_plan(NativeJobEngine::OceanbaseOracle, &request(&data, update), &data).unwrap();+ assert_eq!(plan.steps.len(), 1);+ let value = if change == NativeJobFieldChange::Clear { "NULL" } else { "'zone1'" };+ assert!(plan.steps[0].sql.contains(&format!("DBMS_JOB.ZONE(job => 41, zone => {value}, force => FALSE)")));+ assert!(!plan.steps[0].sql.contains("DBMS_JOB.CHANGE"));+ assert!(+ matches!(&plan.steps[0].effect, NativeJobStepEffect::Fields(fields) if fields.len()==1 && fields[0].name=="INSTANCE" && fields[0].change==change)+ );+ }+}++#[test]+fn legacy_broken_uses_the_successful_definition_source_instead_of_imposing_user_visibility() {+ let mut data = details();+ data.snapshot.job_ref = NativeJobRef::Legacy { scope: data.snapshot.job_ref.scope().clone(), job_id: "41".into() };+ data.sources.insert(+ "definition".into(),+ NativeJobCatalogSource {+ source: Some("SYS.DBA_JOBS".into()),+ coverage: Some(NativeJobCatalogCoverage::Database),+ },+ );+ for engine in [NativeJobEngine::Oracle, NativeJobEngine::OceanbaseOracle] {+ for change in [NativeJobChange::Enable, NativeJobChange::Disable] {+ let plan = native_job_mutation_plan(engine, &request(&data, change), &data).unwrap();+ let sql = &plan.steps[0].sql;+ assert!(sql.contains("FROM SYS.DBA_JOBS WHERE JOB = 41"));+ assert!(!sql.contains("SYS.USER_JOBS"));+ if engine == NativeJobEngine::OceanbaseOracle {+ assert!(sql.contains("next_at); SYS.DBMS_JOB.NEXT_DATE(41, next_at); COMMIT;"));+ } else {+ assert!(!sql.contains("DBMS_JOB.NEXT_DATE"));+ }+ }+ }+}++#[test]+fn scheduler_run_boolean_signatures_and_exact_single_targets_are_not_interchanged() {+ let mut data = details();+ if let NativeJobRef::Scheduler { owner, name, .. } = &mut data.snapshot.job_ref {+ *owner = "O.\"wner".into();+ *name = "J,ob's".into();+ }+ let run = request(&data, NativeJobChange::Run);+ let oracle = native_job_mutation_plan(NativeJobEngine::Oracle, &run, &data).unwrap();+ assert!(oracle.steps[0].sql.contains("use_current_session => FALSE"));+ assert!(oracle.steps[0].sql.contains("'\"O.\"\"wner\".\"J,ob''s\"'"));+ let ob = native_job_mutation_plan(NativeJobEngine::OceanbaseOracle, &run, &data).unwrap();+ assert!(ob.steps[0].sql.contains("force => FALSE"));+ assert!(!ob.steps[0].sql.contains("use_current_session"));+ assert!(ob.steps[0].sql.contains("JOB = 9007199254740993"));+ assert!(ob.steps[0].sql.contains("JOB > 0"));+}++#[test]+fn oracle_attribute_batch_is_transactional_and_does_not_recreate_or_rewrite_untouched_fields() {+ let data = details();+ let change = NativeJobChange::Update {+ final_enabled: None,+ argument_target: None,+ attributes: vec![+ NativeJobAttributeChange {+ name: "COMMENTS".into(),+ change: NativeJobFieldChange::Set { value: json!("a'b") },+ },+ NativeJobAttributeChange {+ name: "AUTO_DROP".into(),+ change: NativeJobFieldChange::Set { value: json!(false) },+ },+ ],+ arguments: vec![],+ };+ let plan = native_job_mutation_plan(NativeJobEngine::Oracle, &request(&data, change), &data).unwrap();+ assert_eq!(plan.steps.len(), 1);+ assert!(plan.steps[0].sql.contains("SET_JOB_ATTRIBUTES"));+ assert!(plan.steps[0].sql.contains("'TRANSACTIONAL'"));+ assert!(plan.steps[0].sql.contains("'a''b'"));+ assert!(!plan.steps[0].sql.contains("DROP_JOB"));+ assert!(!plan.steps[0].sql.contains("job_action"));+}++#[test]+fn the_scalar_builder_never_silently_discards_an_explicit_final_enabled_intent() {+ let mut data = details();+ for enabled in [false, true] {+ let change = NativeJobChange::Update {+ final_enabled: Some(enabled),+ argument_target: None,+ attributes: vec![NativeJobAttributeChange {+ name: "COMMENTS".into(),+ change: NativeJobFieldChange::Set { value: json!("changed") },+ }],+ arguments: vec![],+ };+ assert!(matches!(+ native_job_mutation_plan(NativeJobEngine::Oracle, &request(&data, change), &data),+ Err("native_job_scheduler_transition_required")+ ));+ }+ data.snapshot.job_ref = NativeJobRef::Legacy { scope: data.snapshot.job_ref.scope().clone(), job_id: "41".into() };+ let change = NativeJobChange::Update {+ final_enabled: Some(false),+ argument_target: None,+ attributes: vec![],+ arguments: vec![],+ };+ assert!(matches!(+ native_job_mutation_plan(NativeJobEngine::Oracle, &request(&data, change), &data),+ Err("native_job_final_enabled_not_applicable")+ ));+}++#[test]+fn unsupported_read_only_and_duplicate_field_names_cannot_become_sql() {+ let data = details();+ for names in [vec!["JOB_NAME"], vec!["COMMENTS'); COMMIT; --"], vec!["COMMENTS", "comments"]] {+ let change = NativeJobChange::Update {+ final_enabled: None,+ argument_target: None,+ attributes: names+ .into_iter()+ .map(|name| NativeJobAttributeChange {+ name: name.into(),+ change: NativeJobFieldChange::Set { value: json!("new") },+ })+ .collect(),+ arguments: vec![],+ };+ assert!(native_job_mutation_plan(NativeJobEngine::Oracle, &request(&data, change), &data).is_err());+ }+}++#[test]+fn a_known_argument_edit_does_not_rewrite_its_opaque_neighbor_and_null_is_typed_anydata() {+ let data = details();+ for value in [NativeJobArgumentValue::Value { value: json!("new") }, NativeJobArgumentValue::Null] {+ let change = NativeJobChange::Update {+ final_enabled: None,+ argument_target: None,+ attributes: vec![],+ arguments: vec![NativeJobArgumentChange { position: 1, value }],+ };+ let plan = native_job_mutation_plan(NativeJobEngine::Oracle, &request(&data, change), &data).unwrap();+ assert_eq!(plan.steps.len(), 1);+ assert!(plan.steps[0].sql.contains("argument_position => 1"));+ assert!(!plan.steps[0].sql.contains("argument_position => 2"));+ assert!(!plan.steps[0].sql.contains("unparsed"));+ if plan.steps[0].sql.contains("NULL") {+ assert!(plan.steps[0].sql.contains("SET_JOB_ANYDATA_VALUE"));+ }+ }+ let opaque = NativeJobChange::Update {+ final_enabled: None,+ argument_target: None,+ attributes: vec![],+ arguments: vec![NativeJobArgumentChange { position: 2, value: NativeJobArgumentValue::Unset }],+ };+ assert!(native_job_mutation_plan(NativeJobEngine::Oracle, &request(&data, opaque), &data).is_err());+}++#[test]+fn legacy_enable_preserves_the_latest_next_date_and_removal_commits_in_the_same_native_call() {+ let mut data = details();+ data.snapshot.job_ref =+ NativeJobRef::Legacy { scope: data.snapshot.job_ref.scope().clone(), job_id: "9007199254740993".into() };+ let enable =+ native_job_mutation_plan(NativeJobEngine::Oracle, &request(&data, NativeJobChange::Enable), &data).unwrap();+ assert!(enable.steps[0].sql.contains("SELECT NEXT_DATE INTO next_at"));+ assert!(enable.steps[0].sql.contains("DBMS_JOB.BROKEN(9007199254740993, FALSE, next_at); COMMIT;"));+ assert!(!enable.steps[0].sql.contains("SYSDATE"));+ let drop = native_job_mutation_plan(+ NativeJobEngine::Oracle,+ &request(&data, NativeJobChange::Drop { force: false }),+ &data,+ )+ .unwrap();+ assert!(drop.steps[0].sql.contains("DBMS_JOB.REMOVE(9007199254740993); COMMIT;"));+ assert!(matches!(+ native_job_mutation_plan(+ NativeJobEngine::Oracle,+ &request(&data, NativeJobChange::Stop { force: false }),+ &data+ ),+ Err("native_job_dbms_job_has_no_stop")+ ));+}++#[test]+fn dm_native_control_keeps_large_ids_and_original_names_without_numeric_rounding() {+ let mut data = details();+ data.snapshot.job_ref = NativeJobRef::DamengNative {+ scope: data.snapshot.job_ref.scope().clone(),+ job_id: "9007199254740993".into(),+ name: "exact'job".into(),+ };+ data.sources.insert(+ "identity".into(),+ NativeJobCatalogSource {+ source: Some("SYSJOB.USER_JOBS_VIEW".into()),+ coverage: Some(NativeJobCatalogCoverage::CurrentUser),+ },+ );+ let run = native_job_mutation_plan(NativeJobEngine::Dameng, &request(&data, NativeJobChange::Run), &data).unwrap();+ assert!(run.steps[0].sql.contains("SP_DBMS_JOB_RUN_ASYNC(9007199254740993)"));+ let enable =+ native_job_mutation_plan(NativeJobEngine::Dameng, &request(&data, NativeJobChange::Enable), &data).unwrap();+ assert!(enable.steps[0].sql.contains("SP_ENABLE_JOB('exact''job', 1)"));+}++#[test]+fn ob_legacy_does_not_treat_a_zone_as_an_oracle_instance() {+ let mut data = details();+ data.snapshot.job_ref = NativeJobRef::Legacy { scope: data.snapshot.job_ref.scope().clone(), job_id: "41".into() };+ let change = NativeJobChange::Update {+ final_enabled: None,+ argument_target: None,+ attributes: vec![NativeJobAttributeChange {+ name: "INSTANCE".into(),+ change: NativeJobFieldChange::Set { value: json!(2) },+ }],+ arguments: vec![],+ };+ let change = request(&data, change);+ assert!(native_job_mutation_plan(NativeJobEngine::Oracle, &change, &data).unwrap().steps[0]+ .sql+ .contains("DBMS_JOB.INSTANCE(41, 2)"));+ assert!(matches!(+ native_job_mutation_plan(NativeJobEngine::OceanbaseOracle, &change, &data),+ Err("native_job_attribute_not_editable")+ ));+}++#[test]+fn logging_uses_a_native_constant_and_changed_timestamps_keep_their_explicit_offset() {+ let mut data = details();+ if let NativeJobMetadata::Available { value } = &mut data.snapshot.definition {+ value.insert("LOGGING_LEVEL".into(), json!("RUNS"));+ value.insert("END_DATE".into(), json!(null));+ }+ let change = NativeJobChange::Update {+ final_enabled: None,+ argument_target: None,+ attributes: vec![+ NativeJobAttributeChange {+ name: "LOGGING_LEVEL".into(),+ change: NativeJobFieldChange::Set { value: json!("FULL") },+ },+ NativeJobAttributeChange {+ name: "END_DATE".into(),+ change: NativeJobFieldChange::Set { value: json!("2030-05-01T12:13:14.123+08:00") },+ },+ ],+ arguments: vec![],+ };+ let sql = &native_job_mutation_plan(NativeJobEngine::Oracle, &request(&data, change), &data).unwrap().steps[0].sql;+ assert!(sql.contains("DBMS_SCHEDULER.LOGGING_FULL"));+ assert!(sql.contains("'2030-05-01 12:13:14.123 +08:00'"));+}++#[test]+fn dm_compatibility_only_attributes_are_not_offered_as_effective_edits() {+ let mut data = details();+ if let NativeJobMetadata::Available { value } = &mut data.snapshot.definition {+ value.insert("RESTARTABLE".into(), json!(false));+ }+ let change = NativeJobChange::Update {+ final_enabled: None,+ argument_target: None,+ attributes: vec![NativeJobAttributeChange {+ name: "RESTARTABLE".into(),+ change: NativeJobFieldChange::Set { value: json!(true) },+ }],+ arguments: vec![],+ };+ assert!(matches!(+ native_job_mutation_plan(NativeJobEngine::Dameng, &request(&data, change), &data),+ Err("native_job_attribute_not_editable")+ ));+ let change = NativeJobChange::Update {+ final_enabled: None,+ argument_target: None,+ attributes: vec![NativeJobAttributeChange {+ name: "AUTO_DROP".into(),+ change: NativeJobFieldChange::Set { value: json!(true) },+ }],+ arguments: vec![],+ };+ assert!(native_job_mutation_plan(NativeJobEngine::Dameng, &request(&data, change), &data).is_ok());+}++#[test]+fn ob_unimplemented_scheduler_attributes_cannot_become_mutation_steps() {+ let mut data = details();+ for name in [+ "COMMENTS",+ "AUTO_DROP",+ "JOB_ACTION",+ "JOB_TYPE",+ "NUMBER_OF_ARGUMENTS",+ "START_DATE",+ "END_DATE",+ "REPEAT_INTERVAL",+ "PROGRAM_NAME",+ "JOB_PRIORITY",+ "MAX_RUNS",+ ] {+ if let NativeJobMetadata::Available { value } = &mut data.snapshot.definition {+ value.insert(name.into(), json!(null));+ }+ let change = NativeJobChange::Update {+ final_enabled: None,+ argument_target: None,+ attributes: vec![NativeJobAttributeChange {+ name: name.into(),+ change: NativeJobFieldChange::Set { value: json!("changed") },+ }],+ arguments: vec![],+ };+ assert!(+ matches!(+ native_job_mutation_plan(NativeJobEngine::OceanbaseOracle, &request(&data, change), &data),+ Err("native_job_attribute_not_editable")+ ),+ "{name}"+ );+ }+}++#[test]+fn ob_max_run_duration_serializes_exact_whole_seconds_instead_of_an_oracle_interval() {+ let mut data = details();+ if let NativeJobMetadata::Available { value } = &mut data.snapshot.definition {+ value.insert("MAX_RUN_DURATION".into(), json!("+000 00:00:00"));+ }+ for (value, seconds) in [("+000 00:02:00", "120"), ("1 01:02:03.000", "90123")] {+ let change = NativeJobChange::Update {+ final_enabled: None,+ argument_target: None,+ attributes: vec![NativeJobAttributeChange {+ name: "MAX_RUN_DURATION".into(),+ change: NativeJobFieldChange::Set { value: json!(value) },+ }],+ arguments: vec![],+ };+ let plan = native_job_mutation_plan(NativeJobEngine::OceanbaseOracle, &request(&data, change), &data).unwrap();+ assert!(plan.steps[0].sql.contains(&format!("value => '{seconds}'")));+ assert!(!plan.steps[0].sql.contains("TO_DSINTERVAL"));+ }+ for value in [json!("0 00:00:00.5"), json!("-0 00:02:00"), json!(null)] {+ let change = NativeJobChange::Update {+ final_enabled: None,+ argument_target: None,+ attributes: vec![NativeJobAttributeChange {+ name: "MAX_RUN_DURATION".into(),+ change: NativeJobFieldChange::Set { value },+ }],+ arguments: vec![],+ };+ assert!(native_job_mutation_plan(NativeJobEngine::OceanbaseOracle, &request(&data, change), &data).is_err());+ }+}++#[test]+fn ob_scheduler_instance_id_is_a_zone_string_not_an_oracle_instance_number() {+ let mut data = details();+ if let NativeJobMetadata::Available { value } = &mut data.snapshot.definition {+ value.insert("INSTANCE_ID".into(), json!("RANDOM"));+ }+ let change = NativeJobChange::Update {+ final_enabled: None,+ argument_target: None,+ attributes: vec![NativeJobAttributeChange {+ name: "INSTANCE_ID".into(),+ change: NativeJobFieldChange::Set { value: json!("zone's name") },+ }],+ arguments: vec![],+ };+ let plan = native_job_mutation_plan(NativeJobEngine::OceanbaseOracle, &request(&data, change), &data).unwrap();+ assert!(plan.steps[0].sql.contains("value => 'zone''s name'"));+}++#[test]+fn dm_effective_comments_and_duration_are_not_treated_as_compatibility_only() {+ let mut data = details();+ if let NativeJobMetadata::Available { value } = &mut data.snapshot.definition {+ value.insert("MAX_RUN_DURATION".into(), json!("+000 00:00:00"));+ }+ let change = NativeJobChange::Update {+ final_enabled: None,+ argument_target: None,+ attributes: vec![+ NativeJobAttributeChange {+ name: "COMMENTS".into(),+ change: NativeJobFieldChange::Set { value: json!("new") },+ },+ NativeJobAttributeChange {+ name: "MAX_RUN_DURATION".into(),+ change: NativeJobFieldChange::Set { value: json!("0 00:02:00") },+ },+ ],+ arguments: vec![],+ };+ assert!(native_job_mutation_plan(NativeJobEngine::Dameng, &request(&data, change), &data).is_ok());+}diff --git a/crates/dbx-sql-schema/tests/native_job_dameng_configuration.rs b/crates/dbx-sql-schema/tests/native_job_dameng_configuration.rsnew file mode 100644index 0000000000..d3e0646dc7--- /dev/null+++ b/crates/dbx-sql-schema/tests/native_job_dameng_configuration.rs@@ -0,0 +1,455 @@+use dbx_sql_schema::native_job_changes::{+ native_job_dameng_civil_time, native_job_dameng_identity_queries, native_job_dameng_legacy_time,+ native_job_dameng_what_query, native_job_mutation_plan, NativeJobStepEffect,+};+use dbx_types::native_jobs::*;+use serde_json::json;++fn details(enabled: bool) -> NativeJobDetails {+ serde_json::from_value(json!({+ "snapshot":{"ref":{"kind":"dameng-native","scope":{"connectionId":"c","database":"","contextId":"ctx"},"jobId":"41","name":"Job_1"},"revision":"baseline",+ "definition":{"status":"available","value":{"ID":41,"DBX_JOB_ID":"41","NAME":"Job_1","USERNAME":"Owner","CREATETIME":"creation","ENABLE":enabled,"ENABLE_EMAIL":1,"EMAIL_OPERID":7,"EMAIL_TYPE":2,"ENABLE_NETSEND":0,"NETSEND_OPERID":-1,"NETSEND_TYPE":1,"DESCRIBE":"old","VALID":"Y","EP_SEQNO":0,"RAFT_NAME":null}},+ "arguments":{"status":"available","value":[]}},+ "nativeIdentity":{"status":"available","value":{"DBX_JOB_ID":"41","DBX_CREATED_AT":"creation"}},+ "consistency":{"status":"available","value":null},"parameterMetadata":{"status":"unsupported","reason":"not_applicable"},+ "steps":{"status":"denied","reason":"not_readable"},"schedules":{"status":"denied","reason":"not_readable"},+ "running":{"status":"unknown","reason":"not_readable"},"history":{"status":"empty"},+ "sources":{"definition":{"source":"SYSJOB.USER_JOBS_VIEW","coverage":"current_user"}}+ })).unwrap()+}++fn mutation(details: &NativeJobDetails, attributes: serde_json::Value) -> NativeJobMutation {+ NativeJobMutation {+ target: details.snapshot.job_ref.clone(),+ baseline: "baseline".into(),+ change: NativeJobChange::Update {+ final_enabled: None,+ argument_target: None,+ attributes: serde_json::from_value(attributes).unwrap(),+ arguments: Vec::new(),+ },+ }+}++fn legacy_details(enabled: bool) -> NativeJobDetails {+ let mut details = details(enabled);+ details.snapshot.job_ref =+ NativeJobRef::Legacy { scope: details.snapshot.job_ref.scope().clone(), job_id: "41".into() };+ details.legacy_definition = Some(NativeJobMetadata::Available {+ value: serde_json::from_value(+ json!({"DBX_JOB_ID":"41", "WHAT":"work();", "NEXT_DATE":"native date", "INTERVAL":"86400", "INSTANCE":1}),+ )+ .unwrap(),+ });+ details+}++#[test]+fn legacy_body_edit_freezes_the_original_definition_and_keeps_final_activation_last() {+ let mut before = legacy_details(true);+ before.steps = NativeJobMetadata::Empty;+ before.schedules = NativeJobMetadata::Empty;+ let plan = native_job_mutation_plan(+ NativeJobEngine::Dameng,+ &mutation(&before, json!([{"name":"WHAT","change":{"kind":"set","value":"BEGIN work('O''ne'); END; "}}])),+ &before,+ )+ .unwrap();+ assert!(plan.required_partitions.iter().any(|part| part == "legacyDefinition"));+ let body = plan.steps.iter().position(|step| step.sql.contains("BEGIN work(''O''''ne''); END; ")).unwrap();+ assert!(plan.steps[body].sql.contains("ID = 41 AND NAME = 'Job_1' AND CREATETIME = 'creation'"));+ assert!(plan.steps[body].sql.contains("COMMIT;"));+ assert!(matches!(plan.steps.last().unwrap().effect, NativeJobStepEffect::Enabled(true)));+ assert!(body < plan.steps.len() - 1);+}++#[test]+fn legacy_body_mixed_edits_keep_configuration_and_activation_order_and_reject_read_semantics() {+ let before = legacy_details(true);+ let plan = native_job_mutation_plan(+ NativeJobEngine::Dameng,+ &mutation(+ &before,+ json!([+ {"name":"NAME","change":{"kind":"set","value":"Renamed_Job"}},+ {"name":"INTERVAL","change":{"kind":"set","value":"60"}},+ {"name":"WHAT","change":{"kind":"set","value":"新正文('\\'); "}},+ {"name":"DESCRIBE","change":{"kind":"set","value":"new"}}+ ]),+ ),+ &before,+ )+ .unwrap();+ assert_eq!(+ plan.steps.iter().map(|step| step.id.as_str()).collect::<Vec<_>>(),+ ["pause", "definition", "config_start", "config_commit", "legacy_what", "legacy_interval", "rename", "enable"]+ );+ assert!(+ matches!(&plan.steps[4].effect, NativeJobStepEffect::DamengLegacyWhat { expected } if expected == "新正文('\\'); ")+ );+ for value in [json!(""), json!("a\u{0000}b"), json!(null), json!(42)] {+ assert!(native_job_mutation_plan(+ NativeJobEngine::Dameng,+ &mutation(&before, json!([{"name":"WHAT","change":{"kind":"set","value":value}}])),+ &before+ )+ .is_err());+ }+ assert!(native_job_mutation_plan(+ NativeJobEngine::Dameng,+ &mutation(&before, json!([{"name":"WHAT","change":{"kind":"clear"}}])),+ &before+ )+ .is_err());+}++#[test]+fn legacy_next_date_uses_an_explicit_civil_datetime_and_binds_the_original_date() {+ let mut before = legacy_details(false);+ if let Some(NativeJobMetadata::Available { value }) = &mut before.legacy_definition {+ value.insert("NEXT_DATE".into(), json!("2032-01-02 03:04:05"));+ value.insert("NEXT_SEC".into(), json!("03:04:05"));+ }+ let plan = native_job_mutation_plan(+ NativeJobEngine::Dameng,+ &mutation(+ &before,+ json!([{"name":"NEXT_DATE","change":{"kind":"set","value":"2032-02-03T04:05:06.123456000"}}]),+ ),+ &before,+ )+ .unwrap();+ assert!(plan.compare_next_date);+ assert_eq!(plan.steps.iter().map(|step| step.id.as_str()).collect::<Vec<_>>(), ["pause", "legacy_next_date"]);+ assert!(plan.steps[1].sql.contains("CAST(TIMESTAMP '2032-02-03 04:05:06.123456' AS DATETIME(6))"));+ assert!(plan.steps[1].sql.contains("DBMS_JOB.NEXT_DATE(41,"));+ for input in ["2032-02-03T04:05:06Z", "2032-02-03 04:05:06.123456001", "SYSDATE+1", "02/03/2032 04:05:06"] {+ assert!(native_job_mutation_plan(+ NativeJobEngine::Dameng,+ &mutation(&before, json!([{"name":"NEXT_DATE","change":{"kind":"set","value":input}}])),+ &before+ )+ .is_err());+ }+}++#[test]+fn legacy_civil_time_keeps_microseconds_and_rejects_ambiguous_or_conflicting_catalog_values() {+ for (input, expected) in [+ ("2032-02-03 04:05:06", "2032-02-03 04:05:06.000000"),+ ("2032-02-03T04:05:06.1", "2032-02-03 04:05:06.100000"),+ ("2032-02-03 04:05:06.123456000", "2032-02-03 04:05:06.123456"),+ ] {+ assert_eq!(native_job_dameng_civil_time(input).unwrap(), expected);+ let row = serde_json::from_value(json!({"NEXT_DATE":input, "NEXT_SEC":"04:05:06"})).unwrap();+ assert_eq!(native_job_dameng_legacy_time(&row).unwrap(), expected);+ }+ for row in [+ json!({"NEXT_DATE":"2032-02-03 04:05:06", "NEXT_SEC":"04:05:07"}),+ json!({"NEXT_DATE":"2032-02-03 04:05:06", "NEXT_SEC":"14706"}),+ json!({"NEXT_DATE":"2032-02-03 04:05:06", "NEXT_SEC":"04:05:06.1"}),+ json!({"NEXT_DATE":"2032-02-03 04:05:06", "NEXT_SEC":"24:00:00"}),+ json!({"NEXT_DATE":"native date", "NEXT_SEC":"04:05:06"}),+ json!({"NEXT_DATE":null, "NEXT_SEC":"04:05:06"}),+ json!({"NEXT_DATE":"2032-02-03 04:05:06"}),+ ] {+ assert!(native_job_dameng_legacy_time(&serde_json::from_value(row).unwrap()).is_err());+ }+ let row = serde_json::from_value(json!({"NEXT_DATE":"2032-02-03", "NEXT_SEC":"04:05:06"})).unwrap();+ assert_eq!(native_job_dameng_legacy_time(&row).unwrap(), "2032-02-03 04:05:06.000000");+ let row = serde_json::from_value(json!({"NEXT_DATE":"2032-02-03", "NEXT_SEC":"23:59:59"})).unwrap();+ assert_eq!(native_job_dameng_legacy_time(&row).unwrap(), "2032-02-03 23:59:59.000000");+}++#[test]+fn legacy_body_capacity_is_checked_by_native_construction_without_client_truncation() {+ let before = legacy_details(false);+ for body in ["a".repeat(32767), "汉".repeat(32768), "begin work('\\'); end; ".into()] {+ let plan = native_job_mutation_plan(+ NativeJobEngine::Dameng,+ &mutation(&before, json!([{"name":"WHAT","change":{"kind":"set","value":body}}])),+ &before,+ )+ .unwrap();+ assert!(+ matches!(&plan.steps[1].effect, NativeJobStepEffect::DamengLegacyWhat { expected } if expected == &body)+ );+ let query = native_job_dameng_what_query(&body);+ assert!(query.sql.ends_with("AS VARCHAR2(32767)) AS DBX_WHAT FROM DUAL"));+ assert!(!query.sql.contains("SUBSTR("));+ }+}++#[test]+fn job_rename_is_committed_without_an_invented_configuration_or_activation_change() {+ for before in [details(true), details(false), legacy_details(true)] {+ let plan = native_job_mutation_plan(+ NativeJobEngine::Dameng,+ &mutation(&before, json!([{"name":"NAME","change":{"kind":"set","value":"Renamed_Job"}}])),+ &before,+ )+ .unwrap();+ assert_eq!(plan.steps.len(), 1);+ assert_eq!(plan.steps[0].id, "rename");+ assert!(plan.steps[0].sql.contains("SP_RENAME_JOB('Job_1', 'Renamed_Job'); COMMIT;"));+ assert!(!plan.steps[0].sql.contains("SP_ENABLE_JOB"));+ assert!(!plan.steps[0].sql.contains("SP_JOB_CONFIG_START"));+ assert!(+ matches!(&plan.steps[0].effect, NativeJobStepEffect::DamengRenamed { old_name, new_name } if old_name == "Job_1" && new_name == "Renamed_Job")+ );+ let queries = native_job_dameng_identity_queries(&before.snapshot.job_ref).unwrap();+ assert_eq!(queries.len(), 2);+ for query in queries {+ assert!(query.sql.ends_with("WHERE ID = 41"));+ assert!(query.sql.contains("CREATETIME AS DBX_CREATED_AT, NAME, USERNAME, SYS_FLAG"));+ assert!(!query.sql.contains("NAME ="));+ }+ }+}++#[test]+fn rename_follows_confirmed_configuration_and_previews_the_new_name_for_final_enable() {+ let before = details(true);+ let plan = native_job_mutation_plan(NativeJobEngine::Dameng, &mutation(&before, json!([{"name":"NAME","change":{"kind":"set","value":"Renamed_Job"}}, {"name":"DESCRIBE","change":{"kind":"set","value":"new"}}])), &before).unwrap();+ assert_eq!(+ plan.steps.iter().map(|step| step.id.as_str()).collect::<Vec<_>>(),+ ["pause", "definition", "config_start", "config_commit", "rename", "enable"]+ );+ assert!(plan.steps.last().unwrap().sql.contains("NAME = 'Renamed_Job'"));+ assert!(plan.steps.last().unwrap().sql.contains("SP_ENABLE_JOB('Renamed_Job', 1)"));+ assert_eq!(native_job_mutation_plan(NativeJobEngine::Dameng, &mutation(&before, json!([{"name":"NAME","change":{"kind":"set","value":"a"}}, {"name":"name","change":{"kind":"set","value":"b"}}])), &before).err(), Some("native_job_duplicate_attribute"));+}++#[test]+fn rename_validates_new_names_without_revalidating_catalog_names() {+ let before = details(false);+ for name in ["", "New' Job", "1Job", "新作业", &"a".repeat(129)] {+ assert_eq!(+ native_job_mutation_plan(+ NativeJobEngine::Dameng,+ &mutation(&before, json!([{"name":"NAME","change":{"kind":"set","value":name}}])),+ &before+ )+ .err(),+ Some("native_job_name_invalid")+ );+ }+ let mut old = before;+ if let NativeJobRef::DamengNative { name, .. } = &mut old.snapshot.job_ref {+ *name = "Old' Job".into();+ }+ if let NativeJobMetadata::Available { value } = &mut old.snapshot.definition {+ value.insert("NAME".into(), json!("Old' Job"));+ }+ let plan = native_job_mutation_plan(+ NativeJobEngine::Dameng,+ &mutation(&old, json!([{"name":"NAME","change":{"kind":"set","value":"New_Job"}}])),+ &old,+ )+ .unwrap();+ assert!(plan.steps[0].sql.contains("SP_RENAME_JOB('Old'' Job', 'New_Job'); COMMIT;"));+}++#[test]+fn legacy_interval_uses_one_guarded_commit_after_configuration_before_activation() {+ let before = legacy_details(true);+ for (attributes, expected_ids) in [+ (+ json!([{"name":"INTERVAL","change":{"kind":"set","value":"000900719925474099312345"}}]),+ vec!["pause", "legacy_interval", "enable"],+ ),+ (+ json!([{"name":"DESCRIBE","change":{"kind":"set","value":"new"}}, {"name":"INTERVAL","change":{"kind":"set","value":"900719925474099312345"}}]),+ vec!["pause", "definition", "config_start", "config_commit", "legacy_interval", "enable"],+ ),+ ] {+ let plan = native_job_mutation_plan(NativeJobEngine::Dameng, &mutation(&before, attributes), &before).unwrap();+ assert_eq!(plan.steps.iter().map(|step| step.id.as_str()).collect::<Vec<_>>(), expected_ids);+ let step = plan.steps.iter().find(|step| step.id == "legacy_interval").unwrap();+ assert!(step.sql.contains("DBMS_JOB.\"INTERVAL\"(41, 'SYSDATE+900719925474099312345/86400'); COMMIT;"));+ assert!(step.sql.contains("ID = 41 AND NAME = 'Job_1' AND CREATETIME = 'creation'"));+ assert!(+ matches!(&step.effect, NativeJobStepEffect::DamengLegacyInterval { expected_seconds: Some(value) } if value == "900719925474099312345")+ );+ assert!(plan.required_partitions.iter().any(|part| part == "legacyDefinition"));+ assert!(plan.required_partitions.iter().any(|part| part == "steps"));+ assert!(plan.required_partitions.iter().any(|part| part == "schedules"));+ }+}++#[test]+fn legacy_custom_interval_is_not_evaluated_or_mistaken_for_a_fixed_period() {+ let before = legacy_details(false);+ for expression in ["0", "0.5", "SYSDATE + custom_next('O''ne')"] {+ let plan = native_job_mutation_plan(+ NativeJobEngine::Dameng,+ &mutation(&before, json!([{"name":"INTERVAL","change":{"kind":"set","value":expression}}])),+ &before,+ )+ .unwrap();+ assert_eq!(plan.steps.len(), 2);+ assert!(matches!(plan.steps[1].effect, NativeJobStepEffect::DamengLegacyInterval { expected_seconds: None }));+ assert!(+ !plan.steps[1].sql.contains("SELECT")+ || plan.steps[1].sql.contains("SELECT COUNT(*) INTO dbx_target_count")+ );+ assert!(!plan.steps[1].sql.contains("EXECUTE IMMEDIATE"));+ }+ let denied = NativeJobDetails {+ legacy_definition: Some(NativeJobMetadata::Denied { reason: "denied".into() }),+ ..before.clone()+ };+ assert_eq!(+ native_job_mutation_plan(+ NativeJobEngine::Dameng,+ &mutation(&denied, json!([{"name":"INTERVAL","change":{"kind":"set","value":"1"}}])),+ &denied+ )+ .err(),+ Some("native_job_legacy_definition_unavailable")+ );+ assert_eq!(native_job_mutation_plan(NativeJobEngine::Dameng, &mutation(&before, json!([{"name":"INTERVAL","change":{"kind":"set","value":"1"}}, {"name":"interval","change":{"kind":"set","value":"2"}}])), &before).err(), Some("native_job_duplicate_attribute"));+ assert!(native_job_mutation_plan(+ NativeJobEngine::Dameng,+ &mutation(&denied, json!([{"name":"DESCRIBE","change":{"kind":"set","value":"native-only"}}])),+ &denied+ )+ .is_ok());+}++#[test]+fn a_basic_edit_preserves_notifications_and_uses_a_disabled_configuration_cycle() {+ let before = details(true);+ let request = mutation(&before, json!([{"name":"DESCRIBE","change":{"kind":"set","value":"new's description"}}]));+ let plan = native_job_mutation_plan(NativeJobEngine::Dameng, &request, &before).unwrap();+ assert_eq!(+ plan.steps.iter().map(|step| step.id.as_str()).collect::<Vec<_>>(),+ ["pause", "definition", "config_start", "config_commit", "enable"]+ );+ assert!(plan.steps[0].sql.contains("SP_ENABLE_JOB('Job_1', 0)"));+ assert!(plan.steps[1]+ .sql+ .contains("SP_ALTER_JOB('Job_1', 0, 1, dbx_email_operator, 2, 0, NULL, 1, 'new''s description')"));+ assert!(plan.steps[1].sql.contains("FROM SYSJOB.SYSOPERATORS WHERE ID = 7"));+ assert!(plan.steps.iter().all(|step| step.sql.contains("SYSJOB.USER_JOBS_VIEW")+ && step.sql.contains("ID = 41")+ && step.sql.contains("CREATETIME = 'creation'")));+ assert_eq!(plan.required_partitions, ["definition"]);+ assert!(!plan+ .steps+ .iter()+ .any(|step| step.sql.contains("DROP_JOB") || step.sql.contains("CREATE_JOB") || step.sql.contains("ROLLBACK")));+}++#[test]+fn disabled_and_node_only_edits_do_not_require_unrelated_operator_or_step_access() {+ let before = details(false);+ let request = mutation(&before, json!([{"name":"EP_SEQNO","change":{"kind":"set","value":2}}]));+ let plan = native_job_mutation_plan(NativeJobEngine::Dameng, &request, &before).unwrap();+ assert_eq!(+ plan.steps.iter().map(|step| step.id.as_str()).collect::<Vec<_>>(),+ ["pause", "config_start", "attribute:EP_SEQNO", "config_commit"]+ );+ assert!(plan.steps[2].sql.contains("SP_JOB_SET_EP_SEQNO('Job_1', 2)"));+ assert!(!plan.steps.iter().any(|step| step.sql.contains("SYSOPERATORS")+ || step.sql.contains("SP_ALTER_JOB")+ || step.sql.contains("COMMIT;")));+}++#[test]+fn requested_activation_is_last_and_not_an_intermediate_alter_parameter() {+ let before = details(false);+ let request = mutation(+ &before,+ json!([+ {"name":"ENABLE","change":{"kind":"set","value":true}},+ {"name":"EMAIL_OPERATOR_NAME","change":{"kind":"set","value":"New_Operator"}},+ {"name":"ENABLE_EMAIL","change":{"kind":"set","value":true}}+ ]),+ );+ let plan = native_job_mutation_plan(NativeJobEngine::Dameng, &request, &before).unwrap();+ assert!(plan.steps[1].sql.contains("SP_ALTER_JOB('Job_1', 0,"));+ assert!(plan.steps[1].sql.contains("'New_Operator'"));+ assert!(plan.steps.last().unwrap().sql.contains("SP_ENABLE_JOB('Job_1', 1)"));+}++#[test]+fn incomplete_or_forged_metadata_does_not_generate_a_destructive_definition() {+ let mut before = details(true);+ let NativeJobMetadata::Available { value } = &mut before.snapshot.definition else { unreachable!() };+ value.remove("EMAIL_TYPE");+ let request = mutation(&before, json!([{"name":"DESCRIBE","change":{"kind":"clear"}}]));+ assert_eq!(+ native_job_mutation_plan(NativeJobEngine::Dameng, &request, &before).err(),+ Some("native_job_metadata_incomplete")+ );+ let mut before = details(true);+ before.sources.get_mut("definition").unwrap().source = Some("untrusted_source".into());+ let request = mutation(&before, json!([{"name":"DESCRIBE","change":{"kind":"clear"}}]));+ assert_eq!(+ native_job_mutation_plan(NativeJobEngine::Dameng, &request, &before).err(),+ Some("native_job_catalog_source_unverified")+ );+}++#[test]+fn every_native_control_guards_the_same_id_name_and_creation_before_dispatch() {+ let before = details(true);+ for change in [+ NativeJobChange::Enable,+ NativeJobChange::Disable,+ NativeJobChange::Run,+ NativeJobChange::Stop { force: false },+ NativeJobChange::Drop { force: false },+ NativeJobChange::ClearHistory,+ ] {+ let request =+ NativeJobMutation { target: before.snapshot.job_ref.clone(), baseline: "baseline".into(), change };+ let plan = native_job_mutation_plan(NativeJobEngine::Dameng, &request, &before).unwrap();+ let sql = &plan.steps[0].sql;+ assert!(+ sql.contains("ID = 41 AND NAME = 'Job_1' AND CREATETIME = 'creation'"),+ "native control did not guard its generation"+ );+ assert!(sql.find("RAISE dbx_target_changed").unwrap() < sql.find("SP_").unwrap());+ assert!(!sql.contains("DROP_JOB") || plan.steps[0].id == "drop");+ }+}++#[test]+fn native_controls_refuse_unproven_generation_but_do_not_require_unrelated_definition_fields() {+ let mut before = details(true);+ before.snapshot.definition = NativeJobMetadata::Denied { reason: "definition_columns_not_readable".into() };+ before.sources.insert(+ "identity".into(),+ NativeJobCatalogSource {+ source: Some("SYSJOB.USER_JOBS_VIEW".into()),+ coverage: Some(NativeJobCatalogCoverage::CurrentUser),+ },+ );+ let request = NativeJobMutation {+ target: before.snapshot.job_ref.clone(),+ baseline: "baseline".into(),+ change: NativeJobChange::Run,+ };+ assert!(native_job_mutation_plan(NativeJobEngine::Dameng, &request, &before).is_ok());+ before.native_identity = NativeJobMetadata::Unknown { reason: "not_readable".into() };+ assert_eq!(+ native_job_mutation_plan(NativeJobEngine::Dameng, &request, &before).err(),+ Some("native_job_identity_unverified")+ );+}++#[test]+fn native_drop_does_not_silently_discard_a_requested_force_semantic() {+ let before = details(true);+ let request = NativeJobMutation {+ target: before.snapshot.job_ref.clone(),+ baseline: "baseline".into(),+ change: NativeJobChange::Drop { force: true },+ };+ assert_eq!(+ native_job_mutation_plan(NativeJobEngine::Dameng, &request, &before).err(),+ Some("native_job_force_drop_not_applicable")+ );+}diff --git a/crates/dbx-sql-schema/tests/native_job_dameng_creation.rs b/crates/dbx-sql-schema/tests/native_job_dameng_creation.rsnew file mode 100644index 0000000000..391ba2610a--- /dev/null+++ b/crates/dbx-sql-schema/tests/native_job_dameng_creation.rs@@ -0,0 +1,88 @@+use dbx_sql_schema::native_job_changes::native_job_dameng_create_plan;+use dbx_types::native_jobs::*;+use serde_json::json;++fn definition(enabled: bool) -> NativeJobDamengCreate {+ serde_json::from_value(json!({+ "name":"Daily_job", "enabled":enabled,+ "configuration":{+ "attributes":[{"name":"DESCRIBE","change":{"kind":"set","value":"owner's job"}}],+ "steps":[+ {"kind":"add","name":"first","attributes":[+ {"name":"COMMAND_INPUT","change":{"kind":"set","value":"BEGIN work(':dbx_created_job_id'); END;"}},+ {"name":"SUCC_ACTION","change":{"kind":"set","value":3}},+ {"name":"SUCC_NEXT_STEP","change":{"kind":"set","value":"last"}}+ ]},+ {"kind":"add","name":"last","attributes":[{"name":"TYPE","change":{"kind":"set","value":3}}]}+ ],+ "schedules":[{"kind":"add","name":"daily","attributes":[+ {"name":"DURING_START_DATE","change":{"kind":"set","value":"2026-10-21"}}+ ]}]+ }+ }))+ .unwrap()+}++#[test]+fn creates_disabled_before_configuration_and_never_invents_a_native_id() {+ let plan = native_job_dameng_create_plan(&definition(true)).unwrap();+ assert_eq!(plan.steps[0].id, "create");+ assert!(plan.steps[0].sql.contains("SP_CREATE_JOB('Daily_job', 0,"));+ assert!(plan.steps[0].sql.contains("'owner''s job'"));+ let ids = plan.steps.iter().map(|step| step.id.as_str()).collect::<Vec<_>>();+ assert_eq!(&ids[1..3], &["pause", "config_start"]);+ assert_eq!(&ids[ids.len() - 2..], &["config_commit", "enable"]);+ assert!(plan.steps.iter().all(|step| !step.sql.contains("WHERE ID = 1")));+ let sql = plan.steps.iter().map(|step| step.sql.as_str()).collect::<Vec<_>>().join("\n");+ assert!(sql.contains("work('':dbx_created_job_id'')"));+ let last_add = plan.steps.iter().rposition(|step| step.sql.contains("SP_ADD_JOB_STEP_EX")).unwrap();+ let link = plan.steps.iter().position(|step| step.sql.contains("SP_JOB_STEP_SET_NEXT_STEP")).unwrap();+ assert!(last_add < link);+}++#[test]+fn disabled_creation_still_ends_configuration_without_activation() {+ let plan = native_job_dameng_create_plan(&definition(false)).unwrap();+ assert_eq!(plan.steps.last().unwrap().id, "config_commit");+ assert!(!plan.steps.iter().any(|step| step.id == "enable"));+}++#[test]+fn validates_complete_children_and_dependencies_before_dispatch() {+ let mut input = definition(true);+ input.configuration.steps.pop();+ assert_eq!(native_job_dameng_create_plan(&input).err(), Some("native_job_step_dependency_requires_correction"));+ input.configuration.steps = vec![NativeJobDamengChildChange::Drop { name: "not_created".into() }];+ assert_eq!(native_job_dameng_create_plan(&input).err(), Some("native_job_creation_children_must_be_new"));+ input.configuration.steps.clear();+ input.name = "bad,name".into();+ assert_eq!(native_job_dameng_create_plan(&input).err(), Some("native_job_name_invalid"));+}++#[test]+fn notification_references_are_resolved_before_create_and_not_defaulted_to_other_operators() {+ let mut input = definition(false);+ input.configuration.attributes.extend(+ serde_json::from_value::<Vec<NativeJobAttributeChange>>(json!([+ {"name":"ENABLE_EMAIL","change":{"kind":"set","value":true}},+ {"name":"EMAIL_OPERATOR_NAME","change":{"kind":"set","value":"OnCall"}},+ {"name":"EMAIL_TYPE","change":{"kind":"set","value":2}}+ ]))+ .unwrap(),+ );+ let plan = native_job_dameng_create_plan(&input).unwrap();+ assert!(plan.configuration.operator_query().unwrap().sql.contains("UPPER('OnCall')"));+ assert!(plan.steps[0].sql.contains("SP_CREATE_JOB('Daily_job', 0, 1, dbx_email_operator, 2"));+ input.configuration.attributes.retain(|attribute| attribute.name != "EMAIL_OPERATOR_NAME");+ assert_eq!(native_job_dameng_create_plan(&input).err(), Some("native_job_notification_operator_required"));+}++#[test]+fn creation_has_one_authoritative_activation_choice() {+ let mut input = definition(true);+ input.configuration.attributes.push(NativeJobAttributeChange {+ name: "ENABLE".into(),+ change: NativeJobFieldChange::Set { value: json!(false) },+ });+ assert_eq!(native_job_dameng_create_plan(&input).err(), Some("native_job_duplicate_attribute"));+}diff --git a/crates/dbx-sql-schema/tests/native_job_dameng_parts.rs b/crates/dbx-sql-schema/tests/native_job_dameng_parts.rsnew file mode 100644index 0000000000..e5f14a55bc--- /dev/null+++ b/crates/dbx-sql-schema/tests/native_job_dameng_parts.rs@@ -0,0 +1,322 @@+use dbx_sql_schema::native_job_changes::{+ native_job_dameng_child_key, native_job_mutation_plan, resolve_native_job_dameng_child_step, NativeJobDamengPart,+};+use dbx_types::native_jobs::*;+use serde_json::json;++fn details() -> NativeJobDetails {+ serde_json::from_value(json!({+ "snapshot":{"ref":{"kind":"dameng-native","scope":{"connectionId":"c","database":"","contextId":"ctx"},"jobId":"41","name":"Job_1"},"revision":"baseline",+ "definition":{"status":"available","value":{"ID":41,"DBX_JOB_ID":"41","NAME":"Job_1","USERNAME":"Owner","CREATETIME":"creation","ENABLE":true,"ENABLE_EMAIL":1,"EMAIL_OPERID":7,"EMAIL_TYPE":2,"ENABLE_NETSEND":0,"NETSEND_OPERID":-1,"NETSEND_TYPE":1,"DESCRIBE":"kept","VALID":"Y","EP_SEQNO":0,"RAFT_NAME":null}},+ "arguments":{"status":"available","value":[]}},+ "nativeIdentity":{"status":"available","value":{"DBX_JOB_ID":"41","DBX_CREATED_AT":"creation"}},"consistency":{"status":"available","value":null},"parameterMetadata":{"status":"unsupported","reason":"not_applicable"},+ "steps":{"status":"available","value":[+ {"ID":11,"NAME":"backup","JOBID":41,"SEQNO":1,"TYPE":6,"DBNAME":"DB","COMMAND":"native generated backup command","SUCC_ACTION":3,"FAIL_ACTION":1,"RETRY_ATTEMPTS":2,"RETRY_INTERVAL":1,"OUTPUT_FILE_PATH":null,"APPEND_FLAG":0,"SUCC_NEXT_STEP":"sql","FAIL_NEXT_STEP":null,"DESCRIBE":"keep backup"},+ {"ID":12,"NAME":"sql","JOBID":41,"SEQNO":2,"TYPE":0,"DBNAME":"DB","COMMAND":"SELECT 1;","SUCC_ACTION":1,"FAIL_ACTION":1,"RETRY_ATTEMPTS":0,"RETRY_INTERVAL":0,"OUTPUT_FILE_PATH":null,"APPEND_FLAG":0,"SUCC_NEXT_STEP":null,"FAIL_NEXT_STEP":null,"DESCRIBE":"old sql"}+ ]},+ "schedules":{"status":"available","value":[+ {"ID":21,"NAME":"daily","JOBID":41,"ENABLE":1,"TYPE":1,"FREQ_INTERVAL":1,"FREQ_SUB_INTERVAL":0,"FREQ_MINUTE_INTERVAL":5,"STARTTIME":"23:00:00","ENDTIME":"01:00:00","DURING_START_DATE":"2026-10-21","DURING_END_DATE":"2026-12-31","SCHNAME":"sch1","TRIGNAME":"trig1","VALID":"Y","DESCRIBE":"keep daily"},+ {"ID":22,"NAME":"weekly","JOBID":41,"ENABLE":0,"TYPE":2,"FREQ_INTERVAL":2,"FREQ_SUB_INTERVAL":68,"FREQ_MINUTE_INTERVAL":0,"STARTTIME":"09:00:00","ENDTIME":null,"DURING_START_DATE":"2026-10-21","DURING_END_DATE":null,"SCHNAME":"sch2","TRIGNAME":"trig2","VALID":"Y","DESCRIBE":"keep weekly"}+ ]},+ "running":{"status":"unknown","reason":"not_readable"},"history":{"status":"empty"},+ "sources":{"identity":{"source":"SYSJOB.USER_JOBS_VIEW","coverage":"current_user"},"definition":{"source":"SYSJOB.USER_JOBS_VIEW","coverage":"current_user"},"steps":{"source":"SYSJOB.USER_JOBSTEPS_VIEW","coverage":"current_user"},"schedules":{"source":"SYSJOB.USER_JOBSCHEDULES_VIEW","coverage":"current_user"}}+ })).unwrap()+}++fn request(data: &NativeJobDetails, configuration: serde_json::Value) -> NativeJobMutation {+ NativeJobMutation {+ target: data.snapshot.job_ref.clone(),+ baseline: data.snapshot.revision.clone(),+ change: NativeJobChange::ConfigureDameng { configuration: serde_json::from_value(configuration).unwrap() },+ }+}++#[test]+fn editing_one_sql_step_preserves_other_steps_schedules_and_notifications() {+ let data = details();+ let change = request(+ &data,+ json!({"steps":[{"kind":"update","name":"sql","attributes":[+ {"name":"COMMAND_INPUT","change":{"kind":"set","value":"BEGIN work('private'); END;"}},+ {"name":"RETRY_ATTEMPTS","change":{"kind":"set","value":3}}+ ]}]}),+ );+ let plan = native_job_mutation_plan(NativeJobEngine::Dameng, &change, &data).unwrap();+ let sql = plan.steps.iter().map(|step| step.sql.as_str()).collect::<Vec<_>>().join("\n");+ assert!(sql.contains(+ "SP_ALTER_JOB_STEP_EX('Job_1', 'sql', 0, 'BEGIN work(''private''); END;', 1, 1, 3, 0, NULL, 0, 'old sql')"+ ));+ assert!(!sql.contains("native generated backup command"));+ assert!(!sql.contains("SP_ALTER_JOB("));+ assert!(!sql.contains("SP_ALTER_JOB_SCHEDULE"));+ assert_eq!(plan.required_partitions, ["definition", "steps"]);+ assert_eq!(plan.steps.last().unwrap().id, "enable");+}++#[test]+fn new_steps_are_all_added_before_forward_dependencies_are_linked() {+ let data = details();+ let change = request(+ &data,+ json!({"steps":[+ {"kind":"add","name":"new_a","attributes":[{"name":"COMMAND_INPUT","change":{"kind":"set","value":"SELECT 2;"}},{"name":"SUCC_ACTION","change":{"kind":"set","value":3}},{"name":"SUCC_NEXT_STEP","change":{"kind":"set","value":"new_b"}}]},+ {"kind":"add","name":"new_b","attributes":[{"name":"COMMAND_INPUT","change":{"kind":"set","value":"SELECT 3;"}}]}+ ]}),+ );+ let plan = native_job_mutation_plan(NativeJobEngine::Dameng, &change, &data).unwrap();+ let statements = plan.steps.iter().map(|step| step.sql.as_str()).collect::<Vec<_>>();+ let added = statements.iter().rposition(|sql| sql.contains("SP_ADD_JOB_STEP_EX")).unwrap();+ let linked = statements.iter().position(|sql| sql.contains("SP_JOB_STEP_SET_NEXT_STEP")).unwrap();+ assert!(added < linked);+ assert!(statements[linked].contains("'new_a', 'new_b', NULL"));+ assert!(statements[linked].contains(":dbx_created_step_id"));+}++#[test]+fn generated_backup_commands_need_explicit_native_input_only_when_altering_the_step_definition() {+ let data = details();+ let config = json!({"steps":[{"kind":"update","name":"backup","attributes":[{"name":"DESCRIBE","change":{"kind":"set","value":"new"}}]}]});+ assert_eq!(+ native_job_mutation_plan(NativeJobEngine::Dameng, &request(&data, config), &data).err(),+ Some("native_job_step_command_input_required")+ );+ let config = json!({"steps":[{"kind":"update","name":"backup","attributes":[+ {"name":"DESCRIBE","change":{"kind":"set","value":"new"}},+ {"name":"COMMAND_INPUT","change":{"kind":"set","value":"01000000E:\\backups"}}+ ]}]});+ let plan = native_job_mutation_plan(NativeJobEngine::Dameng, &request(&data, config), &data).unwrap();+ assert!(plan.steps.iter().any(|step| step.sql.contains("'01000000E:\\backups'")));+ let config = json!({"steps":[{"kind":"update","name":"backup","attributes":[{"name":"FAIL_NEXT_STEP","change":{"kind":"clear"}}]}]});+ assert!(native_job_mutation_plan(NativeJobEngine::Dameng, &request(&data, config), &data).is_ok());+}++#[test]+fn dropping_a_referenced_step_requires_a_correction_and_applies_it_before_the_drop() {+ let data = details();+ let config = json!({"steps":[{"kind":"drop","name":"sql"}]});+ assert_eq!(+ native_job_mutation_plan(NativeJobEngine::Dameng, &request(&data, config), &data).err(),+ Some("native_job_step_dependency_requires_correction")+ );+ let config = json!({"steps":[{"kind":"drop","name":"sql"},{"kind":"update","name":"backup","attributes":[{"name":"SUCC_NEXT_STEP","change":{"kind":"clear"}}]}]});+ let plan = native_job_mutation_plan(NativeJobEngine::Dameng, &request(&data, config), &data).unwrap();+ let linked = plan.steps.iter().position(|step| step.sql.contains("SP_JOB_STEP_SET_NEXT_STEP")).unwrap();+ let dropped = plan.steps.iter().position(|step| step.sql.contains("SP_DROP_JOB_STEP")).unwrap();+ assert!(linked < dropped);+ assert!(plan.steps[dropped].sql.contains("ID = 12"));+}++#[test]+fn renaming_a_step_preserves_its_native_id_and_retargets_existing_dependencies_explicitly() {+ let data = details();+ let config = json!({"steps":[{"kind":"update","name":"sql","attributes":[{"name":"NAME","change":{"kind":"set","value":"renamed"}}]}]});+ let plan = native_job_mutation_plan(NativeJobEngine::Dameng, &request(&data, config), &data).unwrap();+ let renamed = plan.steps.iter().position(|step| step.sql.contains("SP_RENAME_JOB_STEP")).unwrap();+ let links = plan+ .steps+ .iter()+ .position(|step| step.sql.contains("SP_JOB_STEP_SET_NEXT_STEP('Job_1', 'backup', 'renamed', NULL)"))+ .unwrap();+ assert!(renamed < links);+ assert!(plan.steps[renamed].sql.contains("ID = 12"));+ assert!(!plan+ .steps+ .iter()+ .any(|step| step.sql.contains("SP_DROP_JOB_STEP") || step.sql.contains("SP_ALTER_JOB_STEP")));+}++#[test]+fn schedules_keep_full_native_options_and_clear_only_requested_values() {+ let data = details();+ let config = json!({"schedules":[{"kind":"update","name":"weekly","attributes":[{"name":"ENABLE","change":{"kind":"set","value":true}},{"name":"DURING_END_DATE","change":{"kind":"clear"}}]}]});+ let plan = native_job_mutation_plan(NativeJobEngine::Dameng, &request(&data, config), &data).unwrap();+ assert!(plan.steps.iter().any(|step| step.sql.contains(+ "SP_ALTER_JOB_SCHEDULE('Job_1', 'weekly', 1, 2, 2, 68, 0, '09:00:00', NULL, '2026-10-21', NULL, 'keep weekly')"+ )));+ assert_eq!(plan.required_partitions, ["definition", "schedules"]);+ assert!(!plan.steps.iter().any(|step| step.sql.contains("SP_ALTER_JOB_STEP") || step.sql.contains("'keep daily'")));+}++#[test]+fn a_denied_unrelated_partition_does_not_block_a_valid_schedule_edit() {+ let mut data = details();+ data.steps = NativeJobMetadata::Denied { reason: "not_readable".into() };+ let config = json!({"schedules":[{"kind":"drop","name":"weekly"}]});+ assert!(native_job_mutation_plan(NativeJobEngine::Dameng, &request(&data, config), &data).is_ok());+ data.schedules = NativeJobMetadata::Truncated { value: vec![], limit: 1 };+ let config = json!({"schedules":[{"kind":"drop","name":"weekly"}]});+ assert_eq!(+ native_job_mutation_plan(NativeJobEngine::Dameng, &request(&data, config), &data).err(),+ Some("native_job_metadata_incomplete")+ );+}++#[test]+fn changing_a_generated_step_to_sql_needs_original_input_and_never_reuses_generated_command() {+ let data = details();+ let config = json!({"steps":[{"kind":"update","name":"backup","attributes":[{"name":"TYPE","change":{"kind":"set","value":0}}]}]});+ assert_eq!(+ native_job_mutation_plan(NativeJobEngine::Dameng, &request(&data, config), &data).err(),+ Some("native_job_step_command_input_required")+ );+ let config = json!({"steps":[{"kind":"update","name":"backup","attributes":[+ {"name":"TYPE","change":{"kind":"set","value":0}},+ {"name":"COMMAND_INPUT","change":{"kind":"set","value":"SELECT 2;"}}+ ]}]});+ let plan = native_job_mutation_plan(NativeJobEngine::Dameng, &request(&data, config), &data).unwrap();+ assert!(plan.steps.iter().any(|step| step.sql.contains("SP_ALTER_JOB_STEP_EX('Job_1', 'backup', 0, 'SELECT 2;'")));+ assert!(!plan.steps.iter().any(|step| step.sql.contains("native generated backup command")));+}++#[test]+fn types_whose_native_command_is_ignored_reject_nonempty_input_but_allow_empty_native_input() {+ let data = details();+ for kind in [2, 3] {+ let config = json!({"steps":[{"kind":"add","name":"stats","attributes":[+ {"name":"TYPE","change":{"kind":"set","value":kind}},+ {"name":"COMMAND_INPUT","change":{"kind":"set","value":"user expects this to execute"}}+ ]}]});+ assert_eq!(+ native_job_mutation_plan(NativeJobEngine::Dameng, &request(&data, config), &data).err(),+ Some("native_job_step_command_not_applicable")+ );+ let config = json!({"steps":[{"kind":"add","name":"stats","attributes":[{"name":"TYPE","change":{"kind":"set","value":kind}}]}]});+ let plan = native_job_mutation_plan(NativeJobEngine::Dameng, &request(&data, config), &data).unwrap();+ assert!(plan+ .steps+ .iter()+ .any(|step| step.sql.contains(&format!("SP_ADD_JOB_STEP_EX('Job_1', 'stats', {kind}, NULL"))));+ }+}++#[test]+fn legacy_type_nine_schedule_is_preserved_but_not_mutated_through_native_schedule_procedures() {+ let mut data = details();+ if let NativeJobMetadata::Available { value } = &mut data.schedules {+ value[0].insert("TYPE".into(), json!(9));+ }+ let config = json!({"schedules":[{"kind":"update","name":"weekly","attributes":[{"name":"ENABLE","change":{"kind":"set","value":true}}]}]});+ assert!(native_job_mutation_plan(NativeJobEngine::Dameng, &request(&data, config), &data).is_ok());+ for change in [+ json!({"kind":"drop","name":"daily"}),+ json!({"kind":"update","name":"daily","attributes":[{"name":"NAME","change":{"kind":"set","value":"legacy_alias"}}]}),+ ] {+ let config = json!({"schedules":[change]});+ assert_eq!(+ native_job_mutation_plan(NativeJobEngine::Dameng, &request(&data, config), &data).err(),+ Some("native_job_legacy_schedule_requires_dbms_job")+ );+ }+}++#[test]+fn illegal_fields_names_duplicate_edits_and_native_identity_mismatches_are_rejected_before_configuration() {+ let data = details();+ for (config, reason) in [+ (+ json!({"steps":[{"kind":"update","name":"sql","attributes":[{"name":"ID","change":{"kind":"set","value":99}}]}]}),+ "native_job_attribute_not_editable",+ ),+ (json!({"steps":[{"kind":"add","name":"sql"}]}), "native_job_child_name_collision"),+ (json!({"steps":[{"kind":"add","name":"1bad"}]}), "native_job_child_name_invalid"),+ (+ json!({"steps":[{"kind":"drop","name":"sql"},{"kind":"drop","name":"SQL"}]}),+ "native_job_duplicate_child_change",+ ),+ (+ json!({"steps":[{"kind":"update","name":"sql","attributes":[{"name":"SUCC_NEXT_STEP","change":{"kind":"set","value":"missing"}}]}]}),+ "native_job_step_dependency_requires_correction",+ ),+ (+ json!({"schedules":[{"kind":"update","name":"weekly","attributes":[{"name":"FREQ_SUB_INTERVAL","change":{"kind":"set","value":128}}]}]}),+ "native_job_attribute_value_invalid",+ ),+ (+ json!({"steps":[{"kind":"update","name":"sql","attributes":[{"name":"NAME","change":{"kind":"set","value":"backup"}}]}]}),+ "native_job_child_name_collision",+ ),+ ] {+ assert_eq!(+ native_job_mutation_plan(NativeJobEngine::Dameng, &request(&data, config), &data).err(),+ Some(reason)+ );+ }+ let mut wrong = data.clone();+ if let NativeJobMetadata::Available { value } = &mut wrong.steps {+ value[0].insert("JOBID".into(), json!(42));+ }+ let config = json!({"steps":[{"kind":"update","name":"sql","attributes":[{"name":"DESCRIBE","change":{"kind":"set","value":"changed"}}]}]});+ assert_eq!(+ native_job_mutation_plan(NativeJobEngine::Dameng, &request(&wrong, config), &wrong).err(),+ Some("native_job_child_identity_unverified")+ );+}++#[test]+fn a_rename_chain_keeps_original_reference_identity_instead_of_cascading_text_replacements() {+ let data = details();+ let config = json!({"steps":[+ {"kind":"update","name":"sql","attributes":[{"name":"NAME","change":{"kind":"set","value":"new_sql"}}]},+ {"kind":"update","name":"backup","attributes":[{"name":"NAME","change":{"kind":"set","value":"sql"}}]}+ ]});+ let plan = native_job_mutation_plan(NativeJobEngine::Dameng, &request(&data, config), &data).unwrap();+ let renames = plan.steps.iter().filter(|step| step.sql.contains("SP_RENAME_JOB_STEP")).collect::<Vec<_>>();+ assert!(renames[0].sql.contains("'sql', 'new_sql'"));+ assert!(renames[1].sql.contains("'backup', 'sql'"));+ assert!(plan+ .steps+ .iter()+ .any(|step| step.sql.contains("SP_JOB_STEP_SET_NEXT_STEP('Job_1', 'sql', 'new_sql', NULL)")));+ let cycle = json!({"steps":[+ {"kind":"update","name":"sql","attributes":[{"name":"NAME","change":{"kind":"set","value":"backup"}}]},+ {"kind":"update","name":"backup","attributes":[{"name":"NAME","change":{"kind":"set","value":"sql"}}]}+ ]});+ assert_eq!(+ native_job_mutation_plan(NativeJobEngine::Dameng, &request(&data, cycle), &data).err(),+ Some("native_job_child_rename_requires_correction")+ );+}++#[test]+fn binding_created_ids_only_rebuilds_native_guards_and_preserves_literal_body_markers() {+ let data = details();+ let body = "SELECT ':dbx_created_step_id', ':dbx_created_reference_id_0';";+ let config = json!({"steps":[{"kind":"add","name":"new_step","attributes":[{"name":"COMMAND_INPUT","change":{"kind":"set","value":body}},{"name":"SUCC_ACTION","change":{"kind":"set","value":3}},{"name":"SUCC_NEXT_STEP","change":{"kind":"set","value":"sql"}}]}]});+ let plan = native_job_mutation_plan(NativeJobEngine::Dameng, &request(&data, config), &data).unwrap();+ let added = plan.steps.iter().find(|step| step.sql.contains("SP_ADD_JOB_STEP_EX")).unwrap();+ let resolved =+ resolve_native_job_dameng_child_step(added, &data.snapshot.job_ref, &data, &Default::default()).unwrap();+ assert_eq!(resolved.sql, added.sql);+ assert!(resolved.sql.contains("'SELECT '':dbx_created_step_id'', '':dbx_created_reference_id_0'';'"));+ let linked = plan.steps.iter().find(|step| step.sql.contains("SP_JOB_STEP_SET_NEXT_STEP")).unwrap();+ assert_eq!(+ resolve_native_job_dameng_child_step(linked, &data.snapshot.job_ref, &data, &Default::default()).err(),+ Some("native_job_child_identity_unverified")+ );+ let created =+ [(native_job_dameng_child_key(NativeJobDamengPart::Steps, "new_step"), "900719925474099312345".into())]+ .into_iter()+ .collect();+ let resolved = resolve_native_job_dameng_child_step(linked, &data.snapshot.job_ref, &data, &created).unwrap();+ assert!(resolved.sql.contains("ID = 900719925474099312345"));+ assert!(resolved.sql.contains("ID = 12"));+ assert!(!resolved.sql.contains(":dbx_created_step_id"));+}++#[test]+fn native_child_configuration_is_not_dispatched_through_another_engine_or_legacy_entry() {+ let data = details();+ let change = request(&data, json!({"steps":[{"kind":"drop","name":"backup"}]}));+ assert_eq!(+ native_job_mutation_plan(NativeJobEngine::Oracle, &change, &data).err(),+ Some("native_job_action_not_applicable")+ );+ let mut legacy = data.clone();+ legacy.snapshot.job_ref =+ NativeJobRef::Legacy { scope: data.snapshot.job_ref.scope().clone(), job_id: "41".into() };+ let change = request(&legacy, json!({"steps":[{"kind":"drop","name":"backup"}]}));+ assert_eq!(+ native_job_mutation_plan(NativeJobEngine::Dameng, &change, &legacy).err(),+ Some("native_job_action_not_applicable")+ );+}diff --git a/crates/dbx-sql-schema/tests/native_job_reference_targets.rs b/crates/dbx-sql-schema/tests/native_job_reference_targets.rsnew file mode 100644index 0000000000..545e142f70--- /dev/null+++ b/crates/dbx-sql-schema/tests/native_job_reference_targets.rs@@ -0,0 +1,84 @@+use dbx_sql_schema::native_job_changes::native_job_scheduler_reference_target;+use dbx_types::native_jobs::NativeJobReferenceKind;+use serde_json::json;++#[test]+fn structured_references_preserve_components_and_choose_only_compatible_categories() {+ for (attribute, category, expected) in [+ ("PROGRAM_NAME", "program", NativeJobReferenceKind::Program),+ ("SCHEDULE_NAME", "schedule", NativeJobReferenceKind::Schedule),+ ("SCHEDULE_NAME", "window", NativeJobReferenceKind::Window),+ ("SCHEDULE_NAME", "window-group", NativeJobReferenceKind::WindowGroup),+ ("CREDENTIAL_NAME", "credential", NativeJobReferenceKind::Credential),+ ("CONNECT_CREDENTIAL_NAME", "credential", NativeJobReferenceKind::Credential),+ ("DESTINATION_NAME", "destination", NativeJobReferenceKind::Destination),+ ("DESTINATION_NAME", "destination-group", NativeJobReferenceKind::DestinationGroup),+ ("JOB_ACTION", "chain", NativeJobReferenceKind::Chain),+ ] {+ let target = native_job_scheduler_reference_target(+ attribute,+ &json!({"owner":" Own.er\" ","name":" A,B.C\" ","kind":category}),+ "JobOwner",+ "CHAIN",+ )+ .unwrap()+ .unwrap();+ assert_eq!(target.kind, expected);+ assert_eq!(target.reference.owner, " Own.er\" ");+ assert_eq!(target.reference.name, " A,B.C\" ");+ assert!(native_job_scheduler_reference_target(+ attribute,+ &json!({"owner":"Owner","name":"Name","kind":"file-watcher"}),+ "JobOwner",+ "CHAIN"+ )+ .is_err());+ }+}++#[test]+fn legacy_name_strings_use_sql_identifier_parsing_not_dot_or_comma_splitting() {+ for (value, owner, name) in [+ ("program", "Exact Job Owner", "PROGRAM"),+ ("own.program", "OWN", "PROGRAM"),+ ("\"Own.er\".\"A,B.C\"\"D\"", "Own.er", "A,B.C\"D"),+ ("\" Leading trailing \"", "Exact Job Owner", " Leading trailing "),+ ] {+ let target =+ native_job_scheduler_reference_target("PROGRAM_NAME", &json!(value), "Exact Job Owner", "STORED_PROCEDURE")+ .unwrap()+ .unwrap();+ assert_eq!(target.reference.owner, owner);+ assert_eq!(target.reference.name, name);+ }+ for value in+ ["", "A,B", "A.B.C", "a; commit", "'not an identifier'", "\"\"", "a -- comment", "a/*comment*/", "\"unclosed"]+ {+ assert!(+ native_job_scheduler_reference_target("PROGRAM_NAME", &json!(value), "Owner", "STORED_PROCEDURE").is_err(),+ "{value}"+ );+ }+}++#[test]+fn ordinary_action_bodies_are_not_parsed_as_references_and_clearing_has_no_new_target() {+ assert!(native_job_scheduler_reference_target(+ "JOB_ACTION",+ &json!("BEGIN p('a.b'); END;"),+ "Owner",+ "PLSQL_BLOCK"+ )+ .unwrap()+ .is_none());+ assert!(native_job_scheduler_reference_target("COMMENTS", &json!("A.B"), "Owner", "CHAIN").unwrap().is_none());+ assert!(native_job_scheduler_reference_target("PROGRAM_NAME", &json!(null), "Owner", "CHAIN").unwrap().is_none());+ for value in [+ json!({"owner":"", "name":"Name"}),+ json!({"owner":"Owner", "name":""}),+ json!({"owner":"Owner", "name":"a\u{0}b"}),+ json!(42),+ ] {+ assert!(native_job_scheduler_reference_target("PROGRAM_NAME", &value, "Owner", "CHAIN").is_err());+ }+}diff --git a/crates/dbx-sql-schema/tests/native_job_references.rs b/crates/dbx-sql-schema/tests/native_job_references.rsnew file mode 100644index 0000000000..5500bb7175--- /dev/null+++ b/crates/dbx-sql-schema/tests/native_job_references.rs@@ -0,0 +1,146 @@+use dbx_sql_schema::native_jobs::native_job_reference_queries;+use dbx_types::native_jobs::*;++fn request(kind: NativeJobReferenceKind) -> NativeJobReferenceListRequest {+ NativeJobReferenceListRequest {+ scope: NativeJobScope { connection_id: "c".into(), database: String::new(), context_id: "context".into() },+ kind,+ schema: None,+ name: None,+ filter: String::new(),+ offset: 0,+ limit: 100,+ }+}++#[test]+fn references_have_exact_owner_name_components_and_current_user_sources_do_not_require_owner_columns() {+ let mut input = request(NativeJobReferenceKind::Program);+ input.schema = Some("Own.er\"One".into());+ input.name = Some("Prog,One's".into());+ let queries = native_job_reference_queries(NativeJobEngine::Oracle, &input).unwrap();+ assert_eq!(queries.len(), 3);+ assert!(queries[0].sql.contains("J.OWNER = 'Own.er\"One'"));+ assert!(queries[0].sql.contains("J.PROGRAM_NAME = 'Prog,One''s'"));+ assert!(queries[2].sql.contains("USER AS DBX_OWNER"));+ assert!(!queries[2].sql.contains("J.OWNER"));+}++#[test]+fn reference_search_is_paged_and_literal_wildcards_cannot_expand_it() {+ let mut input = request(NativeJobReferenceKind::Schedule);+ input.filter = "10%_!".into();+ input.offset = 100;+ let queries = native_job_reference_queries(NativeJobEngine::OceanbaseOracle, &input).unwrap();+ assert_eq!(queries.len(), 2);+ assert!(queries[0].sql.contains("%10!%!_!!%"));+ assert!(queries[0].sql.contains("DBX_ROW_NUM > 100 AND DBX_ROW_NUM <= 201"));+ input.name = Some("Schedule".into());+ assert!(native_job_reference_queries(NativeJobEngine::Oracle, &input).is_err());+}++#[test]+fn program_arguments_require_an_exact_program_and_credentials_do_not_project_login_data() {+ let mut input = request(NativeJobReferenceKind::ProgramArguments);+ assert!(native_job_reference_queries(NativeJobEngine::Oracle, &input).is_err());+ input.schema = Some("Owner".into());+ input.name = Some("Program".into());+ input.limit = 10_000;+ let queries = native_job_reference_queries(NativeJobEngine::Oracle, &input).unwrap();+ assert_eq!(queries[0].source, "SYS.DBA_SCHEDULER_PROGRAM_ARGS");+ assert!(queries[0].sql.contains("J.ARGUMENT_POSITION"));+ for query in &queries {+ assert!(query.sql.contains("J.DEFAULT_ANYDATA_VALUE.GetTypeName()"));+ assert!(query+ .sql+ .contains("TO_CHAR(J.DEFAULT_ANYDATA_VALUE.AccessNumber(), 'TM9', 'NLS_NUMERIC_CHARACTERS=''.,''')"));+ assert!(query.sql.contains("AS DBX_ANYDATA_PRESENT"));+ assert!(query.sql.contains("AS DBX_ANYDATA_IS_NULL"));+ assert!(!query.sql.contains("J.ANYDATA_VALUE"));+ }+ for query in native_job_reference_queries(NativeJobEngine::Dameng, &input).unwrap() {+ assert!(!query.sql.contains("GetTypeName()"));+ }+ let credentials =+ native_job_reference_queries(NativeJobEngine::Oracle, &request(NativeJobReferenceKind::Credential)).unwrap();+ assert_eq!(credentials[0].source, "SYS.DBA_CREDENTIALS");+ assert!(!credentials[0].sql.contains("J.*"));+ assert!(!credentials[0].sql.contains("USERNAME"));+}++#[test]+fn oceanbase_placeholder_argument_views_do_not_authorize_an_empty_argument_list() {+ let mut input = request(NativeJobReferenceKind::ProgramArguments);+ input.schema = Some("Another Owner".into());+ input.name = Some("Program".into());+ let queries = native_job_reference_queries(NativeJobEngine::OceanbaseOracle, &input).unwrap();+ assert!(queries.is_empty());+ let target = NativeJobRef::Scheduler { scope: input.scope, owner: "Owner".into(), name: "Job".into() };+ assert!(dbx_sql_schema::native_jobs::native_job_catalog_queries(+ NativeJobEngine::OceanbaseOracle,+ &target,+ dbx_sql_schema::native_jobs::NativeJobCatalogPart::Arguments,+ )+ .unwrap()+ .is_empty());+ assert!(native_job_reference_queries(NativeJobEngine::Dameng, &request(NativeJobReferenceKind::Chain))+ .unwrap()+ .is_empty());+}++#[test]+fn oceanbase_programs_use_the_documented_native_singular_view_not_oracle_names() {+ let input = request(NativeJobReferenceKind::Program);+ let queries = native_job_reference_queries(NativeJobEngine::OceanbaseOracle, &input).unwrap();+ assert_eq!(queries.len(), 1);+ assert_eq!(queries[0].source, "SYS.DBA_SCHEDULER_PROGRAM");+ assert_eq!(queries[0].coverage, NativeJobCatalogCoverage::Database);+ assert!(queries[0].sql.contains("J.OWNER AS DBX_OWNER"));+ assert!(queries[0].sql.contains("J.PROGRAM_NAME AS DBX_NAME"));+ assert!(!queries[0].sql.contains("SCHEDULER_PROGRAMS"));+}++#[test]+fn oracle_reference_categories_keep_their_native_sources_names_and_group_filters() {+ for (kind, source, name_column, group_filter, count) in [+ ("window", "SYS.DBA_SCHEDULER_WINDOWS", "WINDOW_NAME", None, 2),+ ("window-group", "SYS.DBA_SCHEDULER_GROUPS", "GROUP_NAME", Some("J.GROUP_TYPE = 'WINDOW'"), 3),+ ("file-watcher", "SYS.DBA_SCHEDULER_FILE_WATCHERS", "FILE_WATCHER_NAME", None, 3),+ (+ "destination-group",+ "SYS.DBA_SCHEDULER_GROUPS",+ "GROUP_NAME",+ Some("J.GROUP_TYPE IN ('DB_DEST', 'EXTERNAL_DEST')"),+ 3,+ ),+ ] {+ let mut input = request(serde_json::from_value(serde_json::json!(kind)).unwrap());+ input.schema = Some("Own.er".into());+ input.name = Some("Exact,Name's".into());+ let queries = native_job_reference_queries(NativeJobEngine::Oracle, &input).unwrap();+ assert_eq!(queries.len(), count);+ assert_eq!(queries[0].source, source);+ assert!(queries[0].sql.contains("J.OWNER = 'Own.er'"));+ assert!(queries[0].sql.contains(&format!("J.{name_column} = 'Exact,Name''s'")));+ if let Some(filter) = group_filter {+ assert!(queries.iter().all(|query| query.sql.contains(filter)));+ }+ if count == 3 {+ assert!(queries[2].sql.contains("USER AS DBX_OWNER"));+ assert!(!queries[2].sql.contains("J.OWNER"));+ }+ for engine in [NativeJobEngine::OceanbaseOracle, NativeJobEngine::Dameng] {+ assert!(native_job_reference_queries(engine, &input).unwrap().is_empty());+ }+ }+}++#[test]+fn oracle_unified_destination_view_is_reused_without_reading_connection_details() {+ let queries =+ native_job_reference_queries(NativeJobEngine::Oracle, &request(NativeJobReferenceKind::Destination)).unwrap();+ assert_eq!(queries.len(), 3);+ assert_eq!(queries[0].source, "SYS.DBA_SCHEDULER_DESTS");+ assert!(!queries[0].sql.contains("SCHEDULER_DB_DESTS"));+ assert!(!queries[0].sql.contains("CONNECT_INFO"));+}diff --git a/crates/dbx-sql-schema/tests/native_job_scheduler_creation.rs b/crates/dbx-sql-schema/tests/native_job_scheduler_creation.rsnew file mode 100644index 0000000000..d63e5a3709--- /dev/null+++ b/crates/dbx-sql-schema/tests/native_job_scheduler_creation.rs@@ -0,0 +1,356 @@+use dbx_sql_schema::native_job_changes::{native_job_scheduler_create_plan, NativeJobStepEffect};+use dbx_types::native_jobs::*;+use serde_json::json;++fn scope() -> NativeJobScope {+ NativeJobScope { connection_id: "c".into(), database: "".into(), context_id: "ctx".into() }+}++fn definition() -> NativeJobSchedulerCreate {+ serde_json::from_value(json!({"owner":"Ow\"ner", "name":" Job,'Exact ", "jobType":"STORED_PROCEDURE", "jobAction":"private_call", "numberOfArguments":2, "enabled":true, "autoDrop":false})).unwrap()+}++#[test]+fn only_ob_explicit_create_dates_convert_to_the_executing_session_before_naive_parameters() {+ for engine in [NativeJobEngine::Oracle, NativeJobEngine::OceanbaseOracle, NativeJobEngine::Dameng] {+ for named in [false, true] {+ let mut input = definition();+ input.enabled = false;+ input.start_date = Some("2026-10-21T16:54:25.656000000Z".into());+ input.end_date = Some("2026-10-22T01:02:03.123456000-03:30".into());+ if named {+ input.program = Some(NativeJobObjectReference { owner: input.owner.clone(), name: "Program".into() });+ input.job_type = None;+ input.job_action = None;+ input.number_of_arguments = 0;+ }+ let plan = native_job_scheduler_create_plan(engine, &scope(), &input, None).unwrap();+ let sql = &plan.steps[0].sql;+ for (parameter, value) in [+ ("start_date", "2026-10-21 16:54:25.656000000 +00:00"),+ ("end_date", "2026-10-22 01:02:03.123456000 -03:30"),+ ] {+ let typed = format!("TO_TIMESTAMP_TZ('{value}', 'YYYY-MM-DD HH24:MI:SS.FF TZH:TZM')");+ let expected = if engine == NativeJobEngine::OceanbaseOracle {+ format!("CAST({typed} AT TIME ZONE SESSIONTIMEZONE AS TIMESTAMP(9))")+ } else {+ typed+ };+ assert!(sql.contains(&format!("{parameter} => {expected}")), "{sql}");+ }+ assert!(!sql.contains("ALTER SESSION"));+ input.start_date = None;+ input.end_date = None;+ let omitted = native_job_scheduler_create_plan(engine, &scope(), &input, None).unwrap();+ assert!(!omitted.steps[0].sql.contains("AT TIME ZONE"));+ assert!(!omitted.steps[0].sql.contains("start_date =>"));+ input.start_date = Some("2026-10-21 16:54:25".into());+ assert!(native_job_scheduler_create_plan(engine, &scope(), &input, None).is_err());+ }+ }+}++#[test]+fn ob_create_rejects_only_non_microsecond_aligned_dates_before_returning_either_overload() {+ for named in [false, true] {+ for end in [false, true] {+ for fraction in ["123456789", "987654321", "999999999", "123456001", "12345601", "1234561", "000000001"] {+ let mut input = definition();+ input.start_date = Some("2032-01-01T23:54:25.123456000Z".into());+ input.end_date = Some("2032-01-02T00:04:25.987654000Z".into());+ let date = Some(format!("2032-01-02T00:04:25.{fraction}Z"));+ if end {+ input.end_date = date;+ } else {+ input.start_date = date;+ }+ if named {+ input.program =+ Some(NativeJobObjectReference { owner: input.owner.clone(), name: "Program".into() });+ input.job_type = None;+ input.job_action = None;+ input.number_of_arguments = 0;+ }+ assert_eq!(+ native_job_scheduler_create_plan(NativeJobEngine::OceanbaseOracle, &scope(), &input, None).err(),+ Some("native_job_timestamp_precision_microseconds")+ );+ for engine in [NativeJobEngine::Oracle, NativeJobEngine::Dameng] {+ assert!(native_job_scheduler_create_plan(engine, &scope(), &input, None).is_ok());+ }+ }+ }+ for value in [+ "2032-01-01T23:54:25Z",+ "2032-01-01T23:54:25.1Z",+ "2032-01-01T23:54:25.123456Z",+ "2032-01-01T23:54:25.123456000Z",+ ] {+ let mut input = definition();+ input.start_date = Some(value.into());+ input.end_date = Some("2032-01-02T00:04:25.987654000Z".into());+ if named {+ input.program = Some(NativeJobObjectReference { owner: input.owner.clone(), name: "Program".into() });+ input.job_type = None;+ input.job_action = None;+ input.number_of_arguments = 0;+ }+ assert!(native_job_scheduler_create_plan(NativeJobEngine::OceanbaseOracle, &scope(), &input, None).is_ok());+ }+ }+}++#[test]+fn all_typed_character_inputs_are_validated_before_disabled_creation() {+ let mut input = definition();+ input.arguments = vec![NativeJobCreateArgument {+ position: 1,+ data_type: "NVARCHAR2".into(),+ value: NativeJobArgumentValue::Value {+ value: json!({"$dbx":"oracle-anydata-v1","scalarType":"nvarchar2","value":"中文\\😀 "}),+ },+ }];+ let plan = native_job_scheduler_create_plan(NativeJobEngine::Oracle, &scope(), &input, None).unwrap();+ assert_eq!(plan.steps[0].id, "validate-argument:1");+ assert!(matches!(plan.steps[0].effect, NativeJobStepEffect::ArgumentValidated));+ assert!(!plan.steps[0].sql.contains("DBMS_SCHEDULER"));+ assert_eq!(plan.steps[1].id, "create");+ let setter = plan.steps.iter().find(|step| step.id == "argument:1").unwrap();+ assert!(setter.sql.contains("UNISTR('\\4E2D\\6587\\\\\\D83D\\DE00\\0020')"));+ assert!(setter.sql.contains("STRING_TO_RAW"));+ assert!(+ setter.sql.find("native_job_argument_character_loss").unwrap()+ < setter.sql.find("SET_JOB_ANYDATA_VALUE").unwrap()+ );+}++#[test]+fn lightweight_creation_rejects_anydata_before_returning_a_create_plan() {+ let mut input = definition();+ input.job_type = None;+ input.job_action = None;+ input.number_of_arguments = 0;+ input.program = Some(NativeJobObjectReference { owner: "Owner".into(), name: "Program".into() });+ input.job_style = Some("LIGHTWEIGHT".into());+ for value in [+ NativeJobArgumentValue::Null,+ NativeJobArgumentValue::Value { value: json!("") },+ NativeJobArgumentValue::Value {+ value: json!({"$dbx":"oracle-anydata-v1","typeName":"SYS.NUMBER","value":"1"}),+ },+ ] {+ input.arguments = vec![NativeJobCreateArgument { position: 1, data_type: "NUMBER".into(), value }];+ assert!(matches!(+ native_job_scheduler_create_plan(NativeJobEngine::Oracle, &scope(), &input, None),+ Err("native_job_lightweight_anydata_unsupported")+ ));+ }+ input.arguments[0].value = NativeJobArgumentValue::Value { value: json!("123") };+ let plan = native_job_scheduler_create_plan(NativeJobEngine::Oracle, &scope(), &input, None).unwrap();+ assert!(plan.steps.iter().any(|step| step.sql.contains("SET_JOB_ARGUMENT_VALUE")));+ assert!(plan.steps.iter().all(|step| !step.sql.contains("SET_JOB_ANYDATA_VALUE")));+}++#[test]+fn initial_creation_is_disabled_and_complete_configuration_precedes_activation() {+ let mut input = definition();+ input.start_date = Some("2030-01-01T10:20:30.123+08:00".into());+ input.repeat_interval = Some("FREQ=DAILY;BYHOUR=8".into());+ input.comments = Some("owner's comment".into());+ input.attributes = vec![NativeJobAttributeChange {+ name: "LOGGING_LEVEL".into(),+ change: NativeJobFieldChange::Set { value: json!("FULL") },+ }];+ input.arguments = vec![NativeJobCreateArgument {+ position: 1,+ data_type: "VARCHAR2".into(),+ value: NativeJobArgumentValue::Value { value: json!("value's text") },+ }];+ let plan = native_job_scheduler_create_plan(NativeJobEngine::Oracle, &scope(), &input, None).unwrap();+ assert_eq!(+ plan.steps.iter().map(|step| step.id.as_str()).collect::<Vec<_>>(),+ ["create", "attributes", "argument:1", "enable"]+ );+ assert!(matches!(plan.steps[0].effect, NativeJobStepEffect::Created));+ let sql = &plan.steps[0].sql;+ assert!(sql.contains("job_name => '\"Ow\"\"ner\".\" Job,''Exact \"'"));+ assert!(sql.contains("enabled => FALSE"));+ assert!(sql.contains("auto_drop => FALSE"));+ assert!(sql.contains("TO_TIMESTAMP_TZ('2030-01-01 10:20:30.123 +08:00', 'YYYY-MM-DD HH24:MI:SS.FF TZH:TZM')"));+ assert!(sql.contains("comments => 'owner''s comment'"));+ assert!(plan.steps[1].sql.contains("LOGGING_FULL"));+ assert!(plan.steps[2].sql.contains("argument_value => 'value''s text'"));+ assert!(matches!(plan.steps.last().unwrap().effect, NativeJobStepEffect::Enabled(true)));+ assert!(plan.steps.iter().all(|step| !step.sql.contains("RUN_JOB") && !step.sql.contains("DROP_JOB")));+}++#[test]+fn named_program_and_schedule_overloads_do_not_send_conflicting_inline_fields() {+ for engine in [NativeJobEngine::Oracle, NativeJobEngine::Dameng] {+ for use_program in [false, true] {+ for use_schedule in [false, true] {+ let mut input = definition();+ input.enabled = false;+ if use_program {+ input.job_type = None;+ input.job_action = None;+ input.number_of_arguments = 0;+ input.program =+ Some(NativeJobObjectReference { owner: "Other.Owner".into(), name: "Program\"Name".into() });+ input.job_style = Some("REGULAR".into());+ }+ if use_schedule {+ input.schedule =+ Some(NativeJobObjectReference { owner: "CalendarOwner".into(), name: "Calendar.Name".into() });+ }+ let plan = native_job_scheduler_create_plan(engine, &scope(), &input, None).unwrap();+ let sql = &plan.steps[0].sql;+ assert_eq!(plan.steps.len(), 1);+ assert_eq!(sql.contains("program_name =>"), use_program);+ assert_eq!(sql.contains("job_action =>"), !use_program);+ assert_eq!(sql.contains("number_of_arguments =>"), !use_program);+ assert_eq!(sql.contains("schedule_name =>"), use_schedule);+ if use_program {+ assert!(sql.contains("'\"Other.Owner\".\"Program\"\"Name\"'"));+ }+ if use_schedule {+ assert!(!sql.contains("repeat_interval =>") && !sql.contains("start_date =>"));+ }+ }+ }+ }+}++#[test]+fn ob_uses_its_singular_parameter_and_literal_job_name_and_resolves_only_its_own_guard() {+ let mut input = definition();+ input.job_action = Some("private_call(':dbx_created_job_id')".into());+ let preview = native_job_scheduler_create_plan(NativeJobEngine::OceanbaseOracle, &scope(), &input, None).unwrap();+ assert!(preview.steps[0].sql.contains("job_name => ' Job,''Exact '"));+ assert!(preview.steps[0].sql.contains("number_of_argument => 2"));+ assert!(!preview.steps[0].sql.contains("number_of_arguments =>"));+ assert!(preview.steps.last().unwrap().sql.contains("JOB = :dbx_created_job_id"));+ let identity = NativeJobRow::from([("DBX_JOB_ID".into(), json!("900719925474099312345"))]);+ let applied =+ native_job_scheduler_create_plan(NativeJobEngine::OceanbaseOracle, &scope(), &input, Some(&identity)).unwrap();+ assert!(applied.steps.last().unwrap().sql.contains("JOB = 900719925474099312345"));+ assert!(!applied.steps.last().unwrap().sql.contains(":dbx_created_job_id"));+ assert_eq!(applied.steps[0].sql, preview.steps[0].sql, "the native body is never changed by guard binding");+}++#[test]+fn creation_preserves_unset_and_inherited_arguments_and_uses_typed_null_without_activating() {+ let mut input = definition();+ input.enabled = false;+ input.number_of_arguments = 3;+ input.arguments = vec![+ NativeJobCreateArgument { position: 1, data_type: "VARCHAR2".into(), value: NativeJobArgumentValue::Unset },+ NativeJobCreateArgument { position: 2, data_type: "VARCHAR2".into(), value: NativeJobArgumentValue::Inherit },+ NativeJobCreateArgument { position: 3, data_type: "NUMBER".into(), value: NativeJobArgumentValue::Null },+ ];+ let plan = native_job_scheduler_create_plan(NativeJobEngine::Oracle, &scope(), &input, None).unwrap();+ assert_eq!(plan.steps.len(), 2);+ assert!(plan.steps[1].sql.contains("argument_position => 3"));+ assert!(plan.steps[1].sql.contains("ConvertNumber(CAST(NULL AS NUMBER))"));+ assert!(!plan.steps[1].sql.contains("RESET_JOB_ARGUMENT_VALUE"));+}++#[test]+fn event_overload_supplies_required_nulls_for_a_named_program() {+ let mut input = definition();+ input.program = Some(NativeJobObjectReference { owner: "Owner".into(), name: "Program".into() });+ input.job_type = None;+ input.job_action = None;+ input.number_of_arguments = 0;+ input.event_source = Some(NativeJobEventSource::Queue {+ owner: "QueueOwner".into(),+ name: "Events".into(),+ agent: Some("Agent".into()),+ });+ let plan = native_job_scheduler_create_plan(NativeJobEngine::Oracle, &scope(), &input, None).unwrap();+ let sql = &plan.steps[0].sql;+ assert!(sql.contains("queue_spec => '\"QueueOwner\".\"Events\",\"Agent\"'"));+ for parameter in ["start_date => NULL", "end_date => NULL", "event_condition => NULL"] {+ assert!(sql.contains(parameter));+ }+ input.job_style = Some("LIGHTWEIGHT".into());+ assert!(matches!(+ native_job_scheduler_create_plan(NativeJobEngine::Oracle, &scope(), &input, None),+ Err("native_job_style_not_applicable_to_event")+ ));+}++#[test]+fn invalid_conflicting_or_duplicate_creation_inputs_fail_before_any_plan_is_returned() {+ let original = definition();+ let mut inputs = Vec::new();+ let mut input = original.clone();+ input.program = Some(NativeJobObjectReference { owner: "Owner".into(), name: "Program".into() });+ inputs.push(input);+ let mut input = original.clone();+ input.schedule = Some(NativeJobObjectReference { owner: "Owner".into(), name: "Schedule".into() });+ input.repeat_interval = Some("FREQ=DAILY".into());+ inputs.push(input);+ let mut input = original.clone();+ input.name.clear();+ inputs.push(input);+ let mut input = original.clone();+ input.number_of_arguments = 256;+ inputs.push(input);+ let mut input = original.clone();+ input.start_date = Some("2030-01-01 00:00:00".into());+ inputs.push(input);+ let mut input = original.clone();+ input.attributes = vec![NativeJobAttributeChange {+ name: "ENABLED".into(),+ change: NativeJobFieldChange::Set { value: json!(true) },+ }];+ inputs.push(input);+ let mut input = original.clone();+ input.arguments = vec![NativeJobCreateArgument {+ position: 3,+ data_type: "VARCHAR2".into(),+ value: NativeJobArgumentValue::Null,+ }];+ inputs.push(input);+ let mut input = original;+ input.job_type = Some("PLSQL_BLOCK".into());+ inputs.push(input);+ for input in inputs {+ assert!(native_job_scheduler_create_plan(NativeJobEngine::Oracle, &scope(), &input, None).is_err());+ }+}++#[test]+fn ob_creation_enforces_its_native_argument_limit_and_rejects_unavailable_overloads() {+ let mut input = definition();+ input.number_of_arguments = 256;+ assert!(matches!(+ native_job_scheduler_create_plan(NativeJobEngine::OceanbaseOracle, &scope(), &input, None),+ Err("native_job_argument_count_invalid")+ ));+ input.number_of_arguments = 0;+ for job_type in ["CHAIN", "EXECUTABLE", "EXTERNAL_SCRIPT", "SQL_SCRIPT", "BACKUP_SCRIPT"] {+ input.job_type = Some(job_type.into());+ assert!(+ native_job_scheduler_create_plan(NativeJobEngine::OceanbaseOracle, &scope(), &input, None).is_err(),+ "{job_type}"+ );+ }+ input.job_type = Some("PLSQL_BLOCK".into());+ assert!(native_job_scheduler_create_plan(NativeJobEngine::OceanbaseOracle, &scope(), &input, None).is_ok());+ for field in ["schedule", "credential", "destination"] {+ let mut unsupported = input.clone();+ match field {+ "schedule" => {+ unsupported.schedule = Some(NativeJobObjectReference { owner: "Owner".into(), name: "Schedule".into() })+ }+ "credential" => unsupported.credential_name = Some("Credential".into()),+ _ => unsupported.destination_name = Some("Destination".into()),+ }+ assert!(+ native_job_scheduler_create_plan(NativeJobEngine::OceanbaseOracle, &scope(), &unsupported, None).is_err(),+ "{field}"+ );+ }+}diff --git a/crates/dbx-sql-schema/tests/native_job_scheduler_transitions.rs b/crates/dbx-sql-schema/tests/native_job_scheduler_transitions.rsnew file mode 100644index 0000000000..efd1ff9329--- /dev/null+++ b/crates/dbx-sql-schema/tests/native_job_scheduler_transitions.rs@@ -0,0 +1,491 @@+use dbx_sql_schema::native_job_changes::{native_job_scheduler_edit_plan, NativeJobStepEffect};+use dbx_types::native_jobs::*;+use serde_json::{json, Value};++fn details() -> NativeJobDetails {+ serde_json::from_value(json!({+ "snapshot":{"ref":{"kind":"scheduler","owner":"Owner","name":"Job's,Exact","scope":{"connectionId":"c","database":"","contextId":"ctx"}},"revision":"baseline",+ "definition":{"status":"available","value":{"OWNER":"Owner","JOB_NAME":"Job's,Exact","PROGRAM_OWNER":"Old.Owner","PROGRAM_NAME":"Old.Program","JOB_TYPE":null,"JOB_ACTION":null,"NUMBER_OF_ARGUMENTS":null,"SCHEDULE_OWNER":null,"SCHEDULE_NAME":null,"SCHEDULE_TYPE":"CALENDAR","START_DATE":"2030-01-01T00:00:00+08:00","END_DATE":null,"REPEAT_INTERVAL":"FREQ=DAILY","ENABLED":"TRUE","COMMENTS":"untouched","CREDENTIAL_OWNER":null,"CREDENTIAL_NAME":null,"CONNECT_CREDENTIAL_OWNER":null,"CONNECT_CREDENTIAL_NAME":null,"DESTINATION_OWNER":null,"DESTINATION":null,"JOB_STYLE":"REGULAR","EVENT_CONDITION":null,"EVENT_QUEUE_OWNER":null,"EVENT_QUEUE_NAME":null,"EVENT_QUEUE_AGENT":null,"FILE_WATCHER_OWNER":null,"FILE_WATCHER_NAME":null}},+ "arguments":{"status":"available","value":[]}},+ "nativeIdentity":{"status":"available","value":{"DBX_JOB_ID":"42","DBX_CREATED_AT":"creation"}},"consistency":{"status":"available","value":null},"parameterMetadata":{"status":"empty"},"steps":{"status":"empty"},"schedules":{"status":"empty"},"running":{"status":"empty"},"history":{"status":"empty"},"sources":{}+ })).unwrap()+}++fn request(details: &NativeJobDetails, attributes: Value, argument_target: Value) -> NativeJobMutation {+ serde_json::from_value(json!({"target":details.snapshot.job_ref,"baseline":"baseline","action":"update","attributes":attributes,"arguments":[],"argumentTarget":argument_target})).unwrap()+}++#[test]+fn dameng_named_schedule_replacement_does_not_clear_oracle_inline_or_event_fields() {+ let mut data = details();+ let NativeJobMetadata::Available { value } = &mut data.snapshot.definition else { unreachable!() };+ value.insert("SCHEDULE_OWNER".into(), json!("Old.Owner"));+ value.insert("SCHEDULE_NAME".into(), json!("Old.Schedule"));+ value.insert("SCHEDULE_TYPE".into(), json!("NAMED"));+ let mutation = request(+ &data,+ json!([{"name":"SCHEDULE_NAME","change":{"kind":"set","value":{"owner":"New.Owner","name":"New.Schedule"}}}]),+ Value::Null,+ );+ let plan = native_job_scheduler_edit_plan(NativeJobEngine::Dameng, &mutation, &data).unwrap();+ let sql = plan.sql.steps.iter().map(|step| step.sql.as_str()).collect::<Vec<_>>().join("\n");+ assert!(sql.contains("'schedule_name'"));+ for attribute in ["'event_spec'", "'start_date'", "'end_date'", "'repeat_interval'"] {+ assert!(!sql.contains(attribute), "unexpected Oracle clear: {attribute}");+ }+}++#[test]+fn dameng_inline_reference_changes_do_not_assume_an_unproven_null_transition() {+ let mut data = details();+ let NativeJobMetadata::Available { value } = &mut data.snapshot.definition else { unreachable!() };+ value.insert("PROGRAM_OWNER".into(), Value::Null);+ value.insert("PROGRAM_NAME".into(), Value::Null);+ value.insert("JOB_TYPE".into(), json!("STORED_PROCEDURE"));+ value.insert("JOB_ACTION".into(), json!("proc"));+ value.insert("NUMBER_OF_ARGUMENTS".into(), json!(0));+ let reference = json!({"owner":"New.Owner","name":"New.Program"});+ let mutation = request(+ &data,+ json!([{"name":"PROGRAM_NAME","change":{"kind":"set","value":reference}}]),+ json!({"program":reference,"arguments":[]}),+ );+ assert!(matches!(+ native_job_scheduler_edit_plan(NativeJobEngine::Dameng, &mutation, &data),+ Err("native_job_reference_attach_mapping_unverified")+ ));+}++#[test]+fn dameng_parameter_reset_is_not_serialized_as_an_oracle_package_call() {+ let data = details();+ for value in [NativeJobArgumentValue::Unset, NativeJobArgumentValue::Inherit] {+ let change = NativeJobArgumentChange { position: 1, value };+ assert!(matches!(+ dbx_sql_schema::native_job_changes::scheduler_argument_step(+ NativeJobEngine::Dameng,+ &data.snapshot.job_ref,+ None,+ &change,+ "VARCHAR2"+ ),+ Err("native_job_argument_reset_mapping_unverified")+ ));+ }+}++#[test]+fn dameng_full_inheritance_target_is_a_postcondition_not_a_fabricated_reset() {+ let mut data = details();+ let target = json!({"program":{"owner":"Old.Owner","name":"Old.Program"},"arguments":[{"position":1,"dataType":"VARCHAR2","value":{"kind":"inherit"}}]});+ for metadata in [NativeJobMetadata::Empty, NativeJobMetadata::Available { value: vec![] }] {+ data.parameter_metadata = metadata;+ let plan =+ native_job_scheduler_edit_plan(NativeJobEngine::Dameng, &request(&data, json!([]), target.clone()), &data)+ .unwrap();+ assert!(!plan.sql.steps.iter().any(|step| step.sql.contains("RESET_JOB_ARGUMENT_VALUE")));+ assert!(plan.argument_target.is_some());+ }+ data.parameter_metadata =+ NativeJobMetadata::Available { value: vec![serde_json::from_value(json!({"ARGUMENT_POSITION":1})).unwrap()] };+ assert!(matches!(+ native_job_scheduler_edit_plan(NativeJobEngine::Dameng, &request(&data, json!([]), target), &data),+ Err("native_job_argument_reset_mapping_unverified")+ ));+ let changed = json!({"owner":"New.Owner","name":"New.Program"});+ let plan = native_job_scheduler_edit_plan(+ NativeJobEngine::Dameng,+ &request(+ &data,+ json!([{"name":"PROGRAM_NAME","change":{"kind":"set","value":changed}}]),+ json!({"program":changed,"arguments":[{"position":1,"dataType":"VARCHAR2","value":{"kind":"inherit"}}]}),+ ),+ &data,+ )+ .unwrap();+ assert!(!plan.sql.steps.iter().any(|step| step.sql.contains("RESET_JOB_ARGUMENT_VALUE")));+}++#[test]+fn typed_number_uses_anydata_but_legacy_strings_keep_the_string_setter() {+ use dbx_sql_schema::native_job_changes::scheduler_argument_step;+ use dbx_sql_schema::native_jobs::NativeJobCatalogDialect;+ let data = details();+ let number = json!({"$dbx":"oracle-anydata-v1","typeName":"SYS.NUMBER","value":"9007199254740993.123"});+ let change = NativeJobArgumentChange { position: 1, value: NativeJobArgumentValue::Value { value: number } };+ let step =+ scheduler_argument_step(NativeJobCatalogDialect::Oracle, &data.snapshot.job_ref, None, &change, "NUMBER")+ .unwrap();+ assert!(step.sql.contains("SET_JOB_ANYDATA_VALUE"));+ assert!(step.sql.contains("SYS.ANYDATA.ConvertNumber(9.007199254740993123E15)"));+ let NativeJobStepEffect::Argument(expected, _) = step.effect else { panic!("argument effect required") };+ assert_eq!(serde_json::to_value(expected.value).unwrap()["value"]["value"], "9.007199254740993123E15");+ let legacy = NativeJobArgumentChange {+ position: 1,+ value: NativeJobArgumentValue::Value { value: json!("9007199254740993.123") },+ };+ let step =+ scheduler_argument_step(NativeJobCatalogDialect::Oracle, &data.snapshot.job_ref, None, &legacy, "NUMBER")+ .unwrap();+ assert!(step.sql.contains("SET_JOB_ARGUMENT_VALUE"));+ assert!(!step.sql.contains("ConvertNumber"));+ for dialect in [NativeJobCatalogDialect::Dameng, NativeJobCatalogDialect::OceanbaseOracle] {+ assert!(scheduler_argument_step(dialect, &data.snapshot.job_ref, None, &change, "NUMBER").is_err());+ }+}++#[test]+fn typed_char_null_survives_delta_and_program_conversion_without_becoming_varchar_null() {+ let mut data = details();+ let value = json!({"kind":"value","value":{"$dbx":"oracle-anydata-v1","scalarType":"char","value":null}});+ data.snapshot.arguments = serde_json::from_value(+ json!({"status":"available","value":[{"position":1,"dataType":"VARCHAR2","value":value,"editable":true}]}),+ )+ .unwrap();+ let mut delta = request(&data, json!([]), Value::Null);+ let NativeJobChange::Update { arguments, .. } = &mut delta.change else { unreachable!() };+ arguments.push(serde_json::from_value(json!({"position":1,"value":value})).unwrap());+ let plan = native_job_scheduler_edit_plan(NativeJobEngine::Oracle, &delta, &data).unwrap();+ let step = plan.sql.steps.iter().find(|step| matches!(step.effect, NativeJobStepEffect::Argument(..))).unwrap();+ assert!(step.sql.contains("ConvertChar(CAST(NULL AS CHAR(1)))"));+ assert!(!step.sql.contains("l_anydata := SYS.ANYDATA.ConvertVarchar2"));+ let transition = request(+ &data,+ json!([{"name":"PROGRAM_NAME","change":{"kind":"set","value":{"owner":"Other","name":"Target"}}}]),+ json!({"program":{"owner":"Other","name":"Target"},"arguments":[{"position":1,"dataType":"VARCHAR2","value":value}]}),+ );+ let plan = native_job_scheduler_edit_plan(NativeJobEngine::Oracle, &transition, &data).unwrap();+ let NativeJobStepEffect::ArgumentValidated = plan.sql.steps[0].effect else {+ panic!("preflight must precede pause")+ };+ assert!(plan.sql.steps.iter().any(|step| matches!(step.effect, NativeJobStepEffect::Argument(..))+ && step.sql.contains("ConvertChar(CAST(NULL AS CHAR(1)))")));+}++#[test]+fn lightweight_arguments_are_rejected_before_delta_or_transition_can_pause() {+ let mut data = details();+ let NativeJobMetadata::Available { value } = &mut data.snapshot.definition else { unreachable!() };+ value.insert("JOB_STYLE".into(), json!("LIGHTWEIGHT"));+ data.snapshot.arguments = serde_json::from_value(json!({"status":"available","value":[{"position":1,"dataType":"NUMBER","value":{"kind":"unset"},"editable":true}]})).unwrap();+ for value in [+ json!({"kind":"null"}),+ json!({"kind":"value","value":""}),+ json!({"kind":"value","value":{"$dbx":"oracle-anydata-v1","typeName":"SYS.NUMBER","value":"1"}}),+ ] {+ let mut delta = request(&data, json!([]), Value::Null);+ let NativeJobChange::Update { arguments, .. } = &mut delta.change else { unreachable!() };+ arguments.push(serde_json::from_value(json!({"position":1,"value":value})).unwrap());+ assert!(matches!(+ dbx_sql_schema::native_job_changes::native_job_mutation_plan(NativeJobEngine::Oracle, &delta, &data),+ Err("native_job_lightweight_anydata_unsupported")+ ));+ let transition = request(+ &data,+ json!([]),+ json!({"program":{"owner":"Old.Owner","name":"Old.Program"},"arguments":[{"position":1,"dataType":"NUMBER","value":value}]}),+ );+ assert!(matches!(+ native_job_scheduler_edit_plan(NativeJobEngine::Oracle, &transition, &data),+ Err("native_job_lightweight_anydata_unsupported")+ ));+ }+}++#[test]+fn a_program_switch_is_paused_and_checks_native_columns_not_a_json_name() {+ let data = details();+ let target = json!({"owner":"New.Owner","name":"P,'\"Q"});+ let mutation = request(+ &data,+ json!([{"name":"PROGRAM_NAME","change":{"kind":"set","value":target}}]),+ json!({"program":target,"arguments":[]}),+ );+ let plan = native_job_scheduler_edit_plan(NativeJobEngine::Oracle, &mutation, &data).unwrap();+ assert!(plan.transition);+ assert!(plan.final_enabled);+ assert_eq!(plan.sql.steps[0].id, "pause");+ let definition = &plan.sql.steps[1];+ assert!(definition.sql.contains("SET_JOB_ATTRIBUTES"));+ assert!(definition.sql.contains("TRANSACTIONAL"));+ assert!(definition.sql.contains("\"New.Owner\".\"P,''\"\"Q\""));+ assert!(!definition.sql.contains("CREATE_JOB"));+ let NativeJobStepEffect::SchedulerDefinition(effect) = &definition.effect else {+ panic!("native projection missing")+ };+ assert!(effect.columns.iter().any(|column| column.name == "PROGRAM_OWNER"+ && column.change == NativeJobFieldChange::Set { value: json!("New.Owner") }));+ for column in ["JOB_TYPE", "JOB_ACTION", "NUMBER_OF_ARGUMENTS"] {+ assert!(effect+ .columns+ .iter()+ .any(|change| change.name == column && change.change == NativeJobFieldChange::Clear));+ }+ assert_eq!(plan.sql.steps.last().unwrap().id, "enable");+}++#[test]+fn inline_conversion_clears_the_reference_in_the_same_definition_batch() {+ let data = details();+ let mutation = request(+ &data,+ json!([+ {"name":"PROGRAM_NAME","change":{"kind":"clear"}},+ {"name":"JOB_TYPE","change":{"kind":"set","value":"STORED_PROCEDURE"}},+ {"name":"JOB_ACTION","change":{"kind":"set","value":"proc_new"}},+ {"name":"NUMBER_OF_ARGUMENTS","change":{"kind":"set","value":2}}+ ]),+ json!({"program":null,"arguments":[{"position":1,"dataType":"VARCHAR2","value":{"kind":"unset"}},{"position":2,"dataType":"NUMBER","value":{"kind":"null"}}]}),+ );+ let plan = native_job_scheduler_edit_plan(NativeJobEngine::Oracle, &mutation, &data).unwrap();+ assert!(plan.context_changed);+ let definition = &plan.sql.steps[1];+ assert!(definition.sql.contains("'program_name')"));+ assert!(definition.sql.contains("'job_type', 'STORED_PROCEDURE'"));+ assert!(definition.sql.contains("'number_of_arguments', 2"));+ assert!(plan.sql.steps.iter().any(|step| step.sql.contains("ConvertNumber(CAST(NULL AS NUMBER))")));+}++#[test]+fn an_identical_structured_reference_does_not_add_new_read_or_pause_requirements() {+ let data = details();+ let mutation = request(+ &data,+ json!([+ {"name":"PROGRAM_NAME","change":{"kind":"set","value":{"owner":"Old.Owner","name":"Old.Program"}}},+ {"name":"COMMENTS","change":{"kind":"set","value":"new"}}+ ]),+ Value::Null,+ );+ let plan = native_job_scheduler_edit_plan(NativeJobEngine::Oracle, &mutation, &data).unwrap();+ assert!(!plan.transition);+ assert!(plan.references.is_empty());+ assert_eq!(plan.sql.steps.len(), 1);+ assert!(!plan.sql.steps[0].sql.contains("DISABLE"));+}++#[test]+fn schedule_categories_and_event_spec_keep_their_real_native_contracts() {+ let data = details();+ let mutation = request(+ &data,+ json!([{"name":"SCHEDULE_NAME","change":{"kind":"set","value":{"owner":"SYS","name":"Night,Window","kind":"window"}}}]),+ Value::Null,+ );+ let plan = native_job_scheduler_edit_plan(NativeJobEngine::Oracle, &mutation, &data).unwrap();+ assert_eq!(plan.references[0].target.kind, NativeJobReferenceKind::Window);+ assert!(plan.sql.steps[1].sql.contains("'repeat_interval')"));+ let mutation = request(+ &data,+ json!([{"name":"EVENT_SPEC","change":{"kind":"set","value":{"condition":"tab.user_data.flag = 'Y'","source":{"kind":"queue","owner":"AQ.Owner","name":"Q,1","agent":"Agent.One"}}}}]),+ Value::Null,+ );+ let plan = native_job_scheduler_edit_plan(NativeJobEngine::Oracle, &mutation, &data).unwrap();+ assert!(plan.transition);+ assert!(plan.sql.steps[1]+ .sql+ .contains("'event_spec', 'tab.user_data.flag = ''Y''', '\"AQ.Owner\".\"Q,1\",\"Agent.One\"'"));+}++#[test]+fn unsupported_ob_transitions_and_incomplete_argument_intent_fail_before_a_pause_exists() {+ let data = details();+ let attrs = json!([{"name":"PROGRAM_NAME","change":{"kind":"set","value":{"owner":"New.Owner","name":"New"}}}]);+ let mutation = request(&data, attrs.clone(), Value::Null);+ assert_eq!(+ native_job_scheduler_edit_plan(NativeJobEngine::Oracle, &mutation, &data).err(),+ Some("native_job_argument_target_required")+ );+ let mutation = request(&data, attrs, json!({"program":{"owner":"New.Owner","name":"New"},"arguments":[]}));+ assert_eq!(+ native_job_scheduler_edit_plan(NativeJobEngine::OceanbaseOracle, &mutation, &data).err(),+ Some("native_job_attribute_not_editable")+ );+ let mut wrong = mutation;+ if let NativeJobChange::Update { argument_target: Some(target), .. } = &mut wrong.change {+ target.program = None;+ }+ assert_eq!(+ native_job_scheduler_edit_plan(NativeJobEngine::Oracle, &wrong, &data).err(),+ Some("native_job_argument_target_mismatch")+ );+}++#[test]+fn an_unrelated_unreadable_program_does_not_become_a_new_scalar_edit_precondition() {+ let mut data = details();+ if let NativeJobMetadata::Available { value } = &mut data.snapshot.definition {+ value.remove("PROGRAM_OWNER");+ }+ let mutation = request(&data, json!([{"name":"COMMENTS","change":{"kind":"set","value":"new"}}]), Value::Null);+ let plan = native_job_scheduler_edit_plan(NativeJobEngine::Oracle, &mutation, &data).unwrap();+ assert!(!plan.transition);+ assert!(plan.references.is_empty());+}++#[test]+fn a_numeric_driver_representation_does_not_change_the_argument_context() {+ let mut data = details();+ if let NativeJobMetadata::Available { value } = &mut data.snapshot.definition {+ value.insert("PROGRAM_OWNER".into(), Value::Null);+ value.insert("PROGRAM_NAME".into(), Value::Null);+ value.insert("JOB_TYPE".into(), json!("STORED_PROCEDURE"));+ value.insert("NUMBER_OF_ARGUMENTS".into(), json!("2"));+ }+ let mutation =+ request(&data, json!([{"name":"NUMBER_OF_ARGUMENTS","change":{"kind":"set","value":2}}]), Value::Null);+ let plan = native_job_scheduler_edit_plan(NativeJobEngine::Oracle, &mutation, &data).unwrap();+ assert!(!plan.context_changed);+}++#[test]+fn detaching_a_named_schedule_checks_immediate_and_once_as_different_native_projections() {+ for (start, expected) in [(Value::Null, "IMMEDIATE"), (json!("2030-01-01T00:00:00+08:00"), "ONCE")] {+ let mut data = details();+ if let NativeJobMetadata::Available { value } = &mut data.snapshot.definition {+ value.insert("SCHEDULE_OWNER".into(), json!("Owner"));+ value.insert("SCHEDULE_NAME".into(), json!("Calendar"));+ value.insert("SCHEDULE_TYPE".into(), json!("NAMED"));+ value.insert("START_DATE".into(), Value::Null);+ value.insert("REPEAT_INTERVAL".into(), Value::Null);+ }+ let mutation = request(+ &data,+ json!([{"name":"SCHEDULE_NAME","change":{"kind":"clear"}},{"name":"START_DATE","change":{"kind":"set","value":start}}]),+ Value::Null,+ );+ let plan = native_job_scheduler_edit_plan(NativeJobEngine::Oracle, &mutation, &data).unwrap();+ assert_eq!(plan.definition["SCHEDULE_TYPE"], json!(expected));+ }+}++#[test]+fn typed_null_projection_uses_guarded_anydata_access_only_in_native_oracle() {+ let data = details();+ let queries = dbx_sql_schema::native_jobs::native_job_catalog_queries(+ NativeJobEngine::Oracle,+ &data.snapshot.job_ref,+ dbx_sql_schema::native_jobs::NativeJobCatalogPart::Arguments,+ )+ .unwrap();+ assert_eq!(queries.len(), 3);+ for query in queries {+ assert!(query.sql.contains("CASE WHEN J.ANYDATA_VALUE IS NOT NULL THEN"));+ assert!(query.sql.contains("GetTypeName()"));+ assert!(query+ .sql+ .contains("WHEN 'number' THEN CASE WHEN J.ANYDATA_VALUE.AccessNumber() IS NULL THEN 1 ELSE 0 END"));+ assert!(query.sql.contains("ELSE NULL END END AS DBX_ANYDATA_IS_NULL"));+ assert!(query.sql.contains("THEN 1 ELSE 0 END AS DBX_ANYDATA_PRESENT"));+ assert!(query.sql.contains("TO_CHAR(J.ANYDATA_VALUE.AccessNumber(), 'TM9', 'NLS_NUMERIC_CHARACTERS=''.,''')"));+ assert!(query.sql.contains("AS DBX_ANYDATA_TEXT"));+ }+ for query in dbx_sql_schema::native_jobs::native_job_catalog_queries(+ NativeJobEngine::Dameng,+ &data.snapshot.job_ref,+ dbx_sql_schema::native_jobs::NativeJobCatalogPart::Arguments,+ )+ .unwrap()+ {+ assert!(!query.sql.contains("ANYDATA_VALUE"));+ }+}++#[test]+fn an_inline_schedule_change_carries_its_native_schedule_type_and_pause() {+ let data = details();+ let mutation = request(&data, json!([{"name":"REPEAT_INTERVAL","change":{"kind":"clear"}}]), Value::Null);+ let plan = native_job_scheduler_edit_plan(NativeJobEngine::Oracle, &mutation, &data).unwrap();+ assert!(plan.transition);+ assert_eq!(plan.sql.steps[0].id, "pause");+ assert_eq!(plan.definition["SCHEDULE_TYPE"], json!("ONCE"));+}++#[test]+fn an_old_host_destination_is_not_tokenized_or_treated_as_a_named_target() {+ let mut data = details();+ if let NativeJobMetadata::Available { value } = &mut data.snapshot.definition {+ value.insert("DESTINATION_OWNER".into(), Value::Null);+ value.insert("DESTINATION".into(), json!("host.example:15000"));+ }+ let mutation = request(+ &data,+ json!([{"name":"DESTINATION_NAME","change":{"kind":"set","value":{"owner":"Remote.Owner","name":"Remote.DB"}}}]),+ Value::Null,+ );+ let plan = native_job_scheduler_edit_plan(NativeJobEngine::Oracle, &mutation, &data).unwrap();+ assert_eq!(plan.definition["DESTINATION_OWNER"], json!("Remote.Owner"));+ assert_eq!(plan.definition["DESTINATION"], json!("Remote.DB"));+ assert_eq!(plan.references.len(), 1);+}++#[test]+fn destination_group_member_inventory_is_an_exact_nonselectable_read_not_a_count_formula() {+ use dbx_sql_schema::native_jobs::native_job_reference_queries;+ let mut request: NativeJobReferenceListRequest = serde_json::from_value(json!({"scope":{"connectionId":"c","database":"","contextId":"ctx"},"kind":"destination-group-members","schema":"Owner.With.Dot","name":"Group,One","limit":10000})).unwrap();+ let queries = native_job_reference_queries(NativeJobEngine::Oracle, &request).unwrap();+ assert_eq!(queries.len(), 3);+ for query in queries {+ assert!(query.source.ends_with("SCHEDULER_GROUP_MEMBERS"));+ assert!(query.sql.contains("J.MEMBER_NAME"));+ assert!(query.sql.contains("J.GROUP_NAME = 'Group,One'"));+ assert!(!query.sql.contains("CONNECT_INFO"));+ }+ assert!(native_job_reference_queries(NativeJobEngine::Dameng, &request).unwrap().is_empty());+ request.name = None;+ assert!(native_job_reference_queries(NativeJobEngine::Oracle, &request).is_err());+}++#[test]+fn a_raw_destination_uses_its_native_slot_inside_the_controlled_transition() {+ let mut data = details();+ if let NativeJobMetadata::Available { value } = &mut data.snapshot.definition {+ value.insert("DESTINATION".into(), json!("old.host:1500"));+ }+ for change in [json!({"kind":"set","value":"Host.With.Dots:1501"}), json!({"kind":"clear"})] {+ let mutation = request(&data, json!([{"name":"DESTINATION","change":change}]), Value::Null);+ let plan = native_job_scheduler_edit_plan(NativeJobEngine::Oracle, &mutation, &data).unwrap();+ assert!(plan.transition);+ assert!(plan.references.is_empty());+ assert_eq!(plan.sql.steps.first().unwrap().id, "pause");+ assert_eq!(plan.sql.steps.last().unwrap().id, "enable");+ let step = plan.sql.steps.iter().find(|step| step.id == "attribute:DESTINATION").unwrap();+ assert!(step.sql.contains("attribute => 'destination'"));+ assert!(!step.sql.contains("'destination_name'"));+ if change["kind"] == "clear" {+ assert!(step.sql.contains("SET_ATTRIBUTE_NULL"));+ assert_eq!(plan.definition["DESTINATION"], Value::Null);+ } else {+ assert!(step.sql.contains("value => 'Host.With.Dots:1501'"));+ assert_eq!(plan.definition["DESTINATION"], json!("Host.With.Dots:1501"));+ }+ assert_eq!(plan.definition["DESTINATION_OWNER"], Value::Null);+ }+}++#[test]+fn raw_and_named_destination_intents_cannot_be_combined_or_silently_retyped() {+ let data = details();+ let mutation = request(+ &data,+ json!([+ {"name":"DESTINATION","change":{"kind":"set","value":"raw.host:1500"}},+ {"name":"DESTINATION_NAME","change":{"kind":"set","value":{"owner":"Owner","name":"Named"}}}+ ]),+ Value::Null,+ );+ assert!(matches!(+ native_job_scheduler_edit_plan(NativeJobEngine::Oracle, &mutation, &data),+ Err("native_job_destination_contract_conflict")+ ));+ for value in [json!(""), json!("host\u{0000}name"), json!({"owner":"Owner","name":"Named"})] {+ let mutation =+ request(&data, json!([{"name":"DESTINATION","change":{"kind":"set","value":value}}]), Value::Null);+ assert!(native_job_scheduler_edit_plan(NativeJobEngine::Oracle, &mutation, &data).is_err());+ }+ let mutation =+ request(&data, json!([{"name":"DESTINATION","change":{"kind":"set","value":"raw.host:1500"}}]), Value::Null);+ for engine in [NativeJobEngine::OceanbaseOracle, NativeJobEngine::Dameng] {+ assert!(native_job_scheduler_edit_plan(engine, &mutation, &data).is_err());+ }+}diff --git a/crates/dbx-sql-schema/tests/native_jobs.rs b/crates/dbx-sql-schema/tests/native_jobs.rsnew file mode 100644index 0000000000..771f635f1a--- /dev/null+++ b/crates/dbx-sql-schema/tests/native_jobs.rs@@ -0,0 +1,222 @@+use dbx_sql_schema::native_jobs::{+ native_job_catalog_queries, native_job_definition_queries, native_job_list_queries, NativeJobCatalogDialect,+ NativeJobCatalogPart,+};+use dbx_types::native_jobs::{NativeJobKind, NativeJobRef, NativeJobScope};++fn scheduler(owner: &str, name: &str) -> NativeJobRef {+ NativeJobRef::Scheduler {+ scope: NativeJobScope {+ connection_id: "connection".to_string(),+ database: "database".to_string(),+ context_id: "backend-context".to_string(),+ },+ owner: owner.to_string(),+ name: name.to_string(),+ }+}++#[test]+fn dm_legacy_definition_is_an_independent_exact_id_partition() {+ let target = NativeJobRef::Legacy {+ scope: scheduler("Owner", "Job").scope().clone(),+ job_id: "900719925474099312345".into(),+ };+ let native = native_job_definition_queries(NativeJobCatalogDialect::Dameng, &target).unwrap();+ assert_eq!(native[0].source, "SYSJOB.SYSJOBS");+ assert!(native[0].sql.contains("J.SYS_FLAG = 2"));+ let legacy =+ native_job_catalog_queries(NativeJobCatalogDialect::Dameng, &target, NativeJobCatalogPart::NativeAttributes)+ .unwrap();+ assert_eq!(legacy.len(), 2);+ assert_eq!(legacy[0].source, "SYSJOB.DBA_JOBS");+ assert_eq!(legacy[1].source, "SYSJOB.USER_JOBS");+ for query in legacy {+ assert_eq!(+ query.sql,+ format!(+ "SELECT J.*, CAST(J.JOB AS VARCHAR(40)) AS DBX_JOB_ID FROM {} J WHERE J.JOB = 900719925474099312345",+ query.source+ )+ );+ assert_eq!(query.limit, 1);+ assert!(!query.sql.contains("JOIN"));+ assert!(!query.sql.contains("TO_TIMESTAMP"));+ }+ let native_target =+ NativeJobRef::DamengNative { scope: target.scope().clone(), job_id: "41".into(), name: "Job".into() };+ assert!(native_job_catalog_queries(+ NativeJobCatalogDialect::Dameng,+ &native_target,+ NativeJobCatalogPart::NativeAttributes+ )+ .unwrap()+ .is_empty());+}++#[test]+fn selected_scheduler_reads_preserve_exact_owner_and_name_as_literals() {+ let target = scheduler("Owner.With.Dot", "J'ob,Two");+ let queries = native_job_definition_queries(NativeJobCatalogDialect::OceanbaseOracle, &target).unwrap();+ assert_eq!(queries.len(), 2);+ assert_eq!(queries[0].source, "SYS.DBA_SCHEDULER_JOBS");+ assert_eq!(+ queries[0].sql,+ "SELECT J.* FROM SYS.DBA_SCHEDULER_JOBS J WHERE J.OWNER = 'Owner.With.Dot' AND J.JOB_NAME = 'J''ob,Two'"+ );+ assert_eq!(queries[1].source, "SYS.USER_SCHEDULER_JOBS");+ assert_eq!(queries[1].sql, "SELECT J.*, USER AS DBX_OWNER FROM SYS.USER_SCHEDULER_JOBS J WHERE USER = 'Owner.With.Dot' AND J.JOB_NAME = 'J''ob,Two'");+}++#[test]+fn own_scheduler_sections_do_not_require_the_omitted_owner_column() {+ let target = scheduler("Owner", "Job");+ for part in [NativeJobCatalogPart::Arguments, NativeJobCatalogPart::Running, NativeJobCatalogPart::History] {+ let queries = native_job_catalog_queries(NativeJobCatalogDialect::Oracle, &target, part).unwrap();+ assert_eq!(queries.len(), 3);+ let own = queries.last().unwrap();+ assert!(own.sql.contains("USER AS DBX_OWNER"));+ assert!(own.sql.contains("WHERE USER = 'Owner' AND J.JOB_NAME = 'Job'"));+ assert!(!own.sql.contains("J.OWNER"));+ }+}++#[test]+fn oceanbase_generation_uses_real_positive_job_identity_not_guard_rows() {+ let target = scheduler("Owner", "J'ob");+ let queries =+ native_job_catalog_queries(NativeJobCatalogDialect::OceanbaseOracle, &target, NativeJobCatalogPart::Generation)+ .unwrap();+ assert_eq!(queries.len(), 1);+ assert_eq!(queries[0].sql, "SELECT DISTINCT TO_CHAR(JOB) AS DBX_JOB_ID, TO_CHAR(GMT_CREATE, 'YYYY-MM-DD HH24:MI:SS.FF6') AS DBX_CREATED_AT FROM SYS.ALL_VIRTUAL_TENANT_SCHEDULER_JOB_REAL_AGENT WHERE POWNER = 'Owner' AND JOB_NAME = 'J''ob' AND JOB > 0");+}++#[test]+fn oceanbase_native_definition_attributes_are_identity_bound_but_separate_from_generation() {+ let target = scheduler("Owner.With.Dot", "J'ob");+ let queries = native_job_catalog_queries(+ NativeJobCatalogDialect::OceanbaseOracle,+ &target,+ NativeJobCatalogPart::NativeAttributes,+ )+ .unwrap();+ assert_eq!(queries.len(), 1);+ assert_eq!(queries[0].limit, 1);+ assert!(queries[0].sql.contains("POWNER AS DBX_OWNER, JOB_NAME, MAX_FAILURES"));+ assert!(queries[0].sql.contains("WHERE POWNER = 'Owner.With.Dot' AND JOB_NAME = 'J''ob' AND JOB > 0"));+ for dialect in [NativeJobCatalogDialect::Oracle, NativeJobCatalogDialect::Dameng] {+ assert!(native_job_catalog_queries(dialect, &target, NativeJobCatalogPart::NativeAttributes)+ .unwrap()+ .is_empty());+ }+}++#[test]+fn dameng_native_sections_keep_all_step_and_schedule_fields_and_real_runtime() {+ let target = NativeJobRef::DamengNative {+ scope: scheduler("Owner", "Job").scope().clone(),+ job_id: "9007199254740993".into(),+ name: "J'ob".into(),+ };+ let steps =+ native_job_catalog_queries(NativeJobCatalogDialect::Dameng, &target, NativeJobCatalogPart::Steps).unwrap();+ assert_eq!(+ steps[0].sql,+ "SELECT J.*, CAST(J.ID AS VARCHAR(40)) AS DBX_CHILD_ID FROM SYSJOB.SYSJOBSTEPS J WHERE J.JOBID = 9007199254740993 ORDER BY J.SEQNO, J.NAME"+ );+ assert_eq!(steps[1].source, "SYSJOB.USER_JOBSTEPS_VIEW");+ let schedules =+ native_job_catalog_queries(NativeJobCatalogDialect::Dameng, &target, NativeJobCatalogPart::Schedules).unwrap();+ assert_eq!(+ schedules[0].sql,+ "SELECT J.*, CAST(J.ID AS VARCHAR(40)) AS DBX_CHILD_ID FROM SYSJOB.SYSJOBSCHEDULES J WHERE J.JOBID = 9007199254740993 ORDER BY J.NAME"+ );+ let running =+ native_job_catalog_queries(NativeJobCatalogDialect::Dameng, &target, NativeJobCatalogPart::Running).unwrap();+ assert_eq!(running.len(), 1);+ assert_eq!(running[0].sql, "SELECT J.* FROM SYSJOB.DBA_JOBS_RUNNING J WHERE J.JOB = 9007199254740993");+}++#[test]+fn legacy_id_validation_precedes_query_building_and_keeps_log_priv_schema_distinct() {+ let scope = scheduler("Owner", "Job").scope().clone();+ let invalid = NativeJobRef::Legacy { scope: scope.clone(), job_id: "1 OR 1=1".into() };+ assert!(native_job_definition_queries(NativeJobCatalogDialect::Oracle, &invalid).is_err());+ let target = NativeJobRef::Legacy { scope, job_id: "9007199254740993".into() };+ let queries = native_job_definition_queries(NativeJobCatalogDialect::Oracle, &target).unwrap();+ assert_eq!(+ queries[0].sql,+ "SELECT J.*, TO_CHAR(J.JOB) AS DBX_JOB_ID FROM SYS.DBA_JOBS J WHERE J.JOB = 9007199254740993"+ );+ assert!(native_job_catalog_queries(NativeJobCatalogDialect::Oracle, &target, NativeJobCatalogPart::History)+ .unwrap()+ .is_empty());+}++#[test]+fn histories_are_ordered_newest_first_and_do_not_use_a_different_dialects_error_columns() {+ let target = scheduler("Owner", "Job");+ for dialect in+ [NativeJobCatalogDialect::Oracle, NativeJobCatalogDialect::OceanbaseOracle, NativeJobCatalogDialect::Dameng]+ {+ let queries = native_job_catalog_queries(dialect, &target, NativeJobCatalogPart::History).unwrap();+ assert!(queries[0].sql.ends_with("ORDER BY J.LOG_DATE DESC, J.LOG_ID DESC"));+ assert_eq!(queries[0].limit, 200);+ assert!(!queries[0].sql.contains("ERROR#"));+ }+}++#[test]+fn paged_lists_do_not_read_business_bodies_and_escape_search_metacharacters() {+ let queries = native_job_list_queries(+ NativeJobCatalogDialect::Oracle,+ NativeJobKind::Scheduler,+ Some("Owner"),+ "J%_!'ob",+ 100,+ 50,+ )+ .unwrap();+ let sql = &queries[0].sql;+ assert!(!sql.contains("JOB_ACTION"));+ assert!(sql.contains("J.OWNER = 'Owner'"));+ assert!(sql.contains("UPPER(J.JOB_NAME) LIKE UPPER('%J!%!_!!''ob%') ESCAPE '!'"));+ assert!(sql.contains("DBX_ROW_NUM > 100 AND DBX_ROW_NUM <= 151"));+ assert_eq!(queries[0].limit, 50);+ assert!(queries.last().unwrap().sql.contains("USER AS DBX_OWNER"));+ assert!(!queries.last().unwrap().sql.contains("J.OWNER"));+ assert!(native_job_list_queries(NativeJobCatalogDialect::Oracle, NativeJobKind::Legacy, None, "", 0, 501).is_err());+}++#[test]+fn dameng_native_list_can_identify_dbms_job_without_reading_or_duplicating_its_body() {+ let queries =+ native_job_list_queries(NativeJobCatalogDialect::Dameng, NativeJobKind::DamengNative, None, "", 0, 100)+ .unwrap();+ assert!(queries[0].sql.contains("CAST(J.ID AS VARCHAR(40)) AS DBX_JOB_ID"));+ assert!(queries[0].sql.contains("J.SYS_FLAG"));+ assert!(!queries[0].sql.contains("RUNNING"));+ let legacy =+ native_job_list_queries(NativeJobCatalogDialect::Dameng, NativeJobKind::Legacy, None, "", 0, 100).unwrap();+ assert!(legacy[0].sql.contains("J.SYS_FLAG = 2"));+}++#[test]+fn dameng_search_preserves_name_owner_and_description_matching_across_all_pages() {+ let queries = native_job_list_queries(+ NativeJobCatalogDialect::Dameng,+ NativeJobKind::DamengNative,+ Some("Owner"),+ "Ops%_'team",+ 100,+ 100,+ )+ .unwrap();+ for query in queries {+ assert!(query.sql.contains("J.USERNAME = 'Owner' AND (UPPER(J.NAME) LIKE"));+ assert!(query.sql.contains("OR UPPER(J.USERNAME) LIKE UPPER('%Ops!%!_''team%') ESCAPE '!'"));+ assert!(query.sql.contains("OR UPPER(J.DESCRIBE) LIKE UPPER('%Ops!%!_''team%') ESCAPE '!'"));+ assert!(query.sql.contains("DBX_ROW_NUM > 100 AND DBX_ROW_NUM <= 201"));+ assert!(!query.sql.contains("COMMAND"));+ }+}diff --git a/crates/dbx-sql-schema/tests/oracle_trigger_structure_plan.rs b/crates/dbx-sql-schema/tests/oracle_trigger_structure_plan.rsnew file mode 100644index 0000000000..8d006d4180--- /dev/null+++ b/crates/dbx-sql-schema/tests/oracle_trigger_structure_plan.rs@@ -0,0 +1,139 @@+use dbx_sql_schema::table_structure_sql::{+ build_create_table_sql_plan_with_dialect_options, build_table_structure_change_sql,+ build_table_structure_change_sql_plan, TableStructureSqlOptions,+};+use serde_json::json;++fn replacement_options() -> TableStructureSqlOptions {+ serde_json::from_value(json!({+ "databaseType": "oceanbase-oracle", "schema": "Parent.Owner", "tableName": "T",+ "triggers": [{+ "id": "trigger-draft", "name": " Tr\"ig ", "timing": "BEFORE EACH ROW", "event": "INSERT",+ "statement": "BEGIN :NEW.ID := 7; END;", "enabled": false,+ "oracleExact": {"owner": " Trigger.Owner ", "parentType": "TABLE"},+ "original": {"name": " Tr\"ig ", "timing": "BEFORE EACH ROW", "event": "INSERT", "statement": "BEGIN NULL; END;", "enabled": false}+ }]+ })).unwrap()+}++#[test]+fn exact_structured_trigger_uses_its_own_owner_and_preserves_disabled_in_the_definition() {+ let result = build_table_structure_change_sql(replacement_options());+ assert!(result.warnings.is_empty(), "{:?}", result.warnings);+ assert_eq!(result.statements, vec!["CREATE OR REPLACE TRIGGER \" Trigger.Owner \".\" Tr\"\"ig \" BEFORE INSERT ON \"Parent.Owner\".\"T\"\nFOR EACH ROW\nDISABLE\nBEGIN :NEW.ID := 7; END;"]);+}++#[test]+fn exact_trigger_operation_is_bound_to_its_generated_position_between_columns_and_comments() {+ let mut payload = serde_json::to_value(replacement_options()).unwrap();+ payload["columns"] = json!([{"id":"column-draft","name":"V","dataType":"NUMBER","isNullable":true}]);+ payload["tableComment"] = json!("new comment");+ payload["originalTableComment"] = json!("");+ let plan = build_table_structure_change_sql_plan(serde_json::from_value(payload).unwrap(), None);+ assert!(plan.sql.warnings.is_empty(), "{:?}", plan.sql.warnings);+ assert_eq!(plan.sql.statements.len(), 3);+ assert_eq!(+ serde_json::to_value(&plan).unwrap()["triggerOperations"],+ json!([{+ "draftId": "trigger-draft", "action": "replace", "owner": " Trigger.Owner ", "name": " Tr\"ig ",+ "statementIndex": 1, "statementCount": 1, "enabled": false+ }])+ );+}++#[test]+fn default_structured_payload_keeps_the_legacy_sql_and_json_fields() {+ let mut payload = serde_json::to_value(replacement_options()).unwrap();+ payload["triggers"][0].as_object_mut().unwrap().remove("oracleExact");+ let plan = build_table_structure_change_sql_plan(serde_json::from_value(payload).unwrap(), None);+ assert_eq!(+ serde_json::to_value(plan).unwrap(),+ json!({+ "statements": [+ "CREATE OR REPLACE TRIGGER \"Parent.Owner\".\"Tr\"\"ig\" BEFORE INSERT ON \"Parent.Owner\".\"T\"\nFOR EACH ROW\nBEGIN :NEW.ID := 7; END;",+ "ALTER TRIGGER \"Parent.Owner\".\" Tr\"\"ig \" DISABLE;"+ ], "warnings": []+ })+ );+}++#[test]+fn exact_trigger_noop_acknowledges_the_contract_without_inventing_an_operation() {+ let mut options = replacement_options();+ options.triggers[0].statement = options.triggers[0].original.as_ref().unwrap().statement.clone().unwrap();+ let plan = build_table_structure_change_sql_plan(options, None);+ assert!(plan.sql.statements.is_empty());+ assert!(plan.trigger_operations.is_empty());+ assert_eq!(serde_json::to_value(plan).unwrap()["oracleTriggerContract"], 1);+}++#[test]+fn renamed_trigger_operations_identify_the_old_drop_and_the_new_create_without_replace() {+ let mut options = replacement_options();+ options.triggers[0].name = " NewTrigger ".into();+ let plan = build_table_structure_change_sql_plan(options, None);+ assert!(plan.sql.warnings.is_empty(), "{:?}", plan.sql.warnings);+ assert_eq!(plan.sql.statements.len(), 2);+ assert_eq!(plan.sql.statements[0], "DROP TRIGGER \" Trigger.Owner \".\" Tr\"\"ig \";");+ assert!(!plan.sql.statements[1].contains("OR REPLACE"));+ assert_eq!(+ serde_json::to_value(plan).unwrap()["triggerOperations"],+ json!([+ {"draftId":"trigger-draft","action":"delete","owner":" Trigger.Owner ","name":" Tr\"ig ","statementIndex":0,"statementCount":1},+ {"draftId":"trigger-draft","action":"create","owner":" Trigger.Owner ","name":"NewTrigger","statementIndex":1,"statementCount":1,"enabled":false}+ ])+ );+}++#[test]+fn dm_disabled_replacement_is_one_logical_operation_with_two_explicit_statements() {+ let mut payload = serde_json::to_value(replacement_options()).unwrap();+ payload["databaseType"] = json!("dameng");+ let plan = build_table_structure_change_sql_plan(serde_json::from_value(payload).unwrap(), None);+ assert!(plan.sql.warnings.is_empty(), "{:?}", plan.sql.warnings);+ assert_eq!(plan.sql.statements.len(), 2);+ assert!(!plan.sql.statements[0].contains("\nDISABLE\n"));+ assert_eq!(plan.sql.statements[1], "ALTER TRIGGER \" Trigger.Owner \".\" Tr\"\"ig \" DISABLE;");+ assert_eq!(plan.trigger_operations[0].statement_count, 2);+ assert_eq!(plan.trigger_operations[0].action, "replace");+}++#[test]+fn new_oracle_table_and_trigger_operations_keep_the_existing_name_folding_rule() {+ let mut payload = serde_json::to_value(replacement_options()).unwrap();+ payload["databaseType"] = json!("oracle");+ payload["tableName"] = json!("new_table");+ payload["columns"] = json!([{"id":"new-column","name":"ID","dataType":"NUMBER","isNullable":true}]);+ payload["triggers"][0]["name"] = json!("new_trigger");+ payload["triggers"][0]["original"] = serde_json::Value::Null;+ let plan = build_create_table_sql_plan_with_dialect_options(+ serde_json::from_value(payload).unwrap(),+ None,+ Default::default(),+ );+ assert!(plan.sql.warnings.is_empty(), "{:?}", plan.sql.warnings);+ assert!(plan.sql.statements[0].starts_with("CREATE TABLE \"Parent.Owner\".new_table "));+ assert!(plan.sql.statements[1].contains("TRIGGER \" Trigger.Owner \".\"NEW_TRIGGER\""));+ assert!(plan.sql.statements[1].contains("ON \"Parent.Owner\".\"NEW_TABLE\""));+ assert!(!plan.sql.statements[1].contains("OR REPLACE"));+ assert_eq!(plan.trigger_operations[0].name, "NEW_TRIGGER");+ assert_eq!(plan.trigger_operations[0].statement_index, 1);+}++#[test]+fn a_protected_complete_source_can_toggle_but_cannot_be_rebuilt_from_a_body() {+ let mut options = replacement_options();+ let source = "TRIGGER \" Tr\"\"ig \" BEFORE INSERT ON \"Parent.Owner\".\"T\" FOR EACH ROW WHEN (NEW.ID > 0) BEGIN NULL; END;";+ options.triggers[0].original.as_mut().unwrap().statement = Some(source.into());+ options.triggers[0].statement = source.into();+ options.triggers[0].enabled = Some(true);+ let toggled = build_table_structure_change_sql_plan(options.clone(), None);+ assert!(toggled.sql.warnings.is_empty(), "{:?}", toggled.sql.warnings);+ assert_eq!(toggled.sql.statements, ["ALTER TRIGGER \" Trigger.Owner \".\" Tr\"\"ig \" ENABLE;"]);+ assert_eq!(toggled.trigger_operations[0].action, "enable");+ options.triggers[0].statement = "BEGIN :NEW.ID := 8; END;".into();+ let refused = build_table_structure_change_sql_plan(options, None);+ assert!(refused.sql.statements.is_empty());+ assert!(refused.trigger_operations.is_empty());+ assert!(refused.sql.warnings.iter().any(|warning| warning.contains("complete source definition")));+}diff --git a/crates/dbx-sql/src/lib.rs b/crates/dbx-sql/src/lib.rsindex 1bce9f8b10..f1de62a222 100644--- a/crates/dbx-sql/src/lib.rs+++ b/crates/dbx-sql/src/lib.rs@@ -10,7 +10,9 @@ pub use dbx_sql_data::{database_structure_search_sql, query_result_sql,};pub use dbx_sql_dialect::{dml_binding, postgres_index_key, sql_dialect};-pub use dbx_sql_schema::{db_admin_sql, schema_diff, sql_parser, table_structure_sql};+pub use dbx_sql_schema::{+ db_admin_sql, native_job_arguments, native_job_changes, native_jobs, schema_diff, sql_parser, table_structure_sql,+};pub use dbx_types::{database_manifest, models, types};pub mod dameng_dump;diff --git a/crates/dbx-tauri-schema/src/commands.rs b/crates/dbx-tauri-schema/src/commands.rsindex d3ae4ea971..e27264e397 100644--- a/crates/dbx-tauri-schema/src/commands.rs+++ b/crates/dbx-tauri-schema/src/commands.rs@@ -4,6 +4,77 @@ use tauri::State;use dbx_core::connection::AppState;use dbx_core::db;+use dbx_core::native_jobs::{+ NativeJobContext, NativeJobDetails, NativeJobList, NativeJobListRequest, NativeJobOperationStatus,+ NativeJobPreparedPlan, NativeJobRef, NativeJobReferenceCatalog, NativeJobReferenceListRequest, NativeJobRequest,+};+use dbx_core::schema::native_jobs as jobs;++#[tauri::command]+pub async fn native_job_open_context(+ state: State<'_, Arc<AppState>>,+ connection_id: String,+ database: String,+) -> Result<NativeJobContext, String> {+ jobs::native_job_open_context_core(&state, &connection_id, &database).await+}++#[tauri::command]+pub async fn native_job_list(+ state: State<'_, Arc<AppState>>,+ request: NativeJobListRequest,+) -> Result<NativeJobList, String> {+ jobs::native_job_list_core(&state, &request).await+}++#[tauri::command]+pub async fn native_job_references(+ state: State<'_, Arc<AppState>>,+ request: NativeJobReferenceListRequest,+) -> Result<NativeJobReferenceCatalog, String> {+ jobs::native_job_references_core(&state, &request).await+}++#[tauri::command]+pub async fn native_job_read(+ state: State<'_, Arc<AppState>>,+ target: NativeJobRef,+) -> Result<NativeJobDetails, String> {+ jobs::native_job_read_core(&state, &target).await+}++#[tauri::command]+pub async fn native_job_prepare(+ state: State<'_, Arc<AppState>>,+ mutation: NativeJobRequest,+) -> Result<NativeJobPreparedPlan, String> {+ jobs::native_job_prepare_core(&state, mutation).await+}++#[tauri::command]+pub async fn native_job_apply(+ state: State<'_, Arc<AppState>>,+ plan_id: String,+) -> Result<NativeJobOperationStatus, String> {+ jobs::native_job_apply_core(state.inner().clone(), &plan_id)+}++#[tauri::command]+pub async fn native_job_status(+ state: State<'_, Arc<AppState>>,+ operation_id: String,+ observe: Option<bool>,+) -> Result<NativeJobOperationStatus, String> {+ Ok(jobs::native_job_status_observed_core(&state, &operation_id, observe.unwrap_or(false)).await)+}++#[tauri::command]+pub async fn native_job_cancel(+ state: State<'_, Arc<AppState>>,+ operation_id: String,+) -> Result<NativeJobOperationStatus, String> {+ Ok(jobs::native_job_cancel(&state, &operation_id))+}async fn run_cancellable<T, F>(state: &Arc<AppState>, execution_id: Option<String>, future: F) -> Result<T, String>where@@ -282,6 +353,7 @@ pub async fn list_objects(catalog: Option<String>,table_name_filter: Option<dbx_core::schema::TableNameFilter>,execution_id: Option<String>,+ identity_mode: Option<dbx_core::schema::MetadataIdentityMode>,exact_identity: Option<bool>,) -> Result<Vec<db::ObjectInfo>, String> {let app = Arc::clone(state.inner());@@ -334,7 +406,7 @@ pub async fn list_objects(}).collect());}- dbx_core::schema::list_objects_core(+ dbx_core::schema::list_objects_core_with_options(&operation_app,&connection_id,&database,@@ -344,6 +416,7 @@ pub async fn list_objects(offset,object_types.as_deref(),table_name_filter.as_ref(),+ &dbx_core::schema::MetadataReadOptions { identity_mode, catalog },).await})@@ -388,8 +461,10 @@ pub async fn get_object_source(object_type: db::ObjectSourceKind,signature: Option<String>,relation_name: Option<String>,+ identity_mode: Option<dbx_core::schema::MetadataIdentityMode>,+ catalog: Option<String>,) -> Result<db::ObjectSource, String> {- dbx_core::schema::get_object_source_core(+ dbx_core::schema::get_object_source_core_with_options(&state,&connection_id,&database,@@ -398,6 +473,7 @@ pub async fn get_object_source(object_type,signature.as_deref(),relation_name.as_deref(),+ &dbx_core::schema::MetadataReadOptions { identity_mode, catalog },).await}@@ -648,6 +724,7 @@ pub async fn list_triggers(schema: String,table: String,catalog: Option<String>,+ identity_mode: Option<dbx_core::schema::MetadataIdentityMode>,exact_identity: Option<bool>,) -> Result<Vec<db::TriggerInfo>, String> {if exact_identity.unwrap_or(false) {@@ -657,7 +734,15 @@ pub async fn list_triggers(return dbx_core::schema::list_doris_catalog_triggers_core(&state, &connection_id, &catalog, &database, &table).await;}- dbx_core::schema::list_triggers_core(&state, &connection_id, &database, &schema, &table).await+ dbx_core::schema::list_triggers_core_with_options(+ &state,+ &connection_id,+ &database,+ &schema,+ &table,+ &dbx_core::schema::MetadataReadOptions { identity_mode, catalog },+ )+ .await}#[tauri::command]diff --git a/crates/dbx-tauri-schema/src/lib.rs b/crates/dbx-tauri-schema/src/lib.rsindex e6d17d98c1..5b16779ba3 100644--- a/crates/dbx-tauri-schema/src/lib.rs+++ b/crates/dbx-tauri-schema/src/lib.rs@@ -32,6 +32,14 @@ define_registry![get_object_source,get_event_info,get_custom_type_details,+ native_job_open_context,+ native_job_list,+ native_job_references,+ native_job_read,+ native_job_prepare,+ native_job_apply,+ native_job_status,+ native_job_cancel,get_oracle_type_management_snapshot,build_oracle_type_management_sql,verify_oracle_type_data,@@ -95,8 +103,8 @@ mod tests {use super::{handles, COMMANDS};#[test]- fn handles_only_schema_commands() {- assert_eq!(COMMANDS.len(), 60);+ fn handles_only_schema_commands_including_native_jobs() {+ assert_eq!(COMMANDS.len(), 68);assert!(handles("list_databases"));assert!(handles("load_schema_diff_routines"));assert!(handles("prepare_oracle_routine_save"));@@ -107,6 +115,14 @@ mod tests {assert!(handles("update_oracle_routine_operation_references"));assert!(handles("list_event_triggers"));for command in [+ "native_job_open_context",+ "native_job_list",+ "native_job_references",+ "native_job_read",+ "native_job_prepare",+ "native_job_apply",+ "native_job_status",+ "native_job_cancel","get_oracle_type_management_snapshot","build_oracle_type_management_sql","verify_oracle_type_data",diff --git a/crates/dbx-types/src/lib.rs b/crates/dbx-types/src/lib.rsindex d5326c21b1..0a123f6596 100644--- a/crates/dbx-types/src/lib.rs+++ b/crates/dbx-types/src/lib.rs@@ -6,5 +6,7 @@ pub mod models;#[cfg(feature = "mq-admin")]pub mod mqtt;pub mod mysql_event;+pub mod native_jobs;+pub mod oracle_trigger;pub mod sql_file;pub mod types;diff --git a/crates/dbx-types/src/native_jobs.rs b/crates/dbx-types/src/native_jobs.rsnew file mode 100644index 0000000000..d22917712a--- /dev/null+++ b/crates/dbx-types/src/native_jobs.rs@@ -0,0 +1,630 @@+use serde::{Deserialize, Serialize};+use std::collections::BTreeMap;++#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]+#[serde(rename_all = "kebab-case")]+pub enum NativeJobEngine {+ Oracle,+ OceanbaseOracle,+ Dameng,+}++#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]+#[serde(rename_all = "kebab-case")]+pub enum NativeJobKind {+ Scheduler,+ Legacy,+ DamengNative,+}++pub type NativeJobRow = BTreeMap<String, serde_json::Value>;++#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct NativeJobScope {+ pub connection_id: String,+ pub database: String,+ pub context_id: String,+}++#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]+#[serde(tag = "kind", rename_all = "kebab-case")]+pub enum NativeJobRef {+ Scheduler {+ scope: NativeJobScope,+ owner: String,+ name: String,+ },+ Legacy {+ scope: NativeJobScope,+ #[serde(rename = "jobId")]+ job_id: String,+ },+ DamengNative {+ scope: NativeJobScope,+ #[serde(rename = "jobId")]+ job_id: String,+ name: String,+ },+}++#[derive(Clone, PartialEq, Serialize, Deserialize)]+#[serde(tag = "status", rename_all = "snake_case")]+pub enum NativeJobMetadata<T> {+ Available { value: T },+ Truncated { value: T, limit: usize },+ Empty,+ Denied { reason: String },+ Unsupported { reason: String },+ Error { reason: String },+ Unknown { reason: String },+}++#[derive(Clone, PartialEq, Serialize, Deserialize)]+#[serde(tag = "kind", rename_all = "snake_case")]+pub enum NativeJobArgumentValue {+ Unset,+ Inherit,+ Null,+ Value { value: serde_json::Value },+ Opaque { value: serde_json::Value },+}++#[derive(Clone, PartialEq, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct NativeJobArgument {+ pub position: usize,+ #[serde(skip_serializing_if = "Option::is_none")]+ pub name: Option<String>,+ pub data_type: String,+ pub value: NativeJobArgumentValue,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub default_value: Option<NativeJobMetadata<NativeJobArgumentValue>>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub metadata_attribute: Option<String>,+ pub editable: bool,+ #[serde(skip_serializing_if = "Option::is_none")]+ pub reason: Option<String>,+}++// Definitions and argument values deliberately do not implement Debug.+#[derive(Clone, PartialEq, Serialize, Deserialize)]+pub struct NativeJobSnapshot {+ #[serde(rename = "ref")]+ pub job_ref: NativeJobRef,+ pub revision: String,+ pub definition: NativeJobMetadata<BTreeMap<String, serde_json::Value>>,+ pub arguments: NativeJobMetadata<Vec<NativeJobArgument>>,+}++#[derive(Clone, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct NativeJobContext {+ pub scope: NativeJobScope,+ pub engine: NativeJobEngine,+ pub session_user: String,+ pub actual_database: Option<String>,+ pub product_version: Option<String>,+}++#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]+#[serde(rename_all = "snake_case")]+pub enum NativeJobCatalogCoverage {+ Database,+ Accessible,+ CurrentUser,+}++#[derive(Clone, Serialize, Deserialize)]+pub struct NativeJobCatalogSource {+ pub source: Option<String>,+ pub coverage: Option<NativeJobCatalogCoverage>,+}++#[derive(Clone, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct NativeJobSummary {+ #[serde(rename = "ref")]+ pub job_ref: NativeJobRef,+ pub name: String,+ pub owner: Option<String>,+ pub enabled: Option<bool>,+ pub job_type: Option<String>,+ pub state: Option<String>,+ pub next_run: Option<serde_json::Value>,+ pub comments: Option<String>,+ pub aliases: Vec<NativeJobRef>,+ pub log_user: Option<String>,+ pub priv_user: Option<String>,+ pub schema_user: Option<String>,+}++#[derive(Clone, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct NativeJobList {+ pub jobs: NativeJobMetadata<Vec<NativeJobSummary>>,+ pub source: NativeJobCatalogSource,+ pub offset: usize,+ pub limit: usize,+}++#[derive(Clone, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct NativeJobListRequest {+ pub scope: NativeJobScope,+ pub kind: NativeJobKind,+ pub schema: Option<String>,+ #[serde(default)]+ pub filter: String,+ #[serde(default)]+ pub offset: usize,+ #[serde(default = "native_job_page_size")]+ pub limit: usize,+}++#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]+#[serde(rename_all = "kebab-case")]+pub enum NativeJobReferenceKind {+ Program,+ ProgramArguments,+ Schedule,+ Chain,+ Credential,+ Destination,+ Window,+ WindowGroup,+ FileWatcher,+ DestinationGroup,+ DestinationGroupMembers,+}++#[derive(Clone, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct NativeJobReferenceListRequest {+ pub scope: NativeJobScope,+ pub kind: NativeJobReferenceKind,+ pub schema: Option<String>,+ pub name: Option<String>,+ #[serde(default)]+ pub filter: String,+ #[serde(default)]+ pub offset: usize,+ #[serde(default = "native_job_page_size")]+ pub limit: usize,+}++// Program actions and defaults stay outside diagnostic Debug, like Job definitions.+#[derive(Clone, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct NativeJobReferenceCatalog {+ pub objects: NativeJobMetadata<Vec<NativeJobRow>>,+ pub source: NativeJobCatalogSource,+ pub offset: usize,+ pub limit: usize,+}++fn native_job_page_size() -> usize {+ 100+}++#[derive(Clone, PartialEq, Serialize, Deserialize)]+#[serde(tag = "kind", rename_all = "snake_case")]+pub enum NativeJobFieldChange {+ Keep,+ Set { value: serde_json::Value },+ Clear,+}++#[derive(Clone, PartialEq, Serialize, Deserialize)]+pub struct NativeJobAttributeChange {+ pub name: String,+ pub change: NativeJobFieldChange,+}++#[derive(Clone, PartialEq, Serialize, Deserialize)]+pub struct NativeJobArgumentChange {+ pub position: usize,+ pub value: NativeJobArgumentValue,+}++// The COMMAND_INPUT field is the native configuration input, not a generated catalog COMMAND.+// Keep bodies and parameter values outside Debug, including children retained in a preview.+#[derive(Clone, PartialEq, Serialize, Deserialize)]+#[serde(tag = "kind", rename_all = "snake_case")]+pub enum NativeJobDamengChildChange {+ Add {+ name: String,+ #[serde(default)]+ attributes: Vec<NativeJobAttributeChange>,+ },+ Update {+ name: String,+ #[serde(default)]+ attributes: Vec<NativeJobAttributeChange>,+ },+ Drop {+ name: String,+ },+}++#[derive(Clone, PartialEq, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct NativeJobDamengConfiguration {+ #[serde(default)]+ pub attributes: Vec<NativeJobAttributeChange>,+ #[serde(default)]+ pub steps: Vec<NativeJobDamengChildChange>,+ #[serde(default)]+ pub schedules: Vec<NativeJobDamengChildChange>,+}++#[derive(Clone, PartialEq, Serialize, Deserialize)]+#[serde(tag = "action", rename_all = "kebab-case")]+pub enum NativeJobChange {+ Update {+ #[serde(default, rename = "finalEnabled", skip_serializing_if = "Option::is_none")]+ final_enabled: Option<bool>,+ #[serde(default, rename = "argumentTarget", skip_serializing_if = "Option::is_none")]+ argument_target: Option<NativeJobArgumentTarget>,+ #[serde(default)]+ attributes: Vec<NativeJobAttributeChange>,+ #[serde(default)]+ arguments: Vec<NativeJobArgumentChange>,+ },+ ConfigureDameng {+ configuration: NativeJobDamengConfiguration,+ },+ Enable,+ Disable,+ Run,+ Stop {+ #[serde(default)]+ force: bool,+ },+ Drop {+ #[serde(default)]+ force: bool,+ },+ ClearHistory,+}++#[derive(Clone, PartialEq, Serialize, Deserialize)]+pub struct NativeJobMutation {+ pub target: NativeJobRef,+ pub baseline: String,+ #[serde(flatten)]+ pub change: NativeJobChange,+}++// Bodies remain outside Debug, including creation and the retained immutable request.+#[derive(Clone, PartialEq, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct NativeJobLegacyCreate {+ pub what: String,+ pub next_date: String,+ pub interval: String,+ pub enabled: bool,+ #[serde(default)]+ pub instance: i64,+ #[serde(default)]+ pub schema: String,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub zone: Option<String>,+}++#[derive(Clone, PartialEq, Serialize, Deserialize)]+pub struct NativeJobObjectReference {+ pub owner: String,+ pub name: String,+}++#[derive(Clone, PartialEq, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct NativeJobCreateArgument {+ pub position: usize,+ pub data_type: String,+ pub value: NativeJobArgumentValue,+}++/// A complete replacement context, retained across partial conversions. Ordinary argument edits+/// continue to use their original delta contract.+#[derive(Clone, PartialEq, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct NativeJobArgumentTarget {+ pub program: Option<NativeJobObjectReference>,+ pub arguments: Vec<NativeJobCreateArgument>,+}++#[derive(Clone, PartialEq, Serialize, Deserialize)]+#[serde(tag = "kind", rename_all = "kebab-case")]+pub enum NativeJobEventSource {+ Queue {+ owner: String,+ name: String,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ agent: Option<String>,+ },+ FileWatcher {+ reference: NativeJobObjectReference,+ },+}++#[derive(Clone, PartialEq, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct NativeJobSchedulerCreate {+ pub owner: String,+ pub name: String,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub program: Option<NativeJobObjectReference>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub job_type: Option<String>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub job_action: Option<String>,+ #[serde(default)]+ pub number_of_arguments: usize,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub schedule: Option<NativeJobObjectReference>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub start_date: Option<String>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub repeat_interval: Option<String>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub end_date: Option<String>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub event_condition: Option<String>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub event_source: Option<NativeJobEventSource>,+ pub enabled: bool,+ #[serde(default = "native_job_auto_drop_default")]+ pub auto_drop: bool,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub job_class: Option<String>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub job_style: Option<String>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub comments: Option<String>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub credential_name: Option<String>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub destination_name: Option<String>,+ #[serde(default, skip_serializing_if = "Vec::is_empty")]+ pub attributes: Vec<NativeJobAttributeChange>,+ #[serde(default, skip_serializing_if = "Vec::is_empty")]+ pub arguments: Vec<NativeJobCreateArgument>,+}++fn native_job_auto_drop_default() -> bool {+ true+}++#[derive(Clone, PartialEq, Serialize, Deserialize)]+pub struct NativeJobDamengCreate {+ pub name: String,+ pub enabled: bool,+ pub configuration: NativeJobDamengConfiguration,+}++#[derive(Clone, PartialEq, Serialize, Deserialize)]+#[serde(tag = "kind", rename_all = "kebab-case")]+pub enum NativeJobCreateDefinition {+ Legacy(NativeJobLegacyCreate),+ Scheduler(Box<NativeJobSchedulerCreate>),+ DamengNative(NativeJobDamengCreate),+}++#[derive(Clone, PartialEq, Serialize, Deserialize)]+#[serde(tag = "action", rename_all = "kebab-case")]+pub enum NativeJobRequest {+ Create {+ scope: NativeJobScope,+ definition: NativeJobCreateDefinition,+ },+ #[serde(untagged)]+ Mutation(NativeJobMutation),+}++impl From<NativeJobMutation> for NativeJobRequest {+ fn from(mutation: NativeJobMutation) -> Self {+ Self::Mutation(mutation)+ }+}++#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]+#[serde(rename_all = "snake_case")]+pub enum NativeJobLegacyPhase {+ NotStarted,+ Submitting,+ Configuring,+ Prepared,+ CommitSent,+ Committed,+ RolledBack,+ Unknown,+}++#[derive(Clone, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct NativeJobLegacyReceipt {+ pub operation_id: String,+ pub phase: NativeJobLegacyPhase,+ #[serde(default)]+ pub job_id: Option<String>,+ #[serde(default)]+ pub reason: Option<String>,+ #[serde(default)]+ pub vendor_code: Option<i32>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub disposal_confirmed: Option<bool>,+}++#[derive(Clone, Serialize, Deserialize)]+pub struct NativeJobStepPreview {+ pub id: String,+ pub label: String,+ pub sql: String,+}++#[derive(Clone, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct NativeJobPreparedPlan {+ pub plan_id: String,+ pub operation_id: String,+ pub scope: NativeJobScope,+ /// A traditional job has no native ID until SUBMIT returns; never invent one for preview.+ pub target: Option<NativeJobRef>,+ pub steps: Vec<NativeJobStepPreview>,+}++#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]+#[serde(rename_all = "snake_case")]+pub enum NativeJobOperationState {+ Prepared,+ Queued,+ Running,+ Finished,+}++#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]+#[serde(rename_all = "snake_case")]+pub enum NativeJobOperationOutcome {+ NotStarted,+ NotApplied,+ Partial,+ Unknown,+ Verified,+ Accepted,+}++#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]+#[serde(rename_all = "snake_case")]+pub enum NativeJobStepState {+ Pending,+ Dispatching,+ Applied,+ Accepted,+ Failed,+ Unknown,+ Skipped,+}++#[derive(Clone, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct NativeJobStepStatus {+ pub id: String,+ pub state: NativeJobStepState,+ pub reason: Option<String>,+ pub vendor_code: Option<i32>,+}++#[derive(Clone, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct NativeJobDamengCreatedChild {+ pub partition: String,+ pub name: String,+ pub id: String,+}++#[derive(Clone, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct NativeJobOperationStatus {+ pub operation_id: String,+ pub target: Option<NativeJobRef>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub observed_identity: Option<NativeJobRow>,+ #[serde(default, skip_serializing_if = "Vec::is_empty")]+ pub created_children: Vec<NativeJobDamengCreatedChild>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub execution_observation: Option<NativeJobExecutionObservation>,+ pub state: NativeJobOperationState,+ pub outcome: NativeJobOperationOutcome,+ pub cancel_requested: bool,+ pub steps: Vec<NativeJobStepStatus>,+ pub reason: Option<String>,+}++#[derive(Clone, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct NativeJobExecutionObservation {+ pub observed_at: String,+ pub association: String,+ pub reason: String,+ pub running: NativeJobMetadata<Vec<NativeJobRow>>,+ pub history: NativeJobMetadata<Vec<NativeJobRow>>,+ pub sources: BTreeMap<String, NativeJobCatalogSource>,+ pub candidates: Vec<NativeJobExecutionCandidate>,+}++#[derive(Clone, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct NativeJobExecutionCandidate {+ pub native_key: String,+ pub phase: String,+ pub evidence: String,+ pub row: NativeJobRow,+}++#[derive(Clone, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct NativeJobDetails {+ pub snapshot: NativeJobSnapshot,+ pub native_identity: NativeJobMetadata<NativeJobRow>,+ pub consistency: NativeJobMetadata<()>,+ pub parameter_metadata: NativeJobMetadata<Vec<NativeJobRow>>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub program: Option<NativeJobMetadata<NativeJobRow>>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub program_arguments: Option<NativeJobMetadata<Vec<NativeJobRow>>>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub legacy_definition: Option<NativeJobMetadata<NativeJobRow>>,+ pub steps: NativeJobMetadata<Vec<NativeJobRow>>,+ pub schedules: NativeJobMetadata<Vec<NativeJobRow>>,+ pub running: NativeJobMetadata<Vec<NativeJobRow>>,+ pub history: NativeJobMetadata<Vec<NativeJobRow>>,+ pub sources: BTreeMap<String, NativeJobCatalogSource>,+}++impl NativeJobScope {+ pub fn validate(&self) -> Result<(), &'static str> {+ if !valid_identity_part(&self.connection_id)+ || !valid_identity_part(&self.context_id)+ || self.database.contains('\0')+ {+ return Err("native_job_identity_invalid");+ }+ Ok(())+ }+}++impl NativeJobRef {+ pub fn scope(&self) -> &NativeJobScope {+ match self {+ Self::Scheduler { scope, .. } | Self::Legacy { scope, .. } | Self::DamengNative { scope, .. } => scope,+ }+ }++ pub fn validate(&self) -> Result<(), &'static str> {+ self.scope().validate()?;+ match self {+ Self::Scheduler { owner, name, .. } => {+ if !valid_identity_part(owner) || !valid_identity_part(name) {+ return Err("native_job_identity_invalid");+ }+ }+ Self::Legacy { job_id, .. } | Self::DamengNative { job_id, .. } => {+ if job_id.starts_with('0') || job_id.is_empty() || !job_id.bytes().all(|byte| byte.is_ascii_digit()) {+ return Err("native_job_id_invalid");+ }+ if let Self::DamengNative { name, .. } = self {+ if !valid_identity_part(name) {+ return Err("native_job_identity_invalid");+ }+ }+ }+ }+ Ok(())+ }+}++fn valid_identity_part(value: &str) -> bool {+ !value.is_empty() && !value.contains('\0')+}diff --git a/crates/dbx-types/src/oracle_trigger.rs b/crates/dbx-types/src/oracle_trigger.rsnew file mode 100644index 0000000000..8dda00c509--- /dev/null+++ b/crates/dbx-types/src/oracle_trigger.rs@@ -0,0 +1,96 @@+use std::collections::BTreeMap;++use serde::{Deserialize, Serialize};++/// Opt-in identity semantics. An old provider omitting trigger metadata has not+/// proved this contract even when it accepts the request parameter.+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]+#[serde(rename_all = "lowercase")]+pub enum MetadataIdentityMode {+ Exact,+}++#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct MetadataReadOptions {+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub identity_mode: Option<MetadataIdentityMode>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub catalog: Option<String>,+}++impl MetadataReadOptions {+ pub fn is_exact(&self) -> bool {+ self.identity_mode == Some(MetadataIdentityMode::Exact)+ }++ /// Existing Agent and plugin methods use snake-case request fields.+ pub fn apply_to(&self, params: &mut serde_json::Value) {+ if let Some(mode) = self.identity_mode {+ params["identity_mode"] = serde_json::json!(mode);+ }+ if let Some(catalog) = &self.catalog {+ params["catalog"] = serde_json::json!(catalog);+ }+ }+}++#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct OracleTriggerParent {+ pub owner: String,+ pub name: String,+ pub object_type: String,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub object_id: Option<String>,+}++#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct OracleTriggerDefinition {+ pub origin: String,+ pub format: String,+ pub complete: bool,+}++#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct OracleTriggerError {+ pub sequence: i64,+ pub line: i64,+ pub position: i64,+ pub text: String,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub severity: Option<String>,+}++#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct OracleTriggerReadState {+ pub state: String,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub message: Option<String>,+}++#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct OracleTriggerMetadata {+ pub contract_version: u8,+ pub identity_mode: MetadataIdentityMode,+ pub engine: String,+ pub engine_version: Option<String>,+ pub owner: String,+ pub name: String,+ pub scope: String,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub scope_type: Option<String>,+ pub scope_owner: Option<String>,+ pub parent: Option<OracleTriggerParent>,+ // Dictionary IDs may exceed JavaScript's exact integer range.+ pub object_id: Option<String>,+ pub last_ddl_time: Option<String>,+ pub definition: Option<OracleTriggerDefinition>,+ pub errors: Option<Vec<OracleTriggerError>>,+ #[serde(default)]+ pub reads: BTreeMap<String, OracleTriggerReadState>,+}diff --git a/crates/dbx-types/src/types.rs b/crates/dbx-types/src/types.rsindex 4b8e43f579..f453ec3694 100644--- a/crates/dbx-types/src/types.rs+++ b/crates/dbx-types/src/types.rs@@ -44,6 +44,10 @@ pub fn validate_blob_bound_statements(previews: &[String], bound: &[BlobBoundSta}pub use crate::mysql_event::MysqlEventInfo;+pub use crate::oracle_trigger::{+ MetadataIdentityMode, MetadataReadOptions, OracleTriggerDefinition, OracleTriggerError, OracleTriggerMetadata,+ OracleTriggerParent, OracleTriggerReadState,+};#[derive(Debug, Clone, Default, Serialize, Deserialize)]pub struct DatabaseInfo {@@ -306,6 +310,8 @@ pub struct ObjectSource {pub editable: Option<bool>,#[serde(default, skip_serializing_if = "Option::is_none")]pub routine_parameters: Option<Vec<RoutineParameterMetadata>>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub trigger: Option<TriggerInfo>,}/// Provenance for structured metadata fields that are optional in [`ColumnInfo`].@@ -955,6 +961,8 @@ pub struct TriggerInfo {pub created_at: Option<String>,#[serde(default, skip_serializing_if = "Option::is_none")]pub statement: Option<String>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub oracle_metadata: Option<OracleTriggerMetadata>,}#[derive(Debug, Clone, Serialize, Deserialize)]diff --git a/crates/dbx-types/tests/native_jobs.rs b/crates/dbx-types/tests/native_jobs.rsnew file mode 100644index 0000000000..f359910ad3--- /dev/null+++ b/crates/dbx-types/tests/native_jobs.rs@@ -0,0 +1,192 @@+use dbx_types::native_jobs::{+ NativeJobLegacyReceipt, NativeJobMutation, NativeJobOperationStatus, NativeJobPreparedPlan, NativeJobRef,+ NativeJobRequest, NativeJobSnapshot,+};+use serde_json::json;++#[test]+fn legacy_ids_remain_exact_strings_across_the_transport() {+ let wire = json!({+ "scope": {"connectionId": "connection-a", "database": "", "contextId": "context-1"},+ "kind": "legacy",+ "jobId": "9007199254740993"+ });+ let target: NativeJobRef = serde_json::from_value(wire.clone()).unwrap();+ target.validate().unwrap();+ assert_eq!(serde_json::to_value(target).unwrap(), wire);+ assert!(serde_json::from_value::<NativeJobRef>(json!({+ "scope": {"connectionId": "connection-a", "database": "", "contextId": "context-1"},+ "kind": "legacy",+ "jobId": 9007199254740993_u64+ }))+ .is_err());+}++#[test]+fn snapshot_transport_preserves_parameter_states_and_complex_definitions() {+ let wire = json!({+ "ref": {+ "scope": {"connectionId": "a", "database": "tenant", "contextId": "context"},+ "kind": "scheduler", "owner": "Owner.With.Dot", "name": " Job,\"One "+ },+ "revision": "server-revision",+ "definition": {"status": "available", "value": {+ "comments": null, "auto_drop": false, "advanced": {"native": ["unchanged", 7]}+ }},+ "arguments": {"status": "available", "value": [+ {"position": 1, "dataType": "VARCHAR2", "value": {"kind": "unset"}, "editable": true},+ {"position": 2, "dataType": "VARCHAR2", "value": {"kind": "inherit"}, "editable": true},+ {"position": 3, "dataType": "VARCHAR2", "value": {"kind": "null"}, "editable": true},+ {"position": 4, "dataType": "VARCHAR2", "value": {"kind": "value", "value": ""}, "editable": true},+ {"position": 5, "dataType": "ANYDATA", "value": {"kind": "opaque", "value": {"raw": "preserved"}}, "editable": false, "reason": "unparsed"}+ ]}+ });+ let snapshot: NativeJobSnapshot = serde_json::from_value(wire.clone()).unwrap();+ snapshot.job_ref.validate().unwrap();+ assert_eq!(serde_json::to_value(snapshot).unwrap(), wire);+}++#[test]+fn noncanonical_numeric_ids_are_rejected_before_native_calls() {+ for id in ["0", "01", "-1", "1e3", "1.5", "1 OR 1=1", "١"] {+ let target: NativeJobRef = serde_json::from_value(json!({+ "scope": {"connectionId": "a", "database": "", "contextId": "context"},+ "kind": "legacy", "jobId": id+ }))+ .unwrap();+ assert_eq!(target.validate(), Err("native_job_id_invalid"), "id={id}");+ }+}++#[test]+fn empty_execution_database_remains_valid_but_missing_scope_identity_does_not() {+ let wire = json!({+ "scope": {"connectionId": "a", "database": "", "contextId": "context"},+ "kind": "dameng-native", "jobId": "42", "name": " exact name "+ });+ let target: NativeJobRef = serde_json::from_value(wire.clone()).unwrap();+ target.validate().unwrap();+ assert_eq!(serde_json::to_value(target).unwrap(), wire);+ for missing in ["connectionId", "contextId"] {+ let mut invalid = wire.clone();+ invalid["scope"][missing] = json!("");+ let target: NativeJobRef = serde_json::from_value(invalid).unwrap();+ assert_eq!(target.validate(), Err("native_job_identity_invalid"));+ }+}++#[test]+fn mutation_preview_and_partial_result_share_the_frontend_wire_contract() {+ let target = json!({"scope":{"connectionId":"c","database":"","contextId":"ctx"},"kind":"legacy","jobId":"9007199254740993"});+ let wire = json!({"target":target,"baseline":"revision","action":"update","attributes":[{"name":"WHAT","change":{"kind":"set","value":"BEGIN a('x'); END;"}}],"arguments":[]});+ let mutation: NativeJobMutation = serde_json::from_value(wire.clone()).unwrap();+ mutation.target.validate().unwrap();+ assert_eq!(serde_json::to_value(mutation).unwrap(), wire);+ let wire = json!({"planId":"opaque-plan","operationId":"opaque-operation","scope":target["scope"],"target":target,"steps":[{"id":"definition","label":"native_job_step_definition","sql":"BEGIN NULL; END;"}]});+ let plan: NativeJobPreparedPlan = serde_json::from_value(wire.clone()).unwrap();+ assert_eq!(serde_json::to_value(plan).unwrap(), wire);+ let wire = json!({"operationId":"opaque-operation","target":target,"state":"finished","outcome":"partial","cancelRequested":true,"steps":[{"id":"definition","state":"applied","reason":null,"vendorCode":null},{"id":"argument:1","state":"skipped","reason":null,"vendorCode":null}],"reason":"native_job_canceled_after_dispatch"});+ let status: NativeJobOperationStatus = serde_json::from_value(wire.clone()).unwrap();+ assert_eq!(serde_json::to_value(status).unwrap(), wire);+}++#[test]+fn creation_has_no_invented_native_id_and_existing_requests_keep_their_wire_shape() {+ let scope = json!({"connectionId":"c","database":"","contextId":"ctx"});+ let wire = json!({"action":"create","scope":scope,"definition":{"kind":"legacy","what":"private_call();","nextDate":"2026-10-21 10:20:30","interval":"NULL","enabled":false,"schema":"Exact Owner","instance":0}});+ let request: NativeJobRequest = serde_json::from_value(wire.clone()).unwrap();+ assert_eq!(serde_json::to_value(request).unwrap(), wire);+ let wire = json!({"action":"enable","target":{"scope":scope,"kind":"legacy","jobId":"9007199254740993"},"baseline":"baseline"});+ let request: NativeJobRequest = serde_json::from_value(wire.clone()).unwrap();+ assert_eq!(serde_json::to_value(request).unwrap(), wire);+ let wire = json!({"planId":"plan","operationId":"operation","scope":scope,"target":null,"steps":[]});+ let preview: NativeJobPreparedPlan = serde_json::from_value(wire.clone()).unwrap();+ assert_eq!(serde_json::to_value(preview).unwrap(), wire);+ assert!(serde_json::from_value::<NativeJobRequest>(json!({"action":"create","scope":scope,"definition":{"kind":"legacy","what":"call();","nextDate":"2026-10-21 10:20:30","interval":"NULL","enabled":"false"}})).is_err());+}++#[test]+fn ob_disposal_fact_is_explicit_without_changing_old_oracle_receipts() {+ let mut wire = json!({"operationId":"op","phase":"committed","jobId":"9007199254740993"});+ let receipt: NativeJobLegacyReceipt = serde_json::from_value(wire.clone()).unwrap();+ assert_eq!(receipt.disposal_confirmed, None);+ assert!(serde_json::to_value(receipt).unwrap().get("disposalConfirmed").is_none());+ for confirmed in [false, true] {+ wire["disposalConfirmed"] = json!(confirmed);+ let receipt: NativeJobLegacyReceipt = serde_json::from_value(wire.clone()).unwrap();+ assert_eq!(receipt.disposal_confirmed, Some(confirmed));+ assert_eq!(serde_json::to_value(receipt).unwrap()["disposalConfirmed"], json!(confirmed));+ }+}++#[test]+fn scheduler_reference_changes_keep_explicit_components_and_the_final_enabled_intent() {+ let target = json!({"scope":{"connectionId":"c","database":"","contextId":"ctx"},"kind":"scheduler","owner":"Owner","name":"Job"});+ for enabled in [false, true] {+ let wire = json!({"action":"update","target":target,"baseline":"revision","finalEnabled":enabled,+ "attributes":[{"name":"PROGRAM_NAME","change":{"kind":"set","value":{"owner":"Own.er","name":"A,B\"C","kind":"program"}}}],"arguments":[]});+ let request: NativeJobRequest = serde_json::from_value(wire.clone()).unwrap();+ assert_eq!(serde_json::to_value(request).unwrap(), wire);+ }+ let wire = json!({"action":"update","target":target,"baseline":"revision","attributes":[],"arguments":[]});+ let request: NativeJobRequest = serde_json::from_value(wire.clone()).unwrap();+ assert_eq!(serde_json::to_value(request).unwrap(), wire);+}++#[test]+fn a_conversion_retains_its_complete_target_arguments_after_a_partial_apply() {+ let target = json!({"scope":{"connectionId":"c","database":"","contextId":"ctx"},"kind":"scheduler","owner":"Owner","name":"Job"});+ for program in [json!({"owner":"Own.er","name":"New,Program"}), serde_json::Value::Null] {+ let wire = json!({"action":"update","target":target,"baseline":"fresh-revision","finalEnabled":true,+ "attributes":[],"arguments":[],"argumentTarget":{"program":program,"arguments":[+ {"position":1,"dataType":"VARCHAR2","value":{"kind":"inherit"}},+ {"position":2,"dataType":"NUMBER","value":{"kind":"null"}}+ ]}});+ let request: NativeJobRequest = serde_json::from_value(wire.clone()).unwrap();+ assert_eq!(serde_json::to_value(request).unwrap(), wire);+ }+}++#[test]+fn scheduler_creation_preserves_reference_identity_and_observed_native_generations() {+ let wire = json!({"action":"create","scope":{"connectionId":"c","database":"","contextId":"ctx"},"definition":{+ "kind":"scheduler","owner":" Exact.Owner ","name":" A,B ","program":{"owner":"ProgramOwner","name":"Program.Name"},+ "schedule":{"owner":"ScheduleOwner","name":"Calendar"},"numberOfArguments":0,"enabled":false,"autoDrop":false,+ "arguments":[{"position":1,"dataType":"VARCHAR2","value":{"kind":"inherit"}}]+ }});+ let request: NativeJobRequest = serde_json::from_value(wire.clone()).unwrap();+ assert_eq!(serde_json::to_value(request).unwrap(), wire);+ let wire = json!({"operationId":"op","target":null,"observedIdentity":{"DBX_JOB_ID":"900719925474099312345","DBX_CREATED_AT":"exact generation"},+ "state":"finished","outcome":"unknown","cancelRequested":false,"steps":[],"reason":"native_job_creation_outcome_unknown"});+ let status: NativeJobOperationStatus = serde_json::from_value(wire.clone()).unwrap();+ assert_eq!(serde_json::to_value(status).unwrap(), wire);+}++#[test]+fn dameng_child_configuration_preserves_native_input_names_and_null_semantics() {+ let wire = json!({"action":"configure-dameng","target":{"kind":"dameng-native","scope":{"connectionId":"c","database":"","contextId":"ctx"},"jobId":"900719925474099312345","name":"Job_1"},"baseline":"native-baseline",+ "configuration":{+ "attributes":[{"name":"ENABLE","change":{"kind":"set","value":false}}],+ "steps":[{"kind":"update","name":"backup","attributes":[{"name":"COMMAND_INPUT","change":{"kind":"set","value":"01000000E:\\backups"}},{"name":"SUCC_NEXT_STEP","change":{"kind":"clear"}}]},{"kind":"add","name":"next_step","attributes":[]}],+ "schedules":[{"kind":"drop","name":"old_schedule"}]+ }});+ let request: NativeJobRequest = serde_json::from_value(wire.clone()).unwrap();+ assert_eq!(serde_json::to_value(request).unwrap(), wire);+ let request: NativeJobRequest = serde_json::from_value(json!({"action":"configure-dameng","target":wire["target"],"baseline":"native-baseline","configuration":{"steps":[{"kind":"add","name":"new_step"}]}})).unwrap();+ let value = serde_json::to_value(request).unwrap();+ assert_eq!(value["configuration"]["attributes"], json!([]));+ assert_eq!(value["configuration"]["schedules"], json!([]));+ assert_eq!(value["configuration"]["steps"][0]["attributes"], json!([]));+}++#[test]+fn dameng_creation_and_acknowledged_child_ids_round_trip_without_fake_or_numeric_targets() {+ let wire = json!({"action":"create","scope":{"connectionId":"c","database":"","contextId":"ctx"},"definition":{+ "kind":"dameng-native","name":"New_job","enabled":false,"configuration":{"attributes":[],"steps":[{"kind":"add","name":"sql","attributes":[{"name":"COMMAND_INPUT","change":{"kind":"set","value":"SELECT 1;"}}]}],"schedules":[]}+ }});+ let request: NativeJobRequest = serde_json::from_value(wire.clone()).unwrap();+ assert_eq!(serde_json::to_value(request).unwrap(), wire);+ let wire = json!({"operationId":"op","target":null,"state":"finished","outcome":"partial","cancelRequested":false,"steps":[],"reason":"native_failure","createdChildren":[{"partition":"steps","name":"sql","id":"900719925474099312345"}]});+ let status: NativeJobOperationStatus = serde_json::from_value(wire.clone()).unwrap();+ assert_eq!(serde_json::to_value(status).unwrap(), wire);+}diff --git a/crates/dbx-types/tests/trigger_metadata.rs b/crates/dbx-types/tests/trigger_metadata.rsnew file mode 100644index 0000000000..3335e7eb52--- /dev/null+++ b/crates/dbx-types/tests/trigger_metadata.rs@@ -0,0 +1,83 @@+use dbx_types::types::{ObjectInfo, ObjectSource, TriggerInfo};+use serde_json::{json, Value};++#[test]+fn metadata_options_keep_the_legacy_request_shape_and_forward_exact_catalog_raw() {+ use dbx_types::oracle_trigger::{MetadataIdentityMode, MetadataReadOptions};+ let mut params = json!({"schema":" Owner ", "name":" Trigger "});+ MetadataReadOptions::default().apply_to(&mut params);+ assert_eq!(params, json!({"schema":" Owner ", "name":" Trigger "}));+ let options =+ MetadataReadOptions { identity_mode: Some(MetadataIdentityMode::Exact), catalog: Some(" Catalog ".into()) };+ options.apply_to(&mut params);+ assert_eq!(params, json!({"schema":" Owner ", "name":" Trigger ", "identity_mode":"exact", "catalog":" Catalog "}));+ assert!(serde_json::from_value::<MetadataReadOptions>(json!({"identityMode":"approximate"})).is_err());+}++fn metadata(scope: &str, parent: Value) -> Value {+ json!({+ "contractVersion": 1,+ "identityMode": "exact",+ "engine": "oceanbase-oracle",+ "engineVersion": "4.2.5.7_107",+ "owner": " Trigger Owner ",+ "name": "Mixed\"Trigger",+ "scope": scope,+ "scopeOwner": null,+ "parent": parent,+ "objectId": "9007199254740993",+ "lastDdlTime": "2026-10-21 08:00:00",+ "definition": {"origin": "ALL_SOURCE", "format": "declaration", "complete": true},+ "errors": [{"sequence": 1, "line": 4, "position": 7, "text": "Missing procedure", "severity": "ERROR"}],+ "reads": {"identity": {"state": "available"}, "errors": {"state": "available"}}+ })+}++#[test]+fn exact_trigger_metadata_preserves_raw_identity_and_independent_states() {+ let raw = json!({+ "name": "Mixed\"Trigger", "event": "INSERT", "timing": "BEFORE EACH ROW",+ "enabled": true, "valid": false,+ "oracle_metadata": metadata("VIEW", json!({"owner": " Parent Owner ", "name": " View ", "objectType": "VIEW", "objectId": "42"}))+ });+ let trigger: TriggerInfo = serde_json::from_value(raw.clone()).unwrap();+ let serialized = serde_json::to_value(trigger).unwrap();+ assert_eq!(serialized["enabled"], true);+ assert_eq!(serialized["valid"], false);+ assert_eq!(serialized["oracle_metadata"], raw["oracle_metadata"]);+}++#[test]+fn source_and_summary_transport_the_same_non_table_trigger() {+ let trigger = json!({+ "name": "Mixed\"Trigger", "event": "CREATE", "timing": "AFTER EVENT",+ "enabled": false, "valid": true,+ "oracle_metadata": metadata("SCHEMA", Value::Null)+ });+ let source: ObjectSource = serde_json::from_value(json!({+ "name": "Mixed\"Trigger", "object_type": "TRIGGER", "schema": " Trigger Owner ",+ "source": "TRIGGER definition", "trigger": trigger+ }))+ .unwrap();+ let summary: ObjectInfo = serde_json::from_value(json!({+ "name": "Mixed\"Trigger", "object_type": "TRIGGER", "schema": " Trigger Owner ",+ "trigger": trigger+ }))+ .unwrap();+ let source = serde_json::to_value(source).unwrap();+ let summary = serde_json::to_value(summary).unwrap();+ assert_eq!(source["trigger"]["oracle_metadata"], trigger["oracle_metadata"]);+ assert_eq!(source["trigger"], summary["trigger"]);+ assert!(source["trigger"]["oracle_metadata"]["parent"].is_null());+}++#[test]+fn legacy_trigger_payload_stays_unknown_and_does_not_claim_exact_support() {+ let trigger: TriggerInfo =+ serde_json::from_value(json!({"name":"T", "event":"INSERT", "timing":"BEFORE"})).unwrap();+ let serialized = serde_json::to_value(trigger).unwrap();+ assert_eq!(serialized, json!({"name":"T", "event":"INSERT", "timing":"BEFORE"}));+ let source: ObjectSource =+ serde_json::from_value(json!({"name":"T", "object_type":"TRIGGER", "source":"body"})).unwrap();+ assert!(serde_json::to_value(source).unwrap().get("trigger").is_none());+}diff --git a/crates/dbx-web/src/main.rs b/crates/dbx-web/src/main.rsindex 074007e37b..5fcd7d564b 100644--- a/crates/dbx-web/src/main.rs+++ b/crates/dbx-web/src/main.rs@@ -799,6 +799,14 @@ async fn serve() -> Result<(), String> {.route("/schema/object-source", get(routes::schema::get_object_source)).route("/schema/event-info", get(routes::schema::get_event_info)).route("/schema/custom-type-details", get(routes::schema::get_custom_type_details))+ .route("/schema/native-jobs/context", post(routes::native_jobs::open_context))+ .route("/schema/native-jobs/list", post(routes::native_jobs::list))+ .route("/schema/native-jobs/references", post(routes::native_jobs::references))+ .route("/schema/native-jobs/read", post(routes::native_jobs::read))+ .route("/schema/native-jobs/prepare", post(routes::native_jobs::prepare))+ .route("/schema/native-jobs/apply", post(routes::native_jobs::apply))+ .route("/schema/native-jobs/status", post(routes::native_jobs::status))+ .route("/schema/native-jobs/cancel", post(routes::native_jobs::cancel)).route("/schema/oracle-type-data", post(routes::schema::verify_oracle_type_data)).route("/schema/oracle-type-evolution", post(routes::schema::prepare_oracle_type_evolution)).route(@@ -916,6 +924,7 @@ async fn serve() -> Result<(), String> {"/query/validate-oracle-executable-object-source",post(routes::query::validate_oracle_executable_object_source),)+ .route("/query/prepare-oracle-trigger-sql", post(routes::query::prepare_oracle_trigger_sql)).route("/query/fingerprint-oracle-routine-object-source",post(routes::query::fingerprint_oracle_routine_object_source),diff --git a/crates/dbx-web/src/routes/mod.rs b/crates/dbx-web/src/routes/mod.rsindex 9cefd08656..d6abaa5c16 100644--- a/crates/dbx-web/src/routes/mod.rs+++ b/crates/dbx-web/src/routes/mod.rs@@ -23,6 +23,7 @@ pub mod mongodb_import_export;#[cfg(feature = "mq-admin")]pub mod mq;pub mod nacos;+pub mod native_jobs;pub mod plugins;pub mod prompt_template;pub mod query;diff --git a/crates/dbx-web/src/routes/native_jobs.rs b/crates/dbx-web/src/routes/native_jobs.rsnew file mode 100644index 0000000000..c2f9d16b3e--- /dev/null+++ b/crates/dbx-web/src/routes/native_jobs.rs@@ -0,0 +1,173 @@+use crate::error::AppError;+use crate::state::WebState;+use axum::extract::State;+use axum::Json;+use dbx_core::native_jobs::{+ NativeJobContext, NativeJobDetails, NativeJobList, NativeJobListRequest, NativeJobOperationStatus,+ NativeJobPreparedPlan, NativeJobRef, NativeJobReferenceCatalog, NativeJobReferenceListRequest, NativeJobRequest,+};+use dbx_core::schema::native_jobs as jobs;+use serde::Deserialize;+use std::sync::Arc;++#[derive(Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct ContextRequest {+ connection_id: String,+ database: String,+}+#[derive(Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct ApplyRequest {+ plan_id: String,+}+#[derive(Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct OperationRequest {+ operation_id: String,+ #[serde(default)]+ observe: bool,+}++pub async fn open_context(+ State(state): State<Arc<WebState>>,+ Json(request): Json<ContextRequest>,+) -> Result<Json<NativeJobContext>, AppError> {+ jobs::native_job_open_context_core(&state.app, &request.connection_id, &request.database)+ .await+ .map(Json)+ .map_err(AppError::from)+}+pub async fn list(+ State(state): State<Arc<WebState>>,+ Json(request): Json<NativeJobListRequest>,+) -> Result<Json<NativeJobList>, AppError> {+ jobs::native_job_list_core(&state.app, &request).await.map(Json).map_err(AppError::from)+}+pub async fn references(+ State(state): State<Arc<WebState>>,+ Json(request): Json<NativeJobReferenceListRequest>,+) -> Result<Json<NativeJobReferenceCatalog>, AppError> {+ jobs::native_job_references_core(&state.app, &request).await.map(Json).map_err(AppError::from)+}+pub async fn read(+ State(state): State<Arc<WebState>>,+ Json(target): Json<NativeJobRef>,+) -> Result<Json<NativeJobDetails>, AppError> {+ jobs::native_job_read_core(&state.app, &target).await.map(Json).map_err(AppError::from)+}+pub async fn prepare(+ State(state): State<Arc<WebState>>,+ Json(mutation): Json<NativeJobRequest>,+) -> Result<Json<NativeJobPreparedPlan>, AppError> {+ jobs::native_job_prepare_core(&state.app, mutation).await.map(Json).map_err(AppError::from)+}+pub async fn apply(+ State(state): State<Arc<WebState>>,+ Json(request): Json<ApplyRequest>,+) -> Result<Json<NativeJobOperationStatus>, AppError> {+ jobs::native_job_apply_core(state.app.clone(), &request.plan_id).map(Json).map_err(AppError::from)+}+pub async fn status(+ State(state): State<Arc<WebState>>,+ Json(request): Json<OperationRequest>,+) -> Json<NativeJobOperationStatus> {+ Json(jobs::native_job_status_observed_core(&state.app, &request.operation_id, request.observe).await)+}+pub async fn cancel(+ State(state): State<Arc<WebState>>,+ Json(request): Json<OperationRequest>,+) -> Json<NativeJobOperationStatus> {+ Json(jobs::native_job_cancel(&state.app, &request.operation_id))+}++#[cfg(test)]+mod tests {+ use super::*;+ use dbx_core::connection::AppState;+ use dbx_core::native_jobs::{NativeJobOperationOutcome, NativeJobScope};++ async fn setup() -> (tempfile::TempDir, Arc<WebState>) {+ let dir = tempfile::tempdir().unwrap();+ let storage = dbx_core::persistence::test_storage::open(&dir.path().join("state.db")).await.unwrap();+ let app = Arc::new(AppState::new_with_plugin_and_agent_dir_and_app_version(+ storage,+ dir.path().join("plugins"),+ dir.path().join("agents"),+ "0.0.0",+ ));+ let state = Arc::new(WebState::for_tests(app, dir.path().into()));+ (dir, state)+ }++ #[tokio::test]+ async fn apply_cannot_replace_server_prepared_content_with_client_sql() {+ let (_dir, state) = setup().await;+ let request: ApplyRequest =+ serde_json::from_value(serde_json::json!({"planId":"missing-plan", "sql":"sensitive client SQL"})).unwrap();+ let error = apply(State(state), Json(request)).await.err().unwrap();+ assert_eq!(error.message, "native_job_preview_stale");+ }++ #[tokio::test]+ async fn lost_records_remain_unknown_through_status_and_cancel_routes() {+ let (_dir, state) = setup().await;+ let request = || OperationRequest { operation_id: "missing-operation".into(), observe: false };+ let Json(status) = status(State(state.clone()), Json(request())).await;+ let Json(canceled) = cancel(State(state), Json(request())).await;+ assert_eq!(status.outcome, NativeJobOperationOutcome::Unknown);+ assert_eq!(canceled.outcome, NativeJobOperationOutcome::Unknown);+ assert!(canceled.target.is_none());+ }++ #[tokio::test]+ async fn invalid_target_scope_is_rejected_by_the_real_core_read_before_driver_access() {+ let (_dir, state) = setup().await;+ let target = NativeJobRef::Legacy {+ scope: NativeJobScope { connection_id: "c".into(), database: "".into(), context_id: "".into() },+ job_id: "9007199254740993".into(),+ };+ let error = read(State(state), Json(target)).await.err().unwrap();+ assert_eq!(error.message, "native_job_identity_invalid");+ }++ #[tokio::test]+ async fn reference_catalog_scope_is_rejected_before_driver_access() {+ let (_dir, state) = setup().await;+ let request = serde_json::from_value(serde_json::json!({+ "scope": {"connectionId":"c", "database":"", "contextId":""}, "kind":"program"+ }))+ .unwrap();+ let error = references(State(state), Json(request)).await.err().unwrap();+ assert_eq!(error.message, "native_job_identity_invalid");+ }++ #[tokio::test]+ async fn legacy_create_preview_keeps_core_scope_and_ignores_a_client_invented_id() {+ let (_dir, state) = setup().await;+ state.app.configs.write().await.insert(+ "c".into(),+ serde_json::from_value(serde_json::json!({+ "id":"c","name":"test","db_type":"oracle","host":"127.0.0.1","port":1,"username":"Owner","password":"",+ }))+ .unwrap(),+ );+ let context = jobs::native_job_open_context_with(&state.app, "c", "", |_| {+ std::future::ready(Ok(jobs::NativeJobRuntimeIdentity { database_info: None, session_user: "Owner".into() }))+ })+ .await+ .unwrap();+ let request = serde_json::from_value(serde_json::json!({+ "action":"create", "scope":context.scope,+ "target":{"kind":"legacy","scope":context.scope,"jobId":"9007199254740993"},+ "definition":{"kind":"legacy","what":"private_call();","nextDate":"2026-10-21 10:20:30","interval":"NULL","enabled":false},+ })).unwrap();+ let Json(preview) = prepare(State(state.clone()), Json(request)).await.unwrap();+ assert!(preview.target.is_none());+ assert_eq!(preview.scope, context.scope);+ assert_eq!(+ jobs::native_job_status(&state.app, &preview.operation_id).state,+ dbx_core::native_jobs::NativeJobOperationState::Prepared+ );+ }+}diff --git a/crates/dbx-web/src/routes/query.rs b/crates/dbx-web/src/routes/query.rsindex 3494d72a26..1df34e9df2 100644--- a/crates/dbx-web/src/routes/query.rs+++ b/crates/dbx-web/src/routes/query.rs@@ -295,6 +295,12 @@ pub struct ValidateOracleExecutableObjectSourceRequest {pub input: dbx_core::object_source_sql::OracleObjectSourceValidationInput,}+#[derive(Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct PrepareOracleTriggerSqlRequest {+ pub input: dbx_core::object_source_sql::OracleTriggerSqlInput,+}+#[derive(Deserialize)]#[serde(rename_all = "camelCase")]pub struct BuildRoutineRenameObjectSourceRequest {@@ -1374,6 +1380,12 @@ pub async fn validate_oracle_executable_object_source(.map_err(AppError::from)}+pub async fn prepare_oracle_trigger_sql(+ Json(req): Json<PrepareOracleTriggerSqlRequest>,+) -> Result<Json<dbx_core::object_source_sql::PreparedOracleTriggerSql>, AppError> {+ dbx_core::object_source_sql::prepare_oracle_trigger_sql(req.input).map(Json).map_err(AppError::from)+}+pub async fn fingerprint_oracle_routine_object_source(Json(req): Json<BuildExecutableObjectSourceRequest>,) -> Result<Json<String>, AppError> {@@ -1432,15 +1444,14 @@ pub async fn review_oracle_view_rename_source(pub async fn build_table_structure_change_sql(Json(req): Json<BuildTableStructureSqlRequest>,-) -> Json<dbx_core::table_structure_sql::TableStructureSqlResult> {+) -> Json<dbx_core::table_structure_sql::TableStructureSqlPlan> {let mysql_table_charset = req.mysql_table_charset.map(|change| dbx_core::table_structure_sql::build_mysql_table_charset_change_sql(&req.options, change));- let mut result =- dbx_core::table_structure_sql::build_table_structure_change_sql_with_context(req.options, req.starrocks);+ let mut result = dbx_core::table_structure_sql::build_table_structure_change_sql_plan(req.options, req.starrocks);if let Some(extra) = mysql_table_charset {- result.statements.extend(extra.statements);- result.warnings.extend(extra.warnings);+ result.sql.statements.extend(extra.statements);+ result.sql.warnings.extend(extra.warnings);}Json(result)}@@ -1496,8 +1507,8 @@ pub async fn apply_sqlite_table_structure_change(pub async fn build_create_table_sql(Json(req): Json<BuildTableStructureSqlRequest>,-) -> Json<dbx_core::table_structure_sql::TableStructureSqlResult> {- Json(dbx_core::table_structure_sql::build_create_table_sql_with_dialect_options(+) -> Json<dbx_core::table_structure_sql::TableStructureSqlPlan> {+ Json(dbx_core::table_structure_sql::build_create_table_sql_plan_with_dialect_options(req.options,req.server_version.as_deref(),req.dialect_options.unwrap_or_default(),diff --git a/crates/dbx-web/src/routes/schema.rs b/crates/dbx-web/src/routes/schema.rsindex f0fa79c772..86615faac6 100644--- a/crates/dbx-web/src/routes/schema.rs+++ b/crates/dbx-web/src/routes/schema.rs@@ -32,6 +32,7 @@ pub struct SchemaQuery {pub include_postgres_access: Option<bool>,pub portable: Option<bool>,pub execution_id: Option<String>,+ pub identity_mode: Option<dbx_core::schema::MetadataIdentityMode>,pub exact_identity: Option<bool>,pub separate_indexes: Option<bool>,}@@ -359,7 +360,7 @@ pub async fn list_objects(}).collect::<Vec<_>>())} else {- dbx_core::schema::list_objects_core(+ dbx_core::schema::list_objects_core_with_options(&state.app,&connection_id,&database,@@ -369,6 +370,7 @@ pub async fn list_objects(q.offset,object_types.as_deref(),table_name_filter.as_ref(),+ &dbx_core::schema::MetadataReadOptions { identity_mode: q.identity_mode, catalog },).await}@@ -418,7 +420,7 @@ pub async fn get_object_source(let schema = q.schema.as_deref().unwrap_or("");let name = q.table.as_deref().unwrap_or("");let object_type = q.object_type.ok_or_else(|| AppError::from("Missing object_type".to_string()))?;- let result = dbx_core::schema::get_object_source_core(+ let result = dbx_core::schema::get_object_source_core_with_options(&state.app,&q.connection_id,database,@@ -427,6 +429,7 @@ pub async fn get_object_source(object_type,q.signature.as_deref(),q.relation_name.as_deref(),+ &dbx_core::schema::MetadataReadOptions { identity_mode: q.identity_mode, catalog: q.catalog },).await.map_err(AppError::from)?;@@ -840,9 +843,16 @@ pub async fn list_triggers(.await.map_err(AppError::from)?} else {- dbx_core::schema::list_triggers_core(&state.app, &q.connection_id, database, schema, table)- .await- .map_err(AppError::from)?+ dbx_core::schema::list_triggers_core_with_options(+ &state.app,+ &q.connection_id,+ database,+ schema,+ table,+ &dbx_core::schema::MetadataReadOptions { identity_mode: q.identity_mode, catalog: q.catalog },+ )+ .await+ .map_err(AppError::from)?};Ok(Json(serde_json::to_value(result).map_err(|e| AppError::from(e.to_string()))?))}diff --git a/docs/assets/schema-trigger-management.png b/docs/assets/schema-trigger-management.pngnew file mode 100644index 0000000000..4a2feb28cdBinary files /dev/null and b/docs/assets/schema-trigger-management.png differdiff --git a/docs/content/docs/databases.cn.mdx b/docs/content/docs/databases.cn.mdxindex c450299c74..5f1f54623e 100644--- a/docs/content/docs/databases.cn.mdx+++ b/docs/content/docs/databases.cn.mdx@@ -98,6 +98,58 @@ Redis、MongoDB、搜索、向量、HBase、配置中心和消息队列工作区- [数据库备份](/cn/docs/database-backup) 当前只在 Desktop 为 MySQL 和 PostgreSQL 提供定时一致性备份- 云同步和配置导出只迁移 DBX 配置,不会备份业务数据库+### 原生 Job 与 Scheduler 作业++Oracle、OceanBase Oracle 连接的 **原生作业** 入口与达梦的 **代理作业** 共用管理页。在 **作业类型** 中切换 Scheduler 和传统 Job;达梦另有 SYSJOB 代理作业。所有者筛选与作业搜索由数据库查询执行,不局限于当前列表页。同名的 Scheduler 作业按所有者分别选择。++Scheduler 的新建和编辑表单包含定义、参数和高级属性。参数可区分保持原值、未设置、继承默认、SQL NULL 和显式值;不能安全转换的原生值保留原样。更改前先预览,再使用同页结果区核对执行状态。传统 Job 保留原生数字 ID,不从显示名称推断身份;`LOG_USER`、`PRIV_USER` 和 `SCHEMA_USER` 分别显示。新建传统 Job 的 `SCHEMA_USER` 设置执行 schema,不改变登录身份。++新建 Scheduler 作业时,可在适用数据库中从数据库对象列表选择 Program、命名 Schedule 或 Chain;高级属性中可选择 Credential 和 Destination。列表按所有者和名称筛选、分页,并显示实际可读范围。系统视图不可读时仍可填写精确名称。选用 Program 或命名 Schedule 后,对应内联字段会保留在草稿中但不写入;清除引用可恢复编辑内联字段。++引用 Program 时,参数数量和默认值从 Program 读取,不使用作业的内联参数数量推断。参数区域分别展示默认值和作业的显式值;数据库提供的元数据参数不可覆盖。无法确定的默认值不会当作 SQL NULL。新建表单及 Oracle 引用编辑会分别保留 Program 和内联参数草稿,不把旧参数自动写入新的 Program。++Oracle 的参数值可选择普通文本或明确的 ANYDATA 标量类型;**SQL NULL** 会保留所选类型,不等于未设置或继承。NUMBER 按完整十进制文本输入;日期与时间分开填写,时间戳最多保留 9 位小数,带本地时区的时间以 UTC 编辑。INTERVAL 使用总月数或总纳秒数,RAW 使用十六进制,BINARY_FLOAT/BINARY_DOUBLE 使用完整位模式。Program 默认值使用同样的只读控件展示;不能保真读取的值保持只读。Lightweight 作业不提供 ANYDATA 输入。++编辑已有 Oracle Scheduler 作业时,可在同一编辑器中更换 Program、Schedule、Window、Window group 或 Chain,并在高级属性中选择凭据和目的地。选择 Program 后,先核对目标参数,再选择最终启用状态。预览包含暂停未来调度及条件参数设置或重置;已满足目标的参数会跳过,出现外部冲突则停止。只有定义和参数全部验证通过后,才应用所选启用状态。++Oracle 的 **触发方式** 可选择日期或重复规则、命名调度或窗口、队列事件、文件到达事件。队列事件分别填写所有者、队列名称、可选 AQ 代理和事件条件;文件到达事件可复用 File watcher 选择器。未选中的时间或引用输入保留在草稿中,不写入当前目标。目的地组只作为引用选择,不展开或修改共享组;不兼容的作业类型会在预览时拒绝,保留输入供修正。++Oracle 高级属性中的 **执行目标** 可选择本地执行、传统远程主机(`host[:port]`)或命名目的地及目标组。主机文本按原样编辑,不按对象名解析。切换模式会保留未选中模式的草稿,预览只包含当前选择;选择本地执行可清除原远程目标。++部分成功后先核对当前状态,再使用 **修正草稿** 重新读取和预览。**恢复原定义草稿** 将最初读到的定义放回编辑器,不直接回滚数据库;仍须核对当前状态并确认新的预览。编辑不会自动重跑作业。++异步运行或停止显示 **已接受** 时,只表示管理请求已被接受。同页的 **原生执行观测** 分别展示当前运行、历史读取状态和可识别的实例,可使用 **刷新运行结果** 再读。新观察到的成功、失败或停止记录不自动归因于本次请求;关联不确定时会明确说明。没有当前运行行不等于未执行,也不等于已由本次请求停止;DBX 不会据此自动重跑。++引用列表需要相应系统视图的读取权限。OceanBase V4.2.5 的 Program 视图为 [`SYS.DBA_SCHEDULER_PROGRAM`](https://www.oceanbase.com/docs/common-oceanbase-database-cn-1000000001500817),不同于 Oracle 的复数名称;普通账号没有该视图的读取权限时,列表可能返回 ORA-00942。列表不可读不等于引用对象不存在,DBX 不会自动授予权限。++OceanBase V4.2.5 的 Job 和 [Program 参数视图](https://www.oceanbase.com/docs/common-oceanbase-database-cn-1000000001500848) 为兼容占位,即使存在实际参数也始终返回空。参数区域会说明无法读取,不将空结果解释为没有参数;仍可操作不依赖这些参数的可读定义和控制项。++OceanBase V4.2.5 的已有 Scheduler 作业基础定义只读;可在 **高级属性** 中修改作业类、最大失败次数、最大运行时长和执行 Zone。时长使用非负整秒的 DS interval,例如 `0 00:02:00` 表示两分钟;Zone 使用名称或 `RANDOM`,不是 Oracle 的数字实例。最大失败次数从身份核对后的原生视图读取,该字段不可读时不影响其他可编辑属性。字段不能清空时,表单不提供清空动作。++这与新建时的输入范围不同:新建仍可设置初始正文、日期、重复表达式和注释,参数数量为 0–255;类型为 `STORED_PROCEDURE` 或 `PLSQL_BLOCK`。本版不提供命名 Schedule、Credential 或 Destination 的创建输入,Program 引用按本版原生规则处理。++OceanBase 传统 Job 使用可为空的 Zone 名称,不使用 Oracle 的数字实例。新建需要配套的 OceanBase Agent 或 Generic JDBC 运行包;页面提示更新时,更新运行包后重新连接。数据库还需由管理员启用 `DBMS_JOB` 包,DBX 不会自动更改全局开关。新建会先设置所选启用状态和日期,再确认首次提交;启禁用保留执行时读取的最新下次运行日期。++Oracle 和 OceanBase 传统 Job 的 **前台运行** 会等待原生调用返回。在已验证的 OceanBase 4.2.5.7 中,运行还会清除禁用标记并重新计算下次运行日期;确认预览前应核对这一调度影响。传统 DBMS_JOB 没有原生停止入口,不能将停止会话当作停止作业。Oracle Scheduler 的普通停止与 **强制停止** 分开预览和确认;OceanBase 不套用 Oracle 的强制停止签名。++#### 达梦 SYSJOB 作业++本期 DM 尚未实现以下操作:已有 Scheduler 作业内联定义与 Program/命名 Schedule 引用之间的建立或解除、参数 RESET/恢复继承、Job 执行 schema 迁移,以及传统 DBMS_JOB 新建。DBX 不会发送未经确认的原生调用;不能将上文 Oracle 的引用编辑和传统 Job 新建能力套用于 DM。这些能力待精确原生契约确认后补齐。原生 Oracle、DM8 实机验收另行暂缓;自动化和模拟边界界面检查不代表实库验证通过。++从达梦连接的 **代理作业** 入口管理 SYSJOB 作业。列表可按名称、所有者或描述搜索;选中作业后分别读取属性、步骤、调度、当前运行和历史。某部分无权限或读取失败时会单独显示,不按空数据处理。++新建作业时:++1. 点击 **新建作业**,填写名称,在 **作业属性** 中选择最终启用状态。+2. 在 **步骤** 中填写 SQL 或原生配置参数;可新增多个步骤并设置成功、失败后的动作和下一步骤。在 **调度** 中配置一个或多个时间安排。+3. 点击 **预览 SQL**,核对目标和配置,再确认执行。DBX 会先禁用创建,在同一物理会话完成配置、读回确认后,才按选择最终启用。++已有作业使用 **编辑作业** 修改,未改属性和子项保持不变。备份、还原或 DTS 步骤显示的 `COMMAND` 可能是数据库生成的语句;修改其定义时应提供原始配置参数,不把生成语句重新当作配置输入。++部分成功或结果未知时,在原结果区使用 **重新读取**、**修正草稿** 和 **查询操作结果**。已确认创建的作业和子项按原生 ID 继续处理;响应不明的新增不会自动按同名认领或重复创建。修正并确认新的预览后,只执行剩余变更,不自动重跑业务作业。++**停止后续步骤** 只取消尚未发送的管理操作。需要停止正在运行的作业时,使用 **停止当前执行**;停用未来调度不等于停止当前运行。作业环境不存在时,页面提供单独的 **初始化作业环境**,不会自动初始化。+### Desktop 和 Docker/Web两种运行方式共享大部分 Rust 核心查询、元数据和安全策略,但并非功能完全相同。Desktop 才有本地 SQL 文件目录、系统文件选择、Deep Link、本机 CLI Agent 和定时数据库备份;Web 文件、驱动和 Agent 都位于服务器数据目录。diff --git a/docs/content/docs/databases.mdx b/docs/content/docs/databases.mdxindex 4771e2d338..ac0616f718 100644--- a/docs/content/docs/databases.mdx+++ b/docs/content/docs/databases.mdx@@ -98,6 +98,58 @@ Redis, MongoDB, search, vector, HBase, configuration-center, and message-queue w- [Database Backup](/en/docs/database-backup) currently schedules consistent MySQL and PostgreSQL backups in Desktop only- Cloud Sync and configuration export migrate DBX settings, not business database contents+### Native Job and Scheduler Management++Oracle and OceanBase Oracle connections expose **Native jobs**; Dameng retains **Agent Jobs**. They share the same management page. Use **Job type** to select Scheduler or traditional Job, with SYSJOB agent jobs available for Dameng. Owner filtering and search run against the database rather than only the loaded page. Scheduler jobs with the same name are selected separately by owner.++Scheduler creation and editing provide definition, argument, and advanced-attribute sections. Arguments distinguish keeping the original, unset, inherited default, SQL NULL, and explicit values; native values that cannot be safely converted remain unchanged. Preview changes, confirm, and inspect the result in the same page. Traditional jobs retain their native numeric IDs and display `LOG_USER`, `PRIV_USER`, and `SCHEMA_USER` separately. When creating a traditional job, `SCHEMA_USER` sets the execution schema, not the login identity.++When creating a Scheduler job, select a Program, named Schedule, or Chain from the catalog where applicable. Credential and Destination selection is available under advanced attributes. The catalog filters by owner and name, pages results, and shows the actual readable scope. You can enter exact names when the catalog is unavailable. Selecting a Program or named Schedule retains the corresponding inline fields in the draft without writing them; clear the reference to edit those inline fields again.++For a referenced Program, argument counts and defaults come from the Program rather than the job's inline argument count. The argument section shows defaults separately from explicit job values; database-supplied metadata arguments cannot be overridden. An unresolved default is not treated as SQL NULL. Creation and Oracle reference editing retain separate Program and inline argument drafts instead of applying old overrides to the newly selected Program.++Oracle argument values offer plain text or an explicit ANYDATA scalar type. **SQL NULL** retains the selected type; it is distinct from unset or inherited. Enter NUMBER as complete decimal text. Date and time inputs are separate; timestamps retain up to 9 fractional digits, and local-time-zone timestamps are edited in UTC. INTERVAL uses total months or nanoseconds, RAW uses hexadecimal, and BINARY_FLOAT/BINARY_DOUBLE use complete bit patterns. Program defaults use the same controls in read-only mode. Values that cannot be read losslessly remain read-only. Lightweight jobs do not offer ANYDATA input.++When editing an existing Oracle Scheduler job, use the same editor to change its Program, Schedule, Window, Window group, or Chain, and choose credentials and destinations under advanced attributes. After selecting a Program, review its arguments and choose the final enabled state. The preview includes pausing future scheduling and conditional argument settings or resets. Arguments already at their target are skipped; conflicting external changes stop the operation. The selected enabled state is applied only after the definition and arguments have been verified.++Oracle's **Trigger** selector offers a date or repeat rule, a named schedule or window, a queue event, or a file arrival event. Queue events have separate owner, queue name, optional AQ agent, and condition inputs. File arrival events reuse the File watcher picker. Inactive time and reference inputs stay in the draft without being written. Destination groups are selected as references, not expanded or modified; an incompatible job type is rejected during preview with the input retained for correction.++Under Oracle's advanced attributes, **Execution target** selects local execution, a legacy remote host (`host[:port]`), or a named destination or group. Host text is edited verbatim, not parsed as an object name. Switching modes retains inactive drafts, while the preview includes only the selected mode. Select local execution to clear the previous remote target.++After partial success, inspect the current state and use **Correct draft** to read and preview again. **Restore original definition draft** puts the initially read definition back in the editor; it does not roll back the database. Review the current state and confirm a new preview before applying it. Editing does not automatically run the job.++For asynchronous Run or Stop, **Accepted** describes the management request, not the job's business result. **Native execution observation** in the same result area shows running/history read states and identifiable instances; use **Refresh run result** to read again. Newly observed success, failure, or stop records are not automatically attributed to this request, and uncertain association is stated explicitly. The absence of a running row does not prove that the job never ran or that this request stopped it. DBX does not automatically rerun the job on that evidence.++Reference lists require read access to the corresponding system views. OceanBase V4.2.5 uses [`SYS.DBA_SCHEDULER_PROGRAM`](https://www.oceanbase.com/docs/common-oceanbase-database-cn-1000000001500817), not Oracle's plural name. An account without read access can receive ORA-00942. An unreadable list does not establish that the referenced object is absent; DBX does not grant privileges automatically.++OceanBase V4.2.5's Job and [Program argument views](https://www.oceanbase.com/docs/common-oceanbase-database-cn-1000000001500848) are compatibility placeholders that always return no rows, including when arguments exist. DBX reports that argument metadata cannot be read instead of treating it as an empty argument list. Readable definition fields and controls that do not depend on those arguments remain available.++Existing OceanBase V4.2.5 Scheduler jobs have read-only base definitions. Use **Advanced attributes** to edit the job class, maximum failures, maximum run duration, and execution Zone. Durations use a nonnegative, whole-second DS interval, such as `0 00:02:00` for two minutes. A Zone is a name or `RANDOM`, not an Oracle numeric instance. Maximum failures is read from the native view after checking the job identity; an unreadable value does not block other editable attributes. Fields that cannot be cleared have no clear action.++Creation accepts a different set of inputs: initial action, dates, repeat expression, and comments remain available, with 0–255 arguments and the `STORED_PROCEDURE` or `PLSQL_BLOCK` job types. This version does not offer named Schedule, Credential, or Destination creation inputs. Program references follow its native naming rules.++OceanBase traditional jobs use a nullable Zone name rather than an Oracle numeric instance. Creation requires a matching OceanBase Agent or Generic JDBC runtime; if DBX requests an update, update the runtime and reconnect. An administrator must also enable the database's `DBMS_JOB` package; DBX does not change the global switch. Creation sets and verifies the selected enabled state and date before the first commit. Enabling or disabling preserves the latest next-run date read during execution.++Oracle and OceanBase traditional jobs use **Run in foreground**, which waits for the native call to return. On the verified OceanBase 4.2.5.7 configuration, running also clears the broken flag and recalculates the next-run date; review this scheduling effect before confirming the preview. Traditional DBMS_JOB has no native stop operation; ending a session is not a substitute. Oracle Scheduler exposes separate normal and **Force stop** previews and confirmation. OceanBase does not reuse Oracle's force-stop signature.++#### Dameng SYSJOB Jobs++This release does not yet implement these DM operations: attaching or detaching Program/named Schedule references when switching an existing Scheduler job to or from an inline definition, argument RESET/default inheritance restoration, job execution-schema migration, and traditional DBMS_JOB creation. DBX does not dispatch native calls whose contracts have not been confirmed. The Oracle reference-editing and traditional-job creation capabilities above do not extend to DM; these DM operations require confirmed native contracts before implementation. Native Oracle and DM8 database acceptance testing remains deferred. Automated tests and UI checks with mocked external boundaries do not establish database acceptance.++Open **Agent Jobs** from a Dameng connection to manage SYSJOB jobs. Search by name, owner, or description, then select a job to read properties, steps, schedules, current runs, and history separately. An unavailable or denied section is shown explicitly rather than treated as empty.++To create a job:++1. Click **New Job**, enter its name, and choose the final enabled state under **Job properties**.+2. Under **Steps**, enter SQL or native configuration input. Add multiple steps and configure success/failure actions and next steps. Use **Schedules** to add one or more schedules.+3. Click **Preview SQL**, review the target and configuration, and confirm. DBX creates the job disabled, completes configuration on one physical session, and verifies readback before applying the selected final enabled state.++Use **Edit job** for existing jobs. Unchanged properties and children are preserved. A backup, restore, or DTS step's catalog `COMMAND` may be database-generated SQL; changing its definition requires the original native configuration, not the generated command.++For a partial or unknown result, use **Read again**, **Correct draft**, and **Check operation result** in the original result area. Acknowledged jobs and children retain their native IDs. An uncertain add is not automatically adopted by name or created again. Correct the draft and confirm a fresh preview to apply remaining changes; business jobs are not rerun automatically.++**Stop remaining steps** only cancels management steps not yet dispatched. Use **Stop Current Run** to request native job stopping; disabling future scheduling does not stop a current run. A missing job environment has a separate **Initialize Job Environment** action and is never initialized automatically.+### Desktop and Docker/WebBoth runtimes share most Rust core query, metadata, and safety policy, but are not feature-identical. Local SQL folders, system file selection, Deep Links, local CLI Agents, and scheduled database backup are Desktop-only. Web files, drivers, and Agents live in the server data directory.diff --git a/docs/content/docs/object-browser.cn.mdx b/docs/content/docs/object-browser.cn.mdxindex 42805e577b..f945a570c9 100644--- a/docs/content/docs/object-browser.cn.mdx+++ b/docs/content/docs/object-browser.cn.mdx@@ -98,6 +98,21 @@ DBX 显示的是当前驱动能获取到的定义。格式、是否包含权限/通过通用 JDBC 连接 OceanBase Oracle 模式时,使用显式 `jdbc:oceanbase:oracle://` URL,使类型列表、详情和源码采用一致的方言。普通 `jdbc:oceanbase://` URL 不会据此推断为 Oracle 模式。+## 查看和修改 Oracle 系触发器++Oracle、OceanBase Oracle 和 DM8 的精确触发器入口按实际驱动与版本开放;旧 Agent、未识别方言或缺少元数据的插件不会自动获得写入能力。原生 Oracle 和 DM8 的实库兼容性仍待验证,不能以 OceanBase 的验证结果替代。++1. 选择「触发器」筛选,按名称定位对象,按需加载更多。单击打开源码侧栏。需要源码标签时,从对象树按当前源码打开设置进入。+2. 核对触发器 owner、真实所属表/视图或非表级作用域。「启用/禁用」和「有效/无效」是独立状态;读取失败或无权限也会单独显示。+3. 修改完整定义并保存,在确认框核对目标、执行 Schema 和实际 SQL。只有正文、截断内容或无法确认的基线不能直接替换对象;可以保留人工补全的候选,补齐权限后显式重读,再重新预览。+4. 查看权威读回结果。数据库接受语句不代表触发器有效;存在编译错误时,在同一详情中查看错误或进入无效对象诊断,再返回源码修正。只有能准确映射到当前源码的错误位置才定位光标。++源码、依赖和被依赖沿用同一详情面板。依赖导航和所属对象入口使用实际 owner/type;非表级触发器没有表导航。切换详情分区保留草稿及撤销记录;关闭或切换对象时,可以取消弃稿。触发器源码刷新与失败后的重试保留最新输入,不自动覆盖草稿。++启停和编译使用原生操作,不通过删建模拟。Oracle/OceanBase 修改会保全已知的禁用状态;DM 的状态恢复可能包含独立步骤,编译失败后不会自动重新启用。++<Callout type="warn">DDL 可能逐条提交。结果未知或部分成功时,先用「只读核实」或刷新读取实际状态;DBX 不自动重放已尝试的写入。保留失败草稿,核实后仅为剩余修改生成新预览。对象或定义已变化时,先重读并核对差异。</Callout>+## 与对象树的区别| 对象树 | 对象浏览器 |diff --git a/docs/content/docs/object-browser.mdx b/docs/content/docs/object-browser.mdxindex eed5ada3ca..675b3c4d2f 100644--- a/docs/content/docs/object-browser.mdx+++ b/docs/content/docs/object-browser.mdx@@ -98,6 +98,21 @@ Metadata sections identify incomplete, unavailable, or unsupported dictionary reFor OceanBase Oracle mode over generic JDBC, use an explicit `jdbc:oceanbase:oracle://` URL so type listing, details, and source use the same dialect. A plain `jdbc:oceanbase://` URL does not identify Oracle mode.+## Inspect and Edit Oracle-Family Triggers++Exact trigger actions for Oracle, OceanBase Oracle, and DM8 depend on the actual driver and version. Older agents, unidentified dialects, or plugins without the metadata contract do not gain write access automatically. Native Oracle and DM8 live-database compatibility still needs validation; OceanBase evidence does not establish it.++1. Select **Triggers**, search by name, and load more as needed. A single click opens the source side panel. To use a bound source tab, open the trigger from the object tree with the source-tab setting.+2. Check the trigger owner and actual owning table/view or non-table scope. Enabled/disabled and valid/invalid are independent states. Failed or denied reads are shown separately.+3. Edit the complete definition and save. Review the fixed target, execution schema, and actual SQL before confirming. A body-only, truncated, or unverified baseline cannot replace the object. Keep a manually completed candidate, repair permissions, explicitly reload authority, and preview again.+4. Inspect the readback. An accepted statement does not prove that the trigger is valid. Read compilation errors in the same details or open invalid-object diagnostics, then return to source to repair them. Cursor navigation is offered only when the error location can be mapped to the current source accurately.++Source, dependencies, and dependents share the existing details panel. Dependency and owning-object navigation use the actual owner and type; non-table triggers have no table navigation. Switching detail sections retains drafts and undo history. Closing or changing objects lets you cancel discarding a draft. Trigger-source refresh and retry retain the latest input rather than overwriting it.++Enable, disable, and compile use native operations, not drop/recreate. Oracle/OceanBase replacement preserves a known disabled state. DM state restoration may require separate steps, and a failed compile never automatically re-enables the trigger.++<Callout type="warn">DDL may commit one statement at a time. After an unknown or partial result, use **Verify without writing** or refresh to inspect actual state. DBX never automatically replays attempted writes. Keep the failed draft and generate a new preview for only the remaining changes after verification. Reload and compare when the object or definition has changed.</Callout>+## Object Tree vs. Object Browser| Object tree | Object browser |diff --git a/docs/content/docs/schema-browser.cn.mdx b/docs/content/docs/schema-browser.cn.mdxindex fbe0b9aee0..03e601f1ef 100644--- a/docs/content/docs/schema-browser.cn.mdx+++ b/docs/content/docs/schema-browser.cn.mdx@@ -94,6 +94,16 @@ description: 使用 DBX 侧边栏组织连接、搜索数据库对象、打开表、对象和数据标签使用不同身份,避免同名对象与表数据标签错误复用。+## 从 Schema 或所属对象打开触发器++Oracle、OceanBase Oracle 和 DM8 在驱动提供精确触发器元数据时,可以从 Schema 的「触发器」组浏览,也可以从实际所属表或视图的触发器节点打开。同名但 owner 不同的触发器是不同对象;触发器 owner、所属对象 owner 和执行 Schema 分别显示,不根据树标签推断。++- 从触发器菜单打开源码;弹窗或源码标签沿用当前打开方式设置。+- 从 Schema、空触发器组或所属表/视图的菜单新建,先选名称和支持的作用域,再生成、修改并预览完整定义。非表级触发器按实际作用域显示,不绑定虚构的父表。+- 菜单按实际驱动能力提供启用、禁用、编译和删除。批量删除沿用同类节点多选规则,先核对全部 SQL,再按序执行;无法核实某一步时停止后续步骤。++结果未知时,保留原行并使用错误详情中的「只读核实」检查数据库,不要直接重发删除。状态含义和源码恢复步骤见 [对象浏览器](/cn/docs/object-browser#查看和修改-oracle-系触发器)。+## 右键菜单与批量操作上下文菜单按节点类型和数据库 capability 动态生成。常见操作包括:diff --git a/docs/content/docs/schema-browser.mdx b/docs/content/docs/schema-browser.mdxindex 3f77f49258..27bb588a98 100644--- a/docs/content/docs/schema-browser.mdx+++ b/docs/content/docs/schema-browser.mdx@@ -100,6 +100,16 @@ Object metadata display is configurable. In large schemas, show only the extra iTable, object, and data tabs use distinct identities so same-named objects do not incorrectly reuse a data tab.+## Open Triggers from a Schema or Owning Object++For Oracle, OceanBase Oracle, and DM8, drivers that provide exact trigger metadata expose a schema-level **Triggers** group as well as triggers under their actual owning table or view. Same-named triggers with different owners remain separate objects. Trigger owner, owning-object owner, and execution schema are shown separately rather than inferred from tree labels.++- Open source from the trigger menu using the configured dialog or source-tab mode.+- Create from a schema, an empty trigger group, or an owning table/view menu. Choose the name and a supported scope, then generate, edit, and preview the complete definition. Non-table triggers show their actual scope without an invented parent table.+- Menus expose enable, disable, compile, and drop according to the driver's capabilities. Tree batch deletion retains same-type selection: review all SQL before serial execution. An unverified step stops the remaining steps.++An unknown result keeps the original row. Use **Verify without writing** in the error details to inspect the database before attempting another deletion. See [Object Browser](/en/docs/object-browser#inspect-and-edit-oracle-family-triggers) for state meanings and source recovery.+## Context Menus and Batch ActionsContext menus are generated from node type and database capabilities. Common actions include:diff --git a/docs/content/docs/table-structure.cn.mdx b/docs/content/docs/table-structure.cn.mdxindex ec7a694bdf..b36724da9a 100644--- a/docs/content/docs/table-structure.cn.mdx+++ b/docs/content/docs/table-structure.cn.mdx@@ -88,6 +88,14 @@ DBX 阻止已知引用,数据库还会拒绝未可见或并发新增的引用其他数据库的外键编辑能力依赖对应方言实现。触发器编辑依赖数据库源码读取和安全 DDL 生成能力;不支持直接修改时仍可以查看源码或复制 DDL。+### Oracle 系触发器的完整源码++在触发器标签选中对象后,复杂定义可使用「编辑完整源码」进入现有源码弹窗,不需要把 compound、CALL、WHEN 或其他复杂子句改写成简单表单。只有正文或读取不完整时,先保留修正候选并补齐权威定义,再保存。该流程的状态和恢复方法见 [对象浏览器](/cn/docs/object-browser#查看和修改-oracle-系触发器)。++源码弹窗只更新对应的触发器,不清除字段、索引、约束或其他触发器草稿。若同一触发器已有结构化草稿,或写入结果未知,先只读核实,再明确选择是否放弃该触发器的结构化草稿;其他结构草稿保留。++保存结构时,继续遵守编辑器原有的组合限制;要求分开保存的索引、主键、约束或已有表外键不能与触发器混合提交。允许的组合按预览顺序逐条执行和读回。触发器重命名可能先删除旧对象再创建新对象;后步失败时旧对象可能已经不存在。DBX 会停止剩余步骤,保留完整草稿与逐步结果,核实后只为必要的剩余修改重新预览,不自动回滚或重放。+## DDL 预览编辑不会立即写入数据库。保存前,DBX 会根据当前方言生成并高亮:diff --git a/docs/content/docs/table-structure.mdx b/docs/content/docs/table-structure.mdxindex 47a21ec8eb..894a5a40be 100644--- a/docs/content/docs/table-structure.mdx+++ b/docs/content/docs/table-structure.mdx@@ -88,6 +88,14 @@ Foreign-key DDL statements commit one at a time. If CREATE succeeds and a laterForeign-key editing on other databases depends on the implementation for that dialect. Trigger editing depends on source retrieval and safe DDL generation; unsupported databases can still expose source or copyable DDL.+### Complete Source for Oracle-Family Triggers++Select a trigger and use **Edit full source** for complex definitions. This opens the existing source dialog without flattening compound, CALL, WHEN, or other complex clauses into a simple form. For body-only or incomplete reads, keep the correction candidate and obtain an authoritative definition before saving. See [Object Browser](/en/docs/object-browser#inspect-and-edit-oracle-family-triggers) for states and recovery.++The source dialog updates only that trigger, leaving columns, indexes, constraints, and other trigger drafts intact. If the same trigger has a structured draft or an unknown write result, verify without writing first, then explicitly decide whether to discard only that trigger's structured draft. Other structure drafts remain.++Existing combination limits still apply: indexes, primary keys, constraints, or existing-table foreign keys that require separate saves cannot be mixed with trigger edits. Allowed combinations execute and read back one statement at a time in preview order. Renaming a trigger may drop the old object before creating the new one; a later failure can leave the old trigger absent. DBX stops remaining steps and retains the complete draft and per-step results. Verify state, then preview only necessary remaining changes without automatic rollback or replay.+## DDL PreviewEdits do not immediately change the database. Before save, DBX generates highlighted dialect-specific SQL such as:diff --git a/docs/content/docs/web-api.cn.mdx b/docs/content/docs/web-api.cn.mdxindex 8d9fbeacc8..c63e433045 100644--- a/docs/content/docs/web-api.cn.mdx+++ b/docs/content/docs/web-api.cn.mdx@@ -216,6 +216,34 @@ GET /api/schema/columns?connection_id=CONNECTION_ID&database=app&schema=&table=uCookie: dbx_session=...```+### 读取 Oracle 系触发器++不需要先知道所属表,可按触发器类型发现对象。精确适配器先筛选,再分页:++```http+GET /api/schema/objects?connection_id=CONNECTION_ID&database=demo&schema=APP&object_types=TRIGGER&filter=audit&limit=100&offset=0&identity_mode=exact+```++所属对象入口使用真实 parent owner/name;返回的触发器 owner 可以不同:++```http+GET /api/schema/triggers?connection_id=CONNECTION_ID&database=demo&schema=DATA&table=ORDERS&identity_mode=exact+```++完整定义使用触发器自身的 owner/name。此路由的 `table` 参数是源码对象名,不是父表:++```http+GET /api/schema/object-source?connection_id=CONNECTION_ID&database=demo&schema=APP&table=AUDIT_ORDERS&object_type=TRIGGER&identity_mode=exact+```++三项接口均接受可选 `identity_mode=exact` 和 `catalog`。省略模式时保持旧读取合同;精确模式保留原始 owner/name,空格、引号等字符应 URL 编码,不应 trim 或转换大小写。`catalog` 透传给实际 provider,不替代 `schema`。++对象和源码响应可包含 `trigger.oracle_metadata`,所属对象列表各项直接包含 `oracle_metadata`。版本 1 提供已核实的 engine、原始身份、作用域、独立 parent、字符串 object ID 及逐字段 `reads` 状态。`enabled` 是启用状态,`valid` 是独立读取的对象有效性;Schema/Database 作用域不填假父表。++exact 源码查询成功且零行时,返回 `reads.identity.state="empty"`,保留已核实的引擎和原始目标。这只表示当前可见范围内无匹配对象,不推断全库不存在;查询失败和旧 provider 缺契约不能产生该证明。新建仍使用不带 REPLACE 的 CREATE。++源码元数据另含来源、格式、完整性及带行列的编译错误。缺失或 null 错误列表表示未知,不是成功读到零错误。不完整或失败的读取不能作为替换基线;保留草稿,补齐字典访问或更新 provider 后重读。旧 Agent/插件仍可按旧模式使用,但缺少新元数据时不能证明 exact 身份。`DBMS_METADATA` 可能附带同目标的状态语句;导出原文和单定义保存内容分别处理。+其他常用 Schema 路由包括:- `/api/schema/databases`@@ -257,6 +285,14 @@ Content-Type: application/json| `/api/query/cancel` | 取消正在执行的查询 || `/api/query/build-table-select-sql` | 生成表浏览 SQL |+### 准备 Oracle 系触发器的单个定义++`POST /api/query/prepare-oracle-trigger-sql` 的请求体为 `{ "input": ... }`。input 包含 `databaseType`(`oracle`、`oceanbase-oracle` 或 `dameng`)、原始 `owner`/`name`、`source` 和 `purpose`(`inspect`、`create` 或 `replace`)。返回单个规范化 `definition`、解析后的 `header`,以及独立的内联/导出启用状态。`comparisonSource` 仅用于读回比较:规范化已确认的声明包装,保留头部其余内容、正文、注释及字符串换行;执行时使用 `definition`。该接口只准备 SQL;核对当前对象、权限和并发变化后,沿正常查询接口执行。++创建和替换还需传入已核实的 `binding`:`scope` 为 `TABLE`、`VIEW`、`SCHEMA`、`DATABASE` 或 `TIMER`;适用时带真实 parent `owner`/`name`,Oracle 容器作用域另带已核实的 `pluggable`。省略的 ON 限定只从该绑定补全。替换还需传入期望保全的 `enabled`。新建生成不带 OR REPLACE 的 CREATE;Oracle/已验证 OB 将状态保全在定义内,DM 返回的 `requiresStateRestore` 表示需要另行预览和核实原生状态步骤。`allowExportAppendix` 仅用于查看可信元数据导出;写入用途拒绝该选项及额外 SQL。++`structuredEditable` 表示完整定义的头部能否由时机、事件和正文表单无损表达。值为 false 或缺失时,结构修改须使用完整源码入口;只有 `TRIGGER_BODY` 不能证明可以安全重建定义。+## Redis APIRedis 浏览和命令执行使用独立路由。diff --git a/docs/content/docs/web-api.mdx b/docs/content/docs/web-api.mdxindex 12ae788c62..795be932d2 100644--- a/docs/content/docs/web-api.mdx+++ b/docs/content/docs/web-api.mdx@@ -217,6 +217,60 @@ GET /api/schema/columns?connection_id=CONNECTION_ID&database=app&schema=&table=uCookie: dbx_session=...```+### Read Oracle-Family Triggers++To find triggers without knowing their owning table, use the object list with a+trigger type filter. Search and type filters are applied before paging in the+exact metadata adapters.++```http+GET /api/schema/objects?connection_id=CONNECTION_ID&database=demo&schema=APP&object_types=TRIGGER&filter=audit&limit=100&offset=0&identity_mode=exact+Cookie: dbx_session=...+```++Use the owning object's schema and name to list its triggers. The returned+trigger owner can differ from that schema.++```http+GET /api/schema/triggers?connection_id=CONNECTION_ID&database=demo&schema=DATA&table=ORDERS&identity_mode=exact+Cookie: dbx_session=...+```++Fetch the full definition using the **trigger's** owner and name. On this route,+`table` is the source object name, not its parent table.++```http+GET /api/schema/object-source?connection_id=CONNECTION_ID&database=demo&schema=APP&table=AUDIT_ORDERS&object_type=TRIGGER&identity_mode=exact+Cookie: dbx_session=...+```++These three routes accept optional `identity_mode=exact` and `catalog` query+parameters. Omitting `identity_mode` retains the existing metadata behavior.+Exact reads preserve raw owner/name values; URL-encode spaces, quotes, and other+reserved characters rather than trimming or changing their case. `catalog` is+forwarded to the selected metadata provider; it does not replace `schema`.++Trigger summaries and source responses may contain `trigger.oracle_metadata`+(`oracle_metadata` directly on entries returned by `/schema/triggers`). Version+1 includes the verified engine, exact owner/name, scope, independent parent,+string-valued object ID, and per-field `reads` states. `enabled` is the trigger+state; `valid` is the independently read object validity. Schema/database scopes+do not have an invented table parent.++An exact source lookup that succeeds with no visible matching trigger returns+`reads.identity.state="empty"` with the verified engine and raw target. It means+empty within current visibility, not global absence. Query failures and legacy+providers cannot supply that proof; creation still uses CREATE without REPLACE.++Source metadata additionally reports definition origin/format/completeness and+compilation errors with line/position. A null or absent error list is unknown,+not an empty successful read. Failed or incomplete reads cannot supply a write+baseline; keep the draft, restore dictionary access or update the provider, and+read again. Old Agents/plugins that omit the metadata contract remain usable in+their original mode but do not prove exact identity. The source text can include+a same-target state appendix from `DBMS_METADATA`; it is export text, not an+arbitrary multi-statement save payload.+Other schema routes include:- `/api/schema/databases`@@ -258,6 +312,31 @@ Related routes:| `/api/query/cancel` | Cancel a running query || `/api/query/build-table-select-sql` | Build a table browse query |+### Prepare One Oracle-Family Trigger Definition++`POST /api/query/prepare-oracle-trigger-sql` accepts `{ "input": ... }` with+`databaseType` (`oracle`, `oceanbase-oracle`, or `dameng`), raw `owner`/`name`,+`source`, and `purpose` (`inspect`, `create`, or `replace`). It returns a single+normalized `definition`, the parsed `header`, and independent inline/export+enabled states. This route only prepares SQL; execute through the normal query+route after checking the current object, privileges, and concurrent changes.++`comparisonSource` is for readback comparison only. It canonicalizes the known+declaration wrapper while preserving the remaining header, body, comments, and+literal newlines. Execute `definition`, not this comparison form.++`structuredEditable` reports whether the complete definition's header can be represented without loss by the timing/event/body form. A false or absent value requires the complete-source editor for structural changes; a plain `TRIGGER_BODY` alone does not establish this capability.++For create/replace, supply `binding` with the verified `scope`+(`TABLE`, `VIEW`, `SCHEMA`, `DATABASE`, or `TIMER`), parent `owner`/`name` where+applicable, and `pluggable` for a verified Oracle container scope. Omitted ON+qualifiers are filled only from that binding. Replace also requires the current+desired `enabled` state. Create produces CREATE without OR REPLACE. Oracle and+verified OceanBase preserve state in the definition; DM's+`requiresStateRestore` indicates a separate native state step to preview and+verify. `allowExportAppendix` is only for inspecting trusted metadata exports;+write purposes reject it and any extra SQL.+## Redis APIsRedis browser and command execution use dedicated routes.diff --git a/docs/screenshots/native-jobs-dm-legacy-editor.jpg b/docs/screenshots/native-jobs-dm-legacy-editor.jpgnew file mode 100644index 0000000000..deed6285c6Binary files /dev/null and b/docs/screenshots/native-jobs-dm-legacy-editor.jpg differdiff --git a/docs/screenshots/native-jobs-operation-summary.jpg b/docs/screenshots/native-jobs-operation-summary.jpgnew file mode 100644index 0000000000..bf9149e509Binary files /dev/null and b/docs/screenshots/native-jobs-operation-summary.jpg differdiff --git a/packages/app-tests/productionGuardEntrypoints.test.ts b/packages/app-tests/productionGuardEntrypoints.test.tsindex 8453c258dd..49dd60760e 100644--- a/packages/app-tests/productionGuardEntrypoints.test.ts+++ b/packages/app-tests/productionGuardEntrypoints.test.ts@@ -72,7 +72,7 @@ test("secondary write entrypoints use the shared production SQL guard", () => {sourceKey: "production.sourceAdmin",},{- path: "apps/desktop/src/components/admin/DamengJobAdmin.vue",+ path: "apps/desktop/src/components/admin/DatabaseJobAdmin.vue",executor: "api.executeMulti",sourceKey: "production.sourceAdmin",},diff --git a/packages/app-tests/sidebarDialogRouting.test.ts b/packages/app-tests/sidebarDialogRouting.test.tsindex 7a9ddce595..891a1ae4cb 100644--- a/packages/app-tests/sidebarDialogRouting.test.ts+++ b/packages/app-tests/sidebarDialogRouting.test.ts@@ -79,7 +79,6 @@ test("shared dialog state is owner-gated and confirm handlers use snapshots", ()assert.match(runtimeHost, /sidebarTreeDialogOwner\.value !== treeItemDialogOwner/);assert.match(runtimeHost, /const node = sidebarDangerTarget\.value \?\? activeNode\.value/);assert.match(runtimeHost, /const node = sidebarFormTarget\.value \?\? activeNode\.value/);- assert.match(runtimeHost, /batchDropTargets\.value = targets\.slice\(\)/);assert.match(runtimeHost, /batchTruncateTargets\.value = targets\.slice\(\)/);assert.match(runtimeHost, /activateActionTarget\(target\)/);});diff --git a/packages/app-tests/sidebarRemoteSearch.test.ts b/packages/app-tests/sidebarRemoteSearch.test.tsindex 7ada662552..c08a077117 100644--- a/packages/app-tests/sidebarRemoteSearch.test.ts+++ b/packages/app-tests/sidebarRemoteSearch.test.ts@@ -1,5 +1,7 @@import { expect, test, vi } from "vitest";-import { collectSidebarRemoteSearchResults, mergeSidebarRemoteSearchResults } from "../../apps/desktop/src/lib/sidebar/sidebarRemoteSearch";+import { effectScope, ref } from "vue";+import { useSidebarRemoteSearch } from "../../apps/desktop/src/composables/useSidebarRemoteSearch";+import { collectSidebarRemoteSearchResults, mergeSidebarRemoteSearchResults, removeVerifiedSidebarTriggerSearchResult } from "../../apps/desktop/src/lib/sidebar/sidebarRemoteSearch";import type { TreeNode, TreeNodeType } from "../../apps/desktop/src/types/database";const remoteObjectGroupTypes = [@@ -32,6 +34,84 @@ function fixture() {return { root, schema, procedures, functions, tables, controller, options };}+test("removes only the verified physical trigger from search projections", () => {+ const trigger = (name: string, objectId: string, catalog = "catalog-a", connectionId = "conn"): TreeNode => ({+ id: name,+ label: name,+ objectName: name,+ type: "trigger",+ connectionId,+ database: "service",+ schema: " Owner ",+ catalog,+ meta: { name, timing: "BEFORE", event: "INSERT", oracle_metadata: { contractVersion: 1, identityMode: "exact", engine: "oracle", owner: " Owner ", name, objectId } },+ });+ const removed = trigger(" Raw Trigger ", "old-id");+ const retained = [trigger(" Raw Trigger ", "replacement-id"), trigger(" raw trigger ", "neighbor-id"), trigger(" Raw Trigger ", "old-id", "catalog-b"), trigger(" Raw Trigger ", "old-id", "catalog-a", "other")];+ const results = [{ parentNodeId: "group", nodeType: "group-triggers" as const, connectionId: "conn", database: "service", children: [removed, ...retained] }];+ const next = removeVerifiedSidebarTriggerSearchResult(results, removed);+ expect(next[0].children).toEqual(retained);+ expect(results[0].children).toHaveLength(5);+ expect(removeVerifiedSidebarTriggerSearchResult(results, { ...removed, meta: undefined })[0].children).toHaveLength(5);+});++test("a late search response cannot resurrect a verified deleted trigger", async () => {+ vi.useFakeTimers();+ const scope = effectScope();+ try {+ const node: TreeNode = {+ id: "trigger",+ label: "trigger",+ objectName: "trigger",+ type: "trigger",+ connectionId: "conn",+ database: "service",+ schema: "owner",+ meta: { name: "trigger", timing: "BEFORE", event: "INSERT", oracle_metadata: { contractVersion: 1, identityMode: "exact", engine: "oracle", owner: "owner", name: "trigger", objectId: "old-id" } },+ };+ const oldResult = [{ parentNodeId: "group", nodeType: "group-triggers" as const, connectionId: "conn", database: "service", schema: "owner", children: [node] }];+ let finish!: (result: typeof oldResult) => void;+ let publish!: (result: typeof oldResult) => void;+ let oldSignal!: AbortSignal;+ let calls = 0;+ const query = ref("");+ const remote = scope.run(() =>+ useSidebarRemoteSearch({+ query,+ enabled: ref(true),+ context: [],+ onError: (error) => {+ throw error;+ },+ load: async (_query, signal, onProgress) => {+ if (calls++ > 0) return [{ ...oldResult[0], children: [] }];+ oldSignal = signal;+ publish = onProgress;+ onProgress(oldResult);+ return new Promise<typeof oldResult>((resolve) => {+ finish = resolve;+ });+ },+ }),+ )!;+ query.value = "trigger";+ await vi.advanceTimersByTimeAsync(300);+ expect(remote.results.value[0].children).toEqual([node]);+ remote.removeVerifiedTriggerNode(node);+ expect(remote.results.value[0].children).toEqual([]);+ publish(oldResult);+ finish(oldResult);+ await vi.advanceTimersByTimeAsync(0);+ expect(remote.results.value[0].children).toEqual([]);+ expect(oldSignal.aborted).toBe(true);+ await vi.advanceTimersByTimeAsync(300);+ expect(remote.results.value[0].children).toEqual([]);+ } finally {+ scope.stop();+ vi.useRealTimers();+ }+});+test("searches never-expanded procedure/function groups, not indexed table/view groups", async () => {const { root, procedures, functions, tables, options } = fixture();const before = structuredClone(root);diff --git a/plugins/jdbc/src/main/java/app/dbx/jdbc/DbxJdbcPlugin.java b/plugins/jdbc/src/main/java/app/dbx/jdbc/DbxJdbcPlugin.javaindex 91ba7263d6..03038c7cf3 100644--- a/plugins/jdbc/src/main/java/app/dbx/jdbc/DbxJdbcPlugin.java+++ b/plugins/jdbc/src/main/java/app/dbx/jdbc/DbxJdbcPlugin.java@@ -184,7 +184,6 @@ public final class DbxJdbcPlugin {new JdbcDriverQuirkRule("jdbc:oracle:", ORACLE_QUIRKS),new JdbcDriverQuirkRule("jdbc:oceanbase:oracle://", ORACLE_QUIRKS),new JdbcDriverQuirkRule("jdbc:dm:", ORACLE_QUIRKS),- new JdbcDriverQuirkRule("jdbc:oceanbase:oracle://", ORACLE_QUIRKS),new JdbcDriverQuirkRule("jdbc:taos:", TAOS_QUIRKS),new JdbcDriverQuirkRule("jdbc:taos-ws:", TAOS_QUIRKS),new JdbcDriverQuirkRule("jdbc:taos-rs:", TAOS_QUIRKS)@@ -204,6 +203,9 @@ public final class DbxJdbcPlugin {String sharedConnectionKey = "";Connection sharedConnection;boolean manualTransactionActive;+ NativeLegacyJobSession nativeLegacyJob;+ String nativeLegacyJobConnectionKey = "";+ NativeJobSession nativeJobSession;boolean deferLobs;final Map<String, QuerySession> querySessions = new HashMap<>();final Map<String, CancellationRequest> cancellationRequests = new HashMap<>();@@ -640,7 +642,12 @@ public final class DbxJdbcPlugin {JdbcConnectionState state) throws Exception {String id = requireText(params, "jdbcSessionId");if ("closeJdbcSession".equals(method)) {- if (state != null) closeLogicalSession(state);+ if (state != null) {+ closeLogicalSession(state);+ if (!nativeDisposalConfirmed(state)) {+ throw new SQLException("native_job_session_dispose_unknown");+ }+ }return okResult();}if (state == null) throw new SQLException("Unknown JDBC logical session");@@ -648,10 +655,15 @@ public final class DbxJdbcPlugin {try {if (shuttingDown || state.closing) throw new SQLException("JDBC logical session is closed");if ("openJdbcSession".equals(method)) return okResult();+ authorizeNativeJobRequest(state, method, params, connection);+ if (state.nativeLegacyJob != null && !NativeLegacyJobSession.isMethod(method)) {+ throw new SQLException("native_job_session_reserved");+ }CONNECTION_STATE.set(state);Set<String> checkpoint = state.largeValues.checkpoint();try {- registerDrivers(connection);+ if (state.nativeJobSession == null && !NativeJobSession.isClose(method)+ && (state.nativeLegacyJob == null || !NativeLegacyJobSession.isMethod(method))) registerDrivers(connection);JsonNode result = handle(method, params, connection);checkResponseBudget(requestId, result, params, 64 * 1024 * 1024);return result;@@ -691,7 +703,7 @@ public final class DbxJdbcPlugin {connection = params.path("connection");if ("jdbcSessionProtocol".equals(method)) {ObjectNode protocol = MAPPER.createObjectNode().put("version", 2);- protocol.set("capabilities", MAPPER.createArrayNode().add("exact_metadata_identity_v1"));+ protocol.putArray("capabilities").add("native_job_legacy_v1").add("native_job_session_v1").add("native_job_legacy_ob_v1").add("exact_metadata_identity_v1");response.set("result", protocol);return response;}@@ -700,23 +712,55 @@ public final class DbxJdbcPlugin {return response;}if ("close".equals(method)) {+ boolean nativeDisposed = true;for (JdbcConnectionState state : LOGICAL_SESSIONS.values()) {closeLogicalSession(state);+ nativeDisposed &= nativeDisposalConfirmed(state);}LOGICAL_SESSIONS.clear();closeSharedConnection();+ nativeDisposed &= nativeDisposalConfirmed(DEFAULT_CONNECTION_STATE);+ DEFAULT_CONNECTION_STATE.nativeLegacyJob = null;+ DEFAULT_CONNECTION_STATE.nativeLegacyJobConnectionKey = "";+ DEFAULT_CONNECTION_STATE.nativeJobSession = null;+ response.put("_dbx_close", true);+ if (!nativeDisposed) throw new SQLException("native_job_session_dispose_unknown");ObjectNode result = MAPPER.createObjectNode();result.put("ok", true);response.set("result", result);- response.put("_dbx_close", true);return response;}- registerDrivers(connection);+ // Native Job callers own a Core metadata process; serve() serializes default requests.+ authorizeNativeJobRequest(connectionState(), method, params, connection);+ if (connectionState().nativeLegacyJob != null && !NativeLegacyJobSession.isMethod(method)) {+ throw new SQLException("native_job_session_reserved");+ }+ if (connectionState().nativeLegacyJob == null && connectionState().nativeJobSession == null+ && !NativeJobSession.isClose(method)) registerDrivers(connection);JsonNode result = handle(method, params, connection);checkResponseBudget(response.path("id"), result, params, 64 * 1024 * 1024);response.set("result", result);} catch (Throwable error) {if (checkpoint != null) connectionState().largeValues.releaseSince(checkpoint);+ if (NativeJobSession.isControl(request.path("method").asText())) {+ boolean notStarted = error instanceof NativeJobSession.ProtocolFailure failure && failure.notStarted;+ String reason = error instanceof NativeJobSession.ProtocolFailure failure+ ? failure.reason : "native_job_protocol_failed";+ String operation = request.path("params").path("operationId").asText("");+ if (operation.length() > 128 || operation.indexOf('\0') >= 0) operation = "";+ response.set("result", NativeJobSession.failure(operation, notStarted ? "not_started" : "unknown", reason, error));+ return response;+ }+ if ("executeQuery".equals(request.path("method").asText())+ && request.path("params").path("nativeDiagnostics").asBoolean(false)) {+ response.set("result", JdbcErrorDiagnostics.queryFailure(error));+ return response;+ }+ if (NativeLegacyJobSession.isMethod(request.path("method").asText())) {+ response.set("result", NativeLegacyJobSession.failure(request.path("params").path("operationId").asText(),+ "unknown", "native_job_protocol_failed", error));+ return response;+ }// The plugin protocol boundary must report linkage errors from vendor drivers instead of exiting silently.ObjectNode errorNode = MAPPER.createObjectNode();errorNode.put("message", enrichDriverHint(connection, throwableMessage(error)));@@ -814,6 +858,11 @@ public final class DbxJdbcPlugin {}}return switch (method) {+ case "openNativeJobSession", "open_native_job_session", "closeNativeJobSession", "close_native_job_session" ->+ nativeJobSession(method, params, connection);+ case "prepareLegacyJob", "prepare_legacy_job", "commitLegacyJob", "commit_legacy_job",+ "rollbackLegacyJob", "rollback_legacy_job", "legacyJobStatus", "legacy_job_status" ->+ nativeLegacyJob(method, params, connection);case "read_large_value_chunk" -> MAPPER.valueToTree(connectionState().largeValues.fetch(connectionState().sharedConnection, requireText(params, "valueRef"),params.path("offset").asLong(-1), params.path("limit").asInt(0)));@@ -826,10 +875,11 @@ public final class DbxJdbcPlugin {result.put("ok", true);yield result;}- case "connectionInfo" -> databaseInfoResult(openConnection(connection));+ case "connectionInfo" -> databaseInfoResult(connectionState().nativeJobSession == null+ ? openConnection(connection) : connectionState().nativeJobSession.connection());case "executeQuery" -> executeQuery(connection,- requireText(params, "sql"),+ connectionState().nativeJobSession == null ? requireText(params, "sql") : NativeJobSession.sql(params),database,optionalText(params, "schema"),positiveInt(params, "maxRows", MAX_ROWS),@@ -880,7 +930,16 @@ public final class DbxJdbcPlugin {nonNegativeInt(params, "offset", 0),optionalStringList(params, "object_types"), exactIdentity);- case "listObjects", "list_objects" -> listObjects(+ case "listObjects", "list_objects" -> exactMetadataRead(params) ? listTriggerObjects(+ connection,+ database,+ triggerMetadataText(params, "schema", false),+ optionalText(params, "filter"),+ nonNegativeInt(params, "limit", 0),+ nonNegativeInt(params, "offset", 0),+ optionalStringList(params, "object_types"),+ true+ ) : listObjects(connection,database,metadataText(params, "schema", exactIdentity),@@ -889,6 +948,8 @@ public final class DbxJdbcPlugin {nonNegativeInt(params, "offset", 0),optionalStringList(params, "object_types"), exactIdentity);+ case "listTriggers", "list_triggers" -> listTriggers(connection,+ triggerMetadataText(params, "schema", false), triggerMetadataText(params, "table", true), exactMetadataRead(params));case "listIndexes", "list_indexes" -> listIndexes(connection,database,@@ -896,7 +957,14 @@ public final class DbxJdbcPlugin {metadataText(params, "table", exactIdentity), exactIdentity);case "listDataTypes", "list_data_types" -> listDataTypes(connection, database);- case "getObjectSource", "get_object_source" -> getObjectSource(+ case "getObjectSource", "get_object_source" -> exactMetadataRead(params) ? getTriggerObjectSource(+ connection,+ database,+ triggerMetadataText(params, "schema", false),+ triggerMetadataText(params, "name", true),+ requireText(params, "object_type"),+ true+ ) : getObjectSource(connection,database,metadataText(params, "schema", exactIdentity),@@ -944,7 +1012,23 @@ public final class DbxJdbcPlugin {private static ObjectNode databaseInfo(Connection connection) {try {DatabaseMetaData metadata = connection.getMetaData();- return metadata == null ? MAPPER.createObjectNode() : databaseInfo(metadata);+ ObjectNode info = metadata == null ? MAPPER.createObjectNode() : databaseInfo(metadata);+ if ("OceanBase".equalsIgnoreCase(info.path("productName").asText())) {+ try (Statement statement = connection.createStatement()) {+ statement.setQueryTimeout(5);+ try (ResultSet rows = statement.executeQuery("SHOW VARIABLES LIKE 'ob_compatibility_mode'")) {+ if (rows.next() && "ob_compatibility_mode".equalsIgnoreCase(rows.getString(1))) {+ String mode = rows.getString(2);+ if (mode != null && (mode.equalsIgnoreCase("oracle") || mode.equalsIgnoreCase("mysql")) && !rows.next()) {+ info.put("compatibilityMode", mode.toLowerCase(Locale.ROOT));+ }+ }+ }+ } catch (SQLException | AbstractMethodError | UnsupportedOperationException ignored) {+ // Optional mode facts must not make ordinary JDBC metadata unavailable.+ }+ }+ return info;} catch (SQLException | AbstractMethodError | UnsupportedOperationException ignored) {return MAPPER.createObjectNode();}@@ -1426,7 +1510,8 @@ public final class DbxJdbcPlugin {int rowOffset,int timeoutSecs) throws Exception {- Connection conn = openConnection(connection);+ Connection conn = connectionState().nativeJobSession == null+ ? openConnection(connection) : connectionState().nativeJobSession.connection();return executeQueryOnConnection(connection, conn, sql, database, schema, maxRows, fetchSize, rowOffset, timeoutSecs);}@@ -1507,9 +1592,17 @@ public final class DbxJdbcPlugin {trackActiveStatement(statement);if (connectionState().closing) throw new SQLException("JDBC logical session is closed");applyStatementOptions(statement, maxRows, fetchSize, timeoutSecs, quirks);- String trimmedSql = trimStatementSql(sql, isOracleUrl(jdbcUrl(connection)));- String effectiveSql = rewritePhoenixSystemCatalogQuery(connection, conn, trimmedSql);- ExecutedStatement executed = executeStatementForResultWithAdhocRetry(connection, statement, effectiveSql, quirks);+ boolean nativeJob = connectionState().nativeJobSession != null;+ String trimmedSql = nativeJob ? sql : trimStatementSql(sql, isOracleUrl(jdbcUrl(connection)));+ String effectiveSql = nativeJob ? trimmedSql : rewritePhoenixSystemCatalogQuery(connection, conn, trimmedSql);+ ExecutedStatement executed;+ if (nativeJob) {+ boolean hasResult = statement.execute(effectiveSql);+ executed = new ExecutedStatement(hasResult ? statement.getResultSet() : null,+ hasResult ? -1 : statement.getUpdateCount());+ } else {+ executed = executeStatementForResultWithAdhocRetry(connection, statement, effectiveSql, quirks);+ }ObjectNode result = MAPPER.createObjectNode();ArrayNode columns = MAPPER.createArrayNode();ArrayNode rows = MAPPER.createArrayNode();@@ -1550,6 +1643,108 @@ public final class DbxJdbcPlugin {}}+ private static void authorizeNativeJobRequest(JdbcConnectionState state, String method, JsonNode params,+ JsonNode connection) throws SQLException {+ if (state.nativeJobSession != null) {+ state.nativeJobSession.authorize(method, params, nativeJobConnectionKey(connection));+ } else if (params.has("nativeJobOperationId") || params.has("nativeJobSessionToken")) {+ throw new NativeJobSession.ProtocolFailure("native_job_session_unavailable", true);+ } else if (NativeJobSession.isOpen(method)) {+ NativeJobSession.operationId(params);+ if (state.nativeLegacyJob != null || state.manualTransactionActive || !state.querySessions.isEmpty()+ || (state.sharedConnection != null && !isConnectionClosed(state.sharedConnection)+ && !state.sharedConnection.getAutoCommit())) {+ throw new NativeJobSession.ProtocolFailure("native_job_session_busy", true);+ }+ if (state.sharedConnection != null && (!connectionKey(connection).equals(state.sharedConnectionKey)+ || !driverKey(connection).equals(registeredDriverKey))) {+ throw new NativeJobSession.ProtocolFailure("native_job_connection_changed", true);+ }+ }+ }++ private static String nativeJobConnectionKey(JsonNode connection) {+ return driverKey(connection) + "\n" + connectionKey(connection);+ }++ private static ObjectNode nativeJobSession(String method, JsonNode params, JsonNode connection) throws SQLException {+ JdbcConnectionState state = connectionState();+ if (NativeJobSession.isClose(method)) {+ if (state.nativeJobSession == null) {+ return NativeJobSession.failure(NativeJobSession.operationId(params), "unknown", "native_job_session_unavailable", null);+ }+ return state.nativeJobSession.close(params);+ }+ String operationId = NativeJobSession.operationId(params);+ if (state.nativeJobSession != null) return state.nativeJobSession.openedFor(operationId);+ NativeJobSession candidate = new NativeJobSession(params, nativeJobConnectionKey(connection));+ try {+ Connection owned = openConnection(connection);+ state.sharedConnection = null;+ state.sharedConnectionKey = "";+ state.nativeJobSession = candidate;+ candidate.open(owned);+ } catch (SQLException | RuntimeException | LinkageError error) {+ Connection owned = state.sharedConnection;+ state.sharedConnection = null;+ state.sharedConnectionKey = "";+ state.nativeJobSession = candidate;+ candidate.openFailed(owned, error);+ }+ return candidate.openedFor(operationId);+ }++ private static boolean nativeDisposalConfirmed(JdbcConnectionState state) {+ return (state.nativeLegacyJob == null || state.nativeLegacyJob.disposalConfirmed())+ && (state.nativeJobSession == null || state.nativeJobSession.disposalConfirmed());+ }++ private static ObjectNode nativeLegacyJob(String method, JsonNode params, JsonNode connection) throws SQLException {+ JdbcConnectionState state = connectionState();+ String operationId = params.path("operationId").asText();+ String key = connectionKey(connection);+ if (state.nativeLegacyJob != null && !key.equals(state.nativeLegacyJobConnectionKey)) {+ return NativeLegacyJobSession.failure(operationId, "unknown", "native_job_connection_changed", null);+ }+ if (NativeLegacyJobSession.isPrepare(method)) {+ NativeLegacyJobSession candidate;+ try {+ candidate = new NativeLegacyJobSession(params);+ } catch (NativeLegacyJobSession.InvalidRequest error) {+ return NativeLegacyJobSession.failure(operationId, "not_started", error.reason, null);+ }+ if (state.nativeLegacyJob != null) {+ return state.nativeLegacyJob.sameRequest(candidate) ? state.nativeLegacyJob.status(operationId)+ : NativeLegacyJobSession.failure(operationId, "unknown", "native_job_operation_mismatch", null);+ }+ if (state.manualTransactionActive || !state.querySessions.isEmpty()+ || (state.sharedConnection != null && !isConnectionClosed(state.sharedConnection)+ && !state.sharedConnection.getAutoCommit())) {+ return NativeLegacyJobSession.failure(operationId, "not_started", "native_job_session_busy", null);+ }+ try {+ Connection owned = openConnection(connection);+ // This dedicated logical session now owns the physical connection exclusively.+ state.sharedConnection = null;+ state.sharedConnectionKey = "";+ state.nativeLegacyJob = candidate;+ state.nativeLegacyJobConnectionKey = key;+ candidate.prepare(owned);+ } catch (SQLException | RuntimeException | LinkageError error) {+ state.nativeLegacyJob = candidate;+ state.nativeLegacyJobConnectionKey = key;+ candidate.openFailed(error);+ }+ return candidate.status(operationId);+ }+ if (state.nativeLegacyJob == null) {+ return NativeLegacyJobSession.failure(operationId, "unknown", "native_job_session_unavailable", null);+ }+ if ("legacyJobStatus".equals(method) || "legacy_job_status".equals(method)) return state.nativeLegacyJob.status(operationId);+ return state.nativeLegacyJob.finish(operationId, params.path("jobId").asText(),+ "commitLegacyJob".equals(method) || "commit_legacy_job".equals(method));+ }+private static ObjectNode beginManualTransaction(JsonNode connection, String database, String schema)throws SQLException {if (connectionState().manualTransactionActive) {@@ -2909,6 +3104,27 @@ public final class DbxJdbcPlugin {return result;}+ private static JsonNode listTriggerObjects(JsonNode connection, String database, String schema, String filter,+ int limit, int offset, List<String> objectTypes, boolean exact) throws SQLException {+ if (!exact) return listObjects(connection, database, schema, filter, limit, offset, objectTypes, false);+ Connection conn = openConnection(connection);+ OracleTriggerMetadataReader.Profile profile = OracleTriggerMetadataReader.profile(conn);+ if (profile == null) throw new SQLFeatureNotSupportedException("Exact Oracle-family trigger metadata is unavailable for the connected product");+ return new OracleTriggerMetadataReader(conn, profile).listObjects(schema, filter, limit, offset, objectTypes);+ }++ private static JsonNode listTriggers(JsonNode connection, String schema, String table, boolean exact) throws SQLException {+ Connection conn = openConnection(connection);+ OracleTriggerMetadataReader.Profile profile = OracleTriggerMetadataReader.profile(conn);+ if (profile == null) {+ if (exact) throw new SQLFeatureNotSupportedException("Exact Oracle-family trigger metadata is unavailable for the connected product");+ return MAPPER.createArrayNode();+ }+ ArrayNode triggers = new OracleTriggerMetadataReader(conn, profile).listTriggers(exact ? schema : oracleEffectiveSchema(conn, schema), table);+ if (!exact) triggers.forEach(trigger -> ((ObjectNode) trigger).remove("oracle_metadata"));+ return triggers;+ }+private static JsonNode listObjects(JsonNode connection,String database,@@ -4646,6 +4862,8 @@ public final class DbxJdbcPlugin {private static void closeSharedConnection() {JdbcConnectionState state = connectionState();closeAllQuerySessions();+ if (state.nativeLegacyJob != null) state.nativeLegacyJob.dispose();+ if (state.nativeJobSession != null) state.nativeJobSession.dispose();state.largeValues.clear();if (state.sharedConnection != null) {if (state.manualTransactionActive) {@@ -5311,6 +5529,15 @@ public final class DbxJdbcPlugin {return result;}+ private static JsonNode getTriggerObjectSource(JsonNode connection, String database, String schema, String name, String objectType, boolean exact)+ throws SQLException {+ if (!exact || !"TRIGGER".equalsIgnoreCase(objectType)) return getObjectSource(connection, database, schema, name, objectType, false);+ Connection conn = openConnection(connection);+ OracleTriggerMetadataReader.Profile profile = OracleTriggerMetadataReader.profile(conn);+ if (profile == null) throw new SQLFeatureNotSupportedException("Exact Oracle-family trigger metadata is unavailable for the connected product");+ return new OracleTriggerMetadataReader(conn, profile).source(schema, name);+ }+private static JsonNode getObjectSource(JsonNode connection, String database, String schema, String name, String objectType)throws SQLException {return getObjectSource(connection, database, schema, name, objectType, false);@@ -5988,6 +6215,17 @@ public final class DbxJdbcPlugin {}}+ if (columnType == -101 || columnType == -102) {+ String typeName = meta.getColumnTypeName(index);+ if (typeName != null) {+ String normalizedType = typeName.trim().toUpperCase(Locale.ROOT);+ if ((columnType == -101 && normalizedType.equals("TIMESTAMP WITH TIME ZONE"))+ || (columnType == -102 && normalizedType.equals("TIMESTAMP WITH LOCAL TIME ZONE"))) {+ return rs.getString(index);+ }+ }+ }+Object value = rs.getObject(index);if (value == null) {return null;@@ -6305,6 +6543,27 @@ public final class DbxJdbcPlugin {}}+ private static boolean exactMetadataRead(JsonNode params) {+ JsonNode mode = params.get("identity_mode"), alias = params.get("identityMode");+ if (mode == null || mode.isNull()) mode = alias;+ if (mode == null || mode.isNull()) return false;+ if (!mode.isTextual() || !mode.asText().equals("exact") || alias != null && !alias.isNull() && !mode.equals(alias)) {+ throw new IllegalArgumentException("Unsupported or conflicting metadata identity mode");+ }+ return true;+ }++ private static String triggerMetadataText(JsonNode params, String field, boolean required) {+ if (!exactMetadataRead(params)) return required ? requireText(params, field) : optionalText(params, field);+ JsonNode value = params.get(field);+ if (value == null || value.isNull()) {+ if (required) throw new IllegalArgumentException(field + " is required.");+ return null;+ }+ if (!value.isTextual() || required && value.asText().isEmpty()) throw new IllegalArgumentException(field + " must be a non-empty string.");+ return value.asText();+ }+private static String requireText(JsonNode node, String field) {String value = optionalText(node, field);if (value == null) {diff --git a/plugins/jdbc/src/main/java/app/dbx/jdbc/JdbcErrorDiagnostics.java b/plugins/jdbc/src/main/java/app/dbx/jdbc/JdbcErrorDiagnostics.javanew file mode 100644index 0000000000..e000a3fbf3--- /dev/null+++ b/plugins/jdbc/src/main/java/app/dbx/jdbc/JdbcErrorDiagnostics.java@@ -0,0 +1,48 @@+package app.dbx.jdbc;++import com.fasterxml.jackson.databind.ObjectMapper;+import com.fasterxml.jackson.databind.node.ObjectNode;++import java.sql.SQLException;+import java.sql.SQLNonTransientConnectionException;+import java.sql.SQLRecoverableException;+import java.sql.SQLTimeoutException;+import java.sql.SQLTransientConnectionException;++/** Typed diagnostics only; native messages may contain job bodies or connection details. */+final class JdbcErrorDiagnostics {+ private static final ObjectMapper MAPPER = new ObjectMapper();++ private JdbcErrorDiagnostics() { }++ private static SQLException sqlError(Throwable cause) {+ for (int depth = 0; cause != null && depth < 8; depth++, cause = cause.getCause()) {+ if (cause instanceof SQLException sql) return sql;+ }+ return null;+ }++ static void appendSql(ObjectNode target, Throwable cause) {+ SQLException sql = sqlError(cause);+ if (sql == null) return;+ if (sql.getErrorCode() != 0) target.put("vendorCode", sql.getErrorCode());+ String state = sql.getSQLState();+ if (state != null && state.matches("[A-Z0-9]{5}")) target.put("sqlState", state);+ }++ static ObjectNode queryFailure(Throwable cause) {+ SQLException sql = sqlError(cause);+ String category = "protocol";+ if (sql != null) {+ category = sql instanceof SQLTimeoutException ? "timeout"+ : sql instanceof SQLRecoverableException || sql instanceof SQLTransientConnectionException+ || sql instanceof SQLNonTransientConnectionException+ || (sql.getSQLState() != null && sql.getSQLState().startsWith("08")) ? "connection" : "sql";+ }+ ObjectNode diagnostics = MAPPER.createObjectNode().put("category", category);+ appendSql(diagnostics, cause);+ ObjectNode result = MAPPER.createObjectNode().put("execution_error", true);+ result.putObject("error").set("diagnostics", diagnostics);+ return result;+ }+}diff --git a/plugins/jdbc/src/main/java/app/dbx/jdbc/NativeJobSession.java b/plugins/jdbc/src/main/java/app/dbx/jdbc/NativeJobSession.javanew file mode 100644index 0000000000..ce751a2671--- /dev/null+++ b/plugins/jdbc/src/main/java/app/dbx/jdbc/NativeJobSession.java@@ -0,0 +1,153 @@+package app.dbx.jdbc;++import com.fasterxml.jackson.databind.JsonNode;+import com.fasterxml.jackson.databind.ObjectMapper;+import com.fasterxml.jackson.databind.node.ObjectNode;+import java.sql.Connection;+import java.sql.SQLException;+import java.util.UUID;++/** Connection ownership only: native SQL, configuration phases and dispatch deduplication stay in Core. */+final class NativeJobSession {+ private static final ObjectMapper MAPPER = new ObjectMapper();+ private final String operationId;+ private final String connectionKey;+ private final String token = UUID.randomUUID().toString();+ private final ObjectNode receipt;+ private Connection owned;+ private boolean closeAttempted;++ static final class ProtocolFailure extends SQLException {+ final String reason;+ final boolean notStarted;++ ProtocolFailure(String reason, boolean notStarted) {+ super(reason);+ this.reason = reason;+ this.notStarted = notStarted;+ }+ }++ NativeJobSession(JsonNode params, String connectionKey) throws ProtocolFailure {+ operationId = operationId(params);+ this.connectionKey = connectionKey;+ receipt = failure(operationId, "not_started", null, null);+ receipt.put("sessionToken", token);+ }++ static String operationId(JsonNode params) throws ProtocolFailure {+ String id = text(params, "operationId");+ if (id.isEmpty() || id.length() > 128 || id.indexOf('\0') >= 0) {+ throw new ProtocolFailure("native_job_request_invalid", true);+ }+ return id;+ }++ static boolean isOpen(String method) {+ return "openNativeJobSession".equals(method) || "open_native_job_session".equals(method);+ }++ static boolean isClose(String method) {+ return "closeNativeJobSession".equals(method) || "close_native_job_session".equals(method);+ }++ static boolean isControl(String method) {+ return isOpen(method) || isClose(method);+ }++ static String sql(JsonNode params) throws ProtocolFailure {+ String sql = text(params, "sql");+ if (sql.isBlank()) throw new ProtocolFailure("native_job_request_invalid", true);+ return sql;+ }++ static ObjectNode failure(String operationId, String phase, String reason, Throwable cause) {+ ObjectNode result = MAPPER.createObjectNode().put("operationId", operationId).put("phase", phase);+ if (reason != null) result.put("reason", reason);+ JdbcErrorDiagnostics.appendSql(result, cause);+ return result;+ }++ void open(Connection connection) {+ owned = connection;+ try {+ owned.setAutoCommit(false);+ receipt.put("phase", "opened");+ } catch (SQLException | RuntimeException | LinkageError error) {+ openFailed(connection, error);+ }+ }++ void openFailed(Connection connection, Throwable error) {+ owned = connection;+ receipt.put("reason", "native_job_session_open_failed");+ JdbcErrorDiagnostics.appendSql(receipt, error);+ dispose();+ }++ void authorize(String method, JsonNode params, String key) throws SQLException {+ if (isClose(method)) return;+ if (!connectionKey.equals(key)) throw new ProtocolFailure("native_job_connection_changed", true);+ if (isOpen(method)) return;+ if (!"executeQuery".equals(method) && !"connectionInfo".equals(method)) {+ throw new ProtocolFailure("native_job_session_reserved", true);+ }+ requireOperation(text(params, "nativeJobOperationId"));+ if (!token.equals(text(params, "nativeJobSessionToken"))) {+ throw new ProtocolFailure("native_job_session_token_invalid", true);+ }+ connection();+ }++ ObjectNode openedFor(String id) throws SQLException {+ requireOperation(id);+ if ("opened".equals(receipt.path("phase").asText())) connection();+ return receipt.deepCopy();+ }++ Connection connection() throws SQLException {+ if (!"opened".equals(receipt.path("phase").asText()) || owned == null || owned.isClosed()) {+ throw new ProtocolFailure("native_job_session_unavailable", true);+ }+ return owned;+ }++ ObjectNode close(JsonNode params) throws SQLException {+ requireOperation(operationId(params));+ String requestedToken = text(params, "sessionToken");+ if (!requestedToken.isEmpty() && !token.equals(requestedToken)) {+ throw new ProtocolFailure("native_job_session_token_invalid", true);+ }+ return dispose();+ }++ ObjectNode dispose() {+ if (closeAttempted) return receipt.deepCopy();+ closeAttempted = true;+ Connection connection = owned;+ owned = null;+ try {+ if (connection != null) connection.close();+ receipt.put("phase", "closed");+ } catch (SQLException | RuntimeException | LinkageError error) {+ receipt.put("phase", "unknown").put("reason", "native_job_session_dispose_unknown");+ JdbcErrorDiagnostics.appendSql(receipt, error);+ }+ return receipt.deepCopy();+ }++ boolean disposalConfirmed() {+ return closeAttempted && "closed".equals(receipt.path("phase").asText());+ }++ private void requireOperation(String id) throws ProtocolFailure {+ if (!operationId.equals(id)) throw new ProtocolFailure("native_job_operation_mismatch", true);+ }++ private static String text(JsonNode params, String key) throws ProtocolFailure {+ JsonNode value = params.path(key);+ if (value.isMissingNode() || value.isNull()) return "";+ if (!value.isTextual()) throw new ProtocolFailure("native_job_request_invalid", true);+ return value.textValue();+ }+}diff --git a/plugins/jdbc/src/main/java/app/dbx/jdbc/NativeLegacyJobSession.java b/plugins/jdbc/src/main/java/app/dbx/jdbc/NativeLegacyJobSession.javanew file mode 100644index 0000000000..3699a288e2--- /dev/null+++ b/plugins/jdbc/src/main/java/app/dbx/jdbc/NativeLegacyJobSession.java@@ -0,0 +1,322 @@+package app.dbx.jdbc;++import com.fasterxml.jackson.databind.JsonNode;+import com.fasterxml.jackson.databind.ObjectMapper;+import com.fasterxml.jackson.databind.node.ObjectNode;++import java.sql.CallableStatement;+import java.sql.Connection;+import java.sql.PreparedStatement;+import java.sql.ResultSet;+import java.sql.SQLException;+import java.sql.Statement;+import java.sql.Types;+import java.time.LocalDateTime;+import java.time.format.DateTimeFormatter;+import java.time.format.DateTimeParseException;+import java.time.format.ResolverStyle;+import java.util.Objects;++/** One confirmed native SUBMIT, separate from the editor's transaction and cursors. */+final class NativeLegacyJobSession {+ private static final ObjectMapper MAPPER = new ObjectMapper();+ private static final DateTimeFormatter DATE = DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss")+ .withResolverStyle(ResolverStyle.STRICT);+ private final String operationId;+ private final String what;+ private final String nextDate;+ private final String interval;+ private final boolean enabled;+ private final long instance;+ private final String dialect;+ private final String zone;+ private final String schema;+ private final int timeoutSecs;+ private final ObjectNode result;+ private Connection connection;+ private boolean transactionActive;+ private boolean disposalConfirmed = true;++ static final class InvalidRequest extends RuntimeException {+ final String reason;++ InvalidRequest(String reason) {+ super(reason);+ this.reason = reason;+ }+ }++ // Do not use a record: its generated toString would include the job body.+ NativeLegacyJobSession(JsonNode request) {+ operationId = text(request, "operationId", "");+ what = text(request, "what", "");+ nextDate = text(request, "nextDate", "");+ interval = text(request, "interval", "");+ schema = text(request, "schema", "");+ dialect = text(request, "dialect", "oracle");+ zone = request.hasNonNull("zone") ? text(request, "zone", "") : null;+ if (operationId.isEmpty() || operationId.length() > 128 || operationId.indexOf('\0') >= 0+ || schema.indexOf('\0') >= 0 || !request.path("enabled").isBoolean()) {+ throw new InvalidRequest("native_job_request_invalid");+ }+ enabled = request.path("enabled").asBoolean();+ JsonNode instanceValue = request.path("instance");+ JsonNode timeoutValue = request.path("timeoutSecs");+ if ((!instanceValue.isMissingNode() && (!instanceValue.isIntegralNumber() || !instanceValue.canConvertToLong()))+ || (!timeoutValue.isMissingNode() && (!timeoutValue.isIntegralNumber() || !timeoutValue.canConvertToInt()))) {+ throw new InvalidRequest("native_job_request_invalid");+ }+ instance = instanceValue.asLong(0);+ timeoutSecs = timeoutValue.asInt(0);+ if (instance < 0 || timeoutSecs < 0+ || (!dialect.equals("oracle") && !dialect.equals("oceanbase-oracle"))+ || (oceanbase() ? instance != 0 || (zone != null && (zone.isEmpty() || zone.indexOf('\0') >= 0)) : zone != null)) {+ throw new InvalidRequest("native_job_request_invalid");+ }+ if (what.isBlank()) throw new InvalidRequest("native_job_action_required");+ try {+ if (!nextDate.matches("[0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}:[0-9]{2}")+ || LocalDateTime.parse(nextDate, DATE).getYear() < 1) {+ throw new InvalidRequest("native_job_date_invalid");+ }+ } catch (DateTimeParseException error) {+ throw new InvalidRequest("native_job_date_invalid");+ }+ result = failure(operationId, "not_started", null, null);+ }++ private static String text(JsonNode request, String key, String fallback) {+ JsonNode value = request.path(key);+ if (value.isMissingNode() || value.isNull()) return fallback;+ if (!value.isTextual()) throw new InvalidRequest("native_job_request_invalid");+ return value.textValue();+ }++ static boolean isMethod(String method) {+ return switch (method) {+ case "prepareLegacyJob", "prepare_legacy_job", "commitLegacyJob", "commit_legacy_job",+ "rollbackLegacyJob", "rollback_legacy_job", "legacyJobStatus", "legacy_job_status" -> true;+ default -> false;+ };+ }++ static boolean isPrepare(String method) {+ return "prepareLegacyJob".equals(method) || "prepare_legacy_job".equals(method);+ }++ boolean sameRequest(NativeLegacyJobSession other) {+ return operationId.equals(other.operationId) && what.equals(other.what) && nextDate.equals(other.nextDate)+ && interval.equals(other.interval) && enabled == other.enabled && instance == other.instance+ && schema.equals(other.schema) && timeoutSecs == other.timeoutSecs+ && dialect.equals(other.dialect) && Objects.equals(zone, other.zone);+ }++ private boolean oceanbase() { return dialect.equals("oceanbase-oracle"); }++ static ObjectNode failure(String operationId, String phase, String reason, Throwable cause) {+ ObjectNode result = MAPPER.createObjectNode().put("operationId", operationId).put("phase", phase);+ if (reason != null) result.put("reason", reason);+ diagnostics(result, cause);+ return result;+ }++ private static void diagnostics(ObjectNode result, Throwable cause) {+ JdbcErrorDiagnostics.appendSql(result, cause);+ }++ void openFailed(Throwable cause) {+ result.put("reason", "native_job_session_open_failed");+ diagnostics(result, cause);+ }++ ObjectNode status(String requestedOperation) {+ if (!operationId.equals(requestedOperation)) {+ return failure(requestedOperation, "unknown", "native_job_session_unavailable", null);+ }+ return result.deepCopy();+ }++ void prepare(Connection ownedConnection) {+ connection = ownedConnection;+ String reason = "native_job_dialect_unverified";+ try {+ var metadata = connection.getMetaData();+ if (metadata == null || !(oceanbase() ? "OceanBase" : "Oracle").equalsIgnoreCase(metadata.getDatabaseProductName())) {+ result.put("reason", reason);+ closeConnection();+ return;+ }+ reason = "native_job_schema_not_selected";+ if (!schema.isEmpty()) {+ try (Statement statement = connection.createStatement()) {+ statement.setQueryTimeout(timeoutSecs);+ statement.execute("ALTER SESSION SET CURRENT_SCHEMA = \"" + schema.replace("\"", "\"\"") + "\"");+ }+ }+ reason = "native_job_transaction_not_started";+ connection.setAutoCommit(false);+ transactionActive = true;+ String sessionUser = null;+ if (oceanbase()) {+ reason = "native_job_initial_identity_unverified";+ try (PreparedStatement statement = connection.prepareStatement("SELECT USER AS DBX_SESSION_USER FROM DUAL")) {+ statement.setQueryTimeout(timeoutSecs);+ try (ResultSet rows = statement.executeQuery()) {+ if (rows.next()) sessionUser = rows.getString(1);+ if (sessionUser == null || sessionUser.isEmpty() || rows.next()) {+ rollback(reason, null);+ return;+ }+ }+ }+ }+ result.put("phase", "submitting");+ reason = "native_job_submit_failed";+ String placement = oceanbase() ? "zone" : "instance";+ try (CallableStatement statement = connection.prepareCall("""+ DECLARE native_id BINARY_INTEGER;+ BEGIN+ SYS.DBMS_JOB.SUBMIT(job => native_id, what => ?, next_date => TO_DATE(?, 'YYYY-MM-DD HH24:MI:SS'), interval => ?, no_parse => FALSE, %s => ?, force => FALSE);+ ? := TO_CHAR(native_id);+ END;+ """.formatted(placement))) {+ statement.setQueryTimeout(timeoutSecs);+ statement.setString(1, what);+ statement.setString(2, nextDate);+ statement.setString(3, interval);+ if (oceanbase()) {+ if (zone == null) statement.setNull(4, Types.VARCHAR);+ else statement.setString(4, zone);+ } else statement.setLong(4, instance);+ statement.registerOutParameter(5, Types.VARCHAR);+ statement.execute();+ reason = "native_job_out_read_failed";+ String id = statement.getString(5);+ if (numericId(id)) result.put("jobId", id);+ }+ if (!result.has("jobId")) {+ rollback("native_job_out_id_unverified", null);+ return;+ }+ result.put("phase", "configuring");+ reason = "native_job_initial_state_failed";+ try (CallableStatement statement = connection.prepareCall(+ "BEGIN SYS.DBMS_JOB.BROKEN(TO_NUMBER(?), ? = 1, TO_DATE(?, 'YYYY-MM-DD HH24:MI:SS')); END;")) {+ statement.setQueryTimeout(timeoutSecs);+ statement.setString(1, result.path("jobId").asText());+ statement.setInt(2, enabled ? 0 : 1);+ statement.setString(3, nextDate);+ statement.execute();+ }+ if (oceanbase()) {+ // OB BROKEN(TRUE) replaces NEXT_DATE even when the requested date is supplied.+ try (CallableStatement statement = connection.prepareCall(+ "BEGIN SYS.DBMS_JOB.NEXT_DATE(TO_NUMBER(?), TO_DATE(?, 'YYYY-MM-DD HH24:MI:SS')); END;")) {+ statement.setQueryTimeout(timeoutSecs);+ statement.setString(1, result.path("jobId").asText());+ statement.setString(2, nextDate);+ statement.execute();+ }+ }+ reason = "native_job_initial_read_failed";+ boolean verified;+ try (PreparedStatement statement = connection.prepareStatement("""+ SELECT TO_CHAR(JOB), WHAT, TO_CHAR(NEXT_DATE, 'YYYY-MM-DD HH24:MI:SS'), INTERVAL,+ BROKEN, %s, LOG_USER, PRIV_USER, SCHEMA_USER+ FROM SYS.USER_JOBS WHERE JOB = TO_NUMBER(?)+ """.formatted(oceanbase() ? "INSTANCE" : "TO_CHAR(INSTANCE)"))) {+ statement.setQueryTimeout(timeoutSecs);+ statement.setString(1, result.path("jobId").asText());+ try (ResultSet rows = statement.executeQuery()) {+ verified = rows.next() && result.path("jobId").asText().equals(rows.getString(1))+ && what.equals(rows.getString(2)) && nextDate.equals(rows.getString(3))+ && interval.equals(Objects.requireNonNullElse(rows.getString(4), ""))+ && (enabled ? "N" : "Y").equals(rows.getString(5))+ && (oceanbase() ? Objects.equals(zone, rows.getString(6)) : Long.toString(instance).equals(rows.getString(6)))+ && (!oceanbase() || (sessionUser.equals(rows.getString(7)) && sessionUser.equals(rows.getString(8))))+ && (schema.isEmpty() || schema.equals(rows.getString(9))) && !rows.next();+ }+ }+ if (!verified) {+ rollback("native_job_initial_state_unverified", null);+ return;+ }+ result.put("phase", "prepared");+ } catch (SQLException | RuntimeException | LinkageError error) {+ if (transactionActive) {+ rollback(reason, error);+ } else {+ result.put("reason", reason);+ diagnostics(result, error);+ closeConnection();+ }+ }+ }++ ObjectNode finish(String requestedOperation, String id, boolean commit) {+ if (!operationId.equals(requestedOperation)) return status(requestedOperation);+ if (!"prepared".equals(result.path("phase").asText())) return status(operationId);+ if ((commit || !id.isEmpty()) && (!numericId(id) || !id.equals(result.path("jobId").asText()))) {+ return failure(operationId, "unknown", "native_job_identity_mismatch", null);+ }+ if (!commit) {+ rollback("native_job_canceled_before_commit", null);+ return status(operationId);+ }+ result.put("phase", "commit_sent");+ // Once COMMIT is sent, disposal must not issue another COMMIT or ROLLBACK.+ transactionActive = false;+ try {+ connection.commit();+ result.put("phase", "committed");+ } catch (SQLException | RuntimeException | LinkageError error) {+ result.put("phase", "unknown").put("reason", "native_job_commit_unknown");+ diagnostics(result, error);+ } finally {+ closeConnection();+ }+ return status(operationId);+ }++ private void rollback(String reason, Throwable cause) {+ result.put("reason", reason);+ diagnostics(result, cause);+ transactionActive = false;+ try {+ connection.rollback();+ result.put("phase", "rolled_back");+ } catch (SQLException | RuntimeException | LinkageError error) {+ result.put("phase", "unknown").put("reason", "native_job_rollback_unknown");+ diagnostics(result, error);+ disposalConfirmed = false;+ } finally {+ closeConnection();+ }+ }++ void dispose() {+ if (transactionActive) rollback("native_job_session_closed_before_commit", null);+ else closeConnection();+ }++ boolean disposalConfirmed() {+ return disposalConfirmed;+ }++ private void closeConnection() {+ Connection owned = connection;+ connection = null;+ if (owned == null) return;+ try {+ owned.close();+ } catch (SQLException | RuntimeException | LinkageError error) {+ disposalConfirmed = false;+ diagnostics(result, error);+ }+ if (oceanbase()) result.put("disposalConfirmed", disposalConfirmed);+ }++ private static boolean numericId(String id) {+ return id != null && id.matches("[1-9][0-9]*");+ }+}diff --git a/plugins/jdbc/src/main/java/app/dbx/jdbc/OracleTriggerMetadataReader.java b/plugins/jdbc/src/main/java/app/dbx/jdbc/OracleTriggerMetadataReader.javanew file mode 100644index 0000000000..f835a8304a--- /dev/null+++ b/plugins/jdbc/src/main/java/app/dbx/jdbc/OracleTriggerMetadataReader.java@@ -0,0 +1,432 @@+package app.dbx.jdbc;++import com.fasterxml.jackson.databind.JsonNode;+import com.fasterxml.jackson.databind.ObjectMapper;+import com.fasterxml.jackson.databind.node.ArrayNode;+import com.fasterxml.jackson.databind.node.ObjectNode;+import java.io.IOException;+import java.io.Reader;+import java.sql.Clob;+import java.sql.Connection;+import java.sql.ResultSet;+import java.sql.ResultSetMetaData;+import java.sql.SQLException;+import java.sql.SQLFeatureNotSupportedException;+import java.util.ArrayList;+import java.util.LinkedHashMap;+import java.util.LinkedHashSet;+import java.util.List;+import java.util.Locale;+import java.util.Map;++/** Trigger metadata for this independently packaged JDBC runtime. */+final class OracleTriggerMetadataReader {+ private static final ObjectMapper JSON = new ObjectMapper();+ private static final String OBJECT_MARKER = "DBX_TRIGGER_OBJECT_MARKER";+ private static final List<String> OBJECT_TYPES = List.of("TABLE", "VIEW", "MATERIALIZED_VIEW", "PROCEDURE", "FUNCTION", "PACKAGE", "PACKAGE_BODY", "SEQUENCE", "SYNONYM", "TRIGGER", "TYPE", "TYPE_BODY");+ record Profile(String engine, String version) {}+ private final Connection connection;+ private final Profile profile;++ OracleTriggerMetadataReader(Connection connection, Profile profile) {+ this.connection = connection;+ this.profile = profile;+ }++ /** Confirm the connected product, not an editable connection label. */+ static Profile profile(Connection connection) throws SQLException {+ var metadata = connection.getMetaData();+ String product = metadata.getDatabaseProductName();+ String version = metadata.getDatabaseProductVersion();+ if ("OceanBase".equalsIgnoreCase(product)) {+ // This Oracle-only read distinguishes OceanBase's two tenant modes.+ try (var statement = connection.prepareStatement("SELECT SYS_CONTEXT('USERENV','CURRENT_SCHEMA') FROM DUAL");+ var rows = statement.executeQuery()) {+ if (rows.next() && rows.getString(1) != null) return new Profile("oceanbase-oracle", version);+ }+ return null;+ }+ if ("Oracle".equalsIgnoreCase(product) || "Oracle Database".equalsIgnoreCase(product)) return new Profile("oracle", version);+ String url = metadata.getURL();+ if (url != null && url.regionMatches(true, 0, "jdbc:dm:", 0, 8)+ && product != null && (product.toUpperCase(Locale.ROOT).startsWith("DM") || product.equalsIgnoreCase("Dameng"))+ && metadata.getDatabaseMajorVersion() == 8) return new Profile("dm", version);+ return null;+ }++ ArrayNode listObjects(String owner, String filter, int limit, int offset, List<String> requestedTypes) throws SQLException {+ requireIdentity(owner);+ LinkedHashSet<String> types = new LinkedHashSet<>();+ for (String type : requestedTypes == null || requestedTypes.isEmpty() ? OBJECT_TYPES : requestedTypes) {+ String normalized = type.trim().toUpperCase(Locale.ROOT).replace(' ', '_');+ if (OBJECT_TYPES.contains(normalized)) types.add(normalized.replace('_', ' '));+ }+ ArrayNode result = JSON.createArrayNode();+ if (types.isEmpty()) return result;+ List<Object> args = new ArrayList<>();+ args.add(owner);+ args.addAll(types);+ String sql = "SELECT o.OBJECT_NAME, REPLACE(o.OBJECT_TYPE,' ','_') AS OBJECT_TYPE, c.COMMENTS FROM ALL_OBJECTS o "+ + "LEFT JOIN ALL_TAB_COMMENTS c ON c.OWNER=o.OWNER AND c.TABLE_NAME=o.OBJECT_NAME AND o.OBJECT_TYPE IN ('TABLE','VIEW') "+ + "WHERE o.OWNER=? AND o.OBJECT_TYPE IN (" + String.join(",", java.util.Collections.nCopies(types.size(), "?")) + ")";+ if (filter != null && !filter.isBlank()) {+ StringBuilder pattern = new StringBuilder("%");+ for (char ch : filter.trim().toUpperCase(Locale.ROOT).toCharArray()) {+ if (ch == '~' || ch == '%' || ch == '_') pattern.append('~');+ pattern.append(ch).append('%');+ }+ sql += " AND (UPPER(o.OBJECT_NAME) LIKE ? ESCAPE '~' OR UPPER(c.COMMENTS) LIKE ? ESCAPE '~')";+ args.add(pattern.toString());+ args.add(pattern.toString());+ }+ sql += " ORDER BY CASE o.OBJECT_TYPE WHEN 'TABLE' THEN 0 WHEN 'VIEW' THEN 1 WHEN 'MATERIALIZED VIEW' THEN 2 WHEN 'PROCEDURE' THEN 3 WHEN 'FUNCTION' THEN 4 WHEN 'SEQUENCE' THEN 5 WHEN 'SYNONYM' THEN 6 WHEN 'PACKAGE' THEN 7 ELSE 8 END, o.OBJECT_NAME, o.OWNER, o.OBJECT_ID";+ if (limit > 0 || offset > 0) {+ sql = "SELECT OBJECT_NAME, OBJECT_TYPE, COMMENTS FROM (SELECT dbx_page.*, ROWNUM DBX_RN FROM (" + sql + ") dbx_page"+ + (limit > 0 ? " WHERE ROWNUM <= ?" : "") + ") WHERE DBX_RN > ?";+ if (limit > 0) args.add((long) limit + offset);+ args.add(offset);+ }+ try (var statement = connection.prepareStatement(sql)) {+ for (int i = 0; i < args.size(); i++) statement.setObject(i + 1, args.get(i));+ try (var rows = statement.executeQuery()) {+ while (rows.next()) {+ ObjectNode object = result.addObject();+ object.put("name", rows.getString(1));+ object.put("object_type", rows.getString(2));+ object.put("schema", owner);+ object.put("comment", rows.getString(3));+ }+ }+ }+ enrich(result, owner);+ return result;+ }++ private void enrich(ArrayNode objects, String owner) throws SQLException {+ List<ObjectNode> triggers = new ArrayList<>();+ objects.forEach(object -> {+ if ("TRIGGER".equals(object.path("object_type").asText())) triggers.add((ObjectNode) object);+ });+ for (int start = 0; start < triggers.size(); start += 500) {+ List<ObjectNode> batch = triggers.subList(start, Math.min(start + 500, triggers.size()));+ List<String> args = new ArrayList<>();+ args.add(owner);+ batch.forEach(object -> args.add(object.path("name").asText()));+ try {+ ArrayNode summaries = summaries("t.OWNER=? AND t.TRIGGER_NAME IN (" + String.join(",", java.util.Collections.nCopies(batch.size(), "?")) + ")", args, false);+ Map<String, JsonNode> byName = new LinkedHashMap<>();+ for (JsonNode trigger : summaries) {+ if (owner.equals(trigger.path("oracle_metadata").path("owner").asText())) {+ if (byName.put(trigger.path("name").asText(), trigger) != null) throw new SQLException("Trigger identity is not unique");+ }+ }+ for (ObjectNode object : batch) {+ JsonNode trigger = byName.get(object.path("name").asText());+ if (trigger == null) trigger = unknown(owner, object.path("name").asText(), state("incomplete", "Trigger changed or is no longer visible; reload"));+ object.set("trigger", trigger);+ object.set("valid", trigger.path("valid"));+ JsonNode parent = trigger.path("oracle_metadata").path("parent");+ if (parent.isObject()) {+ object.set("parent_schema", parent.path("owner"));+ object.set("parent_name", parent.path("name"));+ }+ }+ } catch (SQLException error) {+ for (ObjectNode object : batch) object.set("trigger", unknown(owner, object.path("name").asText(), failure(error)));+ }+ }+ }++ ArrayNode listTriggers(String owner, String parent) throws SQLException {+ requireIdentity(owner);+ requireIdentity(parent);+ return summaries("t.TABLE_OWNER=? AND t.TABLE_NAME=?", List.of(owner, parent), true);+ }++ private ArrayNode summaries(String predicate, List<String> args, boolean body) throws SQLException {+ String columns = body || profile.engine().equals("dm") ? "t.*"+ : "t.OWNER,t.TRIGGER_NAME,t.TRIGGERING_EVENT,t.TRIGGER_TYPE,t.STATUS,t.TABLE_OWNER,t.TABLE_NAME,t.BASE_OBJECT_TYPE,t.WHEN_CLAUSE";+ String sql = "SELECT " + columns + ",o.OBJECT_NAME AS " + OBJECT_MARKER + ",o.* FROM ALL_TRIGGERS t LEFT JOIN ALL_OBJECTS o "+ + "ON o.OWNER=t.OWNER AND o.OBJECT_NAME=t.TRIGGER_NAME AND o.OBJECT_TYPE='TRIGGER' WHERE " + predicate + " ORDER BY t.TRIGGER_NAME,t.OWNER";+ ArrayNode result = JSON.createArrayNode();+ try (var statement = connection.prepareStatement(sql)) {+ for (int i = 0; i < args.size(); i++) statement.setString(i + 1, args.get(i));+ try (var rows = statement.executeQuery()) {+ Columns mapping = new Columns(rows.getMetaData());+ while (rows.next()) {+ String owner = mapping.trigger(rows, "OWNER");+ String name = mapping.trigger(rows, "TRIGGER_NAME");+ requireIdentity(owner);+ requireIdentity(name);+ ObjectNode trigger = result.addObject();+ trigger.put("name", name);+ String event = mapping.trigger(rows, "TRIGGERING_EVENT");+ String timing = mapping.trigger(rows, "TRIGGER_TYPE");+ trigger.put("event", event == null ? "" : event);+ trigger.put("timing", timing == null ? "" : timing);+ trigger.put("condition", mapping.trigger(rows, "WHEN_CLAUSE"));+ Boolean enabled = enabled(mapping.trigger(rows, "STATUS"));+ Boolean valid = valid(mapping.object(rows, "STATUS"));+ if (enabled != null) trigger.put("enabled", enabled);+ if (valid != null) trigger.put("valid", valid);+ if (body) trigger.put("statement", mapping.trigger(rows, "TRIGGER_BODY"));+ ObjectNode metadata = metadata(owner, name);+ trigger.set("oracle_metadata", metadata);+ String scopeType = mapping.trigger(rows, "BASE_OBJECT_TYPE");+ String scope = scopeType == null ? "UNKNOWN" : switch (scopeType.toUpperCase(Locale.ROOT)) {+ case "TABLE", "VIEW", "SCHEMA", "DATABASE", "TIMER" -> scopeType.toUpperCase(Locale.ROOT);+ default -> "OTHER";+ };+ if (profile.engine().equals("dm") && scope.equals("DATABASE") && "TIMER".equalsIgnoreCase(event)) scope = "TIMER";+ metadata.put("scope", scope);+ metadata.put("scopeType", scopeType);+ String parentOwner = mapping.trigger(rows, "TABLE_OWNER");+ String parentName = mapping.trigger(rows, "TABLE_NAME");+ if (List.of("TABLE", "VIEW").contains(scope) && parentOwner != null && parentName != null) {+ ObjectNode parent = metadata.putObject("parent");+ parent.put("owner", parentOwner);+ parent.put("name", parentName);+ parent.put("objectType", scope);+ }+ if (scope.equals("SCHEMA")) metadata.put("scopeOwner", parentOwner);+ String id = mapping.object(rows, "OBJECT_ID");+ metadata.put("objectId", id);+ metadata.put("lastDdlTime", mapping.object(rows, "LAST_DDL_TIME"));+ ObjectNode reads = metadata.withObject("reads");+ reads.set("identity", id == null ? missing("Object ID") : available());+ reads.set("scope", scope.equals("UNKNOWN") || scope.equals("SCHEMA") && parentOwner == null ? missing("Trigger scope") : available());+ reads.set("parent", List.of("UNKNOWN", "OTHER").contains(scope) || List.of("TABLE", "VIEW").contains(scope) && !metadata.has("parent") ? missing("Owning object") : available());+ reads.set("enabled", enabled == null ? missing("Enabled state") : available());+ reads.set("validity", valid == null ? missing("Object validity") : available());+ }+ }+ }+ return result;+ }++ ObjectNode source(String owner, String name) throws SQLException {+ requireIdentity(owner);+ requireIdentity(name);+ List<String> args = List.of(owner, name);+ ArrayNode before = summaries("t.OWNER=? AND t.TRIGGER_NAME=?", args, true);+ ObjectNode result = JSON.createObjectNode();+ result.put("name", name);+ result.put("schema", owner);+ result.put("object_type", "TRIGGER");+ if (before.isEmpty()) {+ result.put("source", "");+ result.put("editable", false);+ ObjectNode trigger = unknown(owner, name, missing("Visible trigger"));+ trigger.withObject("oracle_metadata").withObject("reads").set("identity", state("empty", "No visible trigger with this exact owner/name"));+ result.set("trigger", trigger);+ return result;+ }+ if (before.size() != 1 || !owner.equals(before.get(0).path("oracle_metadata").path("owner").asText())+ || !name.equals(before.get(0).path("name").asText())) {+ throw new SQLException("Trigger identity does not match the exact request");+ }+ String text = "", origin = "catalog-body", format = "body";+ ObjectNode sourceState = missing("Complete trigger definition");+ boolean metadataFirst = profile.engine().equals("dm");+ for (boolean useMetadata : new boolean[]{metadataFirst, !metadataFirst}) {+ try {+ String source = definition(owner, name, useMetadata);+ if (!source.isBlank()) {+ text = source;+ origin = useMetadata ? "DBMS_METADATA" : "ALL_SOURCE";+ format = useMetadata ? "ddl" : "declaration";+ sourceState = available();+ break;+ }+ } catch (SQLException error) {+ sourceState = failure(error);+ }+ }+ if (text.isEmpty()) text = before.get(0).path("statement").asText("");+ ArrayNode errors = null;+ ObjectNode errorState;+ try {+ errors = errors(owner, name);+ errorState = available();+ } catch (SQLException error) {+ errorState = failure(error);+ }+ ArrayNode after = summaries("t.OWNER=? AND t.TRIGGER_NAME=?", args, true);+ boolean stable = before.equals(after);+ ObjectNode trigger = (ObjectNode) (after.size() == 1 ? after.get(0) : before.get(0));+ ObjectNode metadata = (ObjectNode) trigger.path("oracle_metadata");+ ObjectNode reads = metadata.withObject("reads");+ ObjectNode definition = metadata.putObject("definition");+ definition.put("origin", origin);+ definition.put("format", format);+ definition.put("complete", stable && sourceState.path("state").asText().equals("available") && !format.equals("body"));+ reads.set("definition", sourceState);+ reads.set("errors", errorState);+ metadata.set("errors", errors);+ if (!stable) {+ ObjectNode changed = state("incomplete", "Trigger changed while loading; reload");+ reads.set("identity", changed);+ reads.set("definition", changed);+ }+ result.put("source", text);+ result.set("trigger", trigger);+ return result;+ }++ private String definition(String owner, String name, boolean metadata) throws SQLException {+ String sql = metadata ? "SELECT DBMS_METADATA.GET_DDL(?, ?, ?) FROM DUAL" : "SELECT LINE,TEXT FROM ALL_SOURCE WHERE OWNER=? AND NAME=? AND TYPE='TRIGGER' ORDER BY LINE";+ try (var statement = connection.prepareStatement(sql)) {+ if (metadata) {+ statement.setString(1, "TRIGGER");+ statement.setString(2, name);+ statement.setString(3, owner);+ } else {+ statement.setString(1, owner);+ statement.setString(2, name);+ }+ StringBuilder source = new StringBuilder();+ long expectedLine = 1;+ try (var rows = statement.executeQuery()) {+ while (rows.next()) {+ if (!metadata && (rows.getLong(1) != expectedLine++ || rows.wasNull())) throw new SQLException("Trigger source dictionary lines are incomplete");+ String text = text(rows, metadata ? 1 : 2);+ if (text == null) throw new SQLException("Trigger source contains an unreadable line");+ source.append(text);+ }+ }+ return source.toString();+ }+ }++ private ArrayNode errors(String owner, String name) throws SQLException {+ ArrayNode errors = JSON.createArrayNode();+ try (var statement = connection.prepareStatement("SELECT SEQUENCE,LINE,POSITION,TEXT,ATTRIBUTE FROM ALL_ERRORS WHERE OWNER=? AND NAME=? AND TYPE='TRIGGER' ORDER BY SEQUENCE")) {+ statement.setString(1, owner);+ statement.setString(2, name);+ try (var rows = statement.executeQuery()) {+ while (rows.next()) {+ String text = text(rows, 4);+ if (text == null) throw new SQLException("Trigger compilation error text is unreadable");+ ObjectNode error = errors.addObject();+ error.put("sequence", rows.getLong(1));+ error.put("line", rows.getLong(2));+ error.put("position", rows.getLong(3));+ error.put("text", text);+ error.put("severity", rows.getString(5));+ }+ }+ }+ return errors;+ }++ private ObjectNode metadata(String owner, String name) {+ ObjectNode metadata = JSON.createObjectNode();+ metadata.put("contractVersion", 1);+ metadata.put("identityMode", "exact");+ metadata.put("engine", profile.engine());+ metadata.put("engineVersion", profile.version());+ metadata.put("owner", owner);+ metadata.put("name", name);+ metadata.putObject("reads");+ return metadata;+ }++ private ObjectNode unknown(String owner, String name, ObjectNode failure) {+ ObjectNode trigger = JSON.createObjectNode();+ trigger.put("name", name);+ trigger.put("event", "");+ trigger.put("timing", "");+ ObjectNode metadata = metadata(owner, name);+ metadata.put("scope", "UNKNOWN");+ trigger.set("oracle_metadata", metadata);+ for (String field : List.of("identity", "scope", "parent", "enabled", "validity")) metadata.withObject("reads").set(field, failure);+ return trigger;+ }++ private static ObjectNode state(String state, String message) {+ ObjectNode value = JSON.createObjectNode();+ value.put("state", state);+ if (message != null) value.put("message", message);+ return value;+ }+ private static ObjectNode available() { return state("available", null); }+ private static ObjectNode missing(String field) { return state("unavailable", field + " is not exposed by this dictionary"); }+ private static ObjectNode failure(SQLException error) {+ String code = error.getSQLState();+ int vendor = error.getErrorCode();+ String state = vendor == 1031 || "42501".equals(code) ? "denied"+ : vendor == 942 || vendor == 904 || "42S02".equals(code) || "42S22".equals(code) ? "unavailable" : "error";+ return state(state, "Metadata read failed (SQLState " + code + ", code " + vendor + ")");+ }++ private static void requireIdentity(String value) throws SQLException {+ if (value == null || value.isEmpty()) throw new SQLException("Exact trigger metadata requires owner and name");+ }++ private static Boolean enabled(String value) {+ if (value == null) return null;+ return switch (value.trim().toUpperCase(Locale.ROOT)) {+ case "ENABLED", "ENABLE", "Y" -> true;+ case "DISABLED", "DISABLE", "N" -> false;+ default -> null;+ };+ }++ private static Boolean valid(String value) {+ if (value == null) return null;+ return switch (value.trim().toUpperCase(Locale.ROOT)) {+ case "VALID" -> true;+ case "INVALID" -> false;+ default -> null;+ };+ }++ private static String text(ResultSet rows, int column) throws SQLException {+ Reader stream;+ try {+ stream = rows.getCharacterStream(column);+ } catch (SQLFeatureNotSupportedException | AbstractMethodError unsupported) {+ stream = null;+ }+ if (stream == null) {+ Object value = rows.getObject(column);+ if (!(value instanceof Clob clob)) return rows.getString(column);+ stream = clob.getCharacterStream();+ }+ try (Reader reader = stream) {+ StringBuilder text = new StringBuilder();+ char[] buffer = new char[8192];+ for (int count; (count = reader.read(buffer)) != -1;) text.append(buffer, 0, count);+ return text.toString();+ } catch (IOException error) {+ throw new SQLException("Trigger text could not be read completely", error);+ }+ }++ private static final class Columns {+ private final Map<String, Integer> trigger = new LinkedHashMap<>();+ private final Map<String, Integer> object = new LinkedHashMap<>();++ Columns(ResultSetMetaData metadata) throws SQLException {+ boolean objects = false;+ for (int i = 1; i <= metadata.getColumnCount(); i++) {+ String label = metadata.getColumnLabel(i).toUpperCase(Locale.ROOT);+ if (label.equals(OBJECT_MARKER)) {+ objects = true;+ continue;+ }+ (objects ? object : trigger).putIfAbsent(label, i);+ }+ }++ String trigger(ResultSet rows, String field) throws SQLException {+ Integer index = trigger.get(field);+ return index == null ? null : field.equals("TRIGGER_BODY") ? text(rows, index) : rows.getString(index);+ }++ String object(ResultSet rows, String field) throws SQLException {+ Integer index = object.get(field);+ return index == null ? null : rows.getString(index);+ }+ }+}diff --git a/plugins/jdbc/src/test/java/app/dbx/jdbc/DbxJdbcPluginTest.java b/plugins/jdbc/src/test/java/app/dbx/jdbc/DbxJdbcPluginTest.javaindex 9e1fe4af36..6d4eed3de0 100644--- a/plugins/jdbc/src/test/java/app/dbx/jdbc/DbxJdbcPluginTest.java+++ b/plugins/jdbc/src/test/java/app/dbx/jdbc/DbxJdbcPluginTest.java@@ -66,6 +66,221 @@ final class DbxJdbcPluginTest {""".formatted(CONNECTION));}+ @Test+ void exactTriggerMethodsDispatchBothSpellingsWithoutTrimmingIdentity() throws Exception {+ List<String> calls = new ArrayList<>();+ Driver driver = triggerMetadataDriver(calls, "Oracle", false);+ DriverManager.registerDriver(driver);+ String connection = "{\"connection_string\":\"jdbc:dbx-trigger:test\"}";+ try {+ for (String method : List.of("listTriggers", "list_triggers")) {+ JsonNode response = request(method, "{\"connection\":" + connection + ",\"schema\":\" Parent Owner \",\"table\":\" Parent \",\"identity_mode\":\"exact\"}");+ assertFalse(response.has("error"), response.toString());+ JsonNode trigger = response.path("result").path(0);+ assertEquals(" Trigger ", trigger.path("name").asText());+ assertEquals(" Owner ", trigger.path("oracle_metadata").path("owner").asText());+ assertEquals(" Parent Owner ", trigger.path("oracle_metadata").path("parent").path("owner").asText());+ assertFalse(trigger.path("enabled").asBoolean());+ assertFalse(trigger.path("valid").asBoolean());+ }+ assertTrue(calls.contains("bind:1= Parent Owner "), calls.toString());+ assertTrue(calls.contains("bind:2= Parent "), calls.toString());+ } finally { closeAndDeregister(connection, driver); }+ }++ @Test+ void exactJdbcTriggerSourceRetainsLongClobAndMetadataStateAppendix() throws Exception {+ List<String> calls = new ArrayList<>();+ Driver driver = triggerMetadataDriver(calls, "OceanBase", false);+ DriverManager.registerDriver(driver);+ String connection = "{\"connection_string\":\"jdbc:dbx-trigger:test\"}";+ try {+ JsonNode response = request("getObjectSource", "{\"connection\":" + connection + ",\"schema\":\" Owner \",\"name\":\" Trigger \",\"object_type\":\"TRIGGER\",\"identity_mode\":\"exact\"}");+ assertFalse(response.has("error"), response.toString());+ JsonNode source = response.path("result");+ assertEquals(triggerExport(), source.path("source").asText());+ JsonNode metadata = source.path("trigger").path("oracle_metadata");+ assertEquals("oceanbase-oracle", metadata.path("engine").asText());+ assertEquals("9007199254740993", metadata.path("objectId").asText());+ assertEquals("DBMS_METADATA", metadata.path("definition").path("origin").asText());+ assertTrue(metadata.path("definition").path("complete").asBoolean());+ assertEquals("Missing procedure", metadata.path("errors").path(0).path("text").asText());+ assertTrue(calls.contains("bind:2= Trigger "), calls.toString());+ assertTrue(calls.contains("bind:3= Owner "), calls.toString());+ } finally { closeAndDeregister(connection, driver); }+ }++ @Test+ void exactJdbcDiscoveryFiltersBeforePagingAndOnlyThenLoadsSummaries() throws Exception {+ List<String> calls = new ArrayList<>();+ Driver driver = triggerMetadataDriver(calls, "Oracle", false);+ DriverManager.registerDriver(driver);+ String connection = "{\"connection_string\":\"jdbc:dbx-trigger:test\"}";+ try {+ JsonNode response = request("listObjects", "{\"connection\":" + connection + ",\"schema\":\" Owner \",\"object_types\":[\"TRIGGER\"],\"filter\":\"trig\",\"limit\":1,\"offset\":2,\"identity_mode\":\"exact\"}");+ assertFalse(response.has("error"), response.toString());+ JsonNode object = response.path("result").path(0);+ assertEquals(" Trigger ", object.path("name").asText());+ assertEquals(" Parent Owner ", object.path("parent_schema").asText());+ String query = calls.stream().filter(call -> call.contains("FROM ALL_OBJECTS o")).findFirst().orElseThrow();+ assertTrue(query.contains("UPPER(o.OBJECT_NAME) LIKE ?"));+ assertTrue(query.contains("ROWNUM <= ?"));+ assertTrue(query.indexOf("UPPER(o.OBJECT_NAME)") < query.indexOf("ORDER BY"));+ assertTrue(calls.contains("bind:5=3"), calls.toString());+ assertTrue(calls.contains("bind:6=2"), calls.toString());+ assertFalse(calls.stream().anyMatch(call -> call.contains("ALL_SOURCE")), calls.toString());+ } finally { closeAndDeregister(connection, driver); }+ }++ @Test+ void exactJdbcMixedAndDefaultPagesKeepTypesAlongsideTriggers() throws Exception {+ try (Connection connection = DriverManager.getConnection("jdbc:h2:mem:trigger_type_pages;MODE=Oracle", "sa", "")) {+ try (Statement statement = connection.createStatement()) {+ statement.execute("CREATE TABLE ALL_OBJECTS (OWNER VARCHAR, OBJECT_NAME VARCHAR, OBJECT_TYPE VARCHAR, OBJECT_ID BIGINT, STATUS VARCHAR)");+ statement.execute("CREATE TABLE ALL_TAB_COMMENTS (OWNER VARCHAR, TABLE_NAME VARCHAR, COMMENTS VARCHAR)");+ statement.execute("CREATE TABLE ALL_TRIGGERS (OWNER VARCHAR, TRIGGER_NAME VARCHAR, TRIGGERING_EVENT VARCHAR, TRIGGER_TYPE VARCHAR, STATUS VARCHAR, TABLE_OWNER VARCHAR, TABLE_NAME VARCHAR, BASE_OBJECT_TYPE VARCHAR, WHEN_CLAUSE VARCHAR)");+ statement.execute("INSERT INTO ALL_OBJECTS VALUES (' Owner ',' A Trigger ','TRIGGER',1,'VALID'),(' Owner ',' B Type ','TYPE',2,'VALID'),(' Owner ',' C Body ','TYPE BODY',3,'VALID'),('OWNER',' Wrong Owner ','TYPE',4,'VALID')");+ }+ OracleTriggerMetadataReader reader = new OracleTriggerMetadataReader(connection, new OracleTriggerMetadataReader.Profile("oracle", "19"));+ for (boolean explicit : List.of(true, false)) {+ List<String> types = explicit ? List.of("TRIGGER", "TYPE", "TYPE_BODY") : null;+ JsonNode first = reader.listObjects(" Owner ", null, 2, 0, types);+ assertEquals(2, first.size());+ assertEquals("TRIGGER", first.path(0).path("object_type").asText());+ assertEquals(" Owner ", first.path(0).path("trigger").path("oracle_metadata").path("owner").asText());+ assertEquals("TYPE", first.path(1).path("object_type").asText());+ assertEquals(" B Type ", first.path(1).path("name").asText());+ assertFalse(first.path(1).has("trigger"));+ JsonNode next = reader.listObjects(" Owner ", null, 2, 2, types);+ assertEquals(1, next.size());+ assertEquals("TYPE_BODY", next.path(0).path("object_type").asText());+ assertEquals(" C Body ", next.path(0).path("name").asText());+ assertEquals(" Owner ", next.path(0).path("schema").asText());+ assertFalse(next.path(0).has("trigger"));+ }+ }+ }++ @Test+ void exactJdbcSourceDetectsConcurrentSameNameReplacement() throws Exception {+ Driver driver = triggerMetadataDriver(new ArrayList<>(), "Oracle", true);+ DriverManager.registerDriver(driver);+ String connection = "{\"connection_string\":\"jdbc:dbx-trigger:test\"}";+ try {+ JsonNode response = request("get_object_source", "{\"connection\":" + connection + ",\"schema\":\" Owner \",\"name\":\" Trigger \",\"object_type\":\"TRIGGER\",\"identity_mode\":\"exact\"}");+ assertFalse(response.has("error"), response.toString());+ assertEquals(triggerExport(), response.path("result").path("source").asText());+ JsonNode metadata = response.path("result").path("trigger").path("oracle_metadata");+ assertFalse(metadata.path("definition").path("complete").asBoolean());+ assertEquals("incomplete", metadata.path("reads").path("identity").path("state").asText());+ } finally { closeAndDeregister(connection, driver); }+ }++ @Test+ void compatibilityLabelDoesNotAuthorizeExactOracleTriggerMetadata() throws Exception {+ List<String> calls = new ArrayList<>();+ Driver driver = triggerMetadataDriver(calls, "Oracle-compatible YashanDB", false);+ DriverManager.registerDriver(driver);+ String connection = "{\"connection_string\":\"jdbc:dbx-trigger:test\",\"name\":\"Oracle\"}";+ try {+ JsonNode response = request("listTriggers", "{\"connection\":" + connection + ",\"schema\":\"APP\",\"table\":\"T\",\"identity_mode\":\"exact\"}");+ assertTrue(response.has("error"), response.toString());+ assertFalse(calls.stream().anyMatch(call -> call.contains("ALL_TRIGGERS")), calls.toString());+ } finally { closeAndDeregister(connection, driver); }+ }++ @Test+ void exactDmJdbcProfileUsesTheConnectedVersionAndNativeDefinition() throws Exception {+ Driver driver = triggerMetadataDriver(new ArrayList<>(), "DM DBMS", false);+ DriverManager.registerDriver(driver);+ String connection = "{\"connection_string\":\"jdbc:dbx-trigger:test\"}";+ try {+ JsonNode response = request("getObjectSource", "{\"connection\":" + connection + ",\"schema\":\" Owner \",\"name\":\" Trigger \",\"object_type\":\"TRIGGER\",\"identity_mode\":\"exact\"}");+ assertFalse(response.has("error"), response.toString());+ JsonNode metadata = response.path("result").path("trigger").path("oracle_metadata");+ assertEquals("dm", metadata.path("engine").asText());+ assertEquals("8.1.5", metadata.path("engineVersion").asText());+ assertEquals(triggerExport(), response.path("result").path("source").asText());+ assertEquals("", response.path("result").path("trigger").path("event").asText());+ assertEquals("", response.path("result").path("trigger").path("timing").asText());+ } finally { closeAndDeregister(connection, driver); }+ }++ @Test+ void dmJdbcTimerRetainsTheRawDatabaseScopeAndHasNoParent() throws Exception {+ try (Connection connection = triggerMetadataConnection(new ArrayList<>(), "DM DBMS", false, false, "Missing procedure", true)) {+ JsonNode result = new OracleTriggerMetadataReader(connection, OracleTriggerMetadataReader.profile(connection)).source(" Owner ", " Trigger ");+ JsonNode metadata = result.path("trigger").path("oracle_metadata");+ assertEquals("TIMER", metadata.path("scope").asText());+ assertEquals("DATABASE", metadata.path("scopeType").asText());+ assertFalse(metadata.has("parent"));+ assertFalse(metadata.has("scopeOwner"));+ assertTrue(result.path("source").asText().contains("AFTER TIMER ON DATABASE"));+ }+ }++ @Test+ void exactJdbcVisibleEmptyReadIsExplicitAndAQueryFailureCannotBecomeAbsence() throws Exception {+ try (Connection connection = DriverManager.getConnection("jdbc:h2:mem:trigger_empty;MODE=Oracle", "sa", "")) {+ connection.createStatement().execute("CREATE TABLE ALL_TRIGGERS (OWNER VARCHAR, TRIGGER_NAME VARCHAR, TRIGGERING_EVENT VARCHAR, TRIGGER_TYPE VARCHAR, STATUS VARCHAR, TABLE_OWNER VARCHAR, TABLE_NAME VARCHAR, BASE_OBJECT_TYPE VARCHAR, WHEN_CLAUSE VARCHAR, TRIGGER_BODY CLOB)");+ connection.createStatement().execute("CREATE TABLE ALL_OBJECTS (OWNER VARCHAR, OBJECT_NAME VARCHAR, OBJECT_TYPE VARCHAR, OBJECT_ID BIGINT, STATUS VARCHAR)");+ OracleTriggerMetadataReader reader = new OracleTriggerMetadataReader(connection, new OracleTriggerMetadataReader.Profile("oracle", "19"));+ JsonNode result = reader.source(" Owner ", " Trigger ");+ assertEquals("empty", result.path("trigger").path("oracle_metadata").path("reads").path("identity").path("state").asText());+ assertEquals(" Owner ", result.path("schema").asText());+ assertEquals(" Trigger ", result.path("name").asText());+ connection.createStatement().execute("DROP TABLE ALL_TRIGGERS");+ org.junit.jupiter.api.Assertions.assertThrows(SQLException.class, () -> reader.source(" Owner ", " Trigger "));+ }+ }++ @Test+ void jdbcDictionaryLineGapCannotBecomeACompleteReplacementBaseline() throws Exception {+ try (Connection connection = DriverManager.getConnection("jdbc:h2:mem:trigger_gap;MODE=Oracle;NON_KEYWORDS=LINE", "sa", "")) {+ try (Statement statement = connection.createStatement()) {+ statement.execute("CREATE TABLE ALL_TRIGGERS (OWNER VARCHAR, TRIGGER_NAME VARCHAR, TRIGGERING_EVENT VARCHAR, TRIGGER_TYPE VARCHAR, STATUS VARCHAR, TABLE_OWNER VARCHAR, TABLE_NAME VARCHAR, BASE_OBJECT_TYPE VARCHAR, WHEN_CLAUSE VARCHAR, TRIGGER_BODY CLOB)");+ statement.execute("CREATE TABLE ALL_OBJECTS (OWNER VARCHAR, OBJECT_NAME VARCHAR, OBJECT_TYPE VARCHAR, OBJECT_ID BIGINT, STATUS VARCHAR)");+ statement.execute("CREATE TABLE ALL_SOURCE (OWNER VARCHAR,NAME VARCHAR,TYPE VARCHAR,LINE INT,TEXT CLOB)");+ statement.execute("INSERT INTO ALL_TRIGGERS VALUES ('APP','T','INSERT','BEFORE EACH ROW','DISABLED','DATA','ORDERS','TABLE',NULL,'BEGIN NULL; END;')");+ statement.execute("INSERT INTO ALL_OBJECTS VALUES ('APP','T','TRIGGER',1,'INVALID')");+ statement.execute("INSERT INTO ALL_SOURCE VALUES ('APP','T','TRIGGER',1,'TRIGGER APP.T BEFORE INSERT ON DATA.ORDERS BEGIN NULL; END;'),('APP','T','TRIGGER',3,' -- lost dictionary line')");+ }+ JsonNode result = new OracleTriggerMetadataReader(connection, new OracleTriggerMetadataReader.Profile("oracle", "19")).source("APP", "T");+ assertFalse(result.path("trigger").path("oracle_metadata").path("definition").path("complete").asBoolean());+ assertEquals("BEGIN NULL; END;", result.path("source").asText());+ }+ }++ @Test+ void unreadableJdbcCompilationErrorsStayUnknownRatherThanEmpty() throws Exception {+ Driver driver = triggerMetadataDriver(new ArrayList<>(), "Oracle", false, true);+ DriverManager.registerDriver(driver);+ String connection = "{\"connection_string\":\"jdbc:dbx-trigger:test\"}";+ try {+ JsonNode response = request("getObjectSource", "{\"connection\":" + connection + ",\"schema\":\" Owner \",\"name\":\" Trigger \",\"object_type\":\"TRIGGER\",\"identity_mode\":\"exact\"}");+ assertFalse(response.has("error"), response.toString());+ JsonNode metadata = response.path("result").path("trigger").path("oracle_metadata");+ assertTrue(metadata.path("definition").path("complete").asBoolean());+ assertTrue(metadata.path("errors").isNull());+ assertEquals("denied", metadata.path("reads").path("errors").path("state").asText());+ } finally { closeAndDeregister(connection, driver); }+ }++ @Test+ void nullJdbcCompilationErrorTextDoesNotBreakTheSharedSourceContract() throws Exception {+ Driver driver = triggerMetadataDriver(new ArrayList<>(), "Oracle", false, false, null);+ DriverManager.registerDriver(driver);+ String connection = "{\"connection_string\":\"jdbc:dbx-trigger:test\"}";+ try {+ JsonNode response = request("getObjectSource", "{\"connection\":" + connection + ",\"schema\":\" Owner \",\"name\":\" Trigger \",\"object_type\":\"TRIGGER\",\"identity_mode\":\"exact\"}");+ assertFalse(response.has("error"), response.toString());+ JsonNode metadata = response.path("result").path("trigger").path("oracle_metadata");+ assertTrue(metadata.path("definition").path("complete").asBoolean());+ assertTrue(metadata.path("errors").isNull());+ assertEquals("error", metadata.path("reads").path("errors").path("state").asText());+ } finally { closeAndDeregister(connection, driver); }+ }+@Testvoid jdbcProtocolExplicitlyAdvertisesExactMetadataAndRejectsUnconfirmedDialects() throws Exception {JsonNode protocol = request("jdbcSessionProtocol", "{}").path("result");@@ -4591,13 +4806,16 @@ final class DbxJdbcPluginTest {private int index = -1;@Override- public Object invoke(Object proxy, Method method, Object[] args) {+ public Object invoke(Object proxy, Method method, Object[] args) throws SQLException {return switch (method.getName()) {case "next" -> ++index < rows.length;case "getString" -> stringValue(columns, rows[index], args[0]);case "getInt" -> ((Number) columnValue(columns, rows[index], args[0])).intValue();+ case "getLong" -> ((Number) columnValue(columns, rows[index], args[0])).longValue();case "getBoolean" -> booleanValue(columns, rows[index], args[0]);case "getObject" -> columnValue(columns, rows[index], args[0]);+ case "getMetaData" -> resultSetMeta(columns);+ case "getCharacterStream" -> columnValue(columns, rows[index], args[0]) instanceof Clob clob ? clob.getCharacterStream() : null;case "close" -> null;default -> defaultValue(method.getReturnType());};@@ -4634,6 +4852,73 @@ final class DbxJdbcPluginTest {return value == null ? null : String.valueOf(value);}+ private static String triggerExport() {+ return "CREATE TRIGGER \" Owner \".\" Trigger \" BEFORE INSERT ON \" Parent Owner \".\" Parent \" FOR EACH ROW BEGIN /* "+ + "中文😀".repeat(12_000) + " */ NULL; END;\nALTER TRIGGER \" Owner \".\" Trigger \" DISABLE;";+ }++ private static Driver triggerMetadataDriver(List<String> calls, String product, boolean recreate) {+ return triggerMetadataDriver(calls, product, recreate, false);+ }++ private static Driver triggerMetadataDriver(List<String> calls, String product, boolean recreate, boolean denyErrors) {+ return triggerMetadataDriver(calls, product, recreate, denyErrors, "Missing procedure");+ }++ private static Driver triggerMetadataDriver(List<String> calls, String product, boolean recreate, boolean denyErrors, String errorText) {+ return (Driver) Proxy.newProxyInstance(DbxJdbcPluginTest.class.getClassLoader(), new Class<?>[]{Driver.class}, (driver, method, args) -> switch (method.getName()) {+ case "acceptsURL" -> ((String) args[0]).startsWith("jdbc:dbx-trigger:");+ case "connect" -> ((String) args[0]).startsWith("jdbc:dbx-trigger:") ? triggerMetadataConnection(calls, product, recreate, denyErrors, errorText) : null;+ case "getPropertyInfo" -> new DriverPropertyInfo[0];+ case "getParentLogger" -> java.util.logging.Logger.getGlobal();+ default -> defaultValue(method.getReturnType());+ });+ }++ private static Connection triggerMetadataConnection(List<String> calls, String product, boolean recreate, boolean denyErrors, String errorText) {+ return triggerMetadataConnection(calls, product, recreate, denyErrors, errorText, false);+ }++ private static Connection triggerMetadataConnection(List<String> calls, String product, boolean recreate, boolean denyErrors, String errorText, boolean timer) {+ int[] metadataReads = {0};+ DatabaseMetaData metadata = (DatabaseMetaData) Proxy.newProxyInstance(DbxJdbcPluginTest.class.getClassLoader(), new Class<?>[]{DatabaseMetaData.class}, (p, method, args) -> switch (method.getName()) {+ case "getDatabaseProductName" -> product;+ case "getDatabaseProductVersion" -> product.equals("OceanBase") ? "4.2.5.7" : product.equals("DM DBMS") ? "8.1.5" : "19.0.0";+ case "getDatabaseMajorVersion" -> product.equals("DM DBMS") ? 8 : 19;+ case "getURL" -> product.equals("DM DBMS") ? "jdbc:dm://fixture" : "jdbc:dbx-trigger:test";+ default -> defaultValue(method.getReturnType());+ });+ return (Connection) Proxy.newProxyInstance(DbxJdbcPluginTest.class.getClassLoader(), new Class<?>[]{Connection.class}, (p, method, args) -> switch (method.getName()) {+ case "getMetaData" -> metadata;+ case "isValid", "getAutoCommit" -> true;+ case "isClosed" -> false;+ case "prepareStatement" -> {+ String sql = (String) args[0]; calls.add(sql);+ yield Proxy.newProxyInstance(DbxJdbcPluginTest.class.getClassLoader(), new Class<?>[]{PreparedStatement.class}, (statement, m, values) -> {+ if (m.getName().equals("setString") || m.getName().equals("setObject")) { calls.add("bind:" + values[0] + "=" + values[1]); return null; }+ if (m.getName().equals("executeQuery")) {+ if (sql.contains("SYS_CONTEXT")) return rowsResultSet(new String[]{"CURRENT_SCHEMA"}, new Object[][]{{"APP"}});+ if (sql.contains("FROM ALL_TRIGGERS")) {+ metadataReads[0]++;+ return rowsResultSet(new String[]{"OWNER", "TRIGGER_NAME", "TRIGGERING_EVENT", "TRIGGER_TYPE", "STATUS", "TABLE_OWNER", "TABLE_NAME", "BASE_OBJECT_TYPE", "TRIGGER_BODY", "DBX_TRIGGER_OBJECT_MARKER", "OWNER", "OBJECT_NAME", "OBJECT_ID", "LAST_DDL_TIME", "STATUS"},+ new Object[][]{{" Owner ", " Trigger ", timer ? "TIMER" : product.equals("DM DBMS") ? null : "INSERT", product.equals("DM DBMS") ? null : "BEFORE EACH ROW", "DISABLED", " Parent Owner ", timer ? null : " Parent ", timer ? "DATABASE" : "TABLE", "BEGIN NULL; END;", " Trigger ", " Owner ", " Trigger ", recreate && metadataReads[0] > 1 ? "99" : "9007199254740993", "2026-10-21 08:00:00", "INVALID"}});+ }+ if (sql.contains("FROM ALL_OBJECTS o")) return rowsResultSet(new String[]{"OBJECT_NAME", "OBJECT_TYPE", "COMMENTS"}, new Object[][]{{" Trigger ", "TRIGGER", null}});+ if (sql.contains("ALL_SOURCE")) return rowsResultSet(new String[]{"TEXT"}, new Object[0][]);+ if (sql.contains("DBMS_METADATA.GET_DDL")) return rowsResultSet(new String[]{"DDL"}, new Object[][]{{new javax.sql.rowset.serial.SerialClob((timer ? "CREATE TRIGGER \" Owner \".\" Trigger \" AFTER TIMER ON DATABASE FOR EACH 1 DAY FOR EACH 1 MINUTE BEGIN NULL; END;" : triggerExport()).toCharArray())}});+ if (sql.contains("ALL_ERRORS")) {+ if (denyErrors) throw new SQLException("ORA-01031: insufficient privileges", "42501", 1031);+ return rowsResultSet(new String[]{"SEQUENCE", "LINE", "POSITION", "TEXT", "ATTRIBUTE"}, new Object[][]{{1, 4, 7, errorText, "ERROR"}});+ }+ throw new AssertionError("Unexpected trigger query: " + sql);+ }+ return defaultValue(m.getReturnType());+ });+ }+ default -> defaultValue(method.getReturnType());+ });+ }+private static boolean booleanValue(String[] columns, Object[] row, Object key) {Object value = columnValue(columns, row, key);if (value instanceof Boolean bool) return bool;diff --git a/plugins/jdbc/src/test/java/app/dbx/jdbc/NativeJobSessionTest.java b/plugins/jdbc/src/test/java/app/dbx/jdbc/NativeJobSessionTest.javanew file mode 100644index 0000000000..bcc34e6e53--- /dev/null+++ b/plugins/jdbc/src/test/java/app/dbx/jdbc/NativeJobSessionTest.java@@ -0,0 +1,273 @@+package app.dbx.jdbc;++import com.fasterxml.jackson.databind.JsonNode;+import com.fasterxml.jackson.databind.ObjectMapper;+import com.fasterxml.jackson.databind.node.ObjectNode;+import org.junit.jupiter.api.AfterEach;+import org.junit.jupiter.api.Test;++import java.lang.reflect.InvocationTargetException;+import java.lang.reflect.Proxy;+import java.sql.Connection;+import java.sql.Driver;+import java.sql.DriverManager;+import java.sql.DriverPropertyInfo;+import java.sql.SQLException;+import java.sql.Statement;+import java.util.ArrayList;+import java.util.List;+import java.util.Properties;+import java.util.UUID;+import java.util.logging.Logger;++import static org.junit.jupiter.api.Assertions.*;++final class NativeJobSessionTest {+ private static final ObjectMapper MAPPER = new ObjectMapper();+ private static final List<Physical> PHYSICAL = new ArrayList<>();+ private final List<String> sessions = new ArrayList<>();+ private final ObjectNode connection = MAPPER.createObjectNode()+ .put("connection_string", "jdbc:dbx-job:" + UUID.randomUUID())+ .put("jdbc_driver_class", TrackingDriver.class.getName()).put("username", "sa").put("password", "");++ @AfterEach+ void cleanup() throws Exception {+ for (String session : sessions) call("closeJdbcSession", params(session));+ call("close", MAPPER.createObjectNode());+ var logicalDriverKey = DbxJdbcPlugin.class.getDeclaredField("logicalDriverKey");+ logicalDriverKey.setAccessible(true);+ logicalDriverKey.set(null, null);+ PHYSICAL.clear();+ }++ @Test+ void protocolAdvertisesConnectionOwnershipWithoutOpeningADatabase() throws Exception {+ JsonNode protocol = result(call("jdbcSessionProtocol", params(null)));+ assertTrue(protocol.path("capabilities").toString().contains("native_job_session_v1"));+ assertTrue(PHYSICAL.isEmpty());+ }++ @Test+ void defaultAndLogicalRoutesKeepOnePhysicalConnectionAcrossInternalCommitsAndExactSql() throws Exception {+ for (String session : new String[]{null, "owned"}) {+ openLogical(session);+ ObjectNode open = params(session).put("operationId", "operation");+ JsonNode opened = result(call("openNativeJobSession", open));+ assertEquals("opened", opened.path("phase").asText());+ Physical physical = PHYSICAL.getLast();+ assertFalse(physical.connection.getAutoCommit());+ assertEquals(opened, result(call("open_native_job_session", open)));+ int count = PHYSICAL.size();+ String table = session == null ? "default_job_session_probe" : "logical_job_session_probe";+ query(session, opened, "CREATE TABLE " + table + " (id INT)");+ query(session, opened, "INSERT INTO " + table + " VALUES (1)");+ query(session, opened, "COMMIT");+ String exact = " SELECT ';' AS marker; ";+ assertEquals(";", query(session, opened, exact).path("rows").path(0).path(0).asText());+ assertEquals(exact, physical.sql.getLast(), "native SQL must not be trimmed, rewritten or retried");+ assertEquals(1, query(session, opened, "SELECT COUNT(*) FROM " + table).path("rows").path(0).path(0).asInt());+ assertFalse(physical.connection.getAutoCommit());+ assertEquals(count, PHYSICAL.size());+ JsonNode closed = close(session, opened);+ assertEquals("closed", closed.path("phase").asText());+ assertEquals(closed, close(session, opened));+ assertEquals(1, physical.closes);+ assertEquals(0, physical.commits);+ assertEquals(0, physical.rollbacks);+ assertTrue(physical.connection.isClosed());+ }+ }++ @Test+ void reservationRejectsOrdinaryQueriesForeignTokensConfigurationChangesAndOtherProtocols() throws Exception {+ openLogical("owned");+ JsonNode opened = result(call("openNativeJobSession", params("owned").put("operationId", "operation")));+ Physical physical = PHYSICAL.getLast();+ for (String method : List.of("connect", "testConnection", "beginManualTransaction", "executeQueryPage", "prepareLegacyJob")) {+ JsonNode rejected = call(method, params("owned"));+ assertTrue(rejected.has("error") || rejected.path("result").path("phase").asText().equals("unknown"), method);+ }+ assertTrue(call("executeQuery", params("owned").put("sql", "SELECT 1")).has("error"));+ ObjectNode changed = authorized("owned", opened).put("sql", "SELECT 1");+ ((ObjectNode) changed.path("connection")).put("username", "other");+ assertTrue(call("executeQuery", changed).has("error"));+ ObjectNode token = authorized("owned", opened).put("sql", "SELECT 1").put("nativeJobSessionToken", "foreign");+ assertTrue(call("executeQuery", token).has("error"));+ ObjectNode driver = authorized("owned", opened).put("sql", "SELECT 1");+ ((ObjectNode) driver.path("connection")).put("jdbc_driver_class", "foreign.Driver");+ assertTrue(call("executeQuery", driver).has("error"));+ assertEquals(1, query("owned", opened, "SELECT 1").path("rows").path(0).path(0).asInt());+ assertEquals(1, PHYSICAL.size());+ assertEquals(List.of("SELECT 1"), physical.sql);+ }++ @Test+ void aClosedConnectionAndItsOldTokenCannotReopenOnEitherRoute() throws Exception {+ for (String session : new String[]{null, "lost"}) {+ openLogical(session);+ JsonNode opened = result(call("openNativeJobSession", params(session).put("operationId", "operation")));+ PHYSICAL.getLast().connection.close();+ assertTrue(call("executeQuery", authorized(session, opened).put("sql", "SELECT 1")).has("error"));+ int count = PHYSICAL.size();+ String replacement = session == null ? "replacement-default" : "replacement-logical";+ openLogical(replacement);+ assertTrue(call("executeQuery", authorized(replacement, opened).put("sql", "SELECT 1")).has("error"));+ assertEquals(count, PHYSICAL.size());+ if (session == null) call("close", MAPPER.createObjectNode());+ }+ }++ @Test+ void unknownPhysicalCloseIsCachedAndReportedByDefaultAndLogicalCleanup() throws Exception {+ for (String session : new String[]{null, "close-unknown"}) {+ openLogical(session);+ JsonNode opened = result(call("openNativeJobSession", params(session).put("operationId", "operation")));+ Physical physical = PHYSICAL.getLast();+ physical.failClose = true;+ JsonNode unknown = close(session, opened);+ assertEquals("unknown", unknown.path("phase").asText());+ assertEquals(unknown, close(session, opened));+ assertEquals(1, physical.closes);+ JsonNode cleanup = call(session == null ? "close" : "closeJdbcSession",+ session == null ? MAPPER.createObjectNode() : params(session));+ assertTrue(cleanup.has("error"));+ assertEquals(1, physical.closes);+ }+ }++ @Test+ void globalCloseDoesNotForgetUnknownDisposalInAnOwnedLogicalMember() throws Exception {+ openLogical("unknown-member");+ result(call("openNativeJobSession", params("unknown-member").put("operationId", "operation")));+ PHYSICAL.getLast().failClose = true;+ assertTrue(call("close", MAPPER.createObjectNode()).has("error"));+ assertEquals(1, PHYSICAL.getLast().closes);+ }++ @Test+ void lostOpenResponseCanDisposeOnlyItsKnownOperationWithoutTheToken() throws Exception {+ openLogical("lost-open");+ result(call("openNativeJobSession", params("lost-open").put("operationId", "operation")));+ JsonNode wrong = call("closeNativeJobSession", params("lost-open").put("operationId", "other"));+ assertNotEquals("closed", wrong.path("result").path("phase").asText());+ JsonNode closed = result(call("close_native_job_session", params("lost-open").put("operationId", "operation")));+ assertEquals("closed", closed.path("phase").asText());+ assertEquals(1, PHYSICAL.getLast().closes);+ }++ @Test+ void anEditorTransactionSurvivesRejectedOwnershipAndRemainsUsable() throws Exception {+ openLogical("editor");+ result(call("beginManualTransaction", params("editor")));+ Physical editor = PHYSICAL.getLast();+ JsonNode denied = call("openNativeJobSession", params("editor").put("operationId", "operation"));+ assertNotEquals("opened", denied.path("result").path("phase").asText());+ assertFalse(editor.connection.isClosed());+ assertFalse(editor.connection.getAutoCommit());+ assertEquals(0, editor.closes);+ result(call("rollbackManualTransaction", params("editor")));+ assertEquals("opened", result(call("openNativeJobSession", params("editor").put("operationId", "operation"))).path("phase").asText());+ }++ @Test+ void anOpenCursorSurvivesRejectionThenReleasesItsConnectionForNativeOwnership() throws Exception {+ openLogical("cursor");+ JsonNode page = result(call("executeQueryPage", params("cursor")+ .put("sql", "SELECT X FROM SYSTEM_RANGE(1, 3)").put("pageSize", 1)));+ String cursor = page.path("session_id").asText();+ assertFalse(cursor.isEmpty());+ Physical physical = PHYSICAL.getLast();+ JsonNode denied = result(call("openNativeJobSession", params("cursor").put("operationId", "operation")));+ assertEquals("native_job_session_busy", denied.path("reason").asText());+ assertEquals(0, physical.closes);+ result(call("fetchQueryPage", params("cursor").put("sessionId", cursor).put("pageSize", 1)));+ result(call("closeQuerySession", params("cursor").put("sessionId", cursor)));+ assertEquals("opened", result(call("openNativeJobSession", params("cursor").put("operationId", "operation"))).path("phase").asText());+ assertEquals(1, PHYSICAL.size());+ }++ private void openLogical(String session) throws Exception {+ if (session == null) return;+ sessions.add(session);+ result(call("openJdbcSession", params(session)));+ }++ private ObjectNode params(String session) {+ ObjectNode params = MAPPER.createObjectNode();+ params.set("connection", connection.deepCopy());+ if (session != null) params.put("jdbcSessionId", session);+ return params;+ }++ private ObjectNode authorized(String session, JsonNode opened) {+ return params(session).put("nativeJobOperationId", opened.path("operationId").asText())+ .put("nativeJobSessionToken", opened.path("sessionToken").asText());+ }++ private JsonNode query(String session, JsonNode opened, String sql) throws Exception {+ return result(call("executeQuery", authorized(session, opened).put("sql", sql)));+ }++ private JsonNode close(String session, JsonNode opened) throws Exception {+ return result(call("closeNativeJobSession", params(session).put("operationId", opened.path("operationId").asText())+ .put("sessionToken", opened.path("sessionToken").asText())));+ }++ private static JsonNode call(String method, ObjectNode params) throws Exception {+ ObjectNode request = MAPPER.createObjectNode().put("id", 1).put("method", method);+ request.set("params", params);+ var entry = DbxJdbcPlugin.class.getDeclaredMethod("handleLine", String.class);+ entry.setAccessible(true);+ return (JsonNode) entry.invoke(null, request.toString());+ }++ private static JsonNode result(JsonNode response) {+ assertFalse(response.has("error"), response.toString());+ return response.path("result");+ }++ private static final class Physical {+ Connection connection;+ boolean failClose;+ int commits;+ int rollbacks;+ int closes;+ final List<String> sql = new ArrayList<>();+ }++ public static final class TrackingDriver implements Driver {+ @Override public boolean acceptsURL(String url) { return url != null && url.startsWith("jdbc:dbx-job:"); }+ @Override public Connection connect(String url, Properties properties) throws SQLException {+ if (!acceptsURL(url)) return null;+ Connection real = DriverManager.getConnection("jdbc:h2:mem:" + url.substring("jdbc:dbx-job:".length())+ + ";DB_CLOSE_DELAY=-1", properties);+ Physical physical = new Physical();+ physical.connection = (Connection) Proxy.newProxyInstance(getClass().getClassLoader(), new Class<?>[]{Connection.class},+ (proxy, method, arguments) -> {+ if ("commit".equals(method.getName())) physical.commits++;+ if ("rollback".equals(method.getName())) physical.rollbacks++;+ if ("close".equals(method.getName())) physical.closes++;+ try {+ Object value = method.invoke(real, arguments);+ if ("close".equals(method.getName()) && physical.failClose) throw new SQLException("close acknowledgement lost", "08006");+ if ("createStatement".equals(method.getName())) {+ Statement statement = (Statement) value;+ return Proxy.newProxyInstance(getClass().getClassLoader(), new Class<?>[]{Statement.class}, (p, m, args) -> {+ if (m.getName().startsWith("execute") && args != null && args.length > 0 && args[0] instanceof String sql) physical.sql.add(sql);+ try { return m.invoke(statement, args); }+ catch (InvocationTargetException error) { throw error.getCause(); }+ });+ }+ return value;+ } catch (InvocationTargetException error) { throw error.getCause(); }+ });+ PHYSICAL.add(physical);+ return physical.connection;+ }+ @Override public DriverPropertyInfo[] getPropertyInfo(String url, Properties properties) { return new DriverPropertyInfo[0]; }+ @Override public int getMajorVersion() { return 1; }+ @Override public int getMinorVersion() { return 0; }+ @Override public boolean jdbcCompliant() { return false; }+ @Override public Logger getParentLogger() { return Logger.getGlobal(); }+ }+}diff --git a/plugins/jdbc/src/test/java/app/dbx/jdbc/NativeLegacyJobTest.java b/plugins/jdbc/src/test/java/app/dbx/jdbc/NativeLegacyJobTest.javanew file mode 100644index 0000000000..e2f23afd06--- /dev/null+++ b/plugins/jdbc/src/test/java/app/dbx/jdbc/NativeLegacyJobTest.java@@ -0,0 +1,632 @@+package app.dbx.jdbc;++import com.fasterxml.jackson.databind.JsonNode;+import com.fasterxml.jackson.databind.ObjectMapper;+import com.fasterxml.jackson.databind.node.ObjectNode;+import org.junit.jupiter.api.AfterEach;+import org.junit.jupiter.api.Test;++import java.lang.reflect.Method;+import java.lang.reflect.Proxy;+import java.sql.*;+import java.util.ArrayList;+import java.util.HashMap;+import java.util.List;+import java.util.Map;+import java.util.Properties;+import java.util.logging.Logger;++import static org.junit.jupiter.api.Assertions.*;++final class NativeLegacyJobTest {+ private static final ObjectMapper MAPPER = new ObjectMapper();+ private static final List<Physical> PHYSICAL = new ArrayList<>();+ private final List<String> sessions = new ArrayList<>();++ @AfterEach+ void cleanup() throws Exception {+ for (String session : sessions) call("closeJdbcSession", params(session));+ call("close", MAPPER.createObjectNode());+ var driverKey = DbxJdbcPlugin.class.getDeclaredField("logicalDriverKey");+ driverKey.setAccessible(true);+ driverKey.set(null, null);+ FakeDriver.product = "Oracle";+ FakeDriver.nextFailure = "";+ FakeDriver.failOpen = false;+ PHYSICAL.clear();+ }++ @Test+ void advertisesTheNarrowProtocolWithoutOpeningAConnection() throws Exception {+ JsonNode protocol = result(call("jdbcSessionProtocol", params(null)));+ assertEquals(2, protocol.path("version").asInt());+ assertEquals("native_job_legacy_v1", protocol.path("capabilities").path(0).asText());+ assertTrue(PHYSICAL.isEmpty());+ }++ @Test+ void nativeCatalogDiagnosticsUseTheExistingQueryCorridorWithoutChangingOrdinaryErrors() throws Exception {+ open("catalog");+ FakeDriver.nextFailure = "catalog";+ ObjectNode query = params("catalog").put("sql", "SELECT * FROM SYS.DBA_JOBS").put("nativeDiagnostics", true);+ JsonNode response = result(call("executeQuery", query));+ assertTrue(response.path("execution_error").asBoolean());+ assertEquals("sql", response.path("error").path("diagnostics").path("category").asText());+ assertEquals(942, response.path("error").path("diagnostics").path("vendorCode").asInt());+ assertFalse(response.toString().contains("private"));+ query.remove("nativeDiagnostics");+ assertTrue(call("executeQuery", query).path("error").path("message").asText().contains("private"));+ }++ @Test+ void connectionFailureIsNotDisguisedAsAHiddenCatalogEvenWithTheSameVendorCode() throws Exception {+ open("connection");+ FakeDriver.nextFailure = "connection";+ JsonNode response = result(call("executeQuery", params("connection")+ .put("sql", "SELECT * FROM SYS.DBA_JOBS").put("nativeDiagnostics", true)));+ assertEquals("connection", response.path("error").path("diagnostics").path("category").asText());+ assertFalse(response.toString().contains("private"));+ }++ @Test+ void preparesOnOneConnectionWithoutCommittingOrInterpolatingTheBody() throws Exception {+ open("native");+ JsonNode prepared = result(call("prepareLegacyJob", prepare("native", "op")));+ assertEquals("prepared", prepared.path("phase").asText());+ assertEquals("9007199254740993", prepared.path("jobId").asText());+ assertEquals(1, PHYSICAL.size());+ Physical physical = PHYSICAL.getFirst();+ assertFalse(physical.autoCommit);+ assertFalse(physical.closed);+ assertEquals(List.of("schema", "auto:false", "submit", "broken", "read"), physical.events);+ assertEquals(0, physical.commits);+ assertTrue(physical.sql.stream().noneMatch(sql -> sql.contains("private_")));+ assertEquals("private_body('private_argument');", physical.what);+ assertEquals(Types.VARCHAR, physical.outType);+ assertEquals(List.of(17, 17, 17, 17), physical.timeouts);+ }++ @Test+ void finalBrokenStateAndExplicitNextDatePrecedeTheFirstCommit() throws Exception {+ for (boolean enabled : List.of(false, true)) {+ String session = "enabled-" + enabled;+ open(session);+ JsonNode prepared = result(call("prepare_legacy_job", prepare(session, session).put("enabled", enabled)));+ assertEquals("prepared", prepared.path("phase").asText());+ Physical physical = PHYSICAL.getLast();+ assertEquals(enabled ? "N" : "Y", physical.broken);+ assertEquals("2026-10-21 10:20:30", physical.brokenNextDate);+ assertEquals("committed", result(call("commitLegacyJob", finish(session, session, physical.id))).path("phase").asText());+ assertTrue(physical.events.indexOf("broken") < physical.events.indexOf("commit"));+ assertEquals(1, physical.commits);+ assertEquals(0, physical.rollbacks);+ assertTrue(physical.closed);+ }+ }++ @Test+ void duplicatePreparationCannotReplaceTheImmutableDefinition() throws Exception {+ open("native");+ ObjectNode request = prepare("native", "op");+ JsonNode prepared = result(call("prepareLegacyJob", request));+ assertEquals(prepared, result(call("prepareLegacyJob", request)));+ assertEquals("native_job_operation_mismatch", result(call("prepareLegacyJob", request.deepCopy().put("what", "other;"))).path("reason").asText());+ assertEquals(1, PHYSICAL.getFirst().events.stream().filter("submit"::equals).count());+ assertEquals(prepared, result(call("legacyJobStatus", finish("native", "op", null))));+ assertFalse(result(call("legacyJobStatus", finish("native", "different", null))).has("jobId"));+ }++ @Test+ void commitRequiresTheRecordedIdAndNeverReplaysAfterItCompletes() throws Exception {+ open("native");+ result(call("prepareLegacyJob", prepare("native", "op")));+ Physical physical = PHYSICAL.getFirst();+ assertEquals("native_job_identity_mismatch", result(call("commitLegacyJob", finish("native", "op", null))).path("reason").asText());+ assertEquals("native_job_identity_mismatch", result(call("commitLegacyJob", finish("native", "op", "2"))).path("reason").asText());+ assertEquals(0, physical.commits);+ JsonNode committed = result(call("commit_legacy_job", finish("native", "op", physical.id)));+ assertEquals("committed", committed.path("phase").asText());+ assertEquals(committed, result(call("commitLegacyJob", finish("native", "op", physical.id))));+ assertEquals(committed, result(call("rollbackLegacyJob", finish("native", "op", physical.id))));+ assertEquals(1, physical.commits);+ assertEquals(0, physical.rollbacks);+ assertEquals(1, PHYSICAL.size());+ }++ @Test+ void lostPreparationResponseCanBeRolledBackWithoutKnowingTheOutId() throws Exception {+ open("native");+ result(call("prepareLegacyJob", prepare("native", "op")));+ assertEquals("native_job_identity_mismatch", result(call("rollbackLegacyJob", finish("native", "op", "2"))).path("reason").asText());+ JsonNode rolledBack = result(call("rollback_legacy_job", finish("native", "op", null)));+ assertEquals("rolled_back", rolledBack.path("phase").asText());+ assertEquals(rolledBack, result(call("rollbackLegacyJob", finish("native", "op", null))));+ assertEquals(1, PHYSICAL.getFirst().rollbacks);+ assertEquals(0, PHYSICAL.getFirst().commits);+ assertTrue(PHYSICAL.getFirst().closed);+ }++ @Test+ void lostCommitResponseStaysUnknownAndCannotSubmitCommitOrRollbackAgain() throws Exception {+ open("native");+ ObjectNode prepare = prepare("native", "op");+ result(call("prepareLegacyJob", prepare));+ Physical physical = PHYSICAL.getFirst();+ physical.fail = "commit";+ JsonNode unknown = result(call("commitLegacyJob", finish("native", "op", physical.id)));+ assertEquals("unknown", unknown.path("phase").asText());+ assertEquals("native_job_commit_unknown", unknown.path("reason").asText());+ assertEquals(unknown, result(call("prepareLegacyJob", prepare)));+ assertEquals(unknown, result(call("commitLegacyJob", finish("native", "op", physical.id))));+ assertEquals(unknown, result(call("rollbackLegacyJob", finish("native", "op", null))));+ result(call("closeJdbcSession", params("native")));+ assertEquals(1, physical.commits);+ assertEquals(0, physical.rollbacks);+ assertEquals(1, physical.events.stream().filter("submit"::equals).count());+ assertFalse(unknown.toString().contains("private"));+ }++ @Test+ void failedSubmitConfigurationAndReadbackRollBackAndKeepOnlyTypedDiagnostics() throws Exception {+ for (String failure : List.of("submit", "broken", "read", "mismatch", "out")) {+ String session = "fail-" + failure;+ open(session);+ FakeDriver.nextFailure = failure;+ JsonNode response = result(call("prepareLegacyJob", prepare(session, session)));+ Physical physical = PHYSICAL.getLast();+ assertEquals("rolled_back", response.path("phase").asText(), failure);+ assertEquals(1, physical.rollbacks);+ assertEquals(0, physical.commits);+ assertTrue(physical.closed);+ assertFalse(response.toString().contains("private"));+ if (List.of("submit", "broken", "read").contains(failure)) {+ assertEquals(27486, response.path("vendorCode").asInt());+ assertEquals("42501", response.path("sqlState").asText());+ }+ }+ }++ @Test+ void lostRollbackResponseIsUnknownAndCleanupDoesNotReplayIt() throws Exception {+ open("native");+ result(call("prepareLegacyJob", prepare("native", "op")));+ Physical physical = PHYSICAL.getFirst();+ physical.fail = "rollback";+ JsonNode response = result(call("rollbackLegacyJob", finish("native", "op", null)));+ assertEquals("unknown", response.path("phase").asText());+ assertEquals("native_job_rollback_unknown", response.path("reason").asText());+ result(call("rollbackLegacyJob", finish("native", "op", null)));+ call("closeJdbcSession", params("native"));+ assertEquals(1, physical.rollbacks);+ assertEquals(0, physical.commits);+ assertTrue(physical.closed);+ }++ @Test+ void closingAnUncommittedNativeSessionRollsBackInsteadOfEnablingOrCommitting() throws Exception {+ open("native");+ result(call("prepareLegacyJob", prepare("native", "op")));+ result(call("closeJdbcSession", params("native")));+ Physical physical = PHYSICAL.getFirst();+ assertEquals(1, physical.rollbacks);+ assertEquals(0, physical.commits);+ assertTrue(physical.closed);+ assertFalse(physical.events.contains("auto:true"));+ }++ @Test+ void closingReportsAnUnconfirmedRollbackWithoutNativeErrorText() throws Exception {+ open("native");+ result(call("prepareLegacyJob", prepare("native", "op")));+ Physical physical = PHYSICAL.getFirst();+ physical.fail = "rollback";+ JsonNode response = call("closeJdbcSession", params("native"));+ assertEquals("native_job_session_dispose_unknown", response.path("error").path("message").asText());+ assertEquals(1, physical.rollbacks);+ assertEquals(0, physical.commits);+ assertTrue(physical.closed);+ assertFalse(response.toString().contains("private"));+ }++ @Test+ void failedPhysicalDisposalDoesNotHideItsGapOrRepeatTheCommit() throws Exception {+ open("native");+ result(call("prepareLegacyJob", prepare("native", "op")));+ Physical physical = PHYSICAL.getFirst();+ physical.fail = "close";+ JsonNode committed = result(call("commitLegacyJob", finish("native", "op", physical.id)));+ assertEquals("committed", committed.path("phase").asText());+ assertEquals("native_job_session_dispose_unknown", call("closeJdbcSession", params("native")).path("error").path("message").asText());+ assertEquals(1, physical.commits);+ assertEquals(0, physical.rollbacks);+ assertEquals(1, physical.events.stream().filter("close"::equals).count());+ }++ @Test+ void globalCloseRetainsUnknownDisposalFromALogicalLegacyMember() throws Exception {+ open("owned-member");+ result(call("prepareLegacyJob", prepare("owned-member", "operation")));+ PHYSICAL.getFirst().fail = "rollback";+ JsonNode closed = call("close", MAPPER.createObjectNode());+ assertEquals("native_job_session_dispose_unknown", closed.path("error").path("message").asText());+ assertEquals(1, PHYSICAL.getFirst().rollbacks);+ assertEquals(0, PHYSICAL.getFirst().commits);+ }++ @Test+ void aNativePhysicalLeaseCannotTakeOverThePreparedLegacyTransaction() throws Exception {+ open("legacy-owned");+ result(call("prepareLegacyJob", prepare("legacy-owned", "legacy")));+ Physical physical = PHYSICAL.getFirst();+ List<String> before = List.copyOf(physical.events);+ JsonNode denied = result(call("openNativeJobSession", params("legacy-owned").put("operationId", "different")));+ assertEquals("not_started", denied.path("phase").asText());+ assertEquals("native_job_session_busy", denied.path("reason").asText());+ assertEquals(before, physical.events);+ assertEquals(1, PHYSICAL.size());+ }++ @Test+ void editorTransactionsAreNeitherBorrowedNorCommittedByNativeSessions() throws Exception {+ open("editor");+ result(call("beginManualTransaction", params("editor")));+ Physical editor = PHYSICAL.getFirst();+ assertEquals("not_started", result(call("prepareLegacyJob", prepare("editor", "op"))).path("phase").asText());+ open("native");+ JsonNode prepared = result(call("prepareLegacyJob", prepare("native", "other")));+ result(call("commitLegacyJob", finish("native", "other", prepared.path("jobId").asText())));+ assertEquals(2, PHYSICAL.size());+ assertFalse(editor.autoCommit);+ assertFalse(editor.closed);+ assertEquals(0, editor.commits);+ assertEquals(0, editor.rollbacks);+ result(call("rollbackManualTransaction", params("editor")));+ assertEquals(1, editor.rollbacks);+ }++ @Test+ void ordinaryRequestsCannotReconnectOrImplicitlyCommitTheReservedSession() throws Exception {+ open("native");+ result(call("prepareLegacyJob", prepare("native", "op")));+ for (String method : List.of("connect", "connectionInfo", "executeQuery", "beginManualTransaction", "commitManualTransaction")) {+ JsonNode denied = call(method, params("native").put("sql", "COMMIT"));+ assertEquals("native_job_session_reserved", denied.path("error").path("message").asText(), method);+ }+ assertEquals(1, PHYSICAL.size());+ assertFalse(PHYSICAL.getFirst().autoCommit);+ assertEquals(0, PHYSICAL.getFirst().commits);+ }++ @Test+ void endpointChangesDoNotRedirectAnAlreadyPreparedOperation() throws Exception {+ open("native");+ result(call("prepareLegacyJob", prepare("native", "op")));+ ObjectNode changed = finish("native", "op", PHYSICAL.getFirst().id);+ ((ObjectNode) changed.path("connection")).put("connection_string", "jdbc:oracle:thin:@other");+ assertEquals("native_job_connection_changed", result(call("commitLegacyJob", changed)).path("reason").asText());+ assertEquals("prepared", result(call("legacy_job_status", finish("native", "op", null))).path("phase").asText());+ assertEquals(0, PHYSICAL.getFirst().commits);+ assertEquals(1, PHYSICAL.size());+ }++ @Test+ void oracleTransactionSemanticsAreNotAssumedFromAnOracleShapedUrl() throws Exception {+ for (String product : List.of("OceanBase", "DM DBMS", "PostgreSQL")) {+ String session = "product-" + product;+ open(session);+ FakeDriver.product = product;+ JsonNode response = result(call("prepareLegacyJob", prepare(session, session)));+ assertEquals("not_started", response.path("phase").asText());+ assertEquals("native_job_dialect_unverified", response.path("reason").asText());+ assertEquals(0, PHYSICAL.getLast().commits);+ assertEquals(0, PHYSICAL.getLast().rollbacks);+ assertTrue(PHYSICAL.getLast().closed);+ }+ }++ @Test+ void validDefinitionIsRequiredBeforeOpeningTheDriver() throws Exception {+ open("native");+ for (ObjectNode invalid : List.of(+ prepare("native", "op").put("nextDate", "2026-02-30 10:20:30"),+ prepare("native", "op").put("what", " "),+ prepare("native", "op").put("instance", -1),+ prepare("native", "op").put("timeoutSecs", -1))) {+ assertEquals("not_started", result(call("prepareLegacyJob", invalid)).path("phase").asText());+ }+ assertTrue(PHYSICAL.isEmpty());+ }++ @Test+ void dedicatedDefaultProcessUsesTheSameOutProtocolWithoutBorrowingAnEditorTransaction() throws Exception {+ result(call("beginManualTransaction", params(null)));+ assertEquals("native_job_session_busy", result(call("prepareLegacyJob", prepare(null, "blocked"))).path("reason").asText());+ result(call("rollbackManualTransaction", params(null)));+ JsonNode prepared = result(call("prepareLegacyJob", prepare(null, "owned")));+ assertEquals("prepared", prepared.path("phase").asText());+ assertEquals("native_job_session_reserved", call("connect", params(null)).path("error").path("message").asText());+ JsonNode committed = result(call("commitLegacyJob", finish(null, "owned", prepared.path("jobId").asText())));+ assertEquals("committed", committed.path("phase").asText());+ assertEquals(1, PHYSICAL.getFirst().commits);+ assertEquals(1, PHYSICAL.getFirst().rollbacks);+ }++ @Test+ void defaultProcessCloseReportsNativeDisposalFailureBeforeItExits() throws Exception {+ result(call("prepareLegacyJob", prepare(null, "owned")));+ PHYSICAL.getFirst().fail = "rollback";+ JsonNode close = call("close", MAPPER.createObjectNode());+ assertEquals("native_job_session_dispose_unknown", close.path("error").path("message").asText());+ assertTrue(close.path("_dbx_close").asBoolean());+ assertEquals(0, PHYSICAL.getFirst().commits);+ }++ @Test+ void failedOpenIsNotRetriedByDuplicatePreparation() throws Exception {+ open("native");+ FakeDriver.failOpen = true;+ ObjectNode request = prepare("native", "op");+ JsonNode failed = result(call("prepareLegacyJob", request));+ assertEquals("not_started", failed.path("phase").asText());+ assertEquals(12541, failed.path("vendorCode").asInt());+ FakeDriver.failOpen = false;+ assertEquals(failed, result(call("prepareLegacyJob", request)));+ assertTrue(PHYSICAL.isEmpty());+ }++ @Test+ void oceanbaseUsesItsBoundNullableZoneAndNeverCoercesTheNativeInstanceColumn() throws Exception {+ assertTrue(result(call("jdbcSessionProtocol", params(null))).path("capabilities").toString().contains("native_job_legacy_ob_v1"));+ FakeDriver.product = "OceanBase";+ for (String zone : new String[]{null, "zone1"}) {+ String session = zone == null ? "ob-default" : "ob-zone";+ open(session);+ ObjectNode request = prepare(session, session).put("dialect", "oceanbase-oracle");+ if (zone == null) request.putNull("zone"); else request.put("zone", zone);+ JsonNode prepared = result(call("prepareLegacyJob", request));+ assertEquals("prepared", prepared.path("phase").asText());+ Physical physical = PHYSICAL.getLast();+ assertEquals(zone, physical.instance);+ assertTrue(physical.sql.stream().anyMatch(sql -> sql.contains("zone => ?")));+ assertTrue(physical.sql.stream().noneMatch(sql -> sql.contains("TO_CHAR(INSTANCE)") || sql.contains("instance => ?")));+ assertTrue(physical.events.indexOf("broken") < physical.events.indexOf("next-date"));+ assertTrue(physical.events.indexOf("next-date") < physical.events.indexOf("read"));+ assertFalse(prepared.has("disposalConfirmed"));+ assertEquals(0, physical.commits);+ ObjectNode changed = request.deepCopy().put("zone", "other-zone");+ assertEquals("native_job_operation_mismatch", result(call("prepareLegacyJob", changed)).path("reason").asText());+ JsonNode committed = result(call("commitLegacyJob", finish(session, session, physical.id)));+ assertTrue(committed.path("disposalConfirmed").asBoolean());+ assertEquals(1, physical.commits);+ assertEquals(0, physical.rollbacks);+ }+ }++ @Test+ void oceanbaseOutGetterFailureIsDistinctFromSubmitAndRollsBackBeforeFirstCommit() throws Exception {+ FakeDriver.product = "OceanBase";+ open("ob-out");+ FakeDriver.nextFailure = "out-read";+ JsonNode failed = result(call("prepareLegacyJob", prepare("ob-out", "ob-out").put("dialect", "oceanbase-oracle")));+ assertEquals("rolled_back", failed.path("phase").asText());+ assertEquals("native_job_out_read_failed", failed.path("reason").asText());+ assertTrue(failed.path("disposalConfirmed").asBoolean());+ assertEquals(1, PHYSICAL.getLast().rollbacks);+ assertEquals(0, PHYSICAL.getLast().commits);+ assertFalse(failed.toString().contains("private"));+ }++ @Test+ void oceanbaseCloseFailureRemainsVisibleInTerminalStatusWithoutRepeatingNativeWork() throws Exception {+ FakeDriver.product = "OceanBase";+ open("ob-close");+ result(call("prepareLegacyJob", prepare("ob-close", "op").put("dialect", "oceanbase-oracle")));+ Physical physical = PHYSICAL.getLast();+ physical.fail = "close";+ JsonNode committed = result(call("commitLegacyJob", finish("ob-close", "op", physical.id)));+ assertEquals("committed", committed.path("phase").asText());+ assertTrue(committed.has("disposalConfirmed"));+ assertFalse(committed.path("disposalConfirmed").asBoolean());+ assertEquals(committed, result(call("legacyJobStatus", finish("ob-close", "op", null))));+ result(call("rollbackLegacyJob", finish("ob-close", "op", null)));+ assertEquals(1, physical.commits);+ assertEquals(0, physical.rollbacks);+ assertEquals(1, physical.events.stream().filter("close"::equals).count());+ }++ @Test+ void explicitDialectCannotPromoteAnotherProductOrUseAnOracleInstanceForAnObZone() throws Exception {+ for (String dialect : List.of("dameng", "oceanbase-oracle")) {+ String session = "invalid-" + dialect;+ open(session);+ ObjectNode request = prepare(session, session).put("dialect", dialect);+ JsonNode failed = result(call("prepareLegacyJob", request));+ assertEquals("not_started", failed.path("phase").asText());+ assertTrue(PHYSICAL.stream().allMatch(physical -> physical.commits == 0));+ }+ open("ob-instance");+ int opens = PHYSICAL.size();+ JsonNode failed = result(call("prepareLegacyJob", prepare("ob-instance", "invalid").put("dialect", "oceanbase-oracle").put("instance", 1)));+ assertEquals("not_started", failed.path("phase").asText());+ assertEquals(opens, PHYSICAL.size());+ }++ private void open(String session) throws Exception {+ sessions.add(session);+ result(call("openJdbcSession", params(session)));+ }++ private static ObjectNode params(String session) {+ ObjectNode config = MAPPER.createObjectNode().put("connection_string", "jdbc:oracle:thin:@job-test")+ .put("jdbc_driver_class", FakeDriver.class.getName());+ ObjectNode params = MAPPER.createObjectNode();+ params.set("connection", config);+ if (session != null) params.put("jdbcSessionId", session);+ return params;+ }++ private static ObjectNode prepare(String session, String operation) {+ return params(session).put("operationId", operation).put("what", "private_body('private_argument');")+ .put("nextDate", "2026-10-21 10:20:30").put("interval", "SYSDATE + 1")+ .put("enabled", false).put("instance", 0).put("schema", "Ow\"ner").put("timeoutSecs", 17);+ }++ private static ObjectNode finish(String session, String operation, String id) {+ ObjectNode params = params(session).put("operationId", operation);+ if (id != null) params.put("jobId", id);+ return params;+ }++ private static JsonNode result(JsonNode response) {+ assertFalse(response.has("error"), response.toString());+ return response.path("result");+ }++ private static JsonNode call(String name, ObjectNode params) throws Exception {+ Method handler = DbxJdbcPlugin.class.getDeclaredMethod("handleLine", String.class);+ handler.setAccessible(true);+ ObjectNode request = MAPPER.createObjectNode().put("id", 1).put("method", name);+ request.set("params", params);+ return (JsonNode) handler.invoke(null, request.toString());+ }++ public static final class FakeDriver implements Driver {+ static String product = "Oracle";+ static String nextFailure = "";+ static boolean failOpen;++ public Connection connect(String url, Properties properties) throws SQLException {+ if (!acceptsURL(url)) return null;+ if (failOpen) throw new SQLException("private connection details", "08001", 12541);+ Physical physical = new Physical();+ physical.fail = nextFailure;+ nextFailure = "";+ physical.product = product;+ PHYSICAL.add(physical);+ return physical.connection();+ }+ public boolean acceptsURL(String url) { return url.startsWith("jdbc:oracle:thin:@"); }+ public DriverPropertyInfo[] getPropertyInfo(String url, Properties properties) { return new DriverPropertyInfo[0]; }+ public int getMajorVersion() { return 1; }+ public int getMinorVersion() { return 0; }+ public boolean jdbcCompliant() { return true; }+ public Logger getParentLogger() { return Logger.getGlobal(); }+ }++ private static final class Physical {+ boolean autoCommit = true;+ boolean closed;+ int commits;+ int rollbacks;+ int outType;+ String product;+ String fail = "";+ String id = "9007199254740993";+ String what;+ String nextDate;+ String interval;+ String instance;+ String broken;+ String brokenNextDate;+ final List<String> events = new ArrayList<>();+ final List<String> sql = new ArrayList<>();+ final List<Integer> timeouts = new ArrayList<>();++ Connection connection() {+ return proxy(Connection.class, (ignored, method, args) -> switch (method.getName()) {+ case "getAutoCommit" -> autoCommit;+ case "setAutoCommit" -> { autoCommit = (boolean) args[0]; events.add("auto:" + autoCommit); yield null; }+ case "isClosed" -> closed;+ case "close" -> { stage("close"); closed = true; yield null; }+ case "commit" -> { commits++; stage("commit"); yield null; }+ case "rollback" -> { rollbacks++; stage("rollback"); yield null; }+ case "getMetaData" -> proxy(DatabaseMetaData.class, (metadata, called, values) -> switch (called.getName()) {+ case "getDatabaseProductName" -> product;+ case "supportsTransactions" -> true;+ default -> defaultValue(called.getReturnType());+ });+ case "createStatement" -> statement("", Statement.class);+ case "prepareCall" -> statement((String) args[0], CallableStatement.class);+ case "prepareStatement" -> statement((String) args[0], PreparedStatement.class);+ default -> defaultValue(method.getReturnType());+ });+ }++ private void stage(String stage) throws SQLException {+ events.add(stage);+ if (fail.equals(stage)) throw new SQLException("private body/argument must not escape", "42501", 27486);+ }++ private void catalogFailure() throws SQLException {+ if (fail.equals("catalog")) throw new SQLException("private job/connection input", "42000", 942);+ if (fail.equals("connection")) throw new SQLRecoverableException("private connection input", "08006", 942);+ }++ private <T> T statement(String text, Class<T> type) {+ Map<Integer, Object> bindings = new HashMap<>();+ if (!text.isEmpty()) sql.add(text);+ return proxy(type, (ignored, method, args) -> switch (method.getName()) {+ case "setString", "setLong", "setInt" -> { bindings.put((int) args[0], args[1]); yield null; }+ case "setNull" -> { bindings.put((int) args[0], null); yield null; }+ case "registerOutParameter" -> { assertEquals(5, args[0]); outType = (int) args[1]; yield null; }+ case "setQueryTimeout" -> { timeouts.add((int) args[0]); yield null; }+ case "getString" -> { if(fail.equals("out-read"))stage("out-read"); yield fail.equals("out") ? "0" : id; }+ case "execute", "executeUpdate" -> {+ catalogFailure();+ String executed = text.isEmpty() ? (String) args[0] : text;+ if (text.isEmpty()) sql.add(executed);+ if (executed.contains("DBMS_JOB.SUBMIT")) {+ assertEquals(Types.VARCHAR, outType);+ stage("submit");+ what = (String) bindings.get(1);+ nextDate = (String) bindings.get(2);+ interval = (String) bindings.get(3);+ instance = bindings.get(4) == null ? null : bindings.get(4).toString();+ } else if (executed.contains("DBMS_JOB.BROKEN")) {+ stage("broken");+ assertEquals(id, bindings.get(1));+ broken = (int) bindings.get(2) == 1 ? "Y" : "N";+ brokenNextDate = (String) bindings.get(3);+ if(product.equals("OceanBase") && broken.equals("Y"))nextDate="4000-01-01 00:00:00";+ } else if(executed.contains("DBMS_JOB.NEXT_DATE")) {+ stage("next-date");assertEquals(id,bindings.get(1));nextDate=(String)bindings.get(2);+ } else {+ assertEquals("ALTER SESSION SET CURRENT_SCHEMA = \"Ow\"\"ner\"", executed);+ stage("schema");+ }+ yield method.getReturnType() == int.class ? 0 : false;+ }+ case "executeQuery" -> {+ catalogFailure();+ if(text.equals("SELECT USER AS DBX_SESSION_USER FROM DUAL"))yield stringRows(new String[]{"Owner"});+ stage("read"); assertEquals(id, bindings.get(1)); yield rows();+ }+ default -> defaultValue(method.getReturnType());+ });+ }++ private ResultSet rows() {+ String[] values = {id, fail.equals("mismatch") ? "changed;" : what, nextDate, interval, broken, instance, product.equals("OceanBase")?"Owner":"Login", product.equals("OceanBase")?"Owner":"Privilege", "Ow\"ner"};+ return stringRows(values);+ }+ private ResultSet stringRows(String[] values) {+ int[] row = {0};+ return proxy(ResultSet.class, (ignored, method, args) -> switch (method.getName()) {+ case "next" -> ++row[0] == 1;+ case "getString" -> values[(int) args[0] - 1];+ default -> defaultValue(method.getReturnType());+ });+ }+ }++ private static <T> T proxy(Class<T> type, java.lang.reflect.InvocationHandler handler) {+ return type.cast(Proxy.newProxyInstance(NativeLegacyJobTest.class.getClassLoader(), new Class<?>[]{type}, handler));+ }++ private static Object defaultValue(Class<?> type) {+ if (type == boolean.class) return false;+ if (type == int.class) return 0;+ if (type == long.class) return 0L;+ return null;+ }+}diff --git a/plugins/jdbc/src/test/java/app/dbx/jdbc/OceanbaseMetadataTest.java b/plugins/jdbc/src/test/java/app/dbx/jdbc/OceanbaseMetadataTest.javanew file mode 100644index 0000000000..f6af1caf72--- /dev/null+++ b/plugins/jdbc/src/test/java/app/dbx/jdbc/OceanbaseMetadataTest.java@@ -0,0 +1,98 @@+package app.dbx.jdbc;++import com.fasterxml.jackson.databind.JsonNode;+import java.lang.reflect.Method;+import java.lang.reflect.Proxy;+import java.sql.Connection;+import java.sql.DatabaseMetaData;+import java.sql.ResultSet;+import java.sql.SQLException;+import java.sql.Statement;+import java.util.concurrent.atomic.AtomicInteger;+import org.junit.jupiter.api.Test;+import static org.junit.jupiter.api.Assertions.*;++class OceanbaseMetadataTest {+ private static Object defaultValue(Class<?> type) {+ if (type == boolean.class) return false;+ if (type == int.class) return 0;+ if (type == long.class) return 0L;+ return null;+ }++ private static JsonNode metadata(String product, String[][] values, boolean fail, AtomicInteger statements) throws Exception {+ DatabaseMetaData jdbc = (DatabaseMetaData) Proxy.newProxyInstance(DatabaseMetaData.class.getClassLoader(), new Class<?>[]{DatabaseMetaData.class},+ (proxy, method, args) -> switch (method.getName()) {+ case "getDatabaseProductName" -> product;+ case "getDatabaseProductVersion" -> "4.2.5.7";+ default -> defaultValue(method.getReturnType());+ });+ AtomicInteger index = new AtomicInteger(-1);+ ResultSet rows = (ResultSet) Proxy.newProxyInstance(ResultSet.class.getClassLoader(), new Class<?>[]{ResultSet.class},+ (proxy, method, args) -> switch (method.getName()) {+ case "next" -> index.incrementAndGet() < values.length;+ case "getString" -> values[index.get()][(Integer) args[0] - 1];+ default -> defaultValue(method.getReturnType());+ });+ AtomicInteger timeout = new AtomicInteger();+ Statement statement = (Statement) Proxy.newProxyInstance(Statement.class.getClassLoader(), new Class<?>[]{Statement.class},+ (proxy, method, args) -> switch (method.getName()) {+ case "setQueryTimeout" -> { timeout.set((Integer) args[0]); yield null; }+ case "executeQuery" -> {+ assertTrue(timeout.get() > 0 && timeout.get() <= 5);+ assertEquals("SHOW VARIABLES LIKE 'ob_compatibility_mode'", args[0]);+ if (fail) throw new SQLException("isolated metadata unavailable");+ yield rows;+ }+ default -> defaultValue(method.getReturnType());+ });+ Connection connection = (Connection) Proxy.newProxyInstance(Connection.class.getClassLoader(), new Class<?>[]{Connection.class},+ (proxy, method, args) -> switch (method.getName()) {+ case "getMetaData" -> jdbc;+ case "createStatement" -> { statements.incrementAndGet(); yield statement; }+ case "commit", "rollback", "setAutoCommit" -> throw new AssertionError("Metadata must not change transactions");+ default -> defaultValue(method.getReturnType());+ });+ Method reader = DbxJdbcPlugin.class.getDeclaredMethod("databaseInfo", Connection.class);+ reader.setAccessible(true);+ return (JsonNode) reader.invoke(null, connection);+ }++ @Test+ void actualOceanbaseModeIsReadFromTheSameConnection() throws Exception {+ for (String mode : new String[]{"ORACLE", "mysql"}) {+ AtomicInteger statements = new AtomicInteger();+ JsonNode info = metadata("OceanBase", new String[][]{{"ob_compatibility_mode", mode}}, false, statements);+ assertEquals(mode.toLowerCase(java.util.Locale.ROOT), info.path("compatibilityMode").asText());+ assertEquals("OceanBase", info.path("productName").asText());+ assertEquals(1, statements.get());+ }+ }++ @Test+ void absentAmbiguousUnknownOrDeniedModesKeepOrdinaryMetadata() throws Exception {+ for (String[][] values : new String[][][]{+ {}, {{"ob_compatibility_mode", "UNKNOWN"}}, {{"other_variable", "ORACLE"}},+ {{"ob_compatibility_mode", "ORACLE"}, {"ob_compatibility_mode", "ORACLE"}},+ {{"ob_compatibility_mode", null}}+ }) {+ JsonNode info = metadata("OceanBase", values, false, new AtomicInteger());+ assertFalse(info.has("compatibilityMode"));+ assertEquals("4.2.5.7", info.path("productVersion").asText());+ }+ JsonNode failed = metadata("OceanBase", new String[0][], true, new AtomicInteger());+ assertFalse(failed.has("compatibilityMode"));+ assertEquals("OceanBase", failed.path("productName").asText());+ }++ @Test+ void otherProductsDoNotReceiveOceanbaseSql() throws Exception {+ for (String product : new String[]{"Oracle", "H2", "MySQL"}) {+ AtomicInteger statements = new AtomicInteger();+ JsonNode info = metadata(product, new String[0][], false, statements);+ assertEquals(product, info.path("productName").asText());+ assertFalse(info.has("compatibilityMode"));+ assertEquals(0, statements.get());+ }+ }+}diff --git a/plugins/jdbc/src/test/java/app/dbx/jdbc/OceanbaseTemporalValueTest.java b/plugins/jdbc/src/test/java/app/dbx/jdbc/OceanbaseTemporalValueTest.javanew file mode 100644index 0000000000..87a8f58186--- /dev/null+++ b/plugins/jdbc/src/test/java/app/dbx/jdbc/OceanbaseTemporalValueTest.java@@ -0,0 +1,156 @@+package app.dbx.jdbc;++import com.fasterxml.jackson.databind.JsonNode;+import com.fasterxml.jackson.databind.ObjectMapper;+import java.lang.reflect.InvocationTargetException;+import java.lang.reflect.Method;+import java.lang.reflect.Proxy;+import java.sql.*;+import java.time.OffsetDateTime;+import java.util.ArrayList;+import java.util.List;+import java.util.Properties;+import java.util.concurrent.atomic.AtomicInteger;+import org.junit.jupiter.api.Test;+import static org.junit.jupiter.api.Assertions.*;++class OceanbaseTemporalValueTest {+ private static final ObjectMapper MAPPER = new ObjectMapper();++ private static Object defaultValue(Class<?> type) {+ if (type == boolean.class) return false;+ if (type == int.class) return 0;+ if (type == long.class) return 0L;+ return null;+ }++ private static ResultSetMetaData metadata(int code, String name) {+ return (ResultSetMetaData) Proxy.newProxyInstance(ResultSetMetaData.class.getClassLoader(), new Class<?>[]{ResultSetMetaData.class},+ (proxy, method, args) -> switch (method.getName()) {+ case "getColumnCount" -> 1;+ case "getColumnType" -> code;+ case "getColumnTypeName" -> name;+ case "getColumnLabel", "getColumnName" -> "VALUE";+ default -> defaultValue(method.getReturnType());+ });+ }++ private static ResultSet rows(int code, String name, String[] values, List<String> calls, boolean fail) {+ AtomicInteger position = new AtomicInteger(-1);+ return (ResultSet) Proxy.newProxyInstance(ResultSet.class.getClassLoader(), new Class<?>[]{ResultSet.class},+ (proxy, method, args) -> switch (method.getName()) {+ case "next" -> position.incrementAndGet() < values.length;+ case "getMetaData" -> metadata(code, name);+ case "getString" -> {+ calls.add("getString");+ if (fail) throw new SQLException("temporal_text_unavailable", "HY000", 701);+ yield values[Math.max(position.get(), 0)];+ }+ case "getObject" -> { calls.add("getObject"); yield new Object(); }+ default -> defaultValue(method.getReturnType());+ });+ }++ private static Object read(ResultSet rs, int code, String name) throws Exception {+ Method method = DbxJdbcPlugin.class.getDeclaredMethod("readValue", ResultSet.class, ResultSetMetaData.class, int.class, boolean.class);+ method.setAccessible(true);+ return method.invoke(null, rs, metadata(code, name), 1, false);+ }++ @Test+ void preservesKnownPrivateTemporalTextPrecisionOffsetRegionAndNullWithoutMaterializingVendorObjects() throws Exception {+ for (int code : new int[]{-101, -102}) {+ String name = code == -101 ? " timestamp with time zone " : "TIMESTAMP WITH LOCAL TIME ZONE";+ for (String value : new String[]{"2032-01-01 23:54:25.123456789 +5:30", "2032-01-01 23:54:25.987654321 -3:30", "2032-01-02 07:54:25.123456 Asia/Shanghai", null}) {+ for (int repeated = 0; repeated < 2; repeated++) {+ List<String> calls = new ArrayList<>();+ assertEquals(value, read(rows(code, name, new String[]{value}, calls, false), code, name));+ assertEquals(List.of("getString"), calls);+ }+ }+ }+ }++ @Test+ void propagatesKnownTemporalTextFailuresRatherThanReturningHashOrNull() {+ for (int code : new int[]{-101, -102}) {+ String name = code == -101 ? "TIMESTAMP WITH TIME ZONE" : "TIMESTAMP WITH LOCAL TIME ZONE";+ List<String> calls = new ArrayList<>();+ InvocationTargetException error = assertThrows(InvocationTargetException.class, () -> read(rows(code, name, new String[]{"unused"}, calls, true), code, name));+ assertInstanceOf(SQLException.class, error.getCause());+ assertEquals(701, ((SQLException) error.getCause()).getErrorCode());+ assertEquals(List.of("getString"), calls);+ }+ }++ @Test+ void leavesMismatchedUnknownAndStandardTemporalObjectsOnTheirExistingPath() throws Exception {+ for (Object[] type : new Object[][]{{-101, "TIMESTAMP WITH LOCAL TIME ZONE"}, {-102, "TIMESTAMP WITH TIME ZONE"}, {-101, "OTHER"}, {-102, null}, {Types.OTHER, "TIMESTAMP WITH TIME ZONE"}, {Types.TIMESTAMP_WITH_TIMEZONE, "TIMESTAMP WITH TIME ZONE"}}) {+ AtomicInteger objects = new AtomicInteger();+ OffsetDateTime value = OffsetDateTime.parse("2032-01-01T23:54:25.123456789-03:30");+ ResultSet rs = (ResultSet) Proxy.newProxyInstance(ResultSet.class.getClassLoader(), new Class<?>[]{ResultSet.class}, (proxy, method, args) -> {+ if (method.getName().equals("getObject")) { objects.incrementAndGet(); return value; }+ if (method.getName().equals("getString")) throw new AssertionError("Unexpected private temporal mapping");+ return defaultValue(method.getReturnType());+ });+ assertEquals(value.toString(), read(rs, (int) type[0], (String) type[1]));+ assertEquals(1, objects.get());+ }+ }++ private static JsonNode request(String method, String params) throws Exception {+ Method handler = DbxJdbcPlugin.class.getDeclaredMethod("handleLine", String.class);+ handler.setAccessible(true);+ return MAPPER.valueToTree(handler.invoke(null, "{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"" + method + "\",\"params\":" + params + "}"));+ }++ @Test+ void ordinaryAndPagedQueriesConsumeTheSameStableTemporalReader() throws Exception {+ List<String> calls = new ArrayList<>();+ String[] values = {"2032-01-01 23:54:25.123456789 +5:30", null, "2032-01-01 23:54:25.987654 -3:30"};+ Driver driver = new Driver() {+ public Connection connect(String url, Properties info) {+ if (!acceptsURL(url)) return null;+ return (Connection) Proxy.newProxyInstance(Connection.class.getClassLoader(), new Class<?>[]{Connection.class}, (proxy, method, args) -> switch (method.getName()) {+ case "createStatement" -> {+ ResultSet result = rows(-101, "TIMESTAMP WITH TIME ZONE", values, calls, false);+ yield Proxy.newProxyInstance(Statement.class.getClassLoader(), new Class<?>[]{Statement.class}, (statement, invoked, parameters) -> switch (invoked.getName()) {+ case "execute" -> true;+ case "getResultSet" -> result;+ case "getUpdateCount" -> -1;+ default -> defaultValue(invoked.getReturnType());+ });+ }+ default -> defaultValue(method.getReturnType());+ });+ }+ public boolean acceptsURL(String url) { return url != null && url.startsWith("jdbc:dbx-temporal:"); }+ public DriverPropertyInfo[] getPropertyInfo(String url, Properties info) { return new DriverPropertyInfo[0]; }+ public int getMajorVersion() { return 1; }+ public int getMinorVersion() { return 0; }+ public boolean jdbcCompliant() { return false; }+ public java.util.logging.Logger getParentLogger() { return java.util.logging.Logger.getGlobal(); }+ };+ DriverManager.registerDriver(driver);+ String connection = "{\"connection_string\":\"jdbc:dbx-temporal:stable\",\"username\":\"test\"}";+ try {+ JsonNode ordinary = request("executeQuery", "{\"connection\":" + connection + ",\"sql\":\"SELECT VALUE\",\"maxRows\":10}");+ assertFalse(ordinary.has("error"), ordinary.toString());+ assertEquals(values[0], ordinary.path("result").path("rows").get(0).get(0).asText());+ assertTrue(ordinary.path("result").path("rows").get(1).get(0).isNull());+ JsonNode first = request("executeQueryPage", "{\"connection\":" + connection + ",\"sql\":\"SELECT VALUE\",\"pageSize\":1}");+ assertFalse(first.has("error"), first.toString());+ assertEquals(values[0], first.path("result").path("rows").get(0).get(0).asText());+ String cursor = first.path("result").path("session_id").asText();+ assertFalse(cursor.isEmpty());+ JsonNode next = request("fetchQueryPage", "{\"connection\":" + connection + ",\"sessionId\":\"" + cursor + "\",\"pageSize\":2}");+ assertFalse(next.has("error"), next.toString());+ assertTrue(next.path("result").path("rows").get(0).get(0).isNull());+ assertEquals(values[2], next.path("result").path("rows").get(1).get(0).asText());+ assertFalse(calls.contains("getObject"));+ } finally {+ request("close", "{\"connection\":" + connection + "}");+ DriverManager.deregisterDriver(driver);+ }+ }+}diff --git a/src-tauri/src/commands/mcp_cleanup.rs b/src-tauri/src/commands/mcp_cleanup.rsindex 54e93ffb19..a3d0e40fd8 100644--- a/src-tauri/src/commands/mcp_cleanup.rs+++ b/src-tauri/src/commands/mcp_cleanup.rs@@ -51,14 +51,18 @@ pub(super) fn cleanup_directory(directory: &Path) -> io::Result<usize> {mod tests {use super::*;use std::path::PathBuf;+ use std::sync::atomic::{AtomicU64, Ordering};use std::time::{SystemTime, UNIX_EPOCH};+ static NEXT_DIRECTORY_ID: AtomicU64 = AtomicU64::new(0);+struct TestDirectory(PathBuf);impl TestDirectory {fn new() -> Self {let nonce = SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_nanos();- let path = std::env::temp_dir().join(format!("dbx-mcp-cleanup-{}-{nonce}", std::process::id()));+ let sequence = NEXT_DIRECTORY_ID.fetch_add(1, Ordering::Relaxed);+ let path = std::env::temp_dir().join(format!("dbx-mcp-cleanup-{}-{nonce}-{sequence}", std::process::id()));fs::create_dir(&path).unwrap();Self(path)}diff --git a/src-tauri/src/commands/query.rs b/src-tauri/src/commands/query.rsindex 8c5fc3369f..0c31b030bb 100644--- a/src-tauri/src/commands/query.rs+++ b/src-tauri/src/commands/query.rs@@ -924,6 +924,13 @@ pub fn validate_oracle_executable_object_source(dbx_core::object_source_sql::validate_oracle_executable_object_source(input)}+#[tauri::command]+pub fn prepare_oracle_trigger_sql(+ input: dbx_core::object_source_sql::OracleTriggerSqlInput,+) -> Result<dbx_core::object_source_sql::PreparedOracleTriggerSql, String> {+ dbx_core::object_source_sql::prepare_oracle_trigger_sql(input)+}+#[tauri::command]pub fn fingerprint_oracle_routine_object_source(input: dbx_core::object_source_sql::EditableObjectSourceSqlInput,@@ -995,13 +1002,13 @@ pub fn build_table_structure_change_sql(options: dbx_core::table_structure_sql::TableStructureSqlOptions,starrocks: Option<dbx_core::table_structure_sql::StarRocksAlterOptions>,mysql_table_charset: Option<dbx_core::table_structure_sql::MysqlTableCharsetChange>,-) -> Result<dbx_core::table_structure_sql::TableStructureSqlResult, String> {+) -> Result<dbx_core::table_structure_sql::TableStructureSqlPlan, String> {let table_charset = mysql_table_charset.map(|change| dbx_core::table_structure_sql::build_mysql_table_charset_change_sql(&options, change));- let mut result = dbx_core::table_structure_sql::build_table_structure_change_sql_with_context(options, starrocks);+ let mut result = dbx_core::table_structure_sql::build_table_structure_change_sql_plan(options, starrocks);if let Some(extra) = table_charset {- result.statements.extend(extra.statements);- result.warnings.extend(extra.warnings);+ result.sql.statements.extend(extra.statements);+ result.sql.warnings.extend(extra.warnings);}Ok(result)}@@ -1047,8 +1054,8 @@ pub fn build_create_table_sql(options: dbx_core::table_structure_sql::TableStructureSqlOptions,server_version: Option<String>,dialect_options: Option<dbx_core::table_structure_sql::CreateTableDialectOptions>,-) -> Result<dbx_core::table_structure_sql::TableStructureSqlResult, String> {- Ok(dbx_core::table_structure_sql::build_create_table_sql_with_dialect_options(+) -> Result<dbx_core::table_structure_sql::TableStructureSqlPlan, String> {+ Ok(dbx_core::table_structure_sql::build_create_table_sql_plan_with_dialect_options(options,server_version.as_deref(),dialect_options.unwrap_or_default(),diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rsindex e9a9677eee..5f0d89e8d4 100644--- a/src-tauri/src/lib.rs+++ b/src-tauri/src/lib.rs@@ -2588,6 +2588,7 @@ pub fn run() {commands::query::build_copy_table_data_sql,commands::query::build_executable_object_source_statements,commands::query::validate_oracle_executable_object_source,+ commands::query::prepare_oracle_trigger_sql,commands::query::fingerprint_oracle_routine_object_source,commands::query::build_executable_object_source_sql,commands::query::build_editable_object_source,