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(db2): support estimated execution plans
Rendegouf62f75d58511
diff --git a/agents/common/src/main/java/com/dbx/agent/JdbcExecutor.java b/agents/common/src/main/java/com/dbx/agent/JdbcExecutor.javaindex ea6193fff8..41ae65634f 100644--- a/agents/common/src/main/java/com/dbx/agent/JdbcExecutor.java+++ b/agents/common/src/main/java/com/dbx/agent/JdbcExecutor.java@@ -29,6 +29,7 @@ public final class JdbcExecutor {private final ConcurrentHashMap<String, QuerySession> sessions = new ConcurrentHashMap<>();private final ConcurrentHashMap<String, QuerySession> tableReadSessions = new ConcurrentHashMap<>();private final java.util.Set<Statement> activeStatements = ConcurrentHashMap.newKeySet();+ private final java.util.Set<NativeOperation> nativeOperations = ConcurrentHashMap.newKeySet();public JdbcExecutor() {}@@ -37,6 +38,61 @@ public final class JdbcExecutor {return AgentExecutionContext.jdbcExecutor();}+ /** Latch cancellation across the sequential statements of one native driver operation. */+ public NativeOperation beginNativeOperation() {+ NativeOperation operation = new NativeOperation();+ nativeOperations.add(operation);+ return operation;+ }++ public final class NativeOperation implements AutoCloseable {+ private final java.util.concurrent.atomic.AtomicBoolean cancelled = new java.util.concurrent.atomic.AtomicBoolean();++ private NativeOperation() {+ }++ public void checkCancelled() {+ if (cancelled.get()) {+ throw new java.util.concurrent.CancellationException("Native JDBC operation cancelled");+ }+ }++ @Override+ public void close() {+ nativeOperations.remove(this);+ }+ }+ /** Register native-driver statements with this session's cancellation boundary. */+ public <S extends Statement> TrackedStatement<S> trackStatement(S statement) {+ java.util.Objects.requireNonNull(statement, "statement");+ activeStatements.add(statement);+ return new TrackedStatement<>(statement);+ }++ /** Owns the original JDBC Statement without changing its identity or unwrap behavior. */+ public final class TrackedStatement<S extends Statement> implements AutoCloseable {+ private final S statement;+ private boolean closed;++ private TrackedStatement(S statement) {+ this.statement = statement;+ }++ public S statement() {+ return statement;+ }++ @Override+ public void close() throws SQLException {+ if (closed) return;+ closed = true;+ try {+ statement.close();+ } finally {+ activeStatements.remove(statement);+ }+ }+ }public static int statementMaxRows(int maxRows) {int effectiveMaxRows = Math.max(maxRows, 1);return effectiveMaxRows == Integer.MAX_VALUE ? Integer.MAX_VALUE : effectiveMaxRows + 1;@@ -627,6 +683,9 @@ public final class JdbcExecutor {}public void cancelActiveStatements() {+ for (NativeOperation operation : nativeOperations) {+ operation.cancelled.set(true);+ }for (Statement statement : activeStatements) {try {statement.cancel();diff --git a/agents/common/src/main/java/com/dbx/agent/MultiSessionJsonRpcServer.java b/agents/common/src/main/java/com/dbx/agent/MultiSessionJsonRpcServer.javaindex 586bb8039a..309255320e 100644--- a/agents/common/src/main/java/com/dbx/agent/MultiSessionJsonRpcServer.java+++ b/agents/common/src/main/java/com/dbx/agent/MultiSessionJsonRpcServer.java@@ -425,6 +425,8 @@ public final class MultiSessionJsonRpcServer implements AutoCloseable {private boolean quarantineAndClose(ExecutorService cleanup) {state.compareAndSet(State.ACTIVE, State.QUARANTINED);+ // Release native requests before cleanup waits for their session lock.+ cancel();boolean replaceRuntime = server != null && server.quarantine();if (!cleanupScheduled.compareAndSet(false, true)) {return replaceRuntime;diff --git a/agents/common/src/test/java/com/dbx/agent/CommonJavaCompatibilityTest.java b/agents/common/src/test/java/com/dbx/agent/CommonJavaCompatibilityTest.javaindex 216e94f2a0..4e99e9188c 100644--- a/agents/common/src/test/java/com/dbx/agent/CommonJavaCompatibilityTest.java+++ b/agents/common/src/test/java/com/dbx/agent/CommonJavaCompatibilityTest.java@@ -381,6 +381,66 @@ class CommonJavaCompatibilityTest {assertFalse(queryB.isAlive());}+ @Test+ void nativeSessionCancellationOnlyCancelsTargetSession() throws Exception {+ nativeCancellationProof("cancel_session");+ }++ @Test+ void nativeSessionCloseCancelsTargetBeforeWaitingForItsRequestLock() throws Exception {+ nativeCancellationProof("close_session");+ }++ private void nativeCancellationProof(String action) throws Exception {+ List<NativeCancelAgent> created = Collections.synchronizedList(new ArrayList<>());+ MultiSessionJsonRpcServer server = new MultiSessionJsonRpcServer(() -> {+ NativeCancelAgent agent = new NativeCancelAgent();+ created.add(agent);+ return agent;+ });+ nativeRequest(server, "open_session", "a", 1);+ nativeRequest(server, "open_session", "b", 2);+ try (var workers = java.util.concurrent.Executors.newFixedThreadPool(2)) {+ var target = workers.submit(() -> nativeRequest(server, "get_explain_info", "a", 3));+ var sibling = workers.submit(() -> nativeRequest(server, "get_explain_info", "b", 4));+ try {+ assertTrue(created.get(0).started.await(3, TimeUnit.SECONDS));+ assertTrue(created.get(1).started.await(3, TimeUnit.SECONDS));+ nativeRequest(server, action, "a", 5);+ String targetResponse = target.get(2, TimeUnit.SECONDS);+ assertTrue(JsonParser.parseString(targetResponse).getAsJsonObject().has("error"), targetResponse);+ assertTrue(created.get(0).cancelled.get());+ assertTrue(created.get(0).cleaned.get());+ assertFalse(created.get(0).executor.hasActiveStatements());+ assertFalse(created.get(1).cancelled.get(), "Sibling native Statement remains active");+ assertFalse(sibling.isDone(), "Sibling request remains blocked until its own release");+ if ("close_session".equals(action)) {+ assertTrue(created.get(0).closed.await(2, TimeUnit.SECONDS), "Close acquired request lock after cancellation");+ }+ created.get(1).release.countDown();+ String siblingResponse = sibling.get(2, TimeUnit.SECONDS);+ assertTrue(JsonParser.parseString(siblingResponse).getAsJsonObject().has("result"), siblingResponse);+ } finally {+ created.forEach(agent -> agent.release.countDown());+ nativeRequest(server, "close_session", "a", 6);+ nativeRequest(server, "close_session", "b", 7);+ }+ }+ }++ private static String nativeRequest(MultiSessionJsonRpcServer server, String method, String session, int id) {+ JsonObject request = new JsonObject();+ request.addProperty("jsonrpc", "2.0");+ request.addProperty("id", id);+ request.addProperty("method", method);+ JsonObject params = new JsonObject();+ params.addProperty("agentSessionId", session);+ params.addProperty("sql", "SELECT 1");+ params.addProperty("timeoutSecs", 0);+ params.addProperty("mode", "explain");+ request.add("params", params);+ return server.handleRequest(request.toString());+ }@Testvoid cancelActiveStatementsClosesOnlyThatExecutorPagedSessions() {JdbcExecutor target = new JdbcExecutor();@@ -980,6 +1040,41 @@ class CommonJavaCompatibilityTest {}}+ private static final class NativeCancelAgent extends MinimalAgent {+ private final CountDownLatch started = new CountDownLatch(1);+ private final CountDownLatch release = new CountDownLatch(1);+ private final CountDownLatch closed = new CountDownLatch(1);+ private final AtomicBoolean cancelled = new AtomicBoolean();+ private final AtomicBoolean cleaned = new AtomicBoolean();+ private volatile JdbcExecutor executor;+ private final java.sql.Statement statement = proxy(java.sql.Statement.class, (method, args) -> {+ if ("cancel".equals(method.getName())) {+ cancelled.set(true);+ release.countDown();+ }+ return defaultValue(method.getReturnType());+ });++ @Override+ public String getExplainInfo(String sql, String database, String schema, int timeout, String mode) {+ executor = JdbcExecutor.current();+ try (var operation = executor.beginNativeOperation(); var tracked = executor.trackStatement(statement)) {+ started.countDown();+ if (!release.await(5, TimeUnit.SECONDS)) throw new AssertionError("Native Statement was not cancelled");+ operation.checkCancelled();+ return "{}";+ } catch (InterruptedException | java.sql.SQLException error) {+ throw new RuntimeException(error);+ } finally {+ cleaned.set(true);+ }+ }++ @Override+ public void disconnect() {+ closed.countDown();+ }+ }private static final class CancelTrackingAgent extends MinimalAgent {private final CountDownLatch statementStarted = new CountDownLatch(1);private final CountDownLatch release = new CountDownLatch(1);diff --git a/agents/common/src/test/java/com/dbx/agent/JdbcNativeStatementTrackingTest.java b/agents/common/src/test/java/com/dbx/agent/JdbcNativeStatementTrackingTest.javanew file mode 100644index 0000000000..913c636510--- /dev/null+++ b/agents/common/src/test/java/com/dbx/agent/JdbcNativeStatementTrackingTest.java@@ -0,0 +1,66 @@+package com.dbx.agent;++import java.lang.reflect.Proxy;+import java.sql.PreparedStatement;+import java.sql.SQLException;+import java.util.concurrent.CancellationException;+import java.util.concurrent.atomic.AtomicInteger;+import org.junit.jupiter.api.Test;+import static org.junit.jupiter.api.Assertions.*;++class JdbcNativeStatementTrackingTest {+ @Test+ void trackedStatementKeepsOriginalIdentityAndCancellationIsSessionLocal() throws Exception {+ JdbcExecutor target = new JdbcExecutor();+ JdbcExecutor sibling = new JdbcExecutor();+ AtomicInteger targetCancels = new AtomicInteger();+ AtomicInteger siblingCancels = new AtomicInteger();+ PreparedStatement original = statement(targetCancels, null);+ try (var a = target.trackStatement(original); var b = sibling.trackStatement(statement(siblingCancels, null))) {+ assertSame(original, a.statement());+ target.cancelActiveStatements();+ assertEquals(1, targetCancels.get());+ assertEquals(0, siblingCancels.get());+ assertTrue(target.hasActiveStatements());+ assertTrue(sibling.hasActiveStatements());+ }+ assertFalse(target.hasActiveStatements());+ assertFalse(sibling.hasActiveStatements());+ }++ @Test+ void registrationIsRemovedEvenWhenJdbcCloseFails() {+ JdbcExecutor executor = new JdbcExecutor();+ SQLException failure = new SQLException("close failed");+ var tracked = executor.trackStatement(statement(new AtomicInteger(), failure));+ assertSame(failure, assertThrows(SQLException.class, tracked::close));+ assertFalse(executor.hasActiveStatements());+ assertDoesNotThrow(tracked::close);+ }++ @Test+ void cancellationLatchesAcrossStatementGapsButDoesNotPoisonNextNativeOperation() {+ JdbcExecutor executor = new JdbcExecutor();+ try (var operation = executor.beginNativeOperation()) {+ assertFalse(executor.hasActiveStatements());+ executor.cancelActiveStatements();+ assertThrows(CancellationException.class, operation::checkCancelled);+ }+ try (var next = executor.beginNativeOperation()) {+ assertDoesNotThrow(next::checkCancelled);+ }+ }++ private static PreparedStatement statement(AtomicInteger cancels, SQLException closeError) {+ return (PreparedStatement) Proxy.newProxyInstance(PreparedStatement.class.getClassLoader(),+ new Class<?>[]{PreparedStatement.class}, (proxy, method, args) -> {+ if ("cancel".equals(method.getName())) cancels.incrementAndGet();+ if ("close".equals(method.getName()) && closeError != null) throw closeError;+ if ("hashCode".equals(method.getName())) return System.identityHashCode(proxy);+ if ("equals".equals(method.getName())) return proxy == args[0];+ if (method.getReturnType() == boolean.class) return false;+ if (method.getReturnType() == int.class) return 0;+ return null;+ });+ }+}diff --git a/agents/drivers/db2/build.gradle b/agents/drivers/db2/build.gradleindex d9af1aac4b..5e97271558 100644--- a/agents/drivers/db2/build.gradle+++ b/agents/drivers/db2/build.gradle@@ -1,4 +1,5 @@dependencies {+ implementation 'com.google.code.gson:gson:2.12.1'implementation fileTree(dir: 'libs', include: ['*.jar'])implementation 'com.ibm.db2:jcc:11.5.9.0'}diff --git a/agents/drivers/db2/src/main/java/com/dbx/agent/db2/Db2Agent.java b/agents/drivers/db2/src/main/java/com/dbx/agent/db2/Db2Agent.javaindex ce75589136..34f6de5a10 100644--- a/agents/drivers/db2/src/main/java/com/dbx/agent/db2/Db2Agent.java+++ b/agents/drivers/db2/src/main/java/com/dbx/agent/db2/Db2Agent.java@@ -70,6 +70,10 @@ public final class Db2Agent extends AbstractJdbcAgent {deferredTableReadSessions.clear();}+ @Override+ public String getExplainInfo(String sql, String database, String schema, int timeoutSecs, String mode) {+ return unchecked(() -> Db2ExplainPlan.read(requireConnected(), sql, schema, timeoutSecs, mode));+ }@Overridepublic List<DatabaseInfo> listDatabases() {return unchecked(() -> {diff --git a/agents/drivers/db2/src/main/java/com/dbx/agent/db2/Db2ExplainPlan.java b/agents/drivers/db2/src/main/java/com/dbx/agent/db2/Db2ExplainPlan.javanew file mode 100644index 0000000000..e62efc1813--- /dev/null+++ b/agents/drivers/db2/src/main/java/com/dbx/agent/db2/Db2ExplainPlan.java@@ -0,0 +1,347 @@+package com.dbx.agent.db2;++import com.dbx.agent.JdbcIdentifiers;+import com.dbx.agent.JdbcExecutor;+import com.google.gson.Gson;+import java.sql.Connection;+import java.sql.PreparedStatement;+import java.sql.ResultSet;+import java.sql.SQLException;+import java.sql.Statement;+import java.util.ArrayList;+import java.util.LinkedHashMap;+import java.util.List;+import java.util.Map;+import java.util.UUID;++/** Reads a single, tagged DB2 LUW estimated plan on an isolated connection. */+final class Db2ExplainPlan {+ private static final Gson JSON = new Gson();+ private static final int MAX_ROWS = 10_000;+ private static final String[] REQUEST_KEYS = {+ "EXPLAIN_REQUESTER", "EXPLAIN_TIME", "SOURCE_NAME", "SOURCE_SCHEMA",+ "SOURCE_VERSION", "EXPLAIN_LEVEL", "STMTNO", "SECTNO"+ };++ private Db2ExplainPlan() {+ }++ static String read(Connection connection, String sql, String schema, int timeoutSecs, String mode)+ throws SQLException {+ if (mode != null && !mode.isBlank() && !"explain".equalsIgnoreCase(mode)) {+ throw new IllegalArgumentException("DB2 supports estimated execution plans only");+ }+ JdbcExecutor executor = JdbcExecutor.current();+ String source = singleQuery(sql);+ // Do not risk committing or rolling back an existing business transaction.+ if (!connection.getAutoCommit()) {+ throw new IllegalStateException("DB2 execution plans require an isolated connection with autocommit enabled");+ }+ try (var operation = executor.beginNativeOperation()) {+ return readPlan(connection, source, schema, timeoutSecs, executor, operation);+ }+ }++ private static String readPlan(Connection connection, String source, String schema, int timeoutSecs,+ JdbcExecutor executor, JdbcExecutor.NativeOperation operation) throws SQLException {+ String originalSchema = null;+ boolean schemaChanged = false;+ Throwable failure = null;+ connection.setAutoCommit(false);+ try {+ String requester;+ try (var tracked = statement(connection, timeoutSecs, executor, operation);+ ResultSet rows = tracked.statement().executeQuery("SELECT SESSION_USER, CURRENT SCHEMA FROM SYSIBM.SYSDUMMY1")) {+ if (!rows.next()) {+ throw new SQLException("DB2 did not return the session authorization ID");+ }+ requester = rows.getString(1).trim();+ originalSchema = rows.getString(2).trim();+ }+ String explainSchema = findExplainSchema(connection, requester, timeoutSecs, executor, operation);+ if (schema != null && !schema.isBlank() && !schema.equals(originalSchema)) {+ // SET SCHEMA is a session register: rollback alone does not restore it.+ schemaChanged = true;+ execute(connection, "SET SCHEMA " + quote(schema), timeoutSecs, executor, operation);+ }+ String tag = UUID.randomUUID().toString().replace("-", "").substring(0, 20);+ execute(connection, "EXPLAIN PLAN SET QUERYTAG = '" + tag + "' FOR " + source, timeoutSecs, executor, operation);+ Map<String, Object> plan = new LinkedHashMap<>();+ plan.put("version", 1);+ plan.put("databaseType", "db2");+ plan.put("requestTag", tag);+ plan.put("statement", readStatement(connection, explainSchema, requester, tag, timeoutSecs, executor, operation));+ plan.put("operators", readRows(connection, explainSchema, "EXPLAIN_OPERATOR",+ "r.OPERATOR_ID, r.OPERATOR_TYPE, r.TOTAL_COST, r.IO_COST, r.CPU_COST, r.FIRST_ROW_COST",+ "r.OPERATOR_ID", requester, tag, timeoutSecs,+ new String[]{"id", "type", "totalCost", "ioCost", "cpuCost", "firstRowCost"}, executor, operation));+ plan.put("streams", readRows(connection, explainSchema, "EXPLAIN_STREAM",+ "r.STREAM_ID, r.SOURCE_TYPE, r.SOURCE_ID, r.TARGET_TYPE, r.TARGET_ID, r.STREAM_COUNT, r.OBJECT_SCHEMA, r.OBJECT_NAME",+ "r.STREAM_ID", requester, tag, timeoutSecs,+ new String[]{"id", "sourceType", "sourceId", "targetType", "targetId", "rowCount", "objectSchema", "objectName"}, executor, operation));+ plan.put("predicates", readRows(connection, explainSchema, "EXPLAIN_PREDICATE",+ "r.OPERATOR_ID, r.PREDICATE_TEXT, r.HOW_APPLIED",+ "r.OPERATOR_ID, r.PREDICATE_ID", requester, tag, timeoutSecs,+ new String[]{"operatorId", "text", "howApplied"}, executor, operation));+ if (((List<?>) plan.get("operators")).isEmpty()) {+ throw new SQLException("DB2 returned no operators for this execution plan");+ }+ return JSON.toJson(plan);+ } catch (SQLException error) {+ SQLException diagnostic = diagnostic(error);+ failure = diagnostic;+ throw diagnostic;+ } catch (RuntimeException | Error error) {+ failure = error;+ throw error;+ } finally {+ SQLException cleanupFailure = null;+ try {+ connection.rollback();+ if (schemaChanged && originalSchema != null) {+ execute(connection, "SET SCHEMA " + quote(originalSchema), timeoutSecs, executor, null);+ connection.rollback();+ }+ // Never switch autocommit back on when rollback failed: that could commit Explain rows.+ connection.setAutoCommit(true);+ } catch (SQLException error) {+ cleanupFailure = error;+ try {+ connection.close();+ } catch (SQLException closeError) {+ error.addSuppressed(closeError);+ }+ }+ if (cleanupFailure != null) {+ if (failure != null) {+ failure.addSuppressed(cleanupFailure);+ } else {+ throw cleanupFailure;+ }+ }+ }+ }++ private static String findExplainSchema(Connection connection, String requester, int timeoutSecs, JdbcExecutor executor, JdbcExecutor.NativeOperation operation)+ throws SQLException {+ String sql = "SELECT TABSCHEMA FROM SYSCAT.TABLES WHERE TABNAME = 'EXPLAIN_INSTANCE' "+ + "AND TABSCHEMA IN (?, 'SYSTOOLS') ORDER BY CASE WHEN TABSCHEMA = ? THEN 0 ELSE 1 END";+ try (var tracked = prepared(connection, sql, timeoutSecs, executor, operation)) {+ PreparedStatement statement = tracked.statement();+ statement.setString(1, requester);+ statement.setString(2, requester);+ operation.checkCancelled();+ try (ResultSet rows = statement.executeQuery()) {+ // SYSCAT.TABLES includes aliases, so qualify reads through the user's aliases.+ if (rows.next()) {+ return rows.getString(1).trim();+ }+ }+ }+ // Let EXPLAIN produce native SQL0219N when neither location exists, preserving its+ // SQLCODE/SQLSTATE. The diagnostic below adds initialization guidance without fabricating a code.+ return requester;+ }++ private static Map<String, String> readStatement(Connection connection, String schema, String requester,+ String tag, int timeoutSecs, JdbcExecutor executor, JdbcExecutor.NativeOperation operation) throws SQLException {+ String sql = "SELECT " + String.join(", ", REQUEST_KEYS) + " FROM "+ + qualified(schema, "EXPLAIN_STATEMENT") + " WHERE EXPLAIN_REQUESTER = ? AND QUERYTAG = ? AND EXPLAIN_LEVEL = 'P'";+ try (var tracked = prepared(connection, sql, timeoutSecs, executor, operation)) {+ PreparedStatement statement = tracked.statement();+ statement.setString(1, requester);+ statement.setString(2, tag);+ operation.checkCancelled();+ try (ResultSet rows = statement.executeQuery()) {+ if (!rows.next()) {+ throw new SQLException("DB2 returned no tagged plan-selection statement");+ }+ Map<String, String> result = new LinkedHashMap<>();+ for (int index = 0; index < REQUEST_KEYS.length; index++) {+ result.put(REQUEST_KEYS[index], rows.getString(index + 1));+ }+ if (rows.next()) {+ throw new SQLException("DB2 returned multiple statements for one execution plan request");+ }+ return result;+ }+ }+ }++ private static List<Map<String, String>> readRows(Connection connection, String schema, String table,+ String columns, String order, String requester, String tag, int timeoutSecs, String[] fields, JdbcExecutor executor, JdbcExecutor.NativeOperation operation)+ throws SQLException {+ List<String> join = new ArrayList<>();+ for (String key : REQUEST_KEYS) {+ join.add("r." + key + " = s." + key);+ }+ String sql = "SELECT " + columns + " FROM " + qualified(schema, table) + " r JOIN "+ + qualified(schema, "EXPLAIN_STATEMENT") + " s ON " + String.join(" AND ", join)+ + " WHERE s.EXPLAIN_REQUESTER = ? AND s.QUERYTAG = ? AND s.EXPLAIN_LEVEL = 'P' ORDER BY " + order;+ try (var tracked = prepared(connection, sql, timeoutSecs, executor, operation)) {+ PreparedStatement statement = tracked.statement();+ statement.setMaxRows(MAX_ROWS + 1);+ statement.setString(1, requester);+ statement.setString(2, tag);+ operation.checkCancelled();+ try (ResultSet rows = statement.executeQuery()) {+ List<Map<String, String>> result = new ArrayList<>();+ while (rows.next()) {+ if (result.size() >= MAX_ROWS) {+ throw new SQLException("DB2 execution plan exceeds the limit of " + MAX_ROWS + " " + table + " rows");+ }+ Map<String, String> row = new LinkedHashMap<>();+ for (int index = 0; index < fields.length; index++) {+ String value = rows.getString(index + 1);+ if (value != null) {+ // Preserve predicate text; CHAR fields and numeric strings have no useful padding.+ row.put(fields[index], "text".equals(fields[index]) ? value : value.stripTrailing());+ }+ }+ result.add(row);+ }+ return result;+ }+ }+ }++ private static SQLException diagnostic(SQLException error) {+ String hint = "";+ for (SQLException current = error; current != null; current = current.getNextException()) {+ if (current.getErrorCode() == -219) {+ hint = " DB2 Explain tables are missing or incompatible. Ask an administrator to create them for the connecting user with CALL SYSPROC.SYSINSTALLOBJECTS('EXPLAIN', 'C', '', CURRENT USER), or migrate existing Explain tables and grant INSERT/SELECT privileges.";+ break;+ }+ if (current.getErrorCode() == -551 || current.getErrorCode() == -552) {+ hint = " Ask an administrator to grant Explain/object privileges and INSERT/SELECT access to the Explain tables.";+ break;+ }+ }+ if (hint.isEmpty()) {+ return error;+ }+ SQLException result = new SQLException(error.getMessage() + hint, error.getSQLState(), error.getErrorCode(), error);+ result.setNextException(error);+ return result;+ }++ private static JdbcExecutor.TrackedStatement<Statement> statement(Connection connection, int timeoutSecs,+ JdbcExecutor executor, JdbcExecutor.NativeOperation operation) throws SQLException {+ if (operation != null) operation.checkCancelled();+ return configure(executor.trackStatement(connection.createStatement()), timeoutSecs, operation);+ }++ private static JdbcExecutor.TrackedStatement<PreparedStatement> prepared(Connection connection, String sql,+ int timeoutSecs, JdbcExecutor executor, JdbcExecutor.NativeOperation operation) throws SQLException {+ operation.checkCancelled();+ return configure(executor.trackStatement(connection.prepareStatement(sql)), timeoutSecs, operation);+ }++ private static <S extends Statement> JdbcExecutor.TrackedStatement<S> configure(+ JdbcExecutor.TrackedStatement<S> tracked, int timeoutSecs, JdbcExecutor.NativeOperation operation) throws SQLException {+ try {+ if (operation != null) operation.checkCancelled();+ timeout(tracked.statement(), timeoutSecs);+ return tracked;+ } catch (SQLException | RuntimeException error) {+ try {+ tracked.close();+ } catch (SQLException closeError) {+ error.addSuppressed(closeError);+ }+ throw error;+ }+ }+ private static void timeout(Statement statement, int timeoutSecs) throws SQLException {+ if (timeoutSecs >= 0) {+ statement.setQueryTimeout(timeoutSecs);+ }+ }++ private static void execute(Connection connection, String sql, int timeoutSecs, JdbcExecutor executor,+ JdbcExecutor.NativeOperation operation) throws SQLException {+ try (var tracked = statement(connection, timeoutSecs, executor, operation)) {+ if (operation != null) operation.checkCancelled();+ tracked.statement().execute(sql);+ }+ }+ private static String qualified(String schema, String table) {+ return quote(schema) + "." + quote(table);+ }++ private static String quote(String value) {+ return JdbcIdentifiers.INSTANCE.doubleQuote(value);+ }++ /** Rust checks read-only SQL too; this protects direct Agent/RPC callers and trailing terminators. */+ static String singleQuery(String sql) {+ if (sql == null || sql.isBlank()) {+ throw new IllegalArgumentException("DB2 execution plan SQL must not be empty");+ }+ StringBuilder significant = new StringBuilder();+ int terminator = -1;+ for (int index = 0; index < sql.length(); index++) {+ char ch = sql.charAt(index);+ if (Character.isWhitespace(ch)) {+ significant.append(' ');+ } else if (ch == '-' && index + 1 < sql.length() && sql.charAt(index + 1) == '-') {+ index += 2;+ while (index < sql.length() && sql.charAt(index) != '\n' && sql.charAt(index) != '\r') {+ index++;+ }+ significant.append(' ');+ } else if (ch == '/' && index + 1 < sql.length() && sql.charAt(index + 1) == '*') {+ int depth = 1;+ index += 2;+ while (index < sql.length() && depth > 0) {+ if (index + 1 < sql.length() && sql.charAt(index) == '/' && sql.charAt(index + 1) == '*') {+ depth++;+ index += 2;+ } else if (index + 1 < sql.length() && sql.charAt(index) == '*' && sql.charAt(index + 1) == '/') {+ depth--;+ index += 2;+ } else {+ index++;+ }+ }+ if (depth != 0) {+ throw new IllegalArgumentException("Unterminated DB2 SQL comment");+ }+ index--;+ significant.append(' ');+ } else {+ if (terminator >= 0) {+ throw new IllegalArgumentException("DB2 execution plans require a single SQL statement");+ }+ if (ch == ';') {+ terminator = index;+ } else if (ch == '\'' || ch == '"') {+ char quote = ch;+ significant.append(" quoted ");+ boolean closed = false;+ while (++index < sql.length()) {+ if (sql.charAt(index) == quote) {+ if (index + 1 < sql.length() && sql.charAt(index + 1) == quote) {+ index++;+ } else {+ closed = true;+ break;+ }+ }+ }+ if (!closed) {+ throw new IllegalArgumentException("Unterminated DB2 SQL quoted value");+ }+ } else {+ significant.append(ch);+ }+ }+ }+ String code = significant.toString().stripLeading();+ if (!code.matches("(?is)^(SELECT|WITH|VALUES)\\b.*")) {+ throw new IllegalArgumentException("DB2 estimated execution plans accept SELECT, WITH, or VALUES queries");+ }+ // End a possible trailing line comment before SQL assembled around the source can continue.+ return (terminator >= 0 ? sql.substring(0, terminator) : sql).trim() + "\n";+ }+}diff --git a/agents/drivers/db2/src/test/java/com/dbx/agent/db2/Db2ExplainPlanIntegrationTest.java b/agents/drivers/db2/src/test/java/com/dbx/agent/db2/Db2ExplainPlanIntegrationTest.javanew file mode 100644index 0000000000..9b710b88d2--- /dev/null+++ b/agents/drivers/db2/src/test/java/com/dbx/agent/db2/Db2ExplainPlanIntegrationTest.java@@ -0,0 +1,166 @@+package com.dbx.agent.db2;++import com.dbx.agent.JdbcIdentifiers;+import com.dbx.agent.test.TestSupport;+import com.google.gson.JsonObject;+import com.google.gson.JsonParser;+import java.nio.file.Files;+import java.nio.file.Path;+import java.sql.Connection;+import java.sql.DriverManager;+import java.sql.ResultSet;+import java.sql.Statement;+import java.util.ArrayList;+import java.util.HashSet;+import java.util.List;+import java.util.UUID;+import java.util.concurrent.Callable;+import java.util.concurrent.Executors;+import org.junit.jupiter.api.Test;+import org.junit.jupiter.api.condition.EnabledIfEnvironmentVariable;+import static org.junit.jupiter.api.Assertions.*;++/**+ * Opt-in real DB2 LUW checks. Credentials stay in DBX_DB2_JDBC_URL/USER/PASSWORD.+ * The sequence check needs CREATEIN/DROPIN on the connecting user's schema.+ */+@EnabledIfEnvironmentVariable(named = "DBX_DB2_JDBC_URL", matches = ".+")+class Db2ExplainPlanIntegrationTest {+ @Test+ void realPlansRoundTripAndRollbackWithoutChangingSessionSchema() throws Exception {+ try (Connection connection = connect()) {+ String originalSchema = scalar(connection, "VALUES CURRENT SCHEMA").trim();+ String explainSchema = explainSchema(connection);+ long before = requestCount(connection, explainSchema);+ Db2Agent agent = agent(connection);+ String businessSchema = System.getenv("DBX_DB2_SCHEMA");+ List<String> queries = List.of(+ "SELECT IBMREQD FROM SYSIBM.SYSDUMMY1;",+ "WITH x AS (SELECT IBMREQD FROM SYSIBM.SYSDUMMY1) SELECT * FROM x",+ "SELECT a.IBMREQD FROM SYSIBM.SYSDUMMY1 a JOIN SYSIBM.SYSDUMMY1 b ON a.IBMREQD = b.IBMREQD WHERE a.IBMREQD = 'Y'"+ );+ int index = 0;+ for (String sql : queries) {+ String raw = agent.getExplainInfo(sql, null, businessSchema, 30, "explain");+ JsonObject plan = JsonParser.parseString(raw).getAsJsonObject();+ assertFalse(plan.getAsJsonArray("operators").isEmpty());+ assertFalse(plan.getAsJsonArray("streams").isEmpty());+ assertEquals(originalSchema, scalar(connection, "VALUES CURRENT SCHEMA").trim());+ assertTrue(connection.getAutoCommit());+ assertEquals(before, requestCount(connection, explainSchema), "Explain rows must be rolled back");+ String directory = System.getenv("DBX_DB2_PROOF_DIR");+ if (directory != null && !directory.isBlank()) {+ Path path = Path.of(directory);+ Files.createDirectories(path);+ Files.writeString(path.resolve("jdbc-plan-" + index + ".json"), raw);+ }+ index++;+ }+ }+ }++ @Test+ void explainDoesNotConsumeSequenceValueFromTheBusinessStatement() throws Exception {+ try (Connection connection = connect()) {+ String schema = scalar(connection, "VALUES SESSION_USER").trim();+ String name = "DBXEP_" + UUID.randomUUID().toString().replace("-", "").substring(0, 12).toUpperCase();+ String sequence = JdbcIdentifiers.INSTANCE.doubleQuote(schema) + "." + JdbcIdentifiers.INSTANCE.doubleQuote(name);+ try (Statement statement = connection.createStatement()) {+ statement.execute("CREATE SEQUENCE " + sequence + " AS BIGINT START WITH 1 INCREMENT BY 1 NO CACHE");+ try {+ assertEquals("1", scalar(connection, "VALUES NEXT VALUE FOR " + sequence).trim());+ agent(connection).getExplainInfo("SELECT NEXT VALUE FOR " + sequence + " FROM SYSIBM.SYSDUMMY1", null, null, 30, null);+ assertEquals("2", scalar(connection, "VALUES NEXT VALUE FOR " + sequence).trim(),+ "Generating the estimated plan must not execute the sequence expression");+ } finally {+ statement.execute("DROP SEQUENCE " + sequence);+ }+ }+ }+ }++ @Test+ void concurrentConnectionsReturnDistinctRequestsAndLeaveNoPersistedExplainRows() throws Exception {+ String explainSchema;+ long before;+ try (Connection connection = connect()) {+ explainSchema = explainSchema(connection);+ before = requestCount(connection, explainSchema);+ }+ List<Callable<String>> tasks = new ArrayList<>();+ for (int index = 0; index < 16; index++) {+ int value = index;+ tasks.add(() -> {+ try (Connection connection = connect()) {+ JsonObject plan = JsonParser.parseString(agent(connection).getExplainInfo(+ "SELECT " + value + " AS MARKER FROM SYSIBM.SYSDUMMY1", null,+ System.getenv("DBX_DB2_SCHEMA"), 30, null+ )).getAsJsonObject();+ assertFalse(plan.getAsJsonArray("operators").isEmpty());+ return plan.get("requestTag").getAsString();+ }+ });+ }+ HashSet<String> tags = new HashSet<>();+ try (var executor = Executors.newFixedThreadPool(4)) {+ for (var future : executor.invokeAll(tasks)) tags.add(future.get());+ }+ assertEquals(tasks.size(), tags.size());+ try (Connection connection = connect()) {+ assertEquals(before, requestCount(connection, explainSchema));+ }+ }++ @Test+ void existingTransactionRemainsOpenWhenExplainIsRejected() throws Exception {+ try (Connection connection = connect()) {+ connection.setAutoCommit(false);+ assertThrows(IllegalStateException.class,+ () -> agent(connection).getExplainInfo("SELECT * FROM SYSIBM.SYSDUMMY1", null, null, 30, null));+ assertFalse(connection.getAutoCommit());+ assertEquals("Y", scalar(connection, "SELECT IBMREQD FROM SYSIBM.SYSDUMMY1").trim());+ connection.rollback();+ }+ }++ private static Db2Agent agent(Connection connection) {+ Db2Agent agent = new Db2Agent();+ TestSupport.setPrivateConnection(agent, connection);+ return agent;+ }++ private static Connection connect() throws Exception {+ return DriverManager.getConnection(System.getenv("DBX_DB2_JDBC_URL"),+ System.getenv("DBX_DB2_USER"), System.getenv("DBX_DB2_PASSWORD"));+ }++ private static String scalar(Connection connection, String sql) throws Exception {+ try (Statement statement = connection.createStatement(); ResultSet rows = statement.executeQuery(sql)) {+ assertTrue(rows.next());+ return rows.getString(1);+ }+ }++ private static String explainSchema(Connection connection) throws Exception {+ String user = scalar(connection, "VALUES SESSION_USER").trim();+ try (var statement = connection.prepareStatement("SELECT TABSCHEMA FROM SYSCAT.TABLES "+ + "WHERE TABNAME = 'EXPLAIN_INSTANCE' AND TABSCHEMA IN (?, 'SYSTOOLS') "+ + "ORDER BY CASE WHEN TABSCHEMA = ? THEN 0 ELSE 1 END")) {+ statement.setString(1, user);+ statement.setString(2, user);+ try (ResultSet rows = statement.executeQuery()) {+ assertTrue(rows.next(), "The integration database must have Explain tables installed");+ return rows.getString(1).trim();+ }+ }+ }++ private static long requestCount(Connection connection, String schema) throws Exception {+ try (var statement = connection.prepareStatement("SELECT COUNT(*) FROM "+ + JdbcIdentifiers.INSTANCE.doubleQuote(schema) + ".EXPLAIN_INSTANCE WHERE EXPLAIN_REQUESTER = SESSION_USER");+ ResultSet rows = statement.executeQuery()) {+ assertTrue(rows.next());+ return rows.getLong(1);+ }+ }+}diff --git a/agents/drivers/db2/src/test/java/com/dbx/agent/db2/Db2ExplainPlanTest.java b/agents/drivers/db2/src/test/java/com/dbx/agent/db2/Db2ExplainPlanTest.javanew file mode 100644index 0000000000..aece458480--- /dev/null+++ b/agents/drivers/db2/src/test/java/com/dbx/agent/db2/Db2ExplainPlanTest.java@@ -0,0 +1,428 @@+package com.dbx.agent.db2;++import com.dbx.agent.test.TestSupport;+import com.dbx.agent.JdbcExecutor;+import java.util.concurrent.CountDownLatch;+import java.util.concurrent.CancellationException;+import java.util.concurrent.ExecutionException;+import java.util.concurrent.Executors;+import java.util.concurrent.TimeUnit;+import com.google.gson.JsonObject;+import com.google.gson.JsonParser;+import java.lang.reflect.InvocationHandler;+import java.lang.reflect.Proxy;+import java.sql.Connection;+import java.sql.PreparedStatement;+import java.sql.ResultSet;+import java.sql.SQLException;+import java.sql.Statement;+import java.util.ArrayList;+import java.util.Arrays;+import java.util.LinkedHashMap;+import java.util.List;+import java.util.Map;+import org.junit.jupiter.api.Test;+import static org.junit.jupiter.api.Assertions.*;++class Db2ExplainPlanTest {+ @Test+ void agentReturnsTaggedPlanWithoutExecutingBusinessQuery() {+ JdbcBoundary jdbc = new JdbcBoundary();+ JsonObject plan = JsonParser.parseString(jdbc.agent().getExplainInfo(+ "SELECT * FROM ORDERS WHERE NOTE = ';'; -- trailing comment", "DBX", "APP", 9, "explain"+ )).getAsJsonObject();+ assertEquals(1, plan.get("version").getAsInt());+ assertEquals("db2", plan.get("databaseType").getAsString());+ assertTrue(plan.get("requestTag").getAsString().matches("[0-9a-f]{20}"));+ assertEquals("12345678901234567890.123", plan.getAsJsonArray("operators").get(0)+ .getAsJsonObject().get("totalCost").getAsString());+ JsonObject stream = plan.getAsJsonArray("streams").get(0).getAsJsonObject();+ assertEquals("D", stream.get("sourceType").getAsString());+ assertEquals("-1", stream.get("sourceId").getAsString());+ assertEquals("ORDERS", stream.get("objectName").getAsString());+ assertEquals("(Q1.NOTE = ';')", plan.getAsJsonArray("predicates").get(0)+ .getAsJsonObject().get("text").getAsString());+ assertEquals(1, jdbc.executed.stream().filter(sql -> sql.startsWith("EXPLAIN PLAN")).count());+ assertTrue(jdbc.executed.stream().noneMatch(sql -> sql.startsWith("SELECT * FROM ORDERS")));+ assertTrue(jdbc.executed.stream().anyMatch(sql -> sql.endsWith("FOR SELECT * FROM ORDERS WHERE NOTE = ';'\n")));+ assertEquals(List.of(false, true), jdbc.autocommitChanges);+ assertEquals(2, jdbc.rollbacks);+ assertEquals(0, jdbc.commits);+ assertEquals("SESSION_DEFAULT", jdbc.schema);+ assertEquals(0, jdbc.openStatements);+ assertEquals(0, jdbc.openResultSets);+ assertTrue(jdbc.timeouts.stream().allMatch(timeout -> timeout == 9));+ for (String query : jdbc.prepared) {+ if (query.contains(" r JOIN ")) {+ for (String key : List.of("EXPLAIN_REQUESTER", "EXPLAIN_TIME", "SOURCE_NAME", "SOURCE_SCHEMA",+ "SOURCE_VERSION", "EXPLAIN_LEVEL", "STMTNO", "SECTNO")) {+ assertTrue(query.contains("r." + key + " = s." + key), key);+ }+ assertTrue(query.contains("s.EXPLAIN_REQUESTER = ? AND s.QUERYTAG = ?"));+ assertTrue(query.contains("s.EXPLAIN_LEVEL = 'P'"));+ }+ }+ assertTrue(jdbc.boundTags.stream().allMatch(tag -> tag.equals(plan.get("requestTag").getAsString())));+ assertTrue(jdbc.prepared.stream().filter(sql -> sql.contains("EXPLAIN_") && !sql.contains("SYSCAT"))+ .allMatch(sql -> sql.contains("\"AUTH_USER\".")));+ }++ @Test+ void systoolsFallbackIsIndependentOfBusinessSchemaAndIncludesAliases() {+ JdbcBoundary jdbc = new JdbcBoundary();+ jdbc.explainSchema = "SYSTOOLS";+ jdbc.agent().getExplainInfo("WITH x AS (SELECT 1 FROM SYSIBM.SYSDUMMY1) SELECT * FROM x", null, "Mixed \"Schema", -1, null);+ assertTrue(jdbc.executed.contains("SET SCHEMA \"Mixed \"\"Schema\""));+ assertEquals("SESSION_DEFAULT", jdbc.schema);+ assertTrue(jdbc.timeouts.isEmpty());+ assertTrue(jdbc.prepared.stream().filter(sql -> sql.contains(" r JOIN ")).allMatch(sql -> sql.contains("\"SYSTOOLS\".")));+ assertFalse(jdbc.prepared.get(0).contains("TYPE"));+ assertEquals("AUTH_USER", jdbc.catalogRequester);+ }++ @Test+ void existingTransactionIsRejectedWithoutRollbackOrCommit() {+ JdbcBoundary jdbc = new JdbcBoundary();+ jdbc.autocommit = false;+ IllegalStateException error = assertThrows(IllegalStateException.class,+ () -> jdbc.agent().getExplainInfo("SELECT 1 FROM SYSIBM.SYSDUMMY1", null, "APP", 0, "explain"));+ assertTrue(error.getMessage().contains("isolated connection"));+ assertEquals(0, jdbc.rollbacks);+ assertEquals(0, jdbc.commits);+ assertTrue(jdbc.executed.isEmpty());+ assertTrue(jdbc.autocommitChanges.isEmpty());+ }++ @Test+ void acceptsSupportedQueryPrefixes() {+ for (String sql : Arrays.asList("SELECT * FROM \"APP\".\"ORDERS\"",+ "WITH q AS (SELECT 1 FROM SYSIBM.SYSDUMMY1) SELECT * FROM q", "VALUES 1",+ "/* plan */ select * FROM APP.ORDERS",+ "-- plan\nwith q AS (SELECT 1 FROM SYSIBM.SYSDUMMY1) SELECT * FROM q",+ "/* plan */ values (1)",+ "/* outer /* inner */ trailing */ SELECT 1 FROM SYSIBM.SYSDUMMY1",+ "/* outer /* inner */ DELETE */ VALUES ('a;''b')",+ "WITH q AS (/* outer /* inner */ UPDATE */ SELECT 1 FROM SYSIBM.SYSDUMMY1) SELECT * FROM q")) {+ assertEquals(sql + "\n", Db2ExplainPlan.singleQuery(sql));+ }+ }++ @Test+ void rejectsInvalidInputsAndModesBeforeChangingConnection() {+ for (String sql : Arrays.asList(null, "", "DELETE FROM APP.ORDERS", "SELECT 1; DROP TABLE APP.ORDERS",+ "TABLE APP.ORDERS", "table \"APP\".\"ORDERS\";", "/* plan */ TABLE APP.ORDERS",+ "SELECT 1;;", "SELECT 'unterminated", "SELECT 1 /* unterminated", "SELECT 1 /* outer /* inner */")) {+ JdbcBoundary jdbc = new JdbcBoundary();+ assertThrows(IllegalArgumentException.class, () -> jdbc.agent().getExplainInfo(sql, null, null, 5, "explain"));+ assertTrue(jdbc.autocommitChanges.isEmpty());+ assertTrue(jdbc.executed.isEmpty());+ }+ JdbcBoundary jdbc = new JdbcBoundary();+ assertThrows(IllegalArgumentException.class,+ () -> jdbc.agent().getExplainInfo("SELECT 1", null, null, 5, "autotrace"));+ assertTrue(jdbc.autocommitChanges.isEmpty());+ assertEquals("/* leading /* nested */ comment */ VALUES ('a;''b')\n",+ Db2ExplainPlan.singleQuery("/* leading /* nested */ comment */ VALUES ('a;''b'); -- end"));+ assertEquals("SELECT \"semi;column\" FROM T -- comment\n",+ Db2ExplainPlan.singleQuery("SELECT \"semi;column\" FROM T -- comment"));+ }++ @Test+ void preservesSqlCodeStateAndChainWhileAddingPermissionHint() {+ JdbcBoundary jdbc = new JdbcBoundary();+ SQLException nativeError = new SQLException("SQL0551N not authorized", "42501", -551);+ nativeError.setNextException(new SQLException("Additional diagnostic", "42501", -551));+ jdbc.explainError = nativeError;+ RuntimeException error = assertThrows(RuntimeException.class,+ () -> jdbc.agent().getExplainInfo("SELECT * FROM ORDERS", null, "APP", 5, "explain"));+ SQLException diagnostic = sqlCause(error);+ assertEquals(-551, diagnostic.getErrorCode());+ assertEquals("42501", diagnostic.getSQLState());+ assertSame(nativeError, diagnostic.getCause());+ assertSame(nativeError, diagnostic.getNextException());+ assertTrue(error.getMessage().contains("INSERT/SELECT"));+ assertEquals(List.of(false, true), jdbc.autocommitChanges);+ assertEquals("SESSION_DEFAULT", jdbc.schema);+ assertEquals(2, jdbc.rollbacks);+ assertEquals(0, jdbc.openStatements);+ assertEquals(0, jdbc.openResultSets);+ }++ @Test+ void missingTablesGiveInitializationInstructionAndReleaseTransaction() {+ JdbcBoundary jdbc = new JdbcBoundary();+ jdbc.explainSchema = null;+ jdbc.explainError = new SQLException("SQL0219N Explain table does not exist", "42704", -219);+ RuntimeException error = assertThrows(RuntimeException.class,+ () -> jdbc.agent().getExplainInfo("SELECT 1", null, "APP", 0, "explain"));+ assertTrue(error.getMessage().contains("SYSINSTALLOBJECTS"));+ assertTrue(error.getMessage().contains("CURRENT USER"));+ assertEquals(-219, sqlCause(error).getErrorCode());+ assertEquals("42704", sqlCause(error).getSQLState());+ assertTrue(jdbc.executed.stream().anyMatch(sql -> sql.startsWith("EXPLAIN")));+ assertEquals(2, jdbc.rollbacks);+ assertTrue(jdbc.autocommit);+ assertEquals("SESSION_DEFAULT", jdbc.schema);+ }++ @Test+ void rollbackFailureClosesConnectionWithoutEnablingAutocommit() {+ JdbcBoundary jdbc = new JdbcBoundary();+ jdbc.rollbackError = new SQLException("rollback failed", "08006", -30081);+ RuntimeException error = assertThrows(RuntimeException.class,+ () -> jdbc.agent().getExplainInfo("SELECT 1", null, "APP", 1, "explain"));+ assertEquals("08006", sqlCause(error).getSQLState());+ assertTrue(jdbc.closed);+ assertEquals(List.of(false), jdbc.autocommitChanges);+ assertEquals(0, jdbc.commits);+ }++ @Test+ void cleanupFailureIsSuppressedUnderOriginalDatabaseError() {+ JdbcBoundary jdbc = new JdbcBoundary();+ jdbc.explainError = new SQLException("SQL0104N unexpected token", "42601", -104);+ jdbc.rollbackError = new SQLException("rollback failed", "08006", -30081);+ RuntimeException error = assertThrows(RuntimeException.class,+ () -> jdbc.agent().getExplainInfo("SELECT 1", null, null, 1, "explain"));+ assertSame(jdbc.explainError, sqlCause(error));+ assertEquals(1, jdbc.explainError.getSuppressed().length);+ assertSame(jdbc.rollbackError, jdbc.explainError.getSuppressed()[0]);+ assertTrue(jdbc.closed);+ assertEquals(List.of(false), jdbc.autocommitChanges);+ }++ @Test+ void distinctRequestsUseDistinctTagsAndNeverCommit() {+ JdbcBoundary jdbc = new JdbcBoundary();+ Db2Agent agent = jdbc.agent();+ String first = JsonParser.parseString(agent.getExplainInfo("SELECT 1", null, null, 0, null))+ .getAsJsonObject().get("requestTag").getAsString();+ String second = JsonParser.parseString(agent.getExplainInfo("SELECT 2", null, null, 0, null))+ .getAsJsonObject().get("requestTag").getAsString();+ assertNotEquals(first, second);+ assertEquals(2, jdbc.rollbacks);+ assertEquals(0, jdbc.commits);+ }++ @Test+ void rejectsMissingAmbiguousOrEmptyPlanInsteadOfSilentlyReturningAnotherRequest() {+ for (int count : List.of(0, 2)) {+ JdbcBoundary jdbc = new JdbcBoundary();+ jdbc.statementCount = count;+ assertThrows(RuntimeException.class,+ () -> jdbc.agent().getExplainInfo("SELECT 1", null, null, 0, null));+ assertEquals(1, jdbc.rollbacks);+ assertTrue(jdbc.autocommit);+ assertEquals(0, jdbc.openResultSets);+ }+ JdbcBoundary jdbc = new JdbcBoundary();+ jdbc.operatorCount = 0;+ RuntimeException error = assertThrows(RuntimeException.class,+ () -> jdbc.agent().getExplainInfo("SELECT 1", null, null, 0, null));+ assertTrue(error.getMessage().contains("no operators"));+ assertEquals(1, jdbc.rollbacks);+ }++ @Test+ void cancellationReachesBlockedNativeExplainAndCleansUpItsTransaction() throws Exception {+ JdbcBoundary jdbc = new JdbcBoundary();+ jdbc.explainStarted = new CountDownLatch(1);+ jdbc.cancelSignal = new CountDownLatch(1);+ JdbcExecutor executor = JdbcExecutor.current();+ Db2Agent agent = jdbc.agent();+ try (var worker = Executors.newSingleThreadExecutor()) {+ var pending = worker.submit(() -> agent.getExplainInfo("SELECT * FROM ORDERS", null, "APP", 0, "explain"));+ try {+ assertTrue(jdbc.explainStarted.await(3, TimeUnit.SECONDS), "Native Explain entered its blocking call");+ assertTrue(executor.hasActiveStatements(), "Native Statement registered with the session executor");+ executor.cancelActiveStatements();+ ExecutionException error = assertThrows(ExecutionException.class, () -> pending.get(2, TimeUnit.SECONDS));+ assertEquals("57014", sqlCause(error).getSQLState());+ assertEquals(1, jdbc.cancelCalls);+ assertFalse(executor.hasActiveStatements());+ assertEquals(2, jdbc.rollbacks);+ assertEquals(0, jdbc.commits);+ assertTrue(jdbc.autocommit);+ assertEquals("SESSION_DEFAULT", jdbc.schema);+ assertEquals(0, jdbc.openStatements);+ assertEquals(0, jdbc.openResultSets);+ } finally {+ jdbc.cancelSignal.countDown();+ }+ }+ }+ @Test+ void cancellationInNativeStatementGapPreventsExplainAndStillRestoresSchema() throws Exception {+ JdbcBoundary jdbc = new JdbcBoundary();+ jdbc.gapStarted = new CountDownLatch(1);+ jdbc.gapResume = new CountDownLatch(1);+ JdbcExecutor executor = JdbcExecutor.current();+ Db2Agent agent = jdbc.agent();+ try (var worker = Executors.newSingleThreadExecutor()) {+ var pending = worker.submit(() -> agent.getExplainInfo("SELECT * FROM ORDERS", null, "APP", 0, "explain"));+ try {+ assertTrue(jdbc.gapStarted.await(3, TimeUnit.SECONDS));+ assertFalse(executor.hasActiveStatements(), "Previous schema Statement already closed");+ executor.cancelActiveStatements();+ jdbc.gapResume.countDown();+ ExecutionException error = assertThrows(ExecutionException.class, () -> pending.get(2, TimeUnit.SECONDS));+ assertInstanceOf(CancellationException.class, error.getCause());+ assertTrue(jdbc.executed.stream().noneMatch(sql -> sql.startsWith("EXPLAIN")));+ assertEquals(2, jdbc.rollbacks);+ assertTrue(jdbc.autocommit);+ assertEquals("SESSION_DEFAULT", jdbc.schema);+ assertEquals(0, jdbc.openStatements);+ assertFalse(executor.hasActiveStatements());+ } finally {+ jdbc.gapResume.countDown();+ }+ }+ }+ private static SQLException sqlCause(Throwable error) {+ while (!(error instanceof SQLException) && error.getCause() != null) error = error.getCause();+ return assertInstanceOf(SQLException.class, error);+ }++ /** JDBC is the mocked boundary; production Agent and serialization run unchanged. */+ private static final class JdbcBoundary {+ boolean autocommit = true;+ boolean closed;+ String schema = "SESSION_DEFAULT";+ String explainSchema = "AUTH_USER";+ String catalogRequester;+ int rollbacks;+ int commits;+ int openStatements;+ int openResultSets;+ int statementCount = 1;+ int operatorCount = 1;+ SQLException explainError;+ SQLException rollbackError;+ CountDownLatch explainStarted;+ CountDownLatch cancelSignal;+ int cancelCalls;+ CountDownLatch gapStarted;+ CountDownLatch gapResume;+ int nativeStatementCreations;+ final List<Boolean> autocommitChanges = new ArrayList<>();+ final List<String> executed = new ArrayList<>();+ final List<String> prepared = new ArrayList<>();+ final List<Integer> timeouts = new ArrayList<>();+ final List<String> boundTags = new ArrayList<>();++ Db2Agent agent() {+ Db2Agent agent = new Db2Agent();+ TestSupport.setPrivateConnection(agent, proxy(Connection.class, (object, method, args) -> {+ return switch (method.getName()) {+ case "isClosed" -> closed;+ case "getAutoCommit" -> autocommit;+ case "setAutoCommit" -> {+ autocommit = (Boolean) args[0];+ autocommitChanges.add(autocommit);+ yield null;+ }+ case "rollback" -> {+ rollbacks++;+ if (rollbackError != null) throw rollbackError;+ yield null;+ }+ case "commit" -> { commits++; yield null; }+ case "close" -> { closed = true; yield null; }+ case "createStatement" -> {+ nativeStatementCreations++;+ if (nativeStatementCreations == 3 && gapStarted != null) {+ gapStarted.countDown();+ if (!gapResume.await(5, TimeUnit.SECONDS)) throw new SQLException("Native gap was not released");+ }+ yield statement(null);+ }+ case "prepareStatement" -> {+ String query = (String) args[0];+ prepared.add(query);+ yield statement(query);+ }+ default -> defaultValue(method.getReturnType());+ };+ }));+ return agent;+ }++ Statement statement(String query) {+ openStatements++;+ Map<Integer, String> params = new LinkedHashMap<>();+ return proxy(PreparedStatement.class, (object, method, args) -> {+ switch (method.getName()) {+ case "setQueryTimeout": timeouts.add((Integer) args[0]); return null;+ case "setMaxRows": return null;+ case "cancel": cancelCalls++; if (cancelSignal != null) cancelSignal.countDown(); return null;+ case "setString": params.put((Integer) args[0], (String) args[1]); return null;+ case "close": openStatements--; return null;+ case "execute":+ String sql = (String) args[0];+ executed.add(sql);+ if (sql.startsWith("EXPLAIN") && explainStarted != null) {+ explainStarted.countDown();+ if (!cancelSignal.await(5, TimeUnit.SECONDS)) throw new SQLException("Native Statement was not cancelled", "HYT00");+ throw new SQLException("Native Statement cancelled", "57014", -952);+ }+ if (sql.startsWith("EXPLAIN") && explainError != null) throw explainError;+ if (sql.startsWith("SET SCHEMA")) {+ schema = sql.substring("SET SCHEMA ".length() + 1, sql.length() - 1).replace("\"\"", "\"");+ }+ return false;+ case "executeQuery":+ if (query == null) {+ executed.add((String) args[0]);+ return rows(new String[][]{{"AUTH_USER", schema}});+ }+ if (query.contains("SYSCAT.TABLES")) {+ catalogRequester = params.get(1);+ return rows(explainSchema == null ? new String[0][] : new String[][]{{explainSchema}});+ }+ boundTags.add(params.get(2));+ if (!query.contains(" r JOIN ")) {+ String[][] values = new String[statementCount][];+ Arrays.fill(values, new String[]{"AUTH_USER", "2026-10-07 01:02:03.123456", "SQLC2P31", "NULLID", "", "P", "1", "201"});+ return rows(values);+ }+ if (query.contains("\"EXPLAIN_OPERATOR\"")) {+ return rows(operatorCount == 0 ? new String[0][] :+ new String[][]{{"1", "TBSCAN", "12345678901234567890.123", "1.25", "999", "2.125"}});+ }+ if (query.contains("\"EXPLAIN_STREAM\"")) {+ return rows(new String[][]{{"0", "D", "-1", "O", "1", "200.5", "APP", "ORDERS"}});+ }+ if (query.contains("\"EXPLAIN_PREDICATE\"")) {+ return rows(new String[][]{{"1", "(Q1.NOTE = ';')", "SARG "}});+ }+ throw new AssertionError(query);+ default: return defaultValue(method.getReturnType());+ }+ });+ }++ ResultSet rows(String[][] values) {+ openResultSets++;+ int[] cursor = {-1};+ return proxy(ResultSet.class, (object, method, args) -> {+ return switch (method.getName()) {+ case "next" -> ++cursor[0] < values.length;+ case "getString" -> values[cursor[0]][(Integer) args[0] - 1];+ case "close" -> { openResultSets--; yield null; }+ default -> defaultValue(method.getReturnType());+ };+ });+ }+ }++ private static <T> T proxy(Class<T> type, InvocationHandler handler) {+ return type.cast(Proxy.newProxyInstance(type.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/apps/desktop/src/components/editor/AiAssistant.vue b/apps/desktop/src/components/editor/AiAssistant.vueindex 5e978a82ea..2497579f0b 100644--- a/apps/desktop/src/components/editor/AiAssistant.vue+++ b/apps/desktop/src/components/editor/AiAssistant.vue@@ -221,7 +221,7 @@ import { normalizeSqliteNamespace } from "@/lib/database/sqliteNamespace";import { isQueryExecutionErrorResult } from "@/lib/query/queryResultError";import { isSchemaAware, isSingleDatabase } from "@/lib/database/databaseCapabilities";import ExplainPlanViewer from "@/components/explain/ExplainPlanViewer.vue";-import { parseExplainResult, parseOracleExplainText, type ParsedExplainPlan } from "@/lib/diagram/explainPlan";+import { parseExplainResult, parseOracleExplainText, parseDb2ExplainText, type ParsedExplainPlan } from "@/lib/diagram/explainPlan";import { copyToClipboard } from "@/lib/common/clipboard";import { AI_TABLE_MENTION_CANDIDATE_LIMIT, AI_TABLE_MENTION_SCHEMA_LIMIT, filterAiTableMentionCandidates, formatAiTableMention, parseAiTableMentions, type AiTableMention } from "@/lib/ai/aiTableMentions";import { handleAiTableReferenceDropEvent } from "@/lib/ai/aiTableReferenceDrop";@@ -2565,6 +2565,13 @@ function extractExplainData(result: unknown): unknown | undefined {/** Parse explain_data (a serialized QueryResult) into ParsedExplainPlan */function parseExplainFromData(explainData: unknown, dbType: string): ParsedExplainPlan | undefined {+ if (dbType === "db2" && typeof explainData === "string") {+ try {+ return parseDb2ExplainText(explainData);+ } catch {+ return undefined;+ }+ }if (dbType === "oracle" && typeof explainData === "string") {return parseOracleExplainText(explainData);}diff --git a/apps/desktop/src/components/explain/ExplainPlanViewer.vue b/apps/desktop/src/components/explain/ExplainPlanViewer.vueindex 7d5a5e6384..946be67cdb 100644--- a/apps/desktop/src/components/explain/ExplainPlanViewer.vue+++ b/apps/desktop/src/components/explain/ExplainPlanViewer.vue@@ -129,7 +129,7 @@ const rawContent = computed(() => {});const isRawString = computed(() => typeof props.plan?.raw === "string");-const rawFormatLabel = computed(() => (props.plan?.databaseType === "sqlserver" ? "XML" : isRawString.value ? "TEXT" : "JSON"));+const rawFormatLabel = computed(() => (props.plan?.databaseType === "sqlserver" ? "XML" : props.plan?.databaseType === "db2" ? "JSON" : isRawString.value ? "TEXT" : "JSON"));const nodeCount = computed(() => (props.plan ? flattenExplainPlanNodes(props.plan.nodes).length : 0));// Measured rows exist only when the plan was produced by a mode that ran the query:// EXPLAIN ANALYZE on Postgres, SET STATISTICS XML on SQL Server.@@ -221,7 +221,7 @@ function tableCellText(value: unknown): string {{{ t("explain.summary") }}</Button><Button v-if="plan" size="sm" :variant="activeView === 'raw' ? 'secondary' : 'ghost'" class="h-6 px-2 text-xs gap-1" @click="selectView('raw')">- <FileText v-if="isRawString" class="h-3.5 w-3.5" />+ <FileText v-if="rawFormatLabel !== 'JSON'" class="h-3.5 w-3.5" /><Braces v-else class="h-3.5 w-3.5" />{{ rawFormatLabel }}</Button>diff --git a/apps/desktop/src/components/explain/__tests__/ExplainPlanViewer.db2.spec.ts b/apps/desktop/src/components/explain/__tests__/ExplainPlanViewer.db2.spec.tsnew file mode 100644index 0000000000..32e2f0c1aa--- /dev/null+++ b/apps/desktop/src/components/explain/__tests__/ExplainPlanViewer.db2.spec.ts@@ -0,0 +1,65 @@+// @vitest-environment happy-dom+import { afterEach, describe, expect, it, vi } from "vitest";+import { createApp, defineComponent, h, nextTick, type App } from "vue";+import { createI18n } from "vue-i18n";+import en from "@/i18n/locales/en";+import { parseDb2ExplainText } from "@/lib/diagram/explainPlan";+import ExplainPlanViewer from "@/components/explain/ExplainPlanViewer.vue";++vi.mock("@/components/redis/RedisJsonEditor.vue", () => ({+ default: defineComponent({+ props: { modelValue: { type: String, required: true }, readOnly: Boolean },+ setup: (props) => () => h("div", { "data-testid": "json-editor", "data-read-only": String(props.readOnly) }, props.modelValue),+ }),+}));++let app: App | undefined;+afterEach(() => {+ app?.unmount();+ app = undefined;+ document.body.innerHTML = "";+});++const raw = JSON.stringify(+ {+ version: 1,+ databaseType: "db2",+ requestTag: "dbx8834test",+ operators: [+ { id: "1", type: "RETURN", totalCost: "0.75" },+ { id: "2", type: "TBSCAN", totalCost: "0.5" },+ ],+ streams: [+ { id: "1", sourceType: "O", sourceId: "2", targetType: "O", targetId: "1", rowCount: "12" },+ { id: "2", sourceType: "D", sourceId: "-1", targetType: "O", targetId: "2", objectSchema: "APP_A", objectName: "ORDERS" },+ ],+ predicates: [{ operatorId: "2", text: "ID > 1" }],+ },+ null,+ 2,+);++describe("DB2 explain viewer", () => {+ it.each(["canvas", "tree", "summary", "raw"] as const)("displays the %s view with timerons and no measured statistics or fake heat", async (view) => {+ const container = document.createElement("div");+ document.body.append(container);+ app = createApp(ExplainPlanViewer, { plan: parseDb2ExplainText(raw), defaultView: view });+ app.use(createI18n({ legacy: false, locale: "en", messages: { en } }));+ app.mount(container);+ await nextTick();+ expect(container.textContent).toContain("DB2");+ expect(container.textContent).toContain("JSON");+ expect(container.textContent).not.toContain("ANALYZE");+ expect(container.textContent).not.toContain("ACTUAL");+ expect(container.textContent).not.toContain("µs");+ expect(container.textContent).not.toContain(en.explain.legendHeat);+ expect(container.textContent).not.toContain(en.explain.costShare);+ if (view === "raw") {+ expect(container.textContent).toContain(raw);+ expect(container.querySelector("[data-testid='json-editor']")?.getAttribute("data-read-only")).toBe("true");+ } else {+ expect(container.textContent).toContain("APP_A.ORDERS");+ expect(container.textContent).toContain("timerons");+ }+ });+});diff --git a/apps/desktop/src/lib/__tests__/query/db2ExplainPlan.spec.ts b/apps/desktop/src/lib/__tests__/query/db2ExplainPlan.spec.tsnew file mode 100644index 0000000000..d65348733b--- /dev/null+++ b/apps/desktop/src/lib/__tests__/query/db2ExplainPlan.spec.ts@@ -0,0 +1,175 @@+import { describe, expect, it } from "vitest";+import { readFileSync } from "node:fs";+import { flattenExplainPlanNodes, parseDb2ExplainText, parseExplainResult, supportsExplainPlan } from "@/lib/diagram/explainPlan";+import { buildPlanCanvas, categorizePlanNode } from "@/lib/diagram/planCanvas";+import { explainPlanExportRows } from "@/lib/export/explainPlanExport";++const base = () => ({+ version: 1,+ databaseType: "db2",+ requestTag: "dbx8834test",+ operators: [+ { id: "1", type: "RETURN", totalCost: "12.34567890123456789" },+ { id: "2", type: "HSJOIN", totalCost: "12" },+ { id: "3", type: "TBSCAN", totalCost: "0" },+ { id: "4", type: "FETCH" },+ { id: "5", type: "IXSCAN", ioCost: "1.5", cpuCost: "0.25", firstRowCost: "0.5" },+ ],+ streams: [+ { id: "1", sourceType: "O", sourceId: "2", targetType: "O", targetId: "1", rowCount: "2.25" },+ { id: "2", sourceType: "O", sourceId: "3", targetType: "O", targetId: "2", rowCount: "9007199254740993" },+ { id: "3", sourceType: "O", sourceId: "4", targetType: "O", targetId: "2", rowCount: "10" },+ { id: "4", sourceType: "O", sourceId: "5", targetType: "O", targetId: "4", rowCount: "10" },+ { id: "5", sourceType: "D", sourceId: "-1", targetType: "O", targetId: "3", objectSchema: "APP_A", objectName: "ORDERS" },+ { id: "6", sourceType: "D", sourceId: "-1", targetType: "O", targetId: "5", objectSchema: "APP_A", objectName: "CUSTOMERS_IDX" },+ ],+ predicates: [{ operatorId: "2", text: '"O"."CUSTOMER_ID" = "C"."ID"', howApplied: "JOIN" }],+ arguments: [{ operatorId: "5", type: "SCAN_DIRECTION", value: "FORWARD" }],+});++function edge(id: string, sourceId: string, targetId: string) {+ return { id, sourceType: "O", sourceId, targetType: "O", targetId };+}++describe("DB2 native explain plans", () => {+ it("enables the registered capability", () => {+ expect(supportsExplainPlan("db2")).toBe(true);+ });++ it("builds the consumer hierarchy, attaches objects, and preserves decimal/bigint estimates", () => {+ const raw = JSON.stringify(base(), null, 2);+ const plan = parseDb2ExplainText(raw);+ expect(plan.raw).toBe(raw);+ expect(plan.nodes).toHaveLength(1);+ expect(plan.nodes[0]).toMatchObject({ id: "db2-operator-1", nodeType: "RETURN", cost: "12.34567890123456789 timerons", costModel: "unknown" });+ expect(plan.nodes[0].rows).toBeUndefined();+ const join = plan.nodes[0].children[0];+ expect(join.nodeType).toBe("HSJOIN");+ expect(join.rows).toBe("2.25");+ expect(join.details).toContain('Predicate (JOIN): "O"."CUSTOMER_ID" = "C"."ID"');+ expect(join.children.map((node) => node.nodeType)).toEqual(["TBSCAN", "FETCH"]);+ expect(join.children[0]).toMatchObject({ relation: "APP_A.ORDERS", rows: "9007199254740993", cost: "0 timerons" });+ expect(join.children[1].children[0]).toMatchObject({ index: "APP_A.CUSTOMERS_IDX", details: ["I/O Cost: 1.5 page I/Os", "CPU Cost: 0.25 instructions", "First Row Cost: 0.5 timerons", "Object: APP_A.CUSTOMERS_IDX", "SCAN_DIRECTION: FORWARD"] });+ expect(flattenExplainPlanNodes(plan.nodes).every((node) => node.estimatedTimeUs === undefined)).toBe(true);+ });++ it("parses a real DB2 LUW 11.5.9 Agent plan with a shared TEMP input", () => {+ const raw = readFileSync(new URL("./fixtures/db2-shared-temp-plan.json", import.meta.url), "utf8");+ const plan = parseDb2ExplainText(raw);+ const join = plan.nodes[0].children[0];+ expect(plan.raw).toBe(raw);+ expect(plan.nodes[0].nodeType).toBe("RETURN");+ expect(join).toMatchObject({ nodeType: "MSJOIN", rows: "0.0015999999595806003" });+ expect(join.children.map((node) => node.id)).toEqual(["db2-operator-3", "db2-operator-7"]);+ expect(join.children[0].children[0]).toMatchObject({ id: "db2-operator-4", nodeType: "TEMP", rows: "1.0" });+ expect(join.children[0].children[0].children[0]).toMatchObject({ nodeType: "TBSCAN", relation: "SYSIBM.GENROW", cost: "1.1336263924022205E-5 timerons" });+ expect(join.children[1].children[0]).toMatchObject({ id: "db2-reference-5", nodeType: "TEMP", children: [] });+ expect(join.details).toContain("CPU Cost: 94451.4375 instructions");+ expect(flattenExplainPlanNodes(plan.nodes)).toHaveLength(7);+ expect(buildPlanCanvas(plan.nodes).nodes.every((node) => node.costShare === undefined)).toBe(true);+ });++ it("preserves whitespace and punctuation in quoted object identifiers", () => {+ const payload = base();+ payload.streams[4].objectSchema = " Odd Schema ";+ payload.streams[4].objectName = ' Orders"Archive ';+ const plan = parseDb2ExplainText(JSON.stringify(payload));+ expect(plan.nodes[0].children[0].children[0].relation).toBe(' Odd Schema . Orders"Archive ');+ });++ it("uses the same native parser for serialized QueryResult entry points", () => {+ const raw = JSON.stringify(base());+ expect(parseExplainResult("db2", { columns: ["plan"], rows: [[raw]], affected_rows: 0, execution_time_ms: 0 }).raw).toBe(raw);+ });++ it("projects a shared subtree once and keeps disconnected roots and unknown operators", () => {+ const payload = {+ ...base(),+ operators: [+ { id: "1", type: "RETURN" },+ { id: "2", type: "RETURN" },+ { id: "3", type: "CUSTOM_OPERATOR" },+ { id: "4", type: "TBSCAN" },+ ],+ streams: [edge("a", "3", "1"), edge("b", "3", "2"), edge("c", "4", "3")],+ predicates: [],+ arguments: [],+ };+ const plan = parseDb2ExplainText(JSON.stringify(payload));+ expect(plan.nodes).toHaveLength(2);+ expect(plan.nodes[0].children[0].children).toHaveLength(1);+ expect(plan.nodes[1].children[0]).toMatchObject({ id: "db2-reference-b", nodeType: "CUSTOM_OPERATOR", children: [] });+ expect(plan.nodes[1].children[0].details).toContain("Reference to operator 3");+ expect(new Set(flattenExplainPlanNodes(plan.nodes).map((node) => node.id)).size).toBe(5);+ });++ it("does not invent estimates for malformed numbers or conflicting output streams", () => {+ const payload = base();+ payload.operators[0].totalCost = "N/A";+ payload.streams[0].rowCount = "NaN";+ payload.streams.push({ ...payload.streams[1], id: "7", rowCount: "1" });+ const plan = parseDb2ExplainText(JSON.stringify(payload));+ expect(plan.nodes[0].cost).toBeUndefined();+ expect(plan.nodes[0].children[0].rows).toBeUndefined();+ expect(plan.nodes[0].children[0].children[0].rows).toBeUndefined();+ expect(plan.nodes[0].children[0].children).toHaveLength(2);+ });++ it("accepts an operator-only plan without fabricating rows or time", () => {+ const plan = parseDb2ExplainText(JSON.stringify({ ...base(), operators: [{ id: "999999999999999999", type: "UNKNOWN" }], streams: [], predicates: [], arguments: [] }));+ expect(plan.nodes[0]).toMatchObject({ id: "db2-operator-999999999999999999", nodeType: "UNKNOWN", cost: undefined, children: [] });+ expect(plan.nodes[0].rows).toBeUndefined();+ });++ it("reuses canvas categories and exports costs with their units without fake heat", () => {+ const plan = parseDb2ExplainText(JSON.stringify(base()));+ const canvas = buildPlanCanvas(plan.nodes);+ expect(canvas.nodes.map((node) => node.category)).toEqual(["result", "join", "tscan", "lookup", "iscan"]);+ expect(canvas.nodes.every((node) => node.costShare === undefined && node.actualRows === undefined)).toBe(true);+ expect(explainPlanExportRows(plan.nodes, "Estimated time")[0][3]).toBe("12.34567890123456789 timerons");+ for (const [operator, category] of [+ ["NLJOIN", "join"],+ ["MSJOIN", "join"],+ ["SORT", "sort"],+ ["GRPBY", "agg"],+ ["TEMP", "mat"],+ ["TQUEUE", "xchg"],+ ])+ expect(categorizePlanNode(operator, "db2")).toBe(category);+ });++ it.each(["", "[]", "not JSON", "null"])("rejects invalid plan %s", (raw) => {+ expect(() => parseDb2ExplainText(raw)).toThrow("DB2 EXPLAIN:");+ });++ it.each([+ [{ version: 2 }, "unsupported plan version"],+ [{ databaseType: "mysql" }, "invalid database type"],+ [{ requestTag: "" }, "request tag"],+ [{ operators: [] }, "no plan operators"],+ [+ {+ operators: [+ { id: "1", type: "RETURN" },+ { id: "1", type: "TBSCAN" },+ ],+ },+ "duplicate operator",+ ],+ [{ operators: [{ type: "RETURN" }] }, "operator ID"],+ [{ streams: [edge("1", "missing", "1")] }, "dangling operator"],+ [{ streams: [edge("1", "2", "1"), edge("1", "3", "1")] }, "duplicate stream"],+ [{ streams: [edge("1", "2", "1"), edge("2", "1", "2")] }, "cycle"],+ [{ streams: [edge("1", "4", "3"), edge("2", "3", "4")] }, "cycle"],+ [{ predicates: [{ operatorId: "missing", text: "ID = 1" }] }, "dangling operator"],+ ])("rejects malformed graph %j", (override, message) => {+ expect(() => parseDb2ExplainText(JSON.stringify({ ...base(), ...override }))).toThrow(message);+ });++ it("bounds depth and operator count before the viewer recurses", () => {+ const operators = Array.from({ length: 130 }, (_, id) => ({ id: String(id), type: "SORT" }));+ const streams = operators.slice(1).map((operator, index) => edge(String(index), operator.id, String(index)));+ expect(() => parseDb2ExplainText(JSON.stringify({ ...base(), operators, streams, predicates: [], arguments: [] }))).toThrow("supported depth");+ expect(() => parseDb2ExplainText(JSON.stringify({ ...base(), operators: Array.from({ length: 2001 }, (_, id) => ({ id: String(id), type: "TBSCAN" })) }))).toThrow("supported size");+ });+});diff --git a/apps/desktop/src/lib/__tests__/query/fixtures/README.md b/apps/desktop/src/lib/__tests__/query/fixtures/README.mdnew file mode 100644index 0000000000..0a9c1697da--- /dev/null+++ b/apps/desktop/src/lib/__tests__/query/fixtures/README.md@@ -0,0 +1,5 @@+# DB2 estimated-plan fixture++`db2-shared-temp-plan.json` was captured from the production DB2 Java Agent against DB2 LUW 11.5.9 / JCC 4.33.31. It preserves native operator, stream and cost metadata, including a TEMP operator with two consumers. It contains no connection credentials.++The parser test verifies the full subtree appears once and the second consumer is represented by a reference leaf. Generated request tags and timestamps are incidental to the assertions.diff --git a/apps/desktop/src/lib/__tests__/query/fixtures/db2-shared-temp-plan.json b/apps/desktop/src/lib/__tests__/query/fixtures/db2-shared-temp-plan.jsonnew file mode 100644index 0000000000..d2e0809533--- /dev/null+++ b/apps/desktop/src/lib/__tests__/query/fixtures/db2-shared-temp-plan.json@@ -0,0 +1 @@+{"version":1,"databaseType":"db2","requestTag":"b7bf8356081d4747bfbc","statement":{"EXPLAIN_REQUESTER":"DB2INST1","EXPLAIN_TIME":"2026-10-07 04:37:45.949301","SOURCE_NAME":"SYSSH200","SOURCE_SCHEMA":"NULLID ","SOURCE_VERSION":"","EXPLAIN_LEVEL":"P","STMTNO":"1","SECTNO":"65"},"operators":[{"id":"1","type":"RETURN","totalCost":"0.008922720327973366","ioCost":"0.0","cpuCost":"94451.4375","firstRowCost":"0.008922720327973366"},{"id":"2","type":"MSJOIN","totalCost":"0.008922720327973366","ioCost":"0.0","cpuCost":"94451.4375","firstRowCost":"0.008922720327973366"},{"id":"3","type":"TBSCAN","totalCost":"0.004459591582417488","ioCost":"0.0","cpuCost":"47207.0","firstRowCost":"0.004459591582417488"},{"id":"4","type":"TEMP","totalCost":"0.001205895096063614","ioCost":"0.0","cpuCost":"12765.0","firstRowCost":"0.001205895096063614"},{"id":"5","type":"TBSCAN","totalCost":"1.1336263924022205E-5","ioCost":"0.0","cpuCost":"120.0","firstRowCost":"8.502198397764005E-6"},{"id":"7","type":"TBSCAN","totalCost":"0.004459591582417488","ioCost":"0.0","cpuCost":"47207.0","firstRowCost":"0.004459591582417488"}],"streams":[{"id":"1","sourceType":"D","sourceId":"-1","targetType":"O","targetId":"5","rowCount":"1.0","objectSchema":"SYSIBM","objectName":"GENROW"},{"id":"2","sourceType":"O","sourceId":"5","targetType":"O","targetId":"4","rowCount":"1.0"},{"id":"3","sourceType":"O","sourceId":"4","targetType":"O","targetId":"3","rowCount":"1.0"},{"id":"4","sourceType":"O","sourceId":"3","targetType":"O","targetId":"2","rowCount":"0.03999999910593033"},{"id":"5","sourceType":"O","sourceId":"4","targetType":"O","targetId":"7","rowCount":"1.0"},{"id":"6","sourceType":"O","sourceId":"7","targetType":"O","targetId":"2","rowCount":"0.03999999910593033"},{"id":"7","sourceType":"O","sourceId":"2","targetType":"O","targetId":"1","rowCount":"0.0015999999595806003"}],"predicates":[{"operatorId":"2","text":"(Q2.$C0 \u003d Q3.$C0)","howApplied":"JOIN"},{"operatorId":"3","text":"(Q2.$C0 \u003d \u0027Y\u0027)","howApplied":"SARG"},{"operatorId":"7","text":"(Q3.$C0 \u003d \u0027Y\u0027)","howApplied":"SARG"}]}\ No newline at end of filediff --git a/apps/desktop/src/lib/backend/__tests__/getExplainInfo.spec.ts b/apps/desktop/src/lib/backend/__tests__/getExplainInfo.spec.tsindex 79419dddd6..c3987e29a5 100644--- a/apps/desktop/src/lib/backend/__tests__/getExplainInfo.spec.ts+++ b/apps/desktop/src/lib/backend/__tests__/getExplainInfo.spec.ts@@ -39,3 +39,48 @@ describe("getExplainInfo backend error propagation", () => {await expect(getExplainInfo("oracle-1", "ORCL", "APP", "SELECT * FROM DUAL", "explain")).rejects.toThrow("Agent error: PLAN_TABLE is not accessible");});});++describe("native explain cancellation transport", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ vi.unstubAllGlobals();+ });++ it("passes an execution ID to the Tauri backend while preserving legacy arguments", async () => {+ mocks.invoke.mockResolvedValue("{}");+ const { getExplainInfo } = await import("@/lib/backend/tauri");+ await getExplainInfo("db2-1", "DBX8834", "APP_A", "SELECT 1", "explain", "execution-1");+ expect(mocks.invoke).toHaveBeenLastCalledWith("get_explain_info", { connectionId: "db2-1", database: "DBX8834", schema: "APP_A", sql: "SELECT 1", mode: "explain", executionId: "execution-1" });+ await getExplainInfo("oracle-1", "ORCL", "APP", "SELECT 1", "explain");+ expect(mocks.invoke).toHaveBeenLastCalledWith("get_explain_info", { connectionId: "oracle-1", database: "ORCL", schema: "APP", sql: "SELECT 1", mode: "explain" });+ });++ it("passes an execution ID through the HTTP adapter", async () => {+ const fetch = vi.fn().mockResolvedValue({ ok: true, json: vi.fn().mockResolvedValue("{}") });+ vi.stubGlobal("fetch", fetch);+ const { getExplainInfo } = await import("@/lib/backend/http");+ await getExplainInfo("db2-1", "DBX8834", "APP_A", "SELECT 1", "explain", "execution-2");+ expect(JSON.parse(fetch.mock.calls[0][1].body)).toEqual({ connectionId: "db2-1", database: "DBX8834", schema: "APP_A", sql: "SELECT 1", mode: "explain", executionId: "execution-2" });+ await getExplainInfo("oracle-1", "ORCL", "APP", "SELECT 1", "explain");+ expect(JSON.parse(fetch.mock.calls[1][1].body)).not.toHaveProperty("executionId");+ });+});++describe("native explain timeout transport", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ vi.unstubAllGlobals();+ });++ it.each([7, 0])("passes the %s-second override through both adapters, including unlimited", async (timeoutSecs) => {+ mocks.invoke.mockResolvedValue("{}");+ const { getExplainInfo: tauriExplain } = await import("@/lib/backend/tauri");+ await tauriExplain("db2-1", "DBX8834", "APP_A", "SELECT 1", "explain", "execution-1", timeoutSecs);+ expect(mocks.invoke).toHaveBeenLastCalledWith("get_explain_info", { connectionId: "db2-1", database: "DBX8834", schema: "APP_A", sql: "SELECT 1", mode: "explain", executionId: "execution-1", timeoutSecs });+ const fetch = vi.fn().mockResolvedValue({ ok: true, json: vi.fn().mockResolvedValue("{}") });+ vi.stubGlobal("fetch", fetch);+ const { getExplainInfo: httpExplain } = await import("@/lib/backend/http");+ await httpExplain("db2-1", "DBX8834", "APP_A", "SELECT 1", "explain", "execution-2", timeoutSecs);+ expect(JSON.parse(fetch.mock.calls[0][1].body)).toEqual({ connectionId: "db2-1", database: "DBX8834", schema: "APP_A", sql: "SELECT 1", mode: "explain", executionId: "execution-2", timeoutSecs });+ });+});diff --git a/apps/desktop/src/lib/backend/http.ts b/apps/desktop/src/lib/backend/http.tsindex c9fd4bc12d..3d937c3ad9 100644--- a/apps/desktop/src/lib/backend/http.ts+++ b/apps/desktop/src/lib/backend/http.ts@@ -1724,7 +1724,7 @@ export async function buildCreateUserSql(username: string, password: string, tab});}-export async function getExplainInfo(connectionId: string, database: string | undefined, schema: string | undefined, sql: string, mode: string): Promise<string | undefined> {+export async function getExplainInfo(connectionId: string, database: string | undefined, schema: string | undefined, sql: string, mode: string, executionId?: string, timeoutSecs?: number): Promise<string | undefined> {// Match the Tauri path: transport and Agent failures must remain distinguishable from an empty plan.return post<string>("/api/query/get-explain-info", {connectionId,@@ -1732,6 +1732,8 @@ export async function getExplainInfo(connectionId: string, database: string | unschema,sql,mode,+ ...(executionId ? { executionId } : {}),+ ...(timeoutSecs === undefined ? {} : { timeoutSecs }),});}diff --git a/apps/desktop/src/lib/backend/tauri.ts b/apps/desktop/src/lib/backend/tauri.tsindex bf5861cbb8..09cd646d5a 100644--- a/apps/desktop/src/lib/backend/tauri.ts+++ b/apps/desktop/src/lib/backend/tauri.ts@@ -2141,7 +2141,7 @@ export async function buildCreateUserSql(username: string, password: string, tabreturn invoke("build_create_user_sql", { username, password, tablespace });}-export async function getExplainInfo(connectionId: string, database: string | undefined, schema: string | undefined, sql: string, mode: string): Promise<string | undefined> {+export async function getExplainInfo(connectionId: string, database: string | undefined, schema: string | undefined, sql: string, mode: string, executionId?: string, timeoutSecs?: number): Promise<string | undefined> {// Preserve Agent/driver errors so the explain view can show the actionable cause.return invoke<string>("get_explain_info", {connectionId,@@ -2149,6 +2149,8 @@ export async function getExplainInfo(connectionId: string, database: string | unschema,sql,mode,+ ...(executionId ? { executionId } : {}),+ ...(timeoutSecs === undefined ? {} : { timeoutSecs }),});}diff --git a/apps/desktop/src/lib/diagram/__tests__/planCanvas.spec.ts b/apps/desktop/src/lib/diagram/__tests__/planCanvas.spec.tsindex 7d0f24921a..6f17d64879 100644--- a/apps/desktop/src/lib/diagram/__tests__/planCanvas.spec.ts+++ b/apps/desktop/src/lib/diagram/__tests__/planCanvas.spec.ts@@ -58,6 +58,8 @@ describe("parsePlanNumber", () => {expect(parsePlanNumber("12.34")).toBe(12.34);expect(parsePlanNumber("1,234")).toBe(1234);expect(parsePlanNumber("42000")).toBe(42000);+ expect(parsePlanNumber("1.25e+6")).toBe(1_250_000);+ expect(parsePlanNumber("2.5E-3 timerons")).toBe(0.0025);expect(parsePlanNumber("0.29..1830.12")).toBe(1830.12);});diff --git a/apps/desktop/src/lib/diagram/db2ExplainPlan.ts b/apps/desktop/src/lib/diagram/db2ExplainPlan.tsnew file mode 100644index 0000000000..78a5f34d13--- /dev/null+++ b/apps/desktop/src/lib/diagram/db2ExplainPlan.ts@@ -0,0 +1,171 @@+import type { ExplainPlanNode, ParsedExplainPlan } from "./explainPlan";++const MAX_OPERATORS = 2_000;+const MAX_STREAMS = 10_000;+const MAX_DETAILS = 10_000;+const MAX_DEPTH = 128;+const MAX_DISPLAY_NODES = 5_000;+const MAX_RAW_LENGTH = 5 * 1024 * 1024;++type RecordValue = Record<string, unknown>;+interface Operator {+ id: string;+ node: ExplainPlanNode;+ children: Array<{ id: string; streamId: string }>;+ outputRows: Set<string>;+}++function fail(message: string): never {+ throw new Error(`DB2 EXPLAIN: ${message}`);+}++function record(value: unknown, label: string): RecordValue {+ if (!value || typeof value !== "object" || Array.isArray(value)) fail(`invalid ${label}`);+ return value as RecordValue;+}++function requiredText(value: unknown, label: string): string {+ if (typeof value !== "string" || !value.trim()) fail(`missing or invalid ${label}`);+ return value.trim();+}++function optionalText(value: unknown): string | undefined {+ return typeof value === "string" && value.trim() ? value : undefined;+}++/** Keep decimal strings intact: DB2 costs/cardinalities can exceed JS precision. */+function numericText(value: unknown): string | undefined {+ const text = typeof value === "string" ? value.trim() : typeof value === "number" && Number.isFinite(value) ? String(value) : undefined;+ return text && /^\+?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?$/.test(text) ? text : undefined;+}++function records(value: unknown, label: string, limit: number, optional = false): RecordValue[] {+ if (value === undefined && optional) return [];+ if (!Array.isArray(value)) fail(`invalid ${label}`);+ if (value.length > limit) fail(`${label} exceed the supported size (${limit})`);+ return value.map((entry) => record(entry, label));+}++/** Parse the versioned JSON returned by Db2Agent.getExplainInfo(), never db2exfmt text. */+export function parseDb2ExplainText(raw: string): ParsedExplainPlan {+ if (raw.length > MAX_RAW_LENGTH) fail("plan exceeds the supported size");+ let decoded: unknown;+ try {+ decoded = JSON.parse(raw);+ } catch {+ fail("invalid JSON plan");+ }+ const payload = record(decoded, "plan");+ if (payload.version !== 1) fail(`unsupported plan version: ${String(payload.version)}`);+ if (payload.databaseType !== "db2") fail("invalid database type");+ requiredText(payload.requestTag, "request tag");++ const operators = new Map<string, Operator>();+ for (const value of records(payload.operators, "operators", MAX_OPERATORS)) {+ const id = requiredText(value.id, "operator ID");+ if (operators.has(id)) fail(`duplicate operator ID: ${id}`);+ const nodeType = requiredText(value.type, "operator type");+ const cost = numericText(value.totalCost);+ const details: string[] = [];+ for (const [field, label, unit] of [+ ["totalCost", "Total Cost", "timerons"],+ ["ioCost", "I/O Cost", "page I/Os"],+ ["cpuCost", "CPU Cost", "instructions"],+ ["firstRowCost", "First Row Cost", "timerons"],+ ] as const) {+ const number = numericText(value[field]);+ if (number !== undefined) details.push(`${label}: ${number} ${unit}`);+ }+ operators.set(id, {+ id,+ node: { id: `db2-operator-${id}`, title: nodeType, nodeType, dialect: "db2", cost: cost === undefined ? undefined : `${cost} timerons`, costModel: "unknown", details, children: [] },+ children: [],+ outputRows: new Set(),+ });+ }+ if (!operators.size) fail("no plan operators returned");++ const getOperator = (id: string): Operator => operators.get(id) ?? fail(`dangling operator reference: ${id}`);+ const hasParent = new Set<string>();+ const streamIds = new Set<string>();+ for (const value of records(payload.streams, "streams", MAX_STREAMS)) {+ const streamId = requiredText(value.id, "stream ID");+ if (streamIds.has(streamId)) fail(`duplicate stream ID: ${streamId}`);+ streamIds.add(streamId);+ const sourceType = requiredText(value.sourceType, "stream source type").toUpperCase();+ const targetType = requiredText(value.targetType, "stream target type").toUpperCase();+ const sourceId = requiredText(value.sourceId, "stream source ID");+ const targetId = requiredText(value.targetId, "stream target ID");+ const source = sourceType === "O" ? getOperator(sourceId) : undefined;+ const target = targetType === "O" ? getOperator(targetId) : undefined;+ const rowCount = numericText(value.rowCount);+ // Streams run from input to consumer: source operator is the consumer's child.+ if (source && target) {+ if (!target.children.some((child) => child.id === sourceId)) target.children.push({ id: sourceId, streamId });+ hasParent.add(sourceId);+ }+ if (source && rowCount !== undefined) source.outputRows.add(rowCount);+ // D denotes a data object (usually ID -1), never a vertex in the operator graph.+ const objectOperator = source && !target ? source : target && !source ? target : undefined;+ const objectName = optionalText(value.objectName);+ if (objectOperator && objectName) {+ const schema = optionalText(value.objectSchema);+ const name = schema ? `${schema}.${objectName}` : objectName;+ const node = objectOperator.node;+ node.details.push(`Object: ${name}`);+ if (node.nodeType.toUpperCase() === "IXSCAN") node.index ??= name;+ else node.relation ??= name;+ node.title = `${node.nodeType} on ${node.index ?? node.relation}`;+ }+ }++ for (const value of records(payload.predicates, "predicates", MAX_DETAILS, true)) {+ const operator = getOperator(requiredText(value.operatorId, "predicate operator ID"));+ const text = optionalText(value.text);+ const howApplied = optionalText(value.howApplied);+ if (text) operator.node.details.push(`Predicate${howApplied ? ` (${howApplied})` : ""}: ${text}`);+ }+ for (const value of records(payload.arguments, "arguments", MAX_DETAILS, true)) {+ const operator = getOperator(requiredText(value.operatorId, "argument operator ID"));+ const type = optionalText(value.type);+ const text = optionalText(value.value);+ if (type && text) operator.node.details.push(`${type}: ${text}`);+ }++ // Validate every component, including cycles disconnected from valid roots.+ const heights = new Map<string, number>();+ const visiting = new Set<string>();+ function validate(id: string, depth: number): number {+ if (depth > MAX_DEPTH) fail(`plan exceeds the supported depth (${MAX_DEPTH})`);+ if (visiting.has(id)) fail(`cycle involving operator: ${id}`);+ const known = heights.get(id);+ if (known !== undefined) return known;+ visiting.add(id);+ let height = 1;+ for (const child of getOperator(id).children) height = Math.max(height, 1 + validate(child.id, depth + 1));+ visiting.delete(id);+ if (height > MAX_DEPTH) fail(`plan exceeds the supported depth (${MAX_DEPTH})`);+ heights.set(id, height);+ return height;+ }+ for (const operator of operators.values()) {+ validate(operator.id, 1);+ // Multiple streams with different estimates have no single reliable cardinality.+ if (operator.outputRows.size === 1) operator.node.rows = [...operator.outputRows][0];+ }++ const displayed = new Set<string>();+ let displayCount = 0;+ function display(id: string, streamId?: string): ExplainPlanNode {+ if (++displayCount > MAX_DISPLAY_NODES) fail(`display exceeds the supported size (${MAX_DISPLAY_NODES})`);+ const operator = getOperator(id);+ if (displayed.has(id)) {+ // A DAG must not expand exponentially into the viewer's tree model.+ return { ...operator.node, id: `db2-reference-${streamId}`, title: `${operator.node.title} (reference)`, details: [...operator.node.details, `Reference to operator ${id}`], children: [] };+ }+ displayed.add(id);+ return { ...operator.node, children: operator.children.map((child) => display(child.id, child.streamId)) };+ }+ const nodes = [...operators.values()].filter((operator) => !hasParent.has(operator.id)).map((operator) => display(operator.id));+ return { databaseType: "db2", raw, nodes };+}diff --git a/apps/desktop/src/lib/diagram/explainPlan.ts b/apps/desktop/src/lib/diagram/explainPlan.tsindex fd258cbca7..45de1d0670 100644--- a/apps/desktop/src/lib/diagram/explainPlan.ts+++ b/apps/desktop/src/lib/diagram/explainPlan.ts@@ -2,6 +2,8 @@ import type { DatabaseType, QueryResult } from "@/types/database";import * as api from "@/lib/backend/api";import { supportsDatabaseFeature } from "@/lib/database/databaseDriverManifest";import { isQueryExecutionErrorResult } from "@/lib/query/queryResultError";+import { parseDb2ExplainText } from "./db2ExplainPlan";+export { parseDb2ExplainText } from "./db2ExplainPlan";import { parseXuguExplainResult } from "./xuguExplainPlan";export interface ExplainPlanNode {@@ -13,7 +15,7 @@ export interface ExplainPlanNode {relation?: string;index?: string;cost?: string;- /** Suppress derived cost shares when the engine's cost accumulation is undocumented. */+ /** Suppress derived cost shares when costs cannot be safely attributed to nodes. */costModel?: "unknown";rows?: string;width?: string;@@ -22,7 +24,7 @@ export interface ExplainPlanNode {children: ExplainPlanNode[];}-export type ExplainPlanDatabaseType = "mysql" | "postgres" | "dameng" | "questdb" | "doris" | "oracle" | "oceanbase-oracle" | "sqlserver" | "xugu";+export type ExplainPlanDatabaseType = "mysql" | "postgres" | "dameng" | "questdb" | "doris" | "oracle" | "oceanbase-oracle" | "sqlserver" | "xugu" | "db2";export interface ParsedExplainPlan {databaseType: ExplainPlanDatabaseType;@@ -37,7 +39,7 @@ export function formatExplainPlanDetails(node: ExplainPlanNode | undefined, estireturn node.estimatedTimeUs === undefined ? node.details : [`${estimatedTimeLabel}: ${node.estimatedTimeUs} µs`, ...node.details];}-const SUPPORTED_EXPLAIN_TYPES = new Set<DatabaseType>(["mysql", "postgres", "dameng", "questdb", "doris", "oracle", "oceanbase-oracle", "sqlserver", "xugu"]);+const SUPPORTED_EXPLAIN_TYPES = new Set<DatabaseType>(["mysql", "postgres", "dameng", "questdb", "doris", "oracle", "oceanbase-oracle", "sqlserver", "xugu", "db2"]);export function supportsExplainPlan(databaseType?: DatabaseType): databaseType is ExplainPlanDatabaseType {return !!databaseType && supportsDatabaseFeature(databaseType, "sqlExplain") && SUPPORTED_EXPLAIN_TYPES.has(databaseType);}@@ -48,7 +50,10 @@ export function buildExplainSql(databaseType: DatabaseType | undefined, sql: str}export function parseExplainResult(databaseType: ExplainPlanDatabaseType, result: QueryResult): ParsedExplainPlan {- if (databaseType === "xugu") {+ if (databaseType === "db2") {+ if (isQueryExecutionErrorResult(result)) throw new Error(String(result.rows[0]?.[0] ?? "DB2 EXPLAIN failed"));+ return parseDb2ExplainText(String(result.rows[0]?.[0] ?? ""));+ } else if (databaseType === "xugu") {return parseXuguExplainResult(result);} else if (databaseType === "dameng") {return parseDamengExplain(result);diff --git a/apps/desktop/src/lib/diagram/planCanvas.ts b/apps/desktop/src/lib/diagram/planCanvas.tsindex b441fbec18..1212e40396 100644--- a/apps/desktop/src/lib/diagram/planCanvas.ts+++ b/apps/desktop/src/lib/diagram/planCanvas.ts@@ -35,6 +35,20 @@ const XUGU_CATEGORY_RULES: Array<[RegExp, PlanCanvasCategory]> = [[/^(?:hashgroup|sortgroup)$/, "agg"],];+const DB2_CATEGORIES: Record<string, PlanCanvasCategory> = {+ return: "result",+ tbscan: "tscan",+ ixscan: "iscan",+ fetch: "lookup",+ nljoin: "join",+ hsjoin: "join",+ msjoin: "join",+ sort: "sort",+ grpby: "agg",+ temp: "mat",+ tqueue: "xchg",+};+const CATEGORY_RULES: Array<[RegExp, PlanCanvasCategory]> = [// MySQL access types are single ambiguous words, so they only match exactly.[/^(?:eq_ref|const|system)$/, "lookup"],@@ -56,6 +70,7 @@ const CATEGORY_RULES: Array<[RegExp, PlanCanvasCategory]> = [export function categorizePlanNode(nodeType: string, dialect?: ExplainPlanDatabaseType): PlanCanvasCategory {const normalized = nodeType.trim().toLowerCase();if (!normalized) return "other";+ if (dialect === "db2" && Object.prototype.hasOwnProperty.call(DB2_CATEGORIES, normalized)) return DB2_CATEGORIES[normalized];if (dialect === "xugu") {for (const [pattern, category] of XUGU_CATEGORY_RULES) {if (pattern.test(normalized)) return category;@@ -77,7 +92,7 @@ export function parsePlanNumber(value?: string): number | undefined {const rangeIndex = text.lastIndexOf("..");if (rangeIndex >= 0) text = text.slice(rangeIndex + 2).trim();- const match = text.match(/^([+-]?[\d,]*\.?\d+)\s*(?:([kmgt])\b)?/i);+ const match = text.match(/^([+-]?[\d,]*\.?\d+(?:[eE][+-]?\d+)?)\s*(?:([kmgt])\b)?/i);if (!match) return undefined;const base = Number(match[1].replaceAll(",", ""));if (!Number.isFinite(base)) return undefined;diff --git a/apps/desktop/src/stores/__tests__/queryStore.db2Explain.spec.ts b/apps/desktop/src/stores/__tests__/queryStore.db2Explain.spec.tsnew file mode 100644index 0000000000..af83d10dc4--- /dev/null+++ b/apps/desktop/src/stores/__tests__/queryStore.db2Explain.spec.ts@@ -0,0 +1,255 @@+import { createPinia, setActivePinia } from "pinia";+import { beforeEach, describe, expect, it, vi } from "vitest";++const mocks = vi.hoisted(() => ({+ buildExplainSql: vi.fn(),+ getExplainInfo: vi.fn(),+ executeQuery: vi.fn(),+ saveOpenTabsState: vi.fn(),+ getConfig: vi.fn(),+ closeClientSession: vi.fn(),+ cancelQuery: vi.fn(),+ editorSettings: { pageSize: 100, openTabsRestoreMode: "all", confirmUnsavedSqlClose: false, globalQueryTimeoutSecs: 60 },+}));+vi.mock("@/lib/diagram/explainPlan", async (importOriginal) => ({ ...(await importOriginal<typeof import("@/lib/diagram/explainPlan")>()), buildExplainSql: mocks.buildExplainSql }));+vi.mock("@/lib/backend/api", () => ({ getExplainInfo: mocks.getExplainInfo, executeQuery: mocks.executeQuery, saveOpenTabsState: mocks.saveOpenTabsState, closeClientConnectionSession: mocks.closeClientSession, cancelQuery: mocks.cancelQuery }));+vi.mock("@/stores/connectionStore", () => ({ useConnectionStore: () => ({ getConfig: mocks.getConfig, recordConnectionLostError: vi.fn() }) }));+vi.mock("@/stores/settingsStore", () => ({ useSettingsStore: () => ({ editorSettings: mocks.editorSettings }) }));++const SQL = "SELECT * FROM ORDERS";+const EXPLAIN = `EXPLAIN PLAN FOR ${SQL}`;+function plan(type = "RETURN") {+ return JSON.stringify({ version: 1, databaseType: "db2", requestTag: "dbx8834test", operators: [{ id: "1", type, totalCost: "0.5" }], streams: [], predicates: [] });+}+function deferred<T>() {+ let resolve!: (value: T) => void;+ let reject!: (value: unknown) => void;+ const promise = new Promise<T>((success, failure) => {+ resolve = success;+ reject = failure;+ });+ return { promise, resolve, reject };+}+async function setup() {+ const { useQueryStore } = await import("@/stores/queryStore");+ const store = useQueryStore();+ const id = store.createTab("db2-1", "DBX8834", "Query", "query", "APP_A");+ return { store, id };+}++describe("queryStore DB2 native EXPLAIN", () => {+ beforeEach(() => {+ vi.resetAllMocks();+ mocks.editorSettings.globalQueryTimeoutSecs = 60;+ vi.unstubAllGlobals();+ 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());+ mocks.getConfig.mockReturnValue({ id: "db2-1", name: "DB2", db_type: "db2", query_timeout_secs: 30 });+ mocks.buildExplainSql.mockResolvedValue({ ok: true, sql: EXPLAIN });+ mocks.getExplainInfo.mockResolvedValue(plan());+ mocks.saveOpenTabsState.mockResolvedValue(undefined);+ mocks.closeClientSession.mockResolvedValue(undefined);+ mocks.cancelQuery.mockResolvedValue(true);+ });++ it("validates SQL and uses native JSON with the selected database/schema", async () => {+ const { store, id } = await setup();+ await store.explainTabSql(id, SQL, "db2", "autotrace");+ expect(mocks.buildExplainSql).toHaveBeenCalledWith("db2", SQL);+ expect(mocks.getExplainInfo).toHaveBeenCalledWith("db2-1", "DBX8834", "APP_A", SQL, "explain", expect.any(String), 30);+ expect(mocks.executeQuery).not.toHaveBeenCalled();+ expect(store.tabs[0]).toMatchObject({ isExplaining: false, explainError: undefined, explainSql: EXPLAIN, explainPlan: { databaseType: "db2", raw: plan(), nodes: [{ nodeType: "RETURN", cost: "0.5 timerons", costModel: "unknown" }] } });+ });++ it.each([7, 0])("forwards the inherited editor timeout of %s seconds to native explain", async (timeoutSecs) => {+ mocks.editorSettings.globalQueryTimeoutSecs = timeoutSecs;+ mocks.getConfig.mockReturnValue({ id: "db2-1", name: "DB2", db_type: "db2", query_timeout_secs: 30, query_timeout_inherit: true });+ const { store, id } = await setup();+ await store.explainTabSql(id, SQL, "db2");+ expect(mocks.getExplainInfo).toHaveBeenCalledWith("db2-1", "DBX8834", "APP_A", SQL, "explain", expect.any(String), timeoutSecs);+ });++ it("keeps an explicit connection timeout when the editor timeout differs", async () => {+ mocks.editorSettings.globalQueryTimeoutSecs = 7;+ const { store, id } = await setup();+ await store.explainTabSql(id, SQL, "db2");+ expect(mocks.getExplainInfo.mock.calls[0][6]).toBe(30);+ });++ it("keeps the query result and business session state intact", async () => {+ const { store, id } = await setup();+ const tab = store.tabs[0];+ tab.result = { columns: ["ID"], rows: [[42]], affected_rows: 0, execution_time_ms: 0 };+ tab.txnSessionId = "active-business-transaction";+ await store.explainTabSql(id, SQL, "db2");+ expect(tab.result?.rows).toEqual([[42]]);+ expect(tab.txnSessionId).toBe("active-business-transaction");+ expect(tab.schema).toBe("APP_A");+ expect(mocks.closeClientSession).not.toHaveBeenCalled();+ });++ it("does not call the Agent for unsafe SQL", async () => {+ mocks.buildExplainSql.mockResolvedValue({ ok: false, reason: "unsafe" });+ const { store, id } = await setup();+ expect(await store.explainTabSql(id, "DELETE FROM ORDERS", "db2")).toEqual({ ok: false, reason: "unsafe" });+ expect(mocks.getExplainInfo).not.toHaveBeenCalled();+ expect(store.tabs[0]).toMatchObject({ isExplaining: false, explainError: "unsafe", explainExecutionId: undefined });+ });++ it.each(["SQLSTATE=42704: EXPLAIN tables missing; initialize with SYSINSTALLOBJECTS", "SQLCODE=-551 SQLSTATE=42501: insufficient privileges", "query timed out"])("preserves the backend diagnostic: %s", async (message) => {+ mocks.getExplainInfo.mockRejectedValue(new Error(message));+ const { store, id } = await setup();+ await store.explainTabSql(id, SQL, "db2");+ expect(store.tabs[0]).toMatchObject({ isExplaining: false, explainPlan: undefined, explainError: message });+ });++ it("resets state if SQL generation rejects", async () => {+ mocks.buildExplainSql.mockRejectedValue(new Error("SQL parser unavailable"));+ const { store, id } = await setup();+ await store.explainTabSql(id, SQL, "db2");+ expect(mocks.getExplainInfo).not.toHaveBeenCalled();+ expect(store.tabs[0]).toMatchObject({ isExplaining: false, explainExecutionId: undefined, explainError: "SQL parser unavailable" });+ });++ it.each(["", undefined])("shows the empty response error for %s", async (value) => {+ mocks.getExplainInfo.mockResolvedValue(value);+ const { store, id } = await setup();+ await store.explainTabSql(id, SQL, "db2");+ expect(store.tabs[0]).toMatchObject({ isExplaining: false, explainError: "No explain plan returned", explainPlan: undefined });+ });++ it("reports malformed native JSON instead of treating it as a MySQL plan", async () => {+ mocks.getExplainInfo.mockResolvedValue("not JSON");+ const { store, id } = await setup();+ await store.explainTabSql(id, SQL, "db2");+ expect(store.tabs[0]).toMatchObject({ isExplaining: false, explainError: "DB2 EXPLAIN: invalid JSON plan", explainPlan: undefined });+ });++ it("discards an older response and leaves the newer request loading", async () => {+ const first = deferred<string>();+ const second = deferred<string>();+ mocks.getExplainInfo.mockReturnValueOnce(first.promise).mockReturnValueOnce(second.promise);+ const { store, id } = await setup();+ const oldRequest = store.explainTabSql(id, SQL, "db2");+ await vi.waitFor(() => expect(mocks.getExplainInfo).toHaveBeenCalledTimes(1));+ const newRequest = store.explainTabSql(id, "SELECT * FROM CUSTOMERS", "db2");+ await vi.waitFor(() => expect(mocks.getExplainInfo).toHaveBeenCalledTimes(2));+ first.resolve(plan("OLD"));+ await oldRequest;+ expect(store.tabs[0]).toMatchObject({ isExplaining: true, explainPlan: undefined });+ second.resolve(plan("NEW"));+ await newRequest;+ expect(store.tabs[0].explainPlan?.nodes[0].nodeType).toBe("NEW");+ expect(store.tabs[0].isExplaining).toBe(false);+ });++ it("does not start the Agent after cancellation during SQL generation", async () => {+ const generation = deferred<{ ok: true; sql: string }>();+ mocks.buildExplainSql.mockReturnValue(generation.promise);+ const { store, id } = await setup();+ const request = store.explainTabSql(id, SQL, "db2");+ await vi.waitFor(() => expect(mocks.buildExplainSql).toHaveBeenCalledTimes(1));+ await store.cancelTabExplain(id);+ generation.resolve({ ok: true, sql: EXPLAIN });+ await request;+ expect(mocks.getExplainInfo).not.toHaveBeenCalled();+ expect(store.tabs[0].isExplaining).toBe(false);+ });++ it("uses the native request ID for cancellation and discards its later response", async () => {+ const response = deferred<string>();+ mocks.getExplainInfo.mockReturnValue(response.promise);+ const { store, id } = await setup();+ const request = store.explainTabSql(id, SQL, "db2");+ await vi.waitFor(() => expect(mocks.getExplainInfo).toHaveBeenCalledTimes(1));+ const executionId = mocks.getExplainInfo.mock.calls[0][5];+ await store.cancelTabExplain(id);+ expect(mocks.cancelQuery).toHaveBeenCalledWith(executionId);+ response.resolve(plan());+ await request;+ expect(store.tabs[0]).toMatchObject({ isExplaining: false, explainPlan: undefined });+ });++ it.each(["connection", "database", "catalog", "schema", "clear-schema"] as const)("cancels unlimited explain on %s changes without disturbing the new request", async (target) => {+ mocks.getConfig.mockReturnValue({ id: "db2-1", name: "DB2", db_type: "db2", query_timeout_secs: 0 });+ const oldResponse = deferred<string>();+ const newResponse = deferred<string>();+ const cancellation = deferred<boolean>();+ mocks.getExplainInfo.mockReturnValueOnce(oldResponse.promise).mockReturnValueOnce(newResponse.promise);+ mocks.cancelQuery.mockReturnValue(cancellation.promise);+ const { store, id } = await setup();+ const oldRequest = store.explainTabSql(id, SQL, "db2");+ await vi.waitFor(() => expect(mocks.getExplainInfo).toHaveBeenCalledTimes(1));+ const executionId = mocks.getExplainInfo.mock.calls[0][5];+ expect(mocks.getExplainInfo.mock.calls[0][6]).toBe(0);++ if (target === "connection") store.updateConnection(id, "db2-2", "SECONDDB");+ else if (target === "database") store.updateDatabase(id, "SECONDDB");+ else if (target === "catalog") store.updateCatalog(id, "SECOND_CATALOG", "DBX8834");+ else store.updateSchema(id, target === "schema" ? "APP_B" : undefined);++ expect(mocks.cancelQuery).toHaveBeenCalledExactlyOnceWith(executionId);+ expect(store.tabs[0]).toMatchObject({ isExplaining: false, explainExecutionId: undefined, explainPlan: undefined });+ const newRequest = store.explainTabSql(id, "SELECT * FROM CUSTOMERS", "db2");+ await vi.waitFor(() => expect(mocks.getExplainInfo).toHaveBeenCalledTimes(2));+ const newExecutionId = mocks.getExplainInfo.mock.calls[1][5];+ expect(newExecutionId).not.toBe(executionId);+ expect(mocks.getExplainInfo.mock.calls[1].slice(0, 3)).toEqual([store.tabs[0].connectionId, store.tabs[0].database, store.tabs[0].schema]);++ cancellation.resolve(true);+ oldResponse.resolve(plan("OLD"));+ await oldRequest;+ expect(store.tabs[0]).toMatchObject({ isExplaining: true, explainExecutionId: newExecutionId, explainPlan: undefined });+ newResponse.resolve(plan("NEW"));+ await newRequest;+ expect(store.tabs[0]).toMatchObject({ isExplaining: false, explainExecutionId: undefined });+ expect(store.tabs[0].explainPlan?.nodes[0].nodeType).toBe("NEW");+ });++ it.each(["connection", "database", "catalog", "schema"] as const)("keeps the pending explain when the %s target is unchanged", async (target) => {+ const response = deferred<string>();+ mocks.getExplainInfo.mockReturnValue(response.promise);+ const { store, id } = await setup();+ const request = store.explainTabSql(id, SQL, "db2");+ await vi.waitFor(() => expect(mocks.getExplainInfo).toHaveBeenCalledTimes(1));+ const executionId = mocks.getExplainInfo.mock.calls[0][5];+ if (target === "connection") store.updateConnection(id, "db2-1", "DBX8834");+ else if (target === "database") store.updateDatabase(id, "DBX8834");+ else if (target === "catalog") store.updateCatalog(id, undefined, "DBX8834");+ else store.updateSchema(id, "APP_A");+ expect(mocks.cancelQuery).not.toHaveBeenCalled();+ expect(store.tabs[0]).toMatchObject({ isExplaining: true, explainExecutionId: executionId });+ response.resolve(plan());+ await request;+ expect(store.tabs[0].explainPlan?.nodes[0].nodeType).toBe("RETURN");+ });++ it("does not start native explain after the target changes during SQL generation even if cancellation fails", async () => {+ const generation = deferred<{ ok: true; sql: string }>();+ mocks.buildExplainSql.mockReturnValue(generation.promise);+ mocks.cancelQuery.mockRejectedValue(new Error("cancel unavailable"));+ const { store, id } = await setup();+ const request = store.explainTabSql(id, SQL, "db2");+ await vi.waitFor(() => expect(mocks.buildExplainSql).toHaveBeenCalledTimes(1));+ const executionId = store.tabs[0].explainExecutionId;+ store.updateDatabase(id, "SECONDDB");+ expect(mocks.cancelQuery).toHaveBeenCalledExactlyOnceWith(executionId);+ generation.resolve({ ok: true, sql: EXPLAIN });+ await request;+ expect(mocks.getExplainInfo).not.toHaveBeenCalled();+ expect(store.tabs[0]).toMatchObject({ isExplaining: false, explainExecutionId: undefined, explainPlan: undefined });+ });++ it("ignores a response after the tab is closed", async () => {+ const response = deferred<string>();+ mocks.getExplainInfo.mockReturnValue(response.promise);+ const { store, id } = await setup();+ const request = store.explainTabSql(id, SQL, "db2");+ await vi.waitFor(() => expect(mocks.getExplainInfo).toHaveBeenCalledTimes(1));+ store.closeTab(id, { force: true });+ response.resolve(plan());+ await request;+ expect(store.tabs.find((tab) => tab.id === id)).toBeUndefined();+ });+});diff --git a/apps/desktop/src/stores/queryStore.ts b/apps/desktop/src/stores/queryStore.tsindex 32076ab06b..8d01f6991d 100644--- a/apps/desktop/src/stores/queryStore.ts+++ b/apps/desktop/src/stores/queryStore.ts@@ -32,7 +32,7 @@ import type {import { orderPinnedFirst } from "@/lib/app/pinnedItems";import { canCancelQueryExecution } from "@/lib/sql/queryExecutionState";import { isSqlErrorPositionDebugEnabled, logSqlErrorPosition, sqlErrorHasMessagePosition, sqlErrorMessageText } from "@/lib/sql/errorPosition";-import { buildExplainSql, parseExplainResult, parseDamengExplainText, parseOracleExplainText, sqlServerExplainResult, type BuildExplainSqlResult, type ExplainPlanDatabaseType } from "@/lib/diagram/explainPlan";+import { buildExplainSql, parseExplainResult, parseDamengExplainText, parseOracleExplainText, parseDb2ExplainText, sqlServerExplainResult, type BuildExplainSqlResult, type ExplainPlanDatabaseType } from "@/lib/diagram/explainPlan";import { mysqlExplainCompatibilityHint } from "@/lib/diagram/mysqlExplainCompatibility";import {allEditableColumnsWriteable,@@ -5763,6 +5763,7 @@ export const useQueryStore = defineStore("query", () => {function updateDatabase(id: string, database: string, options: UpdateExecutionTargetOptions = {}) {const tab = tabs.value.find((t) => t.id === id);if (!tab || tab.database === database) return;+ if (tab.isExplaining) void cancelTabExplain(id);rollbackTabTransaction(tab);void closeResultSession(tab);void closeClientConnectionSession(tab);@@ -5795,6 +5796,7 @@ export const useQueryStore = defineStore("query", () => {function updateCatalog(id: string, catalog: string | undefined, database: string, options: UpdateExecutionTargetOptions = {}) {const tab = tabs.value.find((candidate) => candidate.id === id);if (!tab || (tab.catalog === catalog && tab.database === database)) return;+ if (tab.isExplaining) void cancelTabExplain(id);rollbackTabTransaction(tab);void closeResultSession(tab);void closeClientConnectionSession(tab);@@ -5814,6 +5816,10 @@ export const useQueryStore = defineStore("query", () => {function updateSchema(id: string, schema: string | undefined, options: UpdateExecutionTargetOptions = {}) {const tab = tabs.value.find((t) => t.id === id);if (!tab || tab.schema === schema) return;+ if (tab.isExplaining) {+ void cancelTabExplain(id);+ clearExplain(tab);+ }rollbackTabTransaction(tab);const clearsQuerySchema = tab.mode === "query" && tab.schema && !schema && supportsClearableQuerySchema(useConnectionStore().getConfig(tab.connectionId)?.db_type);if (clearsQuerySchema) {@@ -5832,6 +5838,7 @@ export const useQueryStore = defineStore("query", () => {function updateConnection(id: string, connectionId: string, database = "", options: UpdateExecutionTargetOptions = {}) {const tab = tabs.value.find((t) => t.id === id);if (!tab || tab.connectionId === connectionId) return;+ if (tab.isExplaining) void cancelTabExplain(id);rollbackTabTransaction(tab, { resetAutoCommit: true, resetAutoCommitDbType: useConnectionStore().getConfig(connectionId)?.db_type });void closeResultSession(tab);void closeClientConnectionSession(tab);@@ -8603,10 +8610,52 @@ export const useQueryStore = defineStore("query", () => {await waitForTabSessionReset(id);} catch (e: any) {// Do not start an explain with a session whose schema reset did not complete.- tab.isExplaining = false;- tab.explainExecutionId = undefined;- tab.explainError = String(e?.message || e);- return { ok: false as const, reason: tab.explainError };+ const reason = String(e?.message || e);+ const current = tabs.value.find((t) => t.id === id);+ if (current?.explainExecutionId === executionId) {+ current.isExplaining = false;+ current.explainExecutionId = undefined;+ current.explainError = reason;+ }+ return { ok: false as const, reason };+ }++ // DB2 writes Explain tables on an isolated backend session and returns native JSON.+ if (databaseType === "db2") {+ if (tabs.value.find((t) => t.id === id)?.explainExecutionId !== executionId) return { ok: true as const, sql: "" };+ const { connectionId, database, schema } = tab;+ let explainSql = sql;+ try {+ const built = await buildExplainSql(databaseType, sql);+ const current = tabs.value.find((t) => t.id === id);+ if (current?.explainExecutionId !== executionId) return built;+ if (!built.ok) {+ current.explainError = built.reason;+ return built;+ }+ explainSql = built.sql;+ current.explainSql = explainSql;+ // Always request an estimate, even if an unrelated UI supplies autotrace.+ const planText = await api.getExplainInfo(connectionId, database, schema, sql, "explain", executionId, queryTimeoutSecs);+ const target = tabs.value.find((t) => t.id === id);+ if (target?.explainExecutionId === executionId) {+ if (typeof planText === "string" && planText.trim()) target.explainPlan = parseDb2ExplainText(planText);+ else target.explainError = "No explain plan returned";+ }+ } catch (error) {+ const current = tabs.value.find((t) => t.id === id);+ if (current?.explainExecutionId === executionId) {+ current.explainPlan = undefined;+ current.explainError = formatError(error);+ }+ } finally {+ const current = tabs.value.find((t) => t.id === id);+ if (current?.explainExecutionId === executionId) {+ current.isExplaining = false;+ current.explainExecutionId = undefined;+ }+ }+ return { ok: true as const, sql: explainSql };}// DM and Oracle agents expose native text plans. DM also supports autotrace.diff --git a/crates/dbx-core/assets/database-drivers.manifest.json b/crates/dbx-core/assets/database-drivers.manifest.jsonindex f2c6a9ca88..f4270c8d73 100644--- a/crates/dbx-core/assets/database-drivers.manifest.json+++ b/crates/dbx-core/assets/database-drivers.manifest.json@@ -2087,7 +2087,7 @@"sqlFileExecution": true,"databaseCreate": false,"fieldLineage": true,- "sqlExplain": false,+ "sqlExplain": true,"userAdmin": false,"driverManagement": true}diff --git a/crates/dbx-core/src/ai/agent_explain.rs b/crates/dbx-core/src/ai/agent_explain.rsindex ea287c2e61..e52cec7805 100644--- a/crates/dbx-core/src/ai/agent_explain.rs+++ b/crates/dbx-core/src/ai/agent_explain.rs@@ -19,6 +19,23 @@ pub async fn get_agent_explain_info_core(sql: &str,mode: Option<&str>,timeout_secs: Option<u64>,+) -> Result<String, String> {+ get_agent_explain_info_core_with_execution_id(state, connection_id, database, schema, sql, mode, timeout_secs, None)+ .await+}++/// DB2 estimated plans run in an isolated session, with optional UI cancellation.+/// Other dialects retain their existing native acquisition contract.+#[allow(clippy::too_many_arguments)]+pub async fn get_agent_explain_info_core_with_execution_id(+ state: &AppState,+ connection_id: &str,+ database: Option<&str>,+ schema: Option<&str>,+ sql: &str,+ mode: Option<&str>,+ timeout_secs: Option<u64>,+ execution_id: Option<&str>,) -> Result<String, String> {let mode = mode.unwrap_or("explain");let (database_type, timeout_secs) = {@@ -32,8 +49,53 @@ pub async fn get_agent_explain_info_core(return Err("unsafe".to_string());}+ if database_type == DatabaseType::Db2 && !mode.eq_ignore_ascii_case("explain") {+ return Err("DB2 supports estimated execution plans only".to_string());+ }let database_for_pool = database.filter(|value| !value.trim().is_empty());- let pool_key = state.get_or_create_pool(connection_id, database_for_pool).await?;+ let client_session_id =+ (database_type == DatabaseType::Db2).then(|| format!("db2-plan-{}:explain", uuid::Uuid::new_v4()));+ // Install before pool creation: cancellation must also reclaim a late install.+ let _cleanup_guard = match client_session_id.as_deref() {+ Some(session_id) => Some(+ state+ .workload_session_pool_cleanup_guard(connection_id, database_for_pool, session_id)+ .await+ .ok_or_else(|| "DB2 execution plans require an isolated session".to_string())?,+ ),+ None => None,+ };+ let execution_id = if database_type == DatabaseType::Db2 {+ execution_id.filter(|id| !id.trim().is_empty()).or(client_session_id.as_deref())+ } else {+ None+ };+ let registered = execution_id.map(|id| {+ state.running_queries.register_task(+ id.to_string(),+ crate::query_cancel::RunningTaskMetadata {+ kind: crate::query_cancel::RunningTaskKind::Explain,+ connection_id: Some(connection_id.to_string()),+ database: database_for_pool.map(str::to_string),+ client_session_id: client_session_id.clone(),+ ..Default::default()+ },+ )+ });+ let cancel_token = registered.as_ref().map(|registration| registration.token());+ let pool_creation =+ state.get_or_create_pool_for_session(connection_id, database_for_pool, client_session_id.as_deref());+ let pool_key = match cancel_token.as_ref() {+ Some(token) => tokio::select! {+ biased;+ _ = token.cancelled() => return Err("Query canceled".to_string()),+ result = pool_creation => result?,+ },+ None => pool_creation.await?,+ };+ if let Some(id) = execution_id {+ state.running_queries.set_pool_key(id, pool_key.clone());+ }enum ExplainTarget {Agent(std::sync::Arc<crate::db::agent_driver::PooledAgentClient>),@@ -63,7 +125,22 @@ pub async fn get_agent_explain_info_core("mode": mode,});let result: Value = match target {- ExplainTarget::Agent(client) => client.lock().await.get_explain_info(params).await?,+ ExplainTarget::Agent(client) => {+ let mut client = match cancel_token.as_ref() {+ Some(token) => tokio::select! {+ biased;+ _ = token.cancelled() => return Err("Query canceled".to_string()),+ guard = client.lock() => guard,+ },+ None => client.lock().await,+ };+ if database_type == DatabaseType::Db2 {+ let timeout = (timeout_secs > 0).then(|| Duration::from_secs(timeout_secs));+ client.get_explain_info_with_timeout_and_cancel(params, timeout, cancel_token).await?+ } else {+ client.get_explain_info(params).await?+ }+ }ExplainTarget::External { config, session } => {let mut params = params;params["connection"] = serde_json::to_value(config.as_ref()).map_err(|error| error.to_string())?;diff --git a/crates/dbx-core/src/ai/agent_tools.rs b/crates/dbx-core/src/ai/agent_tools.rsindex 395b5a9104..487bdf1511 100644--- a/crates/dbx-core/src/ai/agent_tools.rs+++ b/crates/dbx-core/src/ai/agent_tools.rs@@ -1598,7 +1598,13 @@ async fn execute_explain_query(}}- if *db_type == DatabaseType::Oracle {+ let connection_config = state.configs.read().await.get(connection_id).cloned();+ let explain_timeout_secs = agent_query_timeout_secs(+ tool_call.arguments.get("timeout_secs").and_then(Value::as_u64),+ connection_config.as_ref(),+ );++ if matches!(*db_type, DatabaseType::Oracle | DatabaseType::Db2) {return match crate::agent_explain::get_agent_explain_info_core(state,connection_id,@@ -1606,7 +1612,7 @@ async fn execute_explain_query(default_schema,sql,Some("explain"),- None,+ Some(explain_timeout_secs),).await{@@ -1632,18 +1638,9 @@ async fn execute_explain_query(}};- // Execute the EXPLAIN query. Timeout resolves like the execute path- // (per-call `timeout_secs` > connection effective timeout) so the global- // MCP timeout override covers EXPLAIN too.- let connection_config = state.configs.read().await.get(connection_id).cloned();- let options = QueryExecutionOptions {- max_rows: Some(100),- timeout_secs: Some(agent_query_timeout_secs(- tool_call.arguments.get("timeout_secs").and_then(Value::as_u64),- connection_config.as_ref(),- )),- ..Default::default()- };+ // Both native and generated plans use the per-call timeout policy.+ let options =+ QueryExecutionOptions { max_rows: Some(100), timeout_secs: Some(explain_timeout_secs), ..Default::default() };let result = match crate::query::execute_sql_statement_with_options(state,connection_id,diff --git a/crates/dbx-core/src/query/plugin_plan.rs b/crates/dbx-core/src/query/plugin_plan.rsindex 2a625ac912..31afa6dbd9 100644--- a/crates/dbx-core/src/query/plugin_plan.rs+++ b/crates/dbx-core/src/query/plugin_plan.rs@@ -771,6 +771,7 @@ mod tests {(DatabaseType::Questdb, GeneratedSql),(DatabaseType::Dameng, DriverNative),(DatabaseType::Oracle, DriverNative),+ (DatabaseType::Db2, DriverNative),(DatabaseType::OceanbaseOracle, GeneratedSql),(DatabaseType::SqlServer, SqlServerShowPlanSession),] {diff --git a/crates/dbx-driver-agent/src/agent_driver.rs b/crates/dbx-driver-agent/src/agent_driver.rsindex 0fe2d1f0b6..e5f2a32d89 100644--- a/crates/dbx-driver-agent/src/agent_driver.rs+++ b/crates/dbx-driver-agent/src/agent_driver.rs@@ -2712,6 +2712,17 @@ impl AgentDriverClient {self.call_method(AgentMethod::GetExplainInfo, params).await}+ /// Estimated-plan RPC with the same session cancellation contract as queries.+ pub async fn get_explain_info_with_timeout_and_cancel<T: DeserializeOwned + Send + 'static>(+ &mut self,+ params: Value,+ timeout_duration: Option<Duration>,+ cancel_token: Option<CancellationToken>,+ ) -> Result<T, String> {+ self.call_method_with_timeout_and_cancel(AgentMethod::GetExplainInfo, params, timeout_duration, cancel_token)+ .await+ }+pub async fn close_query_session<T: DeserializeOwned + Send + 'static>(&mut self,session_id: &str,@@ -4605,6 +4616,11 @@ def respond(req):value = cancel_countwrite_response(req, value)return+ if method == 'blocked_count':+ with state_lock:+ value = len(blocked)+ write_response(req, value)+ returnif method == 'cancel_session':session_id = params['agentSessionId']with state_lock:@@ -4617,7 +4633,7 @@ def respond(req):session_id = params.get('agentSessionId', '__legacy__')with session_lock(session_id):- if method in ('execute_query', 'start_table_read'):+ if method in ('execute_query', 'start_table_read', 'get_explain_info'):sql = params.get('sql', '')with state_lock:query_count += 1@@ -4763,6 +4779,60 @@ for line in sys.stdin:let _ = std::fs::remove_file(script_path);}+ #[tokio::test]+ async fn native_explain_timeout_and_cancel_preserve_sibling_session() {+ let (runtime, script_path) = spawn_stateful_test_runtime("native-explain-cancel-test").await;+ let mut client = AgentDriverClient::shared_session(runtime.clone(), "explain-session".to_string());+ let mut sibling = AgentDriverClient::shared_session(runtime.clone(), "editor-session".to_string());+ let error = client+ .get_explain_info_with_timeout_and_cancel::<serde_json::Value>(+ serde_json::json!({"sql": "slow-timeout-plan"}),+ Some(Duration::from_millis(75)),+ None,+ )+ .await+ .unwrap_err();+ assert!(error.contains("Agent RPC call timed out"));+ // The cancel acknowledgement can precede the old worker's exit.+ // Drain its session lock before watching the next blocked request.+ client+ .call_with_timeout::<serde_json::Value>("probe", serde_json::json!({}), Some(Duration::from_millis(500)))+ .await+ .unwrap();+ let token = CancellationToken::new();+ let task_token = token.clone();+ let task = tokio::spawn(async move {+ let result = client+ .get_explain_info_with_timeout_and_cancel::<serde_json::Value>(+ serde_json::json!({"sql": "slow-unlimited-plan"}),+ None,+ Some(task_token),+ )+ .await;+ (result, client)+ });+ tokio::time::timeout(Duration::from_secs(2), async {+ while runtime_counter(&runtime, "blocked_count").await == 0 {+ tokio::task::yield_now().await;+ }+ })+ .await+ .unwrap();+ token.cancel();+ let (result, mut client) = tokio::time::timeout(Duration::from_secs(1), task).await.unwrap().unwrap();+ let error = result.unwrap_err();+ assert!(error.contains("Query canceled"), "{error}");+ assert_eq!(runtime_counter(&runtime, "cancel_count").await, 2);+ client+ .call_with_timeout::<serde_json::Value>("probe", serde_json::json!({}), Some(Duration::from_millis(500)))+ .await+ .unwrap();+ let response: serde_json::Value = sibling.call("probe", serde_json::json!({})).await.unwrap();+ assert_eq!(response, serde_json::json!({"ok": true}));+ assert!(!runtime.is_failed());+ runtime.kill_and_wait().await;+ let _ = std::fs::remove_file(script_path);+ }#[tokio::test]async fn table_read_uses_the_supplied_rpc_timeout() {let (runtime, script_path) = spawn_stateful_test_runtime("table-read-timeout-test").await;diff --git a/crates/dbx-sql-core/src/query_execution_sql.rs b/crates/dbx-sql-core/src/query_execution_sql.rsindex 0c386aa8af..5b0693ca71 100644--- a/crates/dbx-sql-core/src/query_execution_sql.rs+++ b/crates/dbx-sql-core/src/query_execution_sql.rs@@ -1,5 +1,5 @@use serde::{Deserialize, Serialize};-use sqlparser::dialect::{MsSqlDialect, PostgreSqlDialect};+use sqlparser::dialect::{GenericDialect, MsSqlDialect, PostgreSqlDialect};use sqlparser::tokenizer::{Token, Tokenizer};use crate::models::connection::DatabaseType;@@ -85,6 +85,7 @@ enum EstimatedPlanSqlGeneration {Plain,Xugu,Oracle,+ Db2,SqlServer,Json,}@@ -127,7 +128,9 @@ pub fn build_explain_sql(options: ExplainSqlOptions) -> ExplainSqlBuildResult {if source.is_empty() {return explain_err("empty");}- if !is_safe_explain_sql_for_database(&source, options.database_type) {+ let safety_source =+ if options.database_type == Some(DatabaseType::Db2) { options.sql.as_str() } else { source.as_str() };+ if !is_safe_explain_sql_for_database(safety_source, options.database_type) {return explain_err("unsafe");}if options.database_type == Some(DatabaseType::Xugu) {@@ -159,7 +162,7 @@ pub fn build_explain_sql(options: ExplainSqlOptions) -> ExplainSqlBuildResult {EstimatedPlanSqlGeneration::Postgres => format!("EXPLAIN (FORMAT JSON) {source}"),EstimatedPlanSqlGeneration::Plain => format!("EXPLAIN {source}"),EstimatedPlanSqlGeneration::Xugu => format!("EXPLAIN VERBOSE {source}"),- EstimatedPlanSqlGeneration::Oracle => format!("EXPLAIN PLAN FOR {source}"),+ EstimatedPlanSqlGeneration::Oracle | EstimatedPlanSqlGeneration::Db2 => format!("EXPLAIN PLAN FOR {source}"),// STATISTICS XML returns the same ShowPlanXML document plus per-operator// runtime counters, at the price of actually running the statement.EstimatedPlanSqlGeneration::SqlServer if options.analyze == Some(true) => {@@ -202,9 +205,10 @@ pub fn build_dropped_file_preview_sql(options: DroppedFilePreviewSqlOptions) ->pub fn estimated_plan_strategy(database_type: Option<DatabaseType>) -> Option<EstimatedPlanStrategy> {use EstimatedPlanAcquisition::{DriverNative, GeneratedSql, SqlServerShowPlanSession};use EstimatedPlanFormat::{Json, Text, Xml};- use EstimatedPlanSqlGeneration::{Mysql, Oracle, Plain, Postgres, SqlServer, Xugu};+ use EstimatedPlanSqlGeneration::{Db2, Mysql, Oracle, Plain, Postgres, SqlServer, Xugu};let strategy = match database_type? {+ DatabaseType::Db2 => EstimatedPlanStrategy { sql_generation: Db2, acquisition: DriverNative, format: Json },DatabaseType::Mysql => EstimatedPlanStrategy { sql_generation: Mysql, acquisition: GeneratedSql, format: Json },DatabaseType::Doris => EstimatedPlanStrategy { sql_generation: Plain, acquisition: GeneratedSql, format: Text },DatabaseType::Xugu => EstimatedPlanStrategy { sql_generation: Xugu, acquisition: GeneratedSql, format: Text },@@ -251,6 +255,9 @@ pub fn is_safe_explain_sql(sql: &str) -> bool {}pub fn is_safe_explain_sql_for_database(sql: &str, database_type: Option<DatabaseType>) -> bool {+ if database_type == Some(DatabaseType::Db2) {+ return is_safe_db2_explain_sql(sql);+ }let source = strip_trailing_semicolons(sql.trim());if source.is_empty() || has_extra_statement_after_semicolon(&source) {return false;@@ -258,9 +265,33 @@ pub fn is_safe_explain_sql_for_database(sql: &str, database_type: Option<Databasif database_type == Some(DatabaseType::Oracle) && is_safe_oracle_explain_dml_source(&source) {return true;}+is_safe_explain_source(&source) && !contains_dangerous_sql_keyword(&source)}+/// Use the existing lexer so nested DB2 comments are removed before every+/// safety check; preserve literal escaping while normalizing only for validation.+fn is_safe_db2_explain_sql(sql: &str) -> bool {+ let Ok(tokens) = Tokenizer::new(&GenericDialect {}, sql).with_unescape(false).tokenize() else {+ return false;+ };+ let mut tokens: Vec<_> = tokens.into_iter().filter(|token| !matches!(token, Token::Whitespace(_))).collect();+ if tokens.last() == Some(&Token::SemiColon) {+ tokens.pop();+ }+ if tokens.iter().any(|token| matches!(token, Token::SemiColon)) {+ return false;+ }+ let Some(Token::Word(word)) = tokens.first() else {+ return false;+ };+ if word.quote_style.is_some() || !["SELECT", "WITH", "VALUES"].contains(&word.value.to_ascii_uppercase().as_str()) {+ return false;+ }+ let normalized = tokens.iter().map(ToString::to_string).collect::<Vec<_>>().join(" ");+ !contains_dangerous_sql_keyword(&normalized)+}+/// Returns true for databases that support SQL query execution (execute_query / get_sample_data)./// Non-SQL databases (Redis, MongoDB, Elasticsearch, InfluxDB, VictoriaMetrics, Neo4j, etcd) are excluded.pub fn supports_sql_query(database_type: DatabaseType) -> bool {@@ -1528,6 +1559,119 @@ mod tests {assert!(!is_oracle_proven_read_only_statement("SELECT 1 UNION SELECT 2"));}+ #[test]+ fn db2_explain_uses_native_json_plan_acquisition() {+ let db_type = Some(DatabaseType::Db2);+ assert!(supports_explain_plan(db_type));+ let strategy = estimated_plan_strategy(db_type).unwrap();+ assert_eq!(strategy.acquisition(), EstimatedPlanAcquisition::DriverNative);+ assert_eq!(strategy.format(), EstimatedPlanFormat::Json);+ for sql in [+ "SELECT * FROM \"APP\".\"ORDERS\"",+ "WITH q AS (SELECT 1 FROM SYSIBM.SYSDUMMY1) SELECT * FROM q",+ "VALUES 1",+ "/* plan */ select * FROM APP.ORDERS",+ "-- plan\nwith q AS (SELECT 1 FROM SYSIBM.SYSDUMMY1) SELECT * FROM q",+ "/* plan */ values (1)",+ ] {+ let result = build_explain_sql(ExplainSqlOptions {+ database_type: db_type,+ format: None,+ analyze: Some(true),+ sql: format!("{sql};"),+ });+ assert!(result.ok, "{result:?}");+ assert_eq!(result.sql, Some(format!("EXPLAIN PLAN FOR {sql}")));+ }+ }++ #[test]+ fn db2_explain_handles_nested_comments_without_hiding_writes() {+ for sql in [+ "/* outer /* inner */ trailing */ SELECT 1 FROM SYSIBM.SYSDUMMY1",+ "/* outer /* inner */ DELETE */ VALUES ('a;''b')",+ "WITH q AS (/* outer /* inner */ UPDATE */ SELECT 1 FROM SYSIBM.SYSDUMMY1) SELECT * FROM q",+ ] {+ assert!(is_safe_explain_sql_for_database(sql, Some(DatabaseType::Db2)), "{sql}");+ assert!(+ build_explain_sql(ExplainSqlOptions {+ database_type: Some(DatabaseType::Db2),+ format: None,+ analyze: None,+ sql: sql.into()+ })+ .ok,+ "{sql}"+ );+ }+ for sql in [+ "/* outer /* inner */ trailing */ DELETE FROM APP.ORDERS",+ "/* outer /* inner */ trailing */ SELECT 1; DELETE FROM APP.ORDERS",+ "/* outer /* inner */ trailing */ TABLE APP.ORDERS",+ "WITH q AS (DELETE FROM APP.ORDERS) SELECT * FROM q",+ "SELECT 1 /* outer /* inner */",+ "SELECT 1;;",+ ] {+ assert!(!is_safe_explain_sql_for_database(sql, Some(DatabaseType::Db2)), "{sql}");+ assert!(+ !build_explain_sql(ExplainSqlOptions {+ database_type: Some(DatabaseType::Db2),+ format: None,+ analyze: None,+ sql: sql.into()+ })+ .ok,+ "{sql}"+ );+ }+ }++ #[test]+ fn db2_explain_rejects_table_shortcuts_in_all_preflight_paths() {+ for sql in ["TABLE APP.ORDERS", "table \"APP\".\"ORDERS\";", "/* plan */ TABLE APP.ORDERS"] {+ assert!(!is_safe_explain_sql_for_database(sql, Some(DatabaseType::Db2)), "{sql}");+ let result = build_explain_sql(ExplainSqlOptions {+ database_type: Some(DatabaseType::Db2),+ format: None,+ analyze: None,+ sql: sql.into(),+ });+ assert!(!result.ok, "{sql}: {result:?}");+ assert_eq!(result.reason.as_deref(), Some("unsafe"));+ assert!(is_safe_explain_sql(sql), "generic TABLE support must remain: {sql}");+ assert!(+ build_explain_sql(ExplainSqlOptions {+ database_type: Some(DatabaseType::Postgres),+ format: None,+ analyze: None,+ sql: sql.into(),+ })+ .ok,+ "PostgreSQL TABLE support must remain: {sql}"+ );+ }+ }++ #[test]+ fn db2_explain_rejects_empty_write_and_multiple_statement_sources() {+ for (sql, reason) in [+ ("", "empty"),+ ("DELETE FROM t", "unsafe"),+ ("UPDATE t SET n=1", "unsafe"),+ ("SELECT 1; DROP TABLE t", "unsafe"),+ ("SELECT 1; SELECT 2", "unsafe"),+ ] {+ let result = build_explain_sql(ExplainSqlOptions {+ database_type: Some(DatabaseType::Db2),+ format: None,+ analyze: None,+ sql: sql.into(),+ });+ assert!(!result.ok);+ assert_eq!(result.reason.as_deref(), Some(reason));+ }+ }+#[test]fn builds_xugu_verbose_text_explain_without_executing_the_query() {for sql in [@@ -1917,6 +2061,7 @@ mod tests {(DatabaseType::Questdb, "EXPLAIN SELECT 1", Text, GeneratedSql),(DatabaseType::Dameng, "EXPLAIN SELECT 1", Text, DriverNative),(DatabaseType::Oracle, "EXPLAIN PLAN FOR SELECT 1", Text, DriverNative),+ (DatabaseType::Db2, "EXPLAIN PLAN FOR SELECT 1", Json, DriverNative),(DatabaseType::OceanbaseOracle, "EXPLAIN FORMAT=JSON SELECT 1", Json, GeneratedSql),(DatabaseType::SqlServer,diff --git a/crates/dbx-sql-core/src/sql.rs b/crates/dbx-sql-core/src/sql.rsindex da3612ab23..d825b37c0d 100644--- a/crates/dbx-sql-core/src/sql.rs+++ b/crates/dbx-sql-core/src/sql.rs@@ -227,6 +227,12 @@ impl SqlDialectProfile {return Self::sql_server();}+ if matches!(db_type, DatabaseType::Db2) {+ // DB2 block comments nest; cursor extraction must skip the complete+ // leading comment before handing the query to the Explain gate.+ return Self { supports_nested_block_comments: true, ..Self::default() };+ }+if matches!(db_type, DatabaseType::ClickHouse) {// ClickHouse documents that C-style block comments nest.return Self { supports_nested_block_comments: true, ..Self::default() };@@ -6117,6 +6123,20 @@ delimiter ;";);}+ #[test]+ fn db2_current_statement_skips_complete_nested_comments() {+ let sql = "/* outer /* inner */ trailing */ SELECT IBMREQD FROM SYSIBM.SYSDUMMY1;";+ let cursor = sql.encode_utf16().count();+ assert_eq!(+ find_statement_at_cursor_for_database(sql, cursor, DatabaseType::Db2),+ "SELECT IBMREQD FROM SYSIBM.SYSDUMMY1"+ );+ let script = "/* outer /* SELECT 99; */ DELETE FROM hidden; */ VALUES 1; VALUES 2;";+ assert_eq!(+ split_sql_statements_for_database(script, DatabaseType::Db2),+ vec!["/* outer /* SELECT 99; */ DELETE FROM hidden; */ VALUES 1", "VALUES 2"]+ );+ }#[test]fn mysql_current_statement_strips_other_leading_block_comments() {for comment in ["/* ordinary */", "/*unknown*/", "/* proxy */", "/*PROXY*/"] {diff --git a/crates/dbx-web/src/routes/query.rs b/crates/dbx-web/src/routes/query.rsindex e9d92c5556..dc82418266 100644--- a/crates/dbx-web/src/routes/query.rs+++ b/crates/dbx-web/src/routes/query.rs@@ -829,6 +829,8 @@ pub struct GetExplainInfoRequest {pub schema: Option<String>,pub sql: String,pub mode: Option<String>,+ pub execution_id: Option<String>,+ pub timeout_secs: Option<u64>,}#[derive(Deserialize)]@@ -849,14 +851,15 @@ pub async fn get_explain_info(State(state): State<Arc<WebState>>,Json(req): Json<GetExplainInfoRequest>,) -> Result<Json<String>, AppError> {- let plan = dbx_core::agent_explain::get_agent_explain_info_core(+ let plan = dbx_core::agent_explain::get_agent_explain_info_core_with_execution_id(&state.app,&req.connection_id,req.database.as_deref(),req.schema.as_deref(),&req.sql,req.mode.as_deref(),- None,+ req.timeout_secs,+ req.execution_id.as_deref(),).await.map_err(AppError::from)?;diff --git a/plugins/connection-types/db2.yaml b/plugins/connection-types/db2.yamlindex c115878016..721e0eb830 100644--- a/plugins/connection-types/db2.yaml+++ b/plugins/connection-types/db2.yaml@@ -30,6 +30,6 @@ capabilities:sqlFileExecution: truedatabaseCreate: falsefieldLineage: true- sqlExplain: false+ sqlExplain: trueuserAdmin: falsedriverManagement: truediff --git a/src-tauri/src/commands/query.rs b/src-tauri/src/commands/query.rsindex 4161382041..d81de5023e 100644--- a/src-tauri/src/commands/query.rs+++ b/src-tauri/src/commands/query.rs@@ -986,15 +986,18 @@ pub async fn get_explain_info(schema: Option<String>,sql: String,mode: Option<String>,+ execution_id: Option<String>,+ timeout_secs: Option<u64>,) -> Result<String, String> {- dbx_core::agent_explain::get_agent_explain_info_core(+ dbx_core::agent_explain::get_agent_explain_info_core_with_execution_id(&state,&connection_id,database.as_deref(),schema.as_deref(),&sql,mode.as_deref(),- None,+ timeout_secs,+ execution_id.as_deref(),).await}