Skip to content

armgit / dbx

Public Imported from GitHub
0

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。

fix(oracle): bind explain plan placeholders

Melody Ruch1d8771a846b8
diff --git a/plugins/jdbc/src/main/java/app/dbx/jdbc/DbxJdbcPlugin.java b/plugins/jdbc/src/main/java/app/dbx/jdbc/DbxJdbcPlugin.java
index 87cc2c4abf..dbf00e6388 100644
--- a/plugins/jdbc/src/main/java/app/dbx/jdbc/DbxJdbcPlugin.java
+++ b/plugins/jdbc/src/main/java/app/dbx/jdbc/DbxJdbcPlugin.java
@@ -25,6 +25,7 @@ import java.sql.Date;
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.DriverPropertyInfo;
+import java.sql.ParameterMetaData;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
@@ -1154,12 +1155,14 @@ public final class DbxJdbcPlugin {
private static String getOracleExplainInfo(Connection connection, String sql, int timeoutSecs) throws SQLException {
String statementId = "DBX_" + UUID.randomUUID().toString().replace("-", "").substring(0, 26);
+ String statementSql = trimStatementSql(sql);
StringBuilder plan = new StringBuilder();
try {
try (PreparedStatement explain = connection.prepareStatement(
- "EXPLAIN PLAN SET STATEMENT_ID = '" + statementId + "' FOR " + trimStatementSql(sql)
+ "EXPLAIN PLAN SET STATEMENT_ID = '" + statementId + "' FOR " + statementSql
)) {
applyExplainTimeout(explain, timeoutSecs);
+ nullBindExplainParameters(explain, statementSql);
explain.execute();
}
try (PreparedStatement read = connection.prepareStatement(
@@ -1186,6 +1189,157 @@ public final class DbxJdbcPlugin {
}
}
+ /**
+ * SQL passed to EXPLAIN PLAN may legitimately contain Oracle bind markers
+ * (":1", ":name", or "?") that aren't meant to be executed with real
+ * values — e.g. statements copied from V$SQL/AWR reports. A PreparedStatement
+ * still requires every marker to be bound before execute(), or Oracle throws
+ * "ORA-17041: Missing IN or OUT parameter". The plan doesn't depend on the
+ * actual bind values, so null them all out.
+ */
+ private static void nullBindExplainParameters(PreparedStatement statement, String sql) throws SQLException {
+ int parameterCount = -1;
+ try {
+ ParameterMetaData metadata = statement.getParameterMetaData();
+ if (metadata != null) {
+ parameterCount = metadata.getParameterCount();
+ }
+ } catch (SQLException ignored) {
+ }
+ if (parameterCount < 0) {
+ parameterCount = oracleExplainBindMarkerCount(sql);
+ }
+ for (int index = 1; index <= parameterCount; index++) {
+ statement.setNull(index, Types.VARCHAR);
+ }
+ }
+
+ private static int oracleExplainBindMarkerCount(String sql) {
+ int count = 0;
+ for (int index = 0; index < sql.length(); index++) {
+ char ch = sql.charAt(index);
+ if (ch == '\'') {
+ index = skipSingleQuotedSql(sql, index);
+ } else if (ch == '"') {
+ index = skipDoubleQuotedSql(sql, index);
+ } else if (ch == 'q' || ch == 'Q') {
+ int end = skipOracleAlternativeQuotedSql(sql, index);
+ if (end != index) {
+ index = end;
+ }
+ } else if (ch == '-' && index + 1 < sql.length() && sql.charAt(index + 1) == '-') {
+ index = skipLineCommentSql(sql, index);
+ } else if (ch == '/' && index + 1 < sql.length() && sql.charAt(index + 1) == '*') {
+ index = skipBlockCommentSql(sql, index);
+ } else if (ch == '?') {
+ count++;
+ } else if (ch == ':') {
+ int end = oracleBindMarkerEnd(sql, index);
+ if (end > index) {
+ count++;
+ index = end - 1;
+ }
+ }
+ }
+ return count;
+ }
+
+ private static int oracleBindMarkerEnd(String sql, int index) {
+ if (index + 1 >= sql.length() || (index > 0 && sql.charAt(index - 1) == ':')) {
+ return index;
+ }
+ char next = sql.charAt(index + 1);
+ int end = index + 2;
+ if (next >= '0' && next <= '9') {
+ while (end < sql.length() && sql.charAt(end) >= '0' && sql.charAt(end) <= '9') {
+ end++;
+ }
+ return end;
+ }
+ if (!isOracleIdentifierStart(next)) {
+ return index;
+ }
+ while (end < sql.length() && isOracleIdentifierPart(sql.charAt(end))) {
+ end++;
+ }
+ return end;
+ }
+
+ private static boolean isOracleIdentifierStart(char ch) {
+ return (ch >= 'a' && ch <= 'z')
+ || (ch >= 'A' && ch <= 'Z')
+ || ch == '_'
+ || ch == '$'
+ || ch == '#';
+ }
+
+ private static boolean isOracleIdentifierPart(char ch) {
+ return isOracleIdentifierStart(ch) || (ch >= '0' && ch <= '9');
+ }
+
+ private static int skipSingleQuotedSql(String sql, int index) {
+ for (int current = index + 1; current < sql.length(); current++) {
+ if (sql.charAt(current) != '\'') {
+ continue;
+ }
+ if (current + 1 < sql.length() && sql.charAt(current + 1) == '\'') {
+ current++;
+ continue;
+ }
+ return current;
+ }
+ return sql.length() - 1;
+ }
+
+ private static int skipDoubleQuotedSql(String sql, int index) {
+ for (int current = index + 1; current < sql.length(); current++) {
+ if (sql.charAt(current) != '"') {
+ continue;
+ }
+ if (current + 1 < sql.length() && sql.charAt(current + 1) == '"') {
+ current++;
+ continue;
+ }
+ return current;
+ }
+ return sql.length() - 1;
+ }
+
+ private static int skipOracleAlternativeQuotedSql(String sql, int index) {
+ if (index + 2 >= sql.length() || sql.charAt(index + 1) != '\'') {
+ return index;
+ }
+ char open = sql.charAt(index + 2);
+ char close = switch (open) {
+ case '[' -> ']';
+ case '{' -> '}';
+ case '(' -> ')';
+ case '<' -> '>';
+ default -> open;
+ };
+ for (int current = index + 3; current + 1 < sql.length(); current++) {
+ if (sql.charAt(current) == close && sql.charAt(current + 1) == '\'') {
+ return current + 1;
+ }
+ }
+ return sql.length() - 1;
+ }
+
+ private static int skipLineCommentSql(String sql, int index) {
+ for (int current = index; current < sql.length(); current++) {
+ char ch = sql.charAt(current);
+ if (ch == '\n' || ch == '\r') {
+ return current;
+ }
+ }
+ return sql.length() - 1;
+ }
+
+ private static int skipBlockCommentSql(String sql, int index) {
+ int end = sql.indexOf("*/", index + 2);
+ return end < 0 ? sql.length() - 1 : end + 1;
+ }
+
private static void applyExplainTimeout(Statement statement, int timeoutSecs) throws SQLException {
if (timeoutSecs >= 0) {
try {
diff --git a/plugins/jdbc/src/test/java/app/dbx/jdbc/DbxJdbcPluginTest.java b/plugins/jdbc/src/test/java/app/dbx/jdbc/DbxJdbcPluginTest.java
index 92a35fb507..f2d5bcc087 100644
--- a/plugins/jdbc/src/test/java/app/dbx/jdbc/DbxJdbcPluginTest.java
+++ b/plugins/jdbc/src/test/java/app/dbx/jdbc/DbxJdbcPluginTest.java
@@ -16,6 +16,7 @@ import java.sql.Date;
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.DriverPropertyInfo;
+import java.sql.ParameterMetaData;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
@@ -29,6 +30,8 @@ import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.Set;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
@@ -1292,6 +1295,89 @@ final class DbxJdbcPluginTest {
}
}
+ @Test
+ void oracleExplainNullsBindPlaceholdersInsteadOfFailingWithMissingParameter() throws Exception {
+ List<String> calls = new ArrayList<>();
+ OracleExplainDriver driver = new OracleExplainDriver(calls);
+ DriverManager.registerDriver(driver);
+ String connection = """
+ {
+ "connection_string": "jdbc:oracle:dbx-explain:test",
+ "username": "system",
+ "query_timeout_secs": 30
+ }
+ """;
+ try {
+ // SQL copied from V$SQL/AWR reports commonly carries literal bind
+ // markers like :B1 with no bound value — EXPLAIN PLAN doesn't need
+ // the real value, but a PreparedStatement still requires every
+ // marker to be bound before execute() or Oracle throws ORA-17041.
+ JsonNode response = request("getExplainInfo", """
+ {
+ "connection": %s,
+ "sql": "SELECT * FROM T WHERE ID = :B1 AND NAME = :B2",
+ "timeoutSecs": 30,
+ "mode": "explain"
+ }
+ """.formatted(connection));
+
+ assertFalse(response.has("error"), response.toString());
+ assertEquals(2, calls.stream().filter(call -> call.equals("setNull:1:12")).count()
+ + calls.stream().filter(call -> call.equals("setNull:2:12")).count());
+ } finally {
+ closeAndDeregister(connection, driver);
+ }
+ }
+
+ @Test
+ void oracleExplainFallsBackToSqlBindScanWhenParameterMetadataIsUnsupported() throws Exception {
+ List<String> calls = new ArrayList<>();
+ OracleExplainDriver driver = new OracleExplainDriver(calls, false);
+ DriverManager.registerDriver(driver);
+ String connection = """
+ {
+ "connection_string": "jdbc:oracle:dbx-explain:test",
+ "username": "system",
+ "query_timeout_secs": 30
+ }
+ """;
+ try {
+ JsonNode response = request("getExplainInfo", """
+ {
+ "connection": %s,
+ "sql": "SELECT * FROM T WHERE ID = :B1 AND NAME = :name AND FLAG = ?",
+ "timeoutSecs": 30,
+ "mode": "explain"
+ }
+ """.formatted(connection));
+
+ assertFalse(response.has("error"), response.toString());
+ assertEquals(
+ List.of("setNull:1:12", "setNull:2:12", "setNull:3:12"),
+ calls.stream().filter(call -> call.startsWith("setNull:")).toList()
+ );
+ } finally {
+ closeAndDeregister(connection, driver);
+ }
+ }
+
+ @Test
+ void oracleExplainFallbackBindScanSkipsQuotedTextAndComments() throws Exception {
+ Method method = DbxJdbcPlugin.class.getDeclaredMethod("oracleExplainBindMarkerCount", String.class);
+ method.setAccessible(true);
+ String sql = """
+ SELECT :B1, :1, ?
+ FROM T
+ WHERE TEXT_VALUE = ':ignored ?'
+ AND Q_VALUE = q'[ignored :Q1 ?]'
+ AND "COL:IGNORED?" = 1
+ -- ignored :LINE ?
+ /* ignored :BLOCK ? */
+ """;
+
+ assertEquals(3, method.invoke(null, sql));
+ }
+
@Test
void optInStatementOptionsCanApplyDriverMaxRowsProtection() throws Exception {
Method method = DbxJdbcPlugin.class.getDeclaredMethod(
@@ -3120,16 +3206,22 @@ final class DbxJdbcPluginTest {
private static final class OracleExplainDriver implements Driver {
private final List<String> calls;
+ private final boolean parameterMetadataSupported;
private OracleExplainDriver(List<String> calls) {
+ this(calls, true);
+ }
+
+ private OracleExplainDriver(List<String> calls, boolean parameterMetadataSupported) {
this.calls = calls;
+ this.parameterMetadataSupported = parameterMetadataSupported;
}
@Override
public Connection connect(String url, Properties info) {
if (!acceptsURL(url)) return null;
calls.add("connect");
- return oracleExplainConnection(calls);
+ return oracleExplainConnection(calls, parameterMetadataSupported);
}
@Override
@@ -3144,12 +3236,16 @@ final class DbxJdbcPluginTest {
@Override public java.util.logging.Logger getParentLogger() { return java.util.logging.Logger.getGlobal(); }
}
- private static Connection oracleExplainConnection(List<String> calls) {
+ private static Connection oracleExplainConnection(List<String> calls, boolean parameterMetadataSupported) {
return (Connection) Proxy.newProxyInstance(
DbxJdbcPluginTest.class.getClassLoader(),
new Class<?>[] { Connection.class },
(proxy, method, args) -> switch (method.getName()) {
- case "prepareStatement" -> oracleExplainStatement(String.valueOf(args[0]), calls);
+ case "prepareStatement" -> oracleExplainStatement(
+ String.valueOf(args[0]),
+ calls,
+ parameterMetadataSupported
+ );
case "isClosed" -> false;
case "close" -> null;
default -> defaultValue(method.getReturnType());
@@ -3157,8 +3253,13 @@ final class DbxJdbcPluginTest {
);
}
- private static PreparedStatement oracleExplainStatement(String sql, List<String> calls) {
+ private static PreparedStatement oracleExplainStatement(
+ String sql,
+ List<String> calls,
+ boolean parameterMetadataSupported
+ ) {
calls.add("prepare:" + sql);
+ int parameterCount = oracleExplainMockParameterCount(sql);
return (PreparedStatement) Proxy.newProxyInstance(
DbxJdbcPluginTest.class.getClassLoader(),
new Class<?>[] { PreparedStatement.class },
@@ -3167,6 +3268,16 @@ final class DbxJdbcPluginTest {
calls.add("bind:" + args[0] + ":" + args[1]);
yield null;
}
+ case "setNull" -> {
+ calls.add("setNull:" + args[0] + ":" + args[1]);
+ yield null;
+ }
+ case "getParameterMetaData" -> {
+ if (!parameterMetadataSupported) {
+ throw new SQLFeatureNotSupportedException("parameter metadata unavailable");
+ }
+ yield oracleExplainMockParameterMetaData(parameterCount);
+ }
case "setQueryTimeout", "close" -> null;
case "execute" -> true;
case "executeUpdate" -> 1;
@@ -3179,6 +3290,27 @@ final class DbxJdbcPluginTest {
);
}
+ // Mirrors, loosely, how Oracle's JDBC driver counts distinct ":name"/":1"/"?"
+ // bind markers in real SQL text — just enough for the mock to exercise
+ // DbxJdbcPlugin's null-binding loop end to end.
+ private static int oracleExplainMockParameterCount(String sql) {
+ Matcher matcher = Pattern.compile("\\?|:[A-Za-z_][A-Za-z0-9_]*|:[0-9]+").matcher(sql);
+ int count = 0;
+ while (matcher.find()) count++;
+ return count;
+ }
+
+ private static ParameterMetaData oracleExplainMockParameterMetaData(int parameterCount) {
+ return (ParameterMetaData) Proxy.newProxyInstance(
+ DbxJdbcPluginTest.class.getClassLoader(),
+ new Class<?>[] { ParameterMetaData.class },
+ (proxy, method, args) -> switch (method.getName()) {
+ case "getParameterCount" -> parameterCount;
+ default -> defaultValue(method.getReturnType());
+ }
+ );
+ }
+
private static final class OracleDateDriver implements Driver {
private final Timestamp[] values;
private final List<String> calls;