fix(jdbc): use query cursors for table exports

This commit is contained in:
Guoyu Su
2026-07-25 09:24:08 +08:00
committed by GitHub
parent 7eda73fbd8
commit e2ecb0ccff
3 changed files with 886 additions and 108 deletions
@@ -513,6 +513,7 @@ public final class DbxJdbcPlugin {
properties.setProperty("password", password);
}
applyConnectTimeout(connection, properties);
applyPagedFetchProperties(connection, url, properties);
applyJdbcxExtensionSecurity(connection, url, properties);
if (isOracleUrl(url)) {
applyOracleProperties(connection, properties);
@@ -586,6 +587,33 @@ public final class DbxJdbcPlugin {
normalized.equals("org.mariadb.jdbc.driver");
}
private static void applyPagedFetchProperties(JsonNode connection, String url, Properties properties) {
if (!isMysqlConnection(connection, url) || jdbcUrlHasParameter(url, "useCursorFetch")) {
return;
}
properties.putIfAbsent("useCursorFetch", "true");
}
private static boolean isMysqlConnection(JsonNode connection, String url) {
if (urlMatchesPrefix(url, "jdbc:mysql:")) {
return true;
}
String driverClass = optionalText(connection, "jdbc_driver_class");
if (driverClass == null) {
return false;
}
String normalized = driverClass.toLowerCase(Locale.ROOT);
return normalized.equals("com.mysql.cj.jdbc.driver") || normalized.equals("com.mysql.jdbc.driver");
}
private static boolean isPostgresConnection(JsonNode connection) {
if (urlMatchesPrefix(jdbcUrl(connection), "jdbc:postgresql:")) {
return true;
}
String driverClass = optionalText(connection, "jdbc_driver_class");
return driverClass != null && driverClass.equalsIgnoreCase("org.postgresql.Driver");
}
private static boolean isPrestoOrTrinoConnection(JsonNode connection) {
String url = jdbcUrl(connection);
if (urlMatchesPrefix(url, "jdbc:presto:") || urlMatchesPrefix(url, "jdbc:trino:")) {
@@ -675,6 +703,8 @@ public final class DbxJdbcPlugin {
private final ArrayNode columns;
private final int maxRows;
private final long startNanos;
private final Connection connection;
private final boolean restoreAutoCommit;
private int rowsReturned;
private ArrayNode pendingRow;
@@ -685,7 +715,9 @@ public final class DbxJdbcPlugin {
ResultSetMetaData meta,
ArrayNode columns,
int maxRows,
long startNanos
long startNanos,
Connection connection,
boolean restoreAutoCommit
) {
this.id = id;
this.statement = statement;
@@ -694,6 +726,8 @@ public final class DbxJdbcPlugin {
this.columns = columns;
this.maxRows = Math.max(1, maxRows);
this.startNanos = startNanos;
this.connection = connection;
this.restoreAutoCommit = restoreAutoCommit;
}
}
@@ -711,7 +745,14 @@ public final class DbxJdbcPlugin {
Connection conn = openConnection(connection);
applyExecutionContext(connection, conn, database, schema);
JdbcDriverQuirks quirks = driverQuirks(connection);
Statement statement = conn.createStatement();
boolean restoreAutoCommit = beginPagedQueryTransaction(connection, conn);
Statement statement;
try {
statement = createPagedQueryStatement(conn);
} catch (Exception | LinkageError error) {
restorePagedQueryTransaction(conn, restoreAutoCommit);
throw error;
}
try {
applyStatementOptions(statement, maxRows, fetchSize, timeoutSecs, quirks);
String trimmedSql = trimStatementSql(sql);
@@ -727,6 +768,7 @@ public final class DbxJdbcPlugin {
result.putNull("session_id");
result.put("has_more", false);
statement.close();
restorePagedQueryTransaction(conn, restoreAutoCommit);
return result;
}
@@ -738,18 +780,65 @@ public final class DbxJdbcPlugin {
columns.add(label == null || label.isBlank() ? meta.getColumnName(i) : label);
}
String sessionId = UUID.randomUUID().toString();
QuerySession session = new QuerySession(sessionId, statement, rs, meta, columns, maxRows, start);
QuerySession session = new QuerySession(
sessionId,
statement,
rs,
meta,
columns,
maxRows,
start,
conn,
restoreAutoCommit
);
QUERY_SESSIONS.put(sessionId, session);
return readQuerySessionPage(session, pageSize);
} catch (Exception error) {
try {
return readQuerySessionPage(session, pageSize);
} catch (Exception | LinkageError error) {
QUERY_SESSIONS.remove(sessionId);
throw error;
}
} catch (Exception | LinkageError error) {
try {
statement.close();
} catch (Exception ignored) {
}
restorePagedQueryTransaction(conn, restoreAutoCommit);
throw error;
}
}
private static Statement createPagedQueryStatement(Connection connection) throws SQLException {
try {
return connection.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
} catch (SQLFeatureNotSupportedException | UnsupportedOperationException | AbstractMethodError ignored) {
return connection.createStatement();
}
}
private static boolean beginPagedQueryTransaction(JsonNode connectionConfig, Connection connection)
throws SQLException {
if (!isPostgresConnection(connectionConfig) || !connection.getAutoCommit()) {
return false;
}
connection.setAutoCommit(false);
return true;
}
private static void restorePagedQueryTransaction(Connection connection, boolean restoreAutoCommit) {
if (!restoreAutoCommit) {
return;
}
try {
connection.rollback();
} catch (SQLException ignored) {
}
try {
connection.setAutoCommit(true);
} catch (SQLException ignored) {
}
}
private static JsonNode fetchQueryPage(String sessionId, int pageSize) throws SQLException {
QuerySession session = QUERY_SESSIONS.get(sessionId);
if (session == null) {
@@ -830,6 +919,7 @@ public final class DbxJdbcPlugin {
session.statement.close();
} catch (Exception ignored) {
}
restorePagedQueryTransaction(session.connection, session.restoreAutoCommit);
return true;
}
@@ -522,6 +522,120 @@ final class DbxJdbcPluginTest {
assertFalse(properties.containsKey("connectTimeout"));
}
@Test
void mysqlPagedQueriesEnableConnectorCursorFetchingByDefault() throws Exception {
Method method = DbxJdbcPlugin.class.getDeclaredMethod(
"applyPagedFetchProperties",
JsonNode.class,
String.class,
Properties.class
);
method.setAccessible(true);
Properties properties = new Properties();
JsonNode connection = MAPPER.readTree("""
{
"connection_string": "jdbc:mysql://127.0.0.1:3306/app",
"jdbc_driver_class": "com.mysql.cj.jdbc.Driver"
}
""");
method.invoke(null, connection, "jdbc:mysql://127.0.0.1:3306/app", properties);
assertEquals("true", properties.getProperty("useCursorFetch"));
}
@Test
void mysqlPagedQueriesPreserveExplicitCursorFetchSetting() throws Exception {
Method method = DbxJdbcPlugin.class.getDeclaredMethod(
"applyPagedFetchProperties",
JsonNode.class,
String.class,
Properties.class
);
method.setAccessible(true);
Properties properties = new Properties();
JsonNode connection = MAPPER.readTree("""
{
"connection_string": "jdbc:mysql://127.0.0.1:3306/app?useCursorFetch=false"
}
""");
method.invoke(
null,
connection,
"jdbc:mysql://127.0.0.1:3306/app?useCursorFetch=false",
properties
);
assertFalse(properties.containsKey("useCursorFetch"));
}
@Test
void postgresPagedQueryUsesCursorTransactionAndRestoresAutoCommit() throws Exception {
Method begin = DbxJdbcPlugin.class.getDeclaredMethod(
"beginPagedQueryTransaction",
JsonNode.class,
Connection.class
);
Method create = DbxJdbcPlugin.class.getDeclaredMethod("createPagedQueryStatement", Connection.class);
Method restore = DbxJdbcPlugin.class.getDeclaredMethod(
"restorePagedQueryTransaction",
Connection.class,
boolean.class
);
begin.setAccessible(true);
create.setAccessible(true);
restore.setAccessible(true);
List<String> calls = new ArrayList<>();
Connection connection = pagedQueryConnection(calls, true);
JsonNode config = MAPPER.readTree("""
{ "connection_string": "jdbc:postgresql://127.0.0.1:5432/app" }
""");
boolean restoreAutoCommit = (boolean) begin.invoke(null, config, connection);
create.invoke(null, connection);
restore.invoke(null, connection, restoreAutoCommit);
assertEquals(true, restoreAutoCommit);
assertEquals(
List.of(
"getAutoCommit",
"setAutoCommit:false",
"createStatement:" + ResultSet.TYPE_FORWARD_ONLY + ":" + ResultSet.CONCUR_READ_ONLY,
"rollback",
"setAutoCommit:true"
),
calls
);
}
@Test
void postgresPagedQueryPreservesExistingManualTransaction() throws Exception {
Method begin = DbxJdbcPlugin.class.getDeclaredMethod(
"beginPagedQueryTransaction",
JsonNode.class,
Connection.class
);
Method restore = DbxJdbcPlugin.class.getDeclaredMethod(
"restorePagedQueryTransaction",
Connection.class,
boolean.class
);
begin.setAccessible(true);
restore.setAccessible(true);
List<String> calls = new ArrayList<>();
Connection connection = pagedQueryConnection(calls, false);
JsonNode config = MAPPER.readTree("""
{ "jdbc_driver_class": "org.postgresql.Driver" }
""");
boolean restoreAutoCommit = (boolean) begin.invoke(null, config, connection);
restore.invoke(null, connection, restoreAutoCommit);
assertFalse(restoreAutoCommit);
assertEquals(List.of("getAutoCommit"), calls);
}
@Test
void jdbcxHighPrivilegeExtensionsAreDisabledByDefault() throws Exception {
Method method = DbxJdbcPlugin.class.getDeclaredMethod(
@@ -1485,6 +1599,36 @@ final class DbxJdbcPluginTest {
);
}
private static Connection pagedQueryConnection(List<String> calls, boolean autoCommit) {
return (Connection) Proxy.newProxyInstance(
DbxJdbcPluginTest.class.getClassLoader(),
new Class<?>[] { Connection.class },
(proxy, method, args) -> switch (method.getName()) {
case "getAutoCommit" -> {
calls.add("getAutoCommit");
yield autoCommit;
}
case "setAutoCommit" -> {
calls.add("setAutoCommit:" + args[0]);
yield null;
}
case "rollback" -> {
calls.add("rollback");
yield null;
}
case "createStatement" -> {
if (args == null || args.length == 0) {
calls.add("createStatement");
} else {
calls.add("createStatement:" + args[0] + ":" + args[1]);
}
yield recordingStatement(new ArrayList<>());
}
default -> defaultValue(method.getReturnType());
}
);
}
private static ResultSet temporalResultSet(Object objectValue, Date dateValue) {
return (ResultSet) Proxy.newProxyInstance(
DbxJdbcPluginTest.class.getClassLoader(),