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
fix(oracle): read and write the same plan table for explain
zipg04bf3be779d4
diff --git a/agents/drivers/oracle-go/main.go b/agents/drivers/oracle-go/main.goindex 813bd117d0..2463bd34a7 100644--- a/agents/drivers/oracle-go/main.go+++ b/agents/drivers/oracle-go/main.go@@ -3674,7 +3674,13 @@ func (s *server) getExplainInfo(sqlText, database, schema string, timeoutSecs in}statementID := "DBX_" + strings.ToUpper(strconv.FormatInt(time.Now().UnixNano(), 36))- defer cleanupOracleExplainPlan(conn, statementID)+ // EXPLAIN PLAN resolves its plan table in the session user's schema, while a bare+ // PLAN_TABLE inside DBMS_XPLAN.DISPLAY resolves through CURRENT_SCHEMA - and the+ // schema switch above changes CURRENT_SCHEMA. Name the table explicitly so the read+ // and the cleanup hit the same object EXPLAIN PLAN wrote to, otherwise DISPLAY answers+ // "cannot fetch plan for statement_id '...'".+ planTable := oracleExplainPlanTableName(ctx, conn)+ defer cleanupOracleExplainPlan(conn, statementID, planTable)statementSQL := trimStatementSQL(sqlText)explainArgs := oracleExplainPlanBindArgs(statementSQL)if _, err := conn.ExecContext(ctx, "EXPLAIN PLAN SET STATEMENT_ID = '"+statementID+"' FOR "+statementSQL, explainArgs...); err != nil {@@ -3682,7 +3688,7 @@ func (s *server) getExplainInfo(sqlText, database, schema string, timeoutSecs in}planRows, err := conn.QueryContext(ctx,- "SELECT PLAN_TABLE_OUTPUT FROM TABLE(DBMS_XPLAN.DISPLAY('PLAN_TABLE', :1, 'TYPICAL +PREDICATE'))",+ "SELECT PLAN_TABLE_OUTPUT FROM TABLE(DBMS_XPLAN.DISPLAY('"+planTable+"', :1, 'TYPICAL +PREDICATE'))",statementID,)if err != nil {@@ -3712,10 +3718,40 @@ func oracleExplainTargetSchema(database, schema, configuredDatabase string) strireturn database}-func cleanupOracleExplainPlan(conn *sql.Conn, statementID string) {+// oracleExplainPlanTableName returns the explicitly qualified name of the plan table that+// EXPLAIN PLAN resolves for this session: the session user's own object named PLAN_TABLE when+// it exists, otherwise the table behind the PUBLIC synonym (usually SYS.PLAN_TABLE$). Falls+// back to the bare name when neither can be resolved.+func oracleExplainPlanTableName(ctx context.Context, conn *sql.Conn) string {+ const probe = `SELECT+ (SELECT OWNER FROM ALL_OBJECTS WHERE OWNER = USER AND OBJECT_NAME = 'PLAN_TABLE' AND ROWNUM = 1),+ (SELECT OBJECT_NAME FROM ALL_OBJECTS WHERE OWNER = USER AND OBJECT_NAME = 'PLAN_TABLE' AND ROWNUM = 1),+ (SELECT TABLE_OWNER FROM ALL_SYNONYMS WHERE OWNER = 'PUBLIC' AND SYNONYM_NAME = 'PLAN_TABLE' AND ROWNUM = 1),+ (SELECT TABLE_NAME FROM ALL_SYNONYMS WHERE OWNER = 'PUBLIC' AND SYNONYM_NAME = 'PLAN_TABLE' AND ROWNUM = 1)+ FROM DUAL`+ var sessionOwner, sessionName, publicOwner, publicName sql.NullString+ if err := conn.QueryRowContext(ctx, probe).Scan(&sessionOwner, &sessionName, &publicOwner, &publicName); err != nil {+ return "PLAN_TABLE"+ }+ return oraclePlanTableName(sessionOwner.String, sessionName.String, publicOwner.String, publicName.String)+}++// oraclePlanTableName picks the qualified plan table name from the probe results, preferring+// the session user's own PLAN_TABLE because that is what EXPLAIN PLAN writes to.+func oraclePlanTableName(sessionOwner, sessionName, publicOwner, publicName string) string {+ if strings.TrimSpace(sessionOwner) != "" && strings.TrimSpace(sessionName) != "" {+ return quoteIdentifier(strings.TrimSpace(sessionOwner)) + "." + quoteIdentifier(strings.TrimSpace(sessionName))+ }+ if strings.TrimSpace(publicOwner) != "" && strings.TrimSpace(publicName) != "" {+ return quoteIdentifier(strings.TrimSpace(publicOwner)) + "." + quoteIdentifier(strings.TrimSpace(publicName))+ }+ return "PLAN_TABLE"+}++func cleanupOracleExplainPlan(conn *sql.Conn, statementID, planTable string) {ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)defer cancel()- _, _ = conn.ExecContext(ctx, "DELETE FROM PLAN_TABLE WHERE STATEMENT_ID = :1", statementID)+ _, _ = conn.ExecContext(ctx, "DELETE FROM "+planTable+" WHERE STATEMENT_ID = :1", statementID)}type oracleBindParam struct {diff --git a/agents/drivers/oracle-go/main_test.go b/agents/drivers/oracle-go/main_test.goindex 37fdaa1836..a5a6cb4891 100644--- a/agents/drivers/oracle-go/main_test.go+++ b/agents/drivers/oracle-go/main_test.go@@ -4421,3 +4421,40 @@ func TestOracleTnsAliasName(t *testing.T) {}}}++func TestOraclePlanTableNamePrefersSessionUserTable(t *testing.T) {+ cases := []struct {+ name string+ sessionOwner, sessionName string+ publicOwner, publicName string+ want string+ }{+ {+ name: "session user table shadows the public synonym",+ sessionOwner: "U_BROKEN", sessionName: "PLAN_TABLE",+ publicOwner: "SYS", publicName: "PLAN_TABLE$",+ want: `"U_BROKEN"."PLAN_TABLE"`,+ },+ {+ name: "public synonym target when the schema has no own table",+ publicOwner: "SYS", publicName: "PLAN_TABLE$",+ want: `"SYS"."PLAN_TABLE$"`,+ },+ {+ name: "bare name when nothing resolves",+ want: "PLAN_TABLE",+ },+ {+ name: "quoted mixed case object is escaped",+ sessionOwner: "user_1", sessionName: `plan"table`,+ want: `"user_1"."plan""table"`,+ },+ }+ for _, tc := range cases {+ t.Run(tc.name, func(t *testing.T) {+ if got := oraclePlanTableName(tc.sessionOwner, tc.sessionName, tc.publicOwner, tc.publicName); got != tc.want {+ t.Fatalf("oraclePlanTableName() = %q, want %q", got, tc.want)+ }+ })+ }+}diff --git a/plugins/jdbc/src/main/java/app/dbx/jdbc/DbxJdbcPlugin.java b/plugins/jdbc/src/main/java/app/dbx/jdbc/DbxJdbcPlugin.javaindex 559cd080cf..256acfd134 100644--- a/plugins/jdbc/src/main/java/app/dbx/jdbc/DbxJdbcPlugin.java+++ b/plugins/jdbc/src/main/java/app/dbx/jdbc/DbxJdbcPlugin.java@@ -1791,6 +1791,15 @@ public final class DbxJdbcPlugin {// ROWS loses the plan rows at the commit in between, so DISPLAY answers with// "cannot fetch plan for statement_id '...'". Run both inside one transaction to keep// the rows written by EXPLAIN PLAN visible for the read.+ //+ // The read must also name the same table Oracle wrote to. EXPLAIN PLAN resolves its plan+ // table in the session user's schema, while a bare 'PLAN_TABLE' inside DBMS_XPLAN.DISPLAY+ // resolves in CURRENT_SCHEMA — and DBX switches CURRENT_SCHEMA whenever a connection+ // browses another schema. Without the explicit name the write and the read can land on+ // two different objects, which is the other way "cannot fetch plan for statement_id"+ // shows up.+ String planTable = oracleExplainPlanTable(connection);+ String displayTable = planTable == null ? "PLAN_TABLE" : planTable;boolean explainTransaction = beginOracleExplainTransaction(connection);try {try (PreparedStatement explain = connection.prepareStatement(@@ -1801,7 +1810,7 @@ public final class DbxJdbcPlugin {explain.execute();}try (PreparedStatement read = connection.prepareStatement(- "SELECT PLAN_TABLE_OUTPUT FROM TABLE(DBMS_XPLAN.DISPLAY('PLAN_TABLE', ?, 'TYPICAL +PREDICATE'))"+ "SELECT PLAN_TABLE_OUTPUT FROM TABLE(DBMS_XPLAN.DISPLAY('" + displayTable + "', ?, 'TYPICAL +PREDICATE'))")) {applyExplainTimeout(read, timeoutSecs);read.setString(1, statementId);@@ -1815,7 +1824,7 @@ public final class DbxJdbcPlugin {return plan.toString();} finally {try (PreparedStatement cleanup = connection.prepareStatement(- "DELETE FROM PLAN_TABLE WHERE STATEMENT_ID = ?"+ "DELETE FROM " + displayTable + " WHERE STATEMENT_ID = ?")) {applyExplainTimeout(cleanup, timeoutSecs);cleanup.setString(1, statementId);@@ -1825,6 +1834,39 @@ public final class DbxJdbcPlugin {}}+ /**+ * Explicitly qualified name of the plan table that EXPLAIN PLAN resolves for this session:+ * the session user's own object named PLAN_TABLE when it exists, otherwise the table behind the+ * PUBLIC synonym (usually SYS.PLAN_TABLE$). Passing that name to DBMS_XPLAN.DISPLAY keeps the+ * read on the table Oracle wrote to even when CURRENT_SCHEMA points at another schema. Returns+ * null when neither can be resolved, so callers fall back to the unqualified name.+ */+ private static String oracleExplainPlanTable(Connection connection) {+ String sql = "SELECT"+ + " (SELECT OWNER || '.' || OBJECT_NAME FROM ALL_OBJECTS"+ + " WHERE OWNER = USER AND OBJECT_NAME = 'PLAN_TABLE' AND ROWNUM = 1),"+ + " (SELECT TABLE_OWNER || '.' || TABLE_NAME FROM ALL_SYNONYMS"+ + " WHERE OWNER = 'PUBLIC' AND SYNONYM_NAME = 'PLAN_TABLE' AND ROWNUM = 1)"+ + " FROM DUAL";+ try (PreparedStatement probe = connection.prepareStatement(sql);+ ResultSet rows = probe.executeQuery()) {+ if (!rows.next()) {+ return null;+ }+ String sessionPlanTable = rows.getString(1);+ if (sessionPlanTable != null && !sessionPlanTable.isBlank()) {+ return sessionPlanTable;+ }+ String publicPlanTable = rows.getString(2);+ if (publicPlanTable != null && !publicPlanTable.isBlank()) {+ return publicPlanTable;+ }+ return null;+ } catch (SQLException | AbstractMethodError | UnsupportedOperationException ignored) {+ return null;+ }+ }+/*** Oracle JDBC commits each statement in auto-commit mode, which is exactly what discards* plan rows held by a session plan table created as ON COMMIT DELETE ROWS. Switch thediff --git a/plugins/jdbc/src/test/java/app/dbx/jdbc/DbxJdbcPluginTest.java b/plugins/jdbc/src/test/java/app/dbx/jdbc/DbxJdbcPluginTest.javaindex f289b8ce3f..0d6110e5be 100644--- a/plugins/jdbc/src/test/java/app/dbx/jdbc/DbxJdbcPluginTest.java+++ b/plugins/jdbc/src/test/java/app/dbx/jdbc/DbxJdbcPluginTest.java@@ -42,6 +42,7 @@ import java.util.regex.Pattern;import static org.junit.jupiter.api.Assertions.assertEquals;import static org.junit.jupiter.api.Assertions.assertFalse;import static org.junit.jupiter.api.Assertions.assertNotEquals;+import static org.junit.jupiter.api.Assertions.assertNull;import static org.junit.jupiter.api.Assertions.assertTrue;final class DbxJdbcPluginTest {@@ -1916,7 +1917,10 @@ final class DbxJdbcPluginTest {explainCall.indexOf("'", explainCall.indexOf("'") + 1));assertEquals(1, calls.stream().filter(call -> call.startsWith("prepare:SELECT PLAN_TABLE_OUTPUT FROM TABLE(DBMS_XPLAN.DISPLAY")).count());- assertEquals(1, calls.stream().filter(call -> call.equals("prepare:DELETE FROM PLAN_TABLE WHERE STATEMENT_ID = ?")).count());+ // EXPLAIN PLAN resolves its plan table in the session user's schema, so the plugin+ // reads and cleans up that exact table instead of the CURRENT_SCHEMA-relative name.+ assertEquals(1, calls.stream().filter(call -> call.startsWith("prepare:SELECT PLAN_TABLE_OUTPUT FROM TABLE(DBMS_XPLAN.DISPLAY('SYSTEM.PLAN_TABLE'")).count());+ assertEquals(1, calls.stream().filter(call -> call.equals("prepare:DELETE FROM SYSTEM.PLAN_TABLE WHERE STATEMENT_ID = ?")).count());assertEquals(2, calls.stream().filter(call -> call.equals("bind:1:" + statementId)).count());} finally {closeAndDeregister(connection, driver);@@ -1955,7 +1959,7 @@ final class DbxJdbcPluginTest {int begin = callIndex(calls, call -> call.equals("setAutoCommit:false"));int explain = callIndex(calls, call -> call.startsWith("prepare:EXPLAIN PLAN SET STATEMENT_ID = 'DBX_"));int display = callIndex(calls, call -> call.startsWith("prepare:SELECT PLAN_TABLE_OUTPUT FROM TABLE(DBMS_XPLAN.DISPLAY"));- int cleanup = callIndex(calls, call -> call.equals("prepare:DELETE FROM PLAN_TABLE WHERE STATEMENT_ID = ?"));+ int cleanup = callIndex(calls, call -> call.equals("prepare:DELETE FROM SYSTEM.PLAN_TABLE WHERE STATEMENT_ID = ?"));int commit = callIndex(calls, call -> call.equals("commit"));int restore = callIndex(calls, call -> call.equals("setAutoCommit:true"));assertTrue(begin >= 0 && begin < explain, calls.toString());@@ -1977,6 +1981,49 @@ final class DbxJdbcPluginTest {return -1;}+ @Test+ void oracleExplainPlanTableMirrorsTheNameExplainPlanResolves() throws Exception {+ Method method = DbxJdbcPlugin.class.getDeclaredMethod("oracleExplainPlanTable", Connection.class);+ method.setAccessible(true);++ // A session user PLAN_TABLE wins, because that is what EXPLAIN PLAN resolves first.+ assertEquals(+ "SYSTEM.PLAN_TABLE",+ method.invoke(null, oraclePlanTableProbeConnection("SYSTEM.PLAN_TABLE", "SYS.PLAN_TABLE$"))+ );+ // Without one, EXPLAIN PLAN falls through to the PUBLIC synonym, whose target must be+ // named explicitly: a bare PLAN_TABLE would follow CURRENT_SCHEMA instead.+ assertEquals(+ "SYS.PLAN_TABLE$",+ method.invoke(null, oraclePlanTableProbeConnection(null, "SYS.PLAN_TABLE$"))+ );+ // Nothing resolvable keeps the caller on the plain unqualified name.+ assertNull(method.invoke(null, oraclePlanTableProbeConnection(null, null)));+ }++ private static Connection oraclePlanTableProbeConnection(String sessionPlanTable, String publicPlanTable) {+ return (Connection) Proxy.newProxyInstance(+ DbxJdbcPluginTest.class.getClassLoader(),+ new Class<?>[] { Connection.class },+ (proxy, method, args) -> switch (method.getName()) {+ case "prepareStatement" -> (PreparedStatement) Proxy.newProxyInstance(+ DbxJdbcPluginTest.class.getClassLoader(),+ new Class<?>[] { PreparedStatement.class },+ (statement, statementMethod, statementArgs) -> switch (statementMethod.getName()) {+ case "executeQuery" -> rowsResultSet(+ new String[] { "SESSION_PLAN_TABLE", "PUBLIC_PLAN_TABLE" },+ new Object[][] { { sessionPlanTable, publicPlanTable } }+ );+ case "close" -> null;+ default -> defaultValue(statementMethod.getReturnType());+ }+ );+ case "close" -> null;+ default -> defaultValue(method.getReturnType());+ }+ );+ }+@Testvoid oracleExplainNullsBindPlaceholdersInsteadOfFailingWithMissingParameter() throws Exception {List<String> calls = new ArrayList<>();@@ -5013,6 +5060,21 @@ final class DbxJdbcPluginTest {boolean parameterMetadataSupported) {calls.add("prepare:" + sql);+ if (sql.contains("FROM ALL_SYNONYMS")) {+ // The plugin resolves the plan table EXPLAIN PLAN will use before reading it back.+ return (PreparedStatement) Proxy.newProxyInstance(+ DbxJdbcPluginTest.class.getClassLoader(),+ new Class<?>[] { PreparedStatement.class },+ (proxy, method, args) -> switch (method.getName()) {+ case "executeQuery" -> rowsResultSet(+ new String[] { "SESSION_PLAN_TABLE", "PUBLIC_PLAN_TABLE" },+ new Object[][] { { "SYSTEM.PLAN_TABLE", "SYS.PLAN_TABLE$" } }+ );+ case "setQueryTimeout", "close" -> null;+ default -> defaultValue(method.getReturnType());+ }+ );+ }int parameterCount = oracleExplainMockParameterCount(sql);return (PreparedStatement) Proxy.newProxyInstance(DbxJdbcPluginTest.class.getClassLoader(),