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(oceanbase): preserve full LOB snapshot read write and export semantics
efeireba1d5ec943d9
diff --git a/agents/common/src/main/java/com/dbx/agent/AbstractJdbcAgent.java b/agents/common/src/main/java/com/dbx/agent/AbstractJdbcAgent.javaindex 528eb48044..e6b64132a9 100644--- a/agents/common/src/main/java/com/dbx/agent/AbstractJdbcAgent.java+++ b/agents/common/src/main/java/com/dbx/agent/AbstractJdbcAgent.java@@ -421,7 +421,7 @@ public abstract class AbstractJdbcAgent extends BaseDatabaseAgent {releasePooledConnection(true);return;}- if (sessionAffinity || executor.hasOpenSessions() || executor.hasActiveStatements()) {+ if (sessionAffinity || executor.hasOpenSessions() || executor.hasActiveStatements() || hasRetainedResultResources()) {return;}releasePooledConnection(!preparePooledConnectionForReturn());@@ -438,7 +438,7 @@ public abstract class AbstractJdbcAgent extends BaseDatabaseAgent {if (sessionAffinity) {return;}- if (executor.hasOpenSessions() || executor.hasActiveStatements()) {+ if (executor.hasOpenSessions() || executor.hasActiveStatements() || hasRetainedResultResources()) {return;}releasePooledConnection(!preparePooledConnectionForReturn());@@ -713,7 +713,12 @@ public abstract class AbstractJdbcAgent extends BaseDatabaseAgent {);}+ protected boolean hasRetainedResultResources() { return false; }++ protected void releaseRetainedResultResources() { }+private void closeCurrentConnection() throws Exception {+ releaseRetainedResultResources();if (pooledLease != null) {boolean evict = pooledConnectionPoisoned || sessionAffinity || !preparePooledConnectionForReturn();releasePooledConnection(evict);@@ -732,7 +737,17 @@ public abstract class AbstractJdbcAgent extends BaseDatabaseAgent {return JdbcSchemaSwitcher.resetBeforeReturn(connection);}+ protected final synchronized void discardConnection(Connection failedConnection) throws java.sql.SQLException {+ if (pooledLease != null && connection == failedConnection) {+ // Evict the checked-out lease before closing its proxy; close alone returns it to the pool.+ releasePooledConnection(true);+ } else {+ failedConnection.close();+ }+ }+private void releasePooledConnection(boolean evict) {+ releaseRetainedResultResources();JdbcConnectionPoolRegistry.Lease lease = pooledLease;pooledLease = null;connection = null;diff --git a/agents/common/src/main/java/com/dbx/agent/AgentProtocol.java b/agents/common/src/main/java/com/dbx/agent/AgentProtocol.javaindex 93cd3d388f..19a9541959 100644--- a/agents/common/src/main/java/com/dbx/agent/AgentProtocol.java+++ b/agents/common/src/main/java/com/dbx/agent/AgentProtocol.java@@ -38,6 +38,8 @@ public final class AgentProtocol {public static final String METHOD_EXECUTE_QUERY_PAGE = "execute_query_page";public static final String METHOD_FETCH_QUERY_PAGE = "fetch_query_page";public static final String METHOD_CLOSE_QUERY_SESSION = "close_query_session";+ public static final String METHOD_READ_LARGE_VALUE_CHUNK = "read_large_value_chunk";+ public static final String METHOD_RELEASE_LARGE_VALUE = "release_large_value";public static final String METHOD_START_TABLE_READ = "start_table_read";public static final String METHOD_FETCH_TABLE_READ_PAGE = "fetch_table_read_page";public static final String METHOD_CLOSE_TABLE_READ_SESSION = "close_table_read_session";@@ -141,6 +143,7 @@ public final class AgentProtocol {public static final String CAPABILITY_MONGO_FIND_CURSOR = "mongo_find_cursor";public static final String CAPABILITY_MULTI_SESSION = "multi_session";public static final String CAPABILITY_STRUCTURED_ERROR_V1 = "structured_error_v1";+ public static final String CAPABILITY_BLOB_BIND_STATEMENTS_V1 = "blob_bind_statements_v1";public static final List<String> CAPABILITIES = Collections.unmodifiableList(Arrays.asList(CAPABILITY_CONNECT,@@ -215,6 +218,8 @@ public final class AgentProtocol {METHOD_EXECUTE_QUERY_PAGE,METHOD_FETCH_QUERY_PAGE,METHOD_CLOSE_QUERY_SESSION,+ METHOD_READ_LARGE_VALUE_CHUNK,+ METHOD_RELEASE_LARGE_VALUE,METHOD_START_TABLE_READ,METHOD_FETCH_TABLE_READ_PAGE,METHOD_CLOSE_TABLE_READ_SESSION,@@ -267,6 +272,7 @@ public final class AgentProtocol {List<String> jdbcAllCapabilities = new java.util.ArrayList<>(MULTI_SESSION_ALL_CAPABILITIES);jdbcAllCapabilities.add(CAPABILITY_STRUCTURED_ERROR_V1);+ jdbcAllCapabilities.add(CAPABILITY_BLOB_BIND_STATEMENTS_V1);MULTI_SESSION_JDBC_ALL_CAPABILITIES = Collections.unmodifiableList(jdbcAllCapabilities);List<String> methods = new java.util.ArrayList<>(COMMON_METHODS);@@ -383,6 +389,13 @@ public final class AgentProtocol {);}+ public static HandshakeResult multiSessionJdbcHandshakeResult(boolean blobBindStatements) {+ if (!blobBindStatements) return multiSessionJdbcHandshakeResult();+ java.util.ArrayList<String> capabilities = new java.util.ArrayList<>(MULTI_SESSION_JDBC_CAPABILITIES);+ capabilities.add(CAPABILITY_BLOB_BIND_STATEMENTS_V1);+ return new HandshakeResult(MULTI_SESSION_PROTOCOL_VERSION, MULTI_SESSION_PROTOCOL_VERSION, capabilities);+ }+public static final class HandshakeResult {private final int protocolVersion;private final int agentProtocolVersion;diff --git a/agents/common/src/main/java/com/dbx/agent/AgentRpcError.java b/agents/common/src/main/java/com/dbx/agent/AgentRpcError.javaindex aed7c39979..2b20dfeb70 100644--- a/agents/common/src/main/java/com/dbx/agent/AgentRpcError.java+++ b/agents/common/src/main/java/com/dbx/agent/AgentRpcError.java@@ -57,6 +57,11 @@ final class AgentRpcError extends RuntimeException {);}+ static AgentRpcError rollbackConfirmedSql(SQLException error) {+ return new AgentRpcError(message(error), "sql", false, "keep", "execute", "unknown",+ safeSqlState(error.getSQLState()), error.getErrorCode(), safeClassName(error), error);+ }+static AgentRpcError backpressure(String stage, Throwable cause) {return new AgentRpcError("Agent request capacity is temporarily exhausted",diff --git a/agents/common/src/main/java/com/dbx/agent/BlobBoundExecutor.java b/agents/common/src/main/java/com/dbx/agent/BlobBoundExecutor.javanew file mode 100644index 0000000000..a554e46a5c--- /dev/null+++ b/agents/common/src/main/java/com/dbx/agent/BlobBoundExecutor.java@@ -0,0 +1,208 @@+package com.dbx.agent;++import java.io.InputStream;+import java.sql.Connection;+import java.sql.PreparedStatement;+import java.sql.Statement;+import java.sql.Savepoint;+import java.sql.SQLException;+import java.sql.SQLTransientConnectionException;+import java.util.ArrayList;+import java.util.Collections;+import java.util.List;+import java.util.Locale;+import java.util.function.Function;+import java.util.function.Supplier;++public final class BlobBoundExecutor {+ private BlobBoundExecutor() { }++ @FunctionalInterface+ public interface PreparedStatementConfigurer {+ void configure(PreparedStatement statement) throws SQLException;+ default void discardConnection(Connection connection) throws SQLException { connection.close(); }+ default boolean isRollbackConfirmedBusinessError(SQLException error) { return false; }+ default boolean isUnsupportedSavepointRelease(SQLException error) { return false; }+ }++ public static QueryResult execute(Connection conn, List<String> previews, List<BlobBoundStatement> statements,+ String schema, Function<String, String> setSchemaSql, Supplier<String> resetSchemaSql,+ int timeoutSecs, boolean transaction) {+ return execute(conn, previews, statements, schema, setSchemaSql, resetSchemaSql, timeoutSecs,+ transaction, statement -> { });+ }++ public static QueryResult execute(Connection conn, List<String> previews, List<BlobBoundStatement> statements,+ String schema, Function<String, String> setSchemaSql, Supplier<String> resetSchemaSql,+ int timeoutSecs, boolean transaction, PreparedStatementConfigurer configurer) {+ BlobBoundStatement.validate(previews, statements);+ if (timeoutSecs < 0) throw new IllegalArgumentException("BLOB binding timeout must be non-negative");+ try (JdbcExecutor.NativeOperation operation = JdbcExecutor.current().beginNativeOperation()) {+ operation.checkCancelled();+ boolean autoCommit = conn.getAutoCommit();+ if (transaction && !autoCommit) {+ throw new IllegalStateException("Cannot start a one-shot transaction while a manual transaction is open");+ }+ // Typed grid saves are atomic even when execute_batch omits useTransaction.+ // Existing manual transactions keep their batch-only savepoint boundary.+ boolean oneShot = transaction || autoCommit;+ if (oneShot && !conn.getMetaData().supportsTransactions()) {+ throw new UnsupportedOperationException("Transactions are not supported by this JDBC driver");+ }+ if (oneShot) conn.setAutoCommit(false);+ Savepoint savepoint = !oneShot ? conn.setSavepoint() : null;+ boolean finished = !oneShot;+ boolean discarded = false;+ boolean commitAttempted = false;+ try {+ long start = System.currentTimeMillis();+ long affected = executeAll(conn, statements, schema, setSchemaSql, resetSchemaSql, timeoutSecs, operation, configurer);+ operation.checkCancelled();+ if (oneShot) { commitAttempted = true; conn.commit(); }+ if (savepoint != null) releaseSavepoint(conn, savepoint, configurer);+ finished = true;+ return new QueryResult(Collections.emptyList(), Collections.emptyList(), affected,+ System.currentTimeMillis() - start, false);+ } catch (Exception failure) {+ if (oneShot) {+ try { conn.rollback(); finished = true; }+ catch (Exception rollbackFailure) {+ discarded = true;+ throw rollbackUnconfirmed(conn, failure, rollbackFailure, configurer);+ }+ if (!commitAttempted && failure instanceof SQLException sqlFailure+ && configurer.isRollbackConfirmedBusinessError(sqlFailure)) {+ throw AgentRpcError.rollbackConfirmedSql(sqlFailure);+ }+ }+ if (savepoint != null) {+ try { conn.rollback(savepoint); }+ catch (Exception rollbackFailure) { throw rollbackUnconfirmed(conn, failure, rollbackFailure, configurer); }+ try { releaseSavepoint(conn, savepoint, configurer); }+ catch (Exception releaseFailure) {+ SQLTransientConnectionException unsafe = new SQLTransientConnectionException(+ "BLOB savepoint cleanup failed after batch rollback; discard this connection and treat transaction state as unknown", "08007", releaseFailure);+ unsafe.addSuppressed(failure);+ try { configurer.discardConnection(conn); } catch (Exception closeFailure) { unsafe.addSuppressed(closeFailure); }+ throw unsafe;+ }+ if (failure instanceof SQLException sqlFailure && configurer.isRollbackConfirmedBusinessError(sqlFailure)) {+ throw AgentRpcError.rollbackConfirmedSql(sqlFailure);+ }+ }+ throw failure;+ } finally {+ if (oneShot) {+ if (finished) {+ try { conn.setAutoCommit(autoCommit); }+ catch (Exception resetFailure) {+ SQLTransientConnectionException unsafe = new SQLTransientConnectionException(+ "BLOB transaction connection reset failed; committed writes may exist and operation outcome is unknown", "08007", resetFailure);+ try { configurer.discardConnection(conn); } catch (Exception closeFailure) { unsafe.addSuppressed(closeFailure); }+ throw unsafe;+ }+ } else if (!discarded) configurer.discardConnection(conn); // Never enable auto-commit after an unconfirmed rollback.+ }+ }+ } catch (RuntimeException failure) {+ throw failure;+ } catch (Exception failure) {+ throw new RuntimeException(failure);+ }+ }++ private static SQLTransientConnectionException rollbackUnconfirmed(Connection conn, Exception failure,+ Exception rollbackFailure, PreparedStatementConfigurer configurer) {+ SQLTransientConnectionException unsafe = new SQLTransientConnectionException(+ "BLOB binding rollback was not confirmed; discard this connection and treat the operation outcome as unknown", "08007", failure);+ unsafe.addSuppressed(rollbackFailure);+ try { configurer.discardConnection(conn); } catch (Exception closeFailure) { unsafe.addSuppressed(closeFailure); }+ return unsafe;+ }++ private static void releaseSavepoint(Connection conn, Savepoint savepoint,+ PreparedStatementConfigurer configurer) throws SQLException {+ try { conn.releaseSavepoint(savepoint); }+ catch (SQLException error) {+ if (!configurer.isUnsupportedSavepointRelease(error)) throw error;+ }+ }++ private static long executeAll(Connection conn, List<BlobBoundStatement> statements, String schema,+ Function<String, String> setSchemaSql, Supplier<String> resetSchemaSql, int timeoutSecs,+ JdbcExecutor.NativeOperation operation, PreparedStatementConfigurer configurer) throws Exception {+ JdbcExecutor executor = JdbcExecutor.current();+ try (BoundResources resources = new BoundResources()) {+ operation.checkCancelled();+ JdbcSchemaSwitcher.apply(conn, schema, setSchemaSql, resetSchemaSql);+ for (BlobBoundStatement bound : statements) {+ operation.checkCancelled();+ String sql = JdbcExecutor.trimSql(bound.sql());+ Statement statement = bound.blobParameters().isEmpty() ? conn.createStatement()+ : isAnonymousBlock(sql) ? conn.prepareCall(sql) : conn.prepareStatement(sql);+ resources.statements.add(executor.trackStatement(statement));+ statement.setQueryTimeout(timeoutSecs);+ if (statement instanceof PreparedStatement prepared) {+ configurer.configure(prepared);+ int index = 1;+ for (String hex : bound.blobParameters()) {+ InputStream stream = new HexStream(hex);+ resources.streams.add(stream);+ prepared.setBlob(index++, stream, (long) hex.length() / 2);+ }+ }+ }+ // Prepare and bind the complete batch before the first write.+ long affected = 0;+ for (int i = 0; i < statements.size(); i++) {+ operation.checkCancelled();+ Statement statement = resources.statements.get(i).statement();+ boolean result = statement instanceof PreparedStatement prepared ? prepared.execute()+ : statement.execute(JdbcExecutor.trimSql(statements.get(i).sql()));+ if (!result) affected += Math.max(0, statement.getUpdateCount());+ operation.checkCancelled();+ }+ return affected;+ }+ }++ private static final class BoundResources implements AutoCloseable {+ final List<JdbcExecutor.TrackedStatement<Statement>> statements = new ArrayList<>();+ final List<InputStream> streams = new ArrayList<>();+ @Override public void close() throws Exception {+ Exception failure = null;+ List<AutoCloseable> resources = new ArrayList<>(statements);+ resources.addAll(streams);+ for (AutoCloseable resource : resources) {+ try { resource.close(); }+ catch (Exception error) {+ if (failure == null) failure = error;+ else failure.addSuppressed(error);+ }+ }+ if (failure != null) throw failure;+ }+ }++ private static boolean isAnonymousBlock(String sql) {+ String normalized = sql.toUpperCase(Locale.ROOT);+ return normalized.startsWith("DECLARE") || normalized.startsWith("BEGIN");+ }++ /** Decode already-validated hex without retaining a second full byte array. */+ private static final class HexStream extends InputStream {+ private final String hex;+ private int offset;+ private boolean closed;+ HexStream(String hex) { this.hex = hex; }+ @Override public int available() { return closed ? 0 : (hex.length() - offset) / 2; }+ @Override public int read() throws java.io.IOException {+ if (closed) throw new java.io.IOException("BLOB binding stream is closed");+ if (offset == hex.length()) return -1;+ int value = Character.digit(hex.charAt(offset), 16) * 16 + Character.digit(hex.charAt(offset + 1), 16);+ offset += 2;+ return value;+ }+ @Override public void close() { closed = true; }+ }+}diff --git a/agents/common/src/main/java/com/dbx/agent/BlobBoundStatement.java b/agents/common/src/main/java/com/dbx/agent/BlobBoundStatement.javanew file mode 100644index 0000000000..a487057100--- /dev/null+++ b/agents/common/src/main/java/com/dbx/agent/BlobBoundStatement.java@@ -0,0 +1,93 @@+package com.dbx.agent;++import java.util.List;++/** Optional BLOB-only binding payload; preview text stays authoritative. */+public final class BlobBoundStatement {+ private String previewSql;+ private String sql;+ private List<String> blobParameters;++ public BlobBoundStatement(String previewSql, String sql, List<String> blobParameters) {+ this.previewSql = previewSql;+ this.sql = sql;+ this.blobParameters = blobParameters;+ }++ public String sql() { return sql; }+ public List<String> blobParameters() { return blobParameters; }++ public static void validate(List<String> statements, List<BlobBoundStatement> boundStatements) {+ if (statements == null || boundStatements == null || statements.size() != boundStatements.size()) {+ throw new IllegalArgumentException("BLOB bound statements must match the complete statement batch");+ }+ for (int i = 0; i < statements.size(); i++) {+ BlobBoundStatement bound = boundStatements.get(i);+ if (bound == null || statements.get(i) == null || !statements.get(i).equals(bound.previewSql)+ || bound.sql == null || bound.sql.trim().isEmpty() || bound.blobParameters == null) {+ throw new IllegalArgumentException("BLOB binding preview mismatch at statement " + (i + 1));+ }+ if (bound.blobParameters.isEmpty() && !bound.sql.equals(bound.previewSql)) {+ throw new IllegalArgumentException("Unbound statement SQL must match its preview");+ }+ SqlScan scan = scanSql(bound.sql);+ String visible = scan.visible().stripLeading().toUpperCase(java.util.Locale.ROOT);+ if (!visible.matches("(?s)^(?:UPDATE|INSERT|DELETE)\\b.*")+ && !visible.matches("(?s)^(?:DECLARE\\b.*?)?BEGIN\\s+(?:UPDATE|INSERT|DELETE)\\b.*")+ || java.util.regex.Pattern.compile("\\b(?:CREATE|ALTER|DROP|TRUNCATE|COMMIT|ROLLBACK|SAVEPOINT|GRANT|REVOKE|EXECUTE)\\b").matcher(visible).find()) {+ throw new IllegalArgumentException("BLOB binding only supports data-grid DML, without DDL or transaction control");+ }+ if (!bound.blobParameters.isEmpty() && scan.parameters() != bound.blobParameters.size()) {+ throw new IllegalArgumentException("BLOB parameter count does not match statement " + (i + 1));+ }+ for (String hex : bound.blobParameters) {+ if (hex == null || (hex.length() & 1) != 0) {+ throw new IllegalArgumentException("BLOB parameters must contain even-length hexadecimal bytes");+ }+ for (int j = 0; j < hex.length(); j++) {+ if (Character.digit(hex.charAt(j), 16) < 0 || hex.charAt(j) > 127) {+ throw new IllegalArgumentException("BLOB parameters must contain hexadecimal bytes only");+ }+ }+ }+ }+ }++ private record SqlScan(int parameters, String visible) { }++ private static SqlScan scanSql(String sql) {+ int count = 0;+ StringBuilder visible = new StringBuilder();+ for (int i = 0; i < sql.length(); i++) {+ char ch = sql.charAt(i);+ char next = i + 1 < sql.length() ? sql.charAt(i + 1) : '\0';+ if (ch == '-' && next == '-') {+ visible.append(' ');+ while (i + 1 < sql.length() && sql.charAt(i + 1) != '\n') i++;+ } else if (ch == '/' && next == '*') {+ visible.append(' ');+ int end = sql.indexOf("*/", i + 2);+ i = end < 0 ? sql.length() : end + 1;+ } else if ((ch == 'q' || ch == 'Q') && next == '\'' && i + 2 < sql.length()) {+ visible.append(' ');+ char open = sql.charAt(i + 2);+ char close = open == '[' ? ']' : open == '(' ? ')' : open == '{' ? '}' : open == '<' ? '>' : open;+ int end = sql.indexOf("" + close + '\'', i + 3);+ i = end < 0 ? sql.length() : end + 1;+ } else if (ch == '\'' || ch == '"') {+ visible.append(' ');+ char quote = ch;+ while (++i < sql.length()) {+ if (sql.charAt(i) == quote) {+ if (i + 1 < sql.length() && sql.charAt(i + 1) == quote) i++;+ else break;+ }+ }+ } else {+ visible.append(ch);+ if (ch == '?') count++;+ }+ }+ return new SqlScan(count, visible.toString());+ }+}diff --git a/agents/common/src/main/java/com/dbx/agent/DatabaseAgent.java b/agents/common/src/main/java/com/dbx/agent/DatabaseAgent.javaindex 042238ac90..181b68e204 100644--- a/agents/common/src/main/java/com/dbx/agent/DatabaseAgent.java+++ b/agents/common/src/main/java/com/dbx/agent/DatabaseAgent.java@@ -14,6 +14,13 @@ public interface DatabaseAgent {/** Opt in to request-boundary timing, including pooled connection lifecycle. */default boolean supportsQueryTiming() { return false; }+ default boolean supportsBlobBindStatements() { return false; }++ default QueryResult executeBlobBoundStatements(List<String> previews, List<BlobBoundStatement> statements,+ String schema, int timeoutSecs, boolean transaction) {+ throw new UnsupportedOperationException("BLOB statement binding is not supported by this agent");+ }+/** A dedicated manual transaction must never migrate to a replacement connection. */default boolean permitsAutomaticReconnect() { return true; }@@ -208,6 +215,14 @@ public interface DatabaseAgent {return AgentExecutionContext.jdbcExecutor().closeQuerySession(sessionId);}+ default Object readLargeValueChunk(String valueRef, long offset, int limit) {+ throw new UnsupportedOperationException("LOB snapshot chunks are not supported by this agent");+ }++ default boolean releaseLargeValue(String valueRef) { return false; }++ default void invalidateLargeValues() { }+default QueryPageResult startTableRead(String sql, String schema, QueryPageOptions options) {Connection conn = getConnection();if (conn == null) {diff --git a/agents/common/src/main/java/com/dbx/agent/JdbcExecutor.java b/agents/common/src/main/java/com/dbx/agent/JdbcExecutor.javaindex 6bc97aac73..4b41de492b 100644--- a/agents/common/src/main/java/com/dbx/agent/JdbcExecutor.java+++ b/agents/common/src/main/java/com/dbx/agent/JdbcExecutor.java@@ -1217,6 +1217,20 @@ public final class JdbcExecutor {* agents to convert vendor-specific column types (e.g. PostGIS* {@code geometry}) without re-querying the metadata.*/+ public <T> T withActiveStatement(Statement statement, SqlOperation<T> operation) throws SQLException {+ activeStatements.add(statement);+ try {+ return operation.run();+ } finally {+ activeStatements.remove(statement);+ }+ }++ @FunctionalInterface+ public interface SqlOperation<T> {+ T run() throws SQLException;+ }+public interface ColumnAwareResultValueReader extends ResultValueReader {Object read(ResultSet rs, int index, int sqlType, String columnTypeName) throws SQLException;diff --git a/agents/common/src/main/java/com/dbx/agent/JsonRpcServer.java b/agents/common/src/main/java/com/dbx/agent/JsonRpcServer.javaindex 996738e5e5..46cae463e6 100644--- a/agents/common/src/main/java/com/dbx/agent/JsonRpcServer.java+++ b/agents/common/src/main/java/com/dbx/agent/JsonRpcServer.java@@ -152,6 +152,7 @@ public final class JsonRpcServer {void cancelActiveStatements() {jdbcExecutor.cancelActiveStatements();+ agent.invalidateLargeValues();AbstractJdbcAgent jdbcAgent = pooledJdbcAgent();if (jdbcAgent != null) {jdbcAgent.releaseIdlePooledConnection(jdbcExecutor);@@ -325,6 +326,13 @@ public final class JsonRpcServer {if (AgentProtocol.METHOD_CLOSE_QUERY_SESSION.equals(method)) {return agent.closeQuerySession(params.get("sessionId").getAsString());}+ if (AgentProtocol.METHOD_READ_LARGE_VALUE_CHUNK.equals(method)) {+ return agent.readLargeValueChunk(params.get("valueRef").getAsString(),+ params.get("offset").getAsLong(), intOrDefault(params, "limit", 4096));+ }+ if (AgentProtocol.METHOD_RELEASE_LARGE_VALUE.equals(method)) {+ return agent.releaseLargeValue(params.get("valueRef").getAsString());+ }if (AgentProtocol.METHOD_START_TABLE_READ.equals(method)) {return agent.startTableRead(params.get("sql").getAsString(),@@ -361,22 +369,33 @@ public final class JsonRpcServer {return result;}if (AgentProtocol.METHOD_EXECUTE_TRANSACTION.equals(method)) {+ agent.invalidateLargeValues();Type statementsType = new TypeToken<List<String>>() {}.getType();List<String> statements = gson.fromJson(params.get("statements"), statementsType);+ if (params.has("boundStatements")) {+ return executeBlobBoundStatements(params, statements, true);+ }return agent.executeTransaction(statements, stringOrNull(params, "schema"));}if (AgentProtocol.METHOD_BEGIN_MANUAL_TRANSACTION.equals(method)) {+ agent.invalidateLargeValues();return agent.beginManualTransaction(stringOrNull(params, "schema"));}if (AgentProtocol.METHOD_COMMIT_MANUAL_TRANSACTION.equals(method)) {+ agent.invalidateLargeValues();return agent.commitManualTransaction();}if (AgentProtocol.METHOD_ROLLBACK_MANUAL_TRANSACTION.equals(method)) {+ agent.invalidateLargeValues();return agent.rollbackManualTransaction();}if (AgentProtocol.METHOD_EXECUTE_BATCH.equals(method)) {+ agent.invalidateLargeValues();Type statementsType = new TypeToken<List<String>>() {}.getType();List<String> statements = gson.fromJson(params.get("statements"), statementsType);+ if (params.has("boundStatements")) {+ return executeBlobBoundStatements(params, statements, false);+ }return agent.executeBatch(statements, stringOrNull(params, "schema"));}if (AgentProtocol.METHOD_DISCONNECT.equals(method)) {@@ -396,6 +415,38 @@ public final class JsonRpcServer {throw new IllegalArgumentException("Unknown method: " + method);}+ private QueryResult executeBlobBoundStatements(JsonObject params, List<String> previews, boolean transaction) {+ if (!agent.supportsBlobBindStatements()) {+ throw new UnsupportedOperationException("Agent does not support blob_bind_statements_v1");+ }+ if (!params.get("boundStatements").isJsonArray()) {+ throw new IllegalArgumentException("BLOB bound statements must be an array");+ }+ for (com.google.gson.JsonElement entry : params.getAsJsonArray("boundStatements")) {+ if (!entry.isJsonObject()) throw new IllegalArgumentException("BLOB bound statement must be an object");+ JsonObject item = entry.getAsJsonObject();+ for (String field : java.util.Arrays.asList("previewSql", "sql")) {+ if (!item.has(field) || !item.get(field).isJsonPrimitive()+ || !item.get(field).getAsJsonPrimitive().isString()) {+ throw new IllegalArgumentException("BLOB bound statement text fields must be strings");+ }+ }+ if (!item.has("blobParameters") || !item.get("blobParameters").isJsonArray()) {+ throw new IllegalArgumentException("BLOB parameters must be an array of hexadecimal strings");+ }+ for (com.google.gson.JsonElement value : item.getAsJsonArray("blobParameters")) {+ if (!value.isJsonPrimitive() || !value.getAsJsonPrimitive().isString()) {+ throw new IllegalArgumentException("BLOB parameter must be a hexadecimal string");+ }+ }+ }+ Type boundType = new TypeToken<List<BlobBoundStatement>>() {}.getType();+ List<BlobBoundStatement> statements = gson.fromJson(params.get("boundStatements"), boundType);+ BlobBoundStatement.validate(previews, statements);+ return agent.executeBlobBoundStatements(previews, statements, stringOrNull(params, "schema"),+ intOrDefault(params, "queryTimeoutSecs", 0), transaction);+ }+private void switchCatalog(JsonObject params) throws Exception {String database = stringOrNull(params, "database");if (database != null && !database.trim().isEmpty() && agent.getConnection() != null) {diff --git a/agents/common/src/main/java/com/dbx/agent/MultiSessionJsonRpcServer.java b/agents/common/src/main/java/com/dbx/agent/MultiSessionJsonRpcServer.javaindex 309255320e..f67b8dbdcd 100644--- a/agents/common/src/main/java/com/dbx/agent/MultiSessionJsonRpcServer.java+++ b/agents/common/src/main/java/com/dbx/agent/MultiSessionJsonRpcServer.java@@ -45,6 +45,7 @@ public final class MultiSessionJsonRpcServer implements AutoCloseable {private final Object maintenanceLock = new Object();private final AtomicBoolean closed = new AtomicBoolean();private ScheduledExecutorService maintenance;+ private boolean blobBindStatements;public MultiSessionJsonRpcServer(Supplier<? extends DatabaseAgent> agentFactory) {this(agentFactory, new JdbcConnectionPoolRegistry(), RuntimeLimits.defaults());@@ -91,6 +92,12 @@ public final class MultiSessionJsonRpcServer implements AutoCloseable {return new MultiSessionJsonRpcServer(sessionHandlerFactory, true);}+ public static MultiSessionJsonRpcServer withBlobBindings(Supplier<? extends DatabaseAgent> agentFactory) {+ MultiSessionJsonRpcServer server = new MultiSessionJsonRpcServer(agentFactory);+ server.blobBindStatements = true;+ return server;+ }+public void run() {synchronized (outputLock) {protocolOutput.println("{\"ready\":true}");@@ -138,7 +145,9 @@ public final class MultiSessionJsonRpcServer implements AutoCloseable {try {Object result;if (AgentProtocol.METHOD_HANDSHAKE.equals(method)) {- result = sessionHandlerFactory == null ? AgentProtocol.multiSessionJdbcHandshakeResult() : customHandshake();+ result = sessionHandlerFactory == null+ ? AgentProtocol.multiSessionJdbcHandshakeResult(blobBindStatements)+ : customHandshake();} else if (AgentProtocol.METHOD_OPEN_SESSION.equals(method)) {result = openSession(requiredSessionId(params), params);} else if (AgentProtocol.METHOD_CLOSE_SESSION.equals(method)) {diff --git a/agents/common/src/main/resources/agent-protocol-v1.json b/agents/common/src/main/resources/agent-protocol-v1.jsonindex b363666a9e..af91085bbf 100644--- a/agents/common/src/main/resources/agent-protocol-v1.json+++ b/agents/common/src/main/resources/agent-protocol-v1.json@@ -32,6 +32,8 @@"execute_query_page","fetch_query_page","close_query_session",+ "read_large_value_chunk",+ "release_large_value","start_table_read","fetch_table_read_page","close_table_read_session",diff --git a/agents/common/src/main/resources/agent-protocol-v2.json b/agents/common/src/main/resources/agent-protocol-v2.jsonindex 8cd5f4e230..76d831bce7 100644--- a/agents/common/src/main/resources/agent-protocol-v2.json+++ b/agents/common/src/main/resources/agent-protocol-v2.json@@ -2,7 +2,7 @@"protocolVersion": 2,"handshakeMethod": "handshake","handshakeResponseFields": ["protocolVersion", "agentProtocolVersion", "capabilities"],- "allCapabilities": ["connect", "test_connection", "metadata", "query", "paged_query", "transaction", "ddl", "kv", "kv_ttl", "kv_cas", "kv_list_values", "kv_status", "kv_history", "etcd_compaction", "etcd_defrag", "etcd_watch", "etcd_lease", "etcd_auth", "mongo_drop_database", "mongo_clone_collection", "mongo_run_command", "mongo_insert_documents", "mongo_replace_document", "mongo_bulk_write", "mongo_rename_collection", "mongo_find_cursor", "multi_session", "structured_error_v1"],+ "allCapabilities": ["connect", "test_connection", "metadata", "query", "paged_query", "transaction", "ddl", "kv", "kv_ttl", "kv_cas", "kv_list_values", "kv_status", "kv_history", "etcd_compaction", "etcd_defrag", "etcd_watch", "etcd_lease", "etcd_auth", "mongo_drop_database", "mongo_clone_collection", "mongo_run_command", "mongo_insert_documents", "mongo_replace_document", "mongo_bulk_write", "mongo_rename_collection", "mongo_find_cursor", "multi_session", "structured_error_v1", "blob_bind_statements_v1"],"capabilities": ["connect", "test_connection", "metadata", "query", "paged_query", "transaction", "ddl", "multi_session"],"defaultSqlCapabilities": ["connect", "test_connection", "metadata", "query", "paged_query", "transaction", "ddl", "multi_session", "structured_error_v1"],"commonMethods": [@@ -36,6 +36,8 @@"execute_query_page","fetch_query_page","close_query_session",+ "read_large_value_chunk",+ "release_large_value","start_table_read","fetch_table_read_page","close_table_read_session",@@ -51,5 +53,15 @@"mongoLegacyMethods": ["list_databases", "list_collections", "find_documents", "find_one", "explain_find", "aggregate_documents", "find_documents_extended_json", "count_documents", "server_version", "create_index", "create_user", "drop_indexes", "drop_collection", "clone_collection", "drop_database", "insert_document", "insert_documents", "update_document", "update_documents", "replace_document", "bulk_write", "rename_collection", "delete_document", "delete_documents", "run_command", "start_find_cursor", "fetch_find_cursor", "close_find_cursor"],"kvMethods": ["kv_list_prefix", "kv_get", "kv_put", "kv_delete", "kv_rename", "kv_history", "kv_status", "etcd_compact", "etcd_defrag", "etcd_watch_start", "etcd_watch_poll", "etcd_watch_stop", "etcd_lease_list", "etcd_lease_get", "etcd_lease_grant", "etcd_lease_keepalive_once", "etcd_lease_revoke", "etcd_auth_user_list", "etcd_auth_user_get", "etcd_auth_user_add", "etcd_auth_user_delete", "etcd_auth_user_change_password", "etcd_auth_user_grant_role", "etcd_auth_user_revoke_role", "etcd_auth_role_list", "etcd_auth_role_get", "etcd_auth_role_add", "etcd_auth_role_delete", "etcd_auth_role_grant_permission", "etcd_auth_role_revoke_permission"],"sessionField": "agentSessionId",- "cursorSessionField": "sessionId"+ "cursorSessionField": "sessionId",+ "blobBindStatementsV1": {+ "capability": "blob_bind_statements_v1",+ "methods": ["execute_batch", "execute_transaction"],+ "optionalFields": ["boundStatements", "queryTimeoutSecs"],+ "statementFields": ["previewSql", "sql", "blobParameters"],+ "blobEncoding": "even-length hexadecimal without 0x",+ "previewRule": "complete array length and each previewSql must exactly match statements; unbound sql equals previewSql",+ "manualTransaction": "same connection, per-batch savepoint, no implicit commit; rollback to savepoint on failure",+ "unsupported": "reject complete request before executing any statement; no SQL-text fallback"+ }}diff --git a/agents/common/src/test/java/com/dbx/agent/BlobBoundExecutorTest.java b/agents/common/src/test/java/com/dbx/agent/BlobBoundExecutorTest.javanew file mode 100644index 0000000000..db83019541--- /dev/null+++ b/agents/common/src/test/java/com/dbx/agent/BlobBoundExecutorTest.java@@ -0,0 +1,322 @@+package com.dbx.agent;++import com.google.gson.JsonParser;+import org.junit.jupiter.api.Test;+import java.io.InputStream;+import java.lang.reflect.Proxy;+import java.sql.Connection;+import java.sql.DatabaseMetaData;+import java.sql.PreparedStatement;+import java.sql.CallableStatement;+import java.sql.Savepoint;+import java.sql.SQLTimeoutException;+import java.util.ArrayList;+import java.util.Arrays;+import java.util.List;+import static org.junit.jupiter.api.Assertions.*;++class BlobBoundExecutorTest {+ private static final String PREVIEW = "UPDATE t SET b=HEXTORAW('00ff80')";+ private static final String SQL = "BEGIN UPDATE t SET b=? WHERE DBMS_LOB.COMPARE(b,?)=0; END;";+ private static BlobBoundStatement bound() { return new BlobBoundStatement(PREVIEW, SQL, Arrays.asList("00ff80", "cafe")); }++ @Test void bindsStreamsOnFixedCallableSqlAndClosesThemBeforeCommit() throws Exception {+ Fake jdbc = new Fake();+ QueryResult result = run(jdbc, Arrays.asList(bound()), true);+ assertEquals(SQL, jdbc.preparedSql);+ assertEquals(Arrays.asList("00ff80", "cafe"), jdbc.boundHex);+ assertEquals(Arrays.asList(3L, 2L), jdbc.lengths);+ assertEquals(7, jdbc.timeout);+ assertEquals(1, jdbc.closedStatements);+ assertTrue(jdbc.events.indexOf("close") < jdbc.events.indexOf("commit"));+ assertEquals(1, jdbc.commits);+ assertEquals(0, jdbc.rollbacks);+ assertTrue(jdbc.autoCommit);+ assertEquals(1, result.getAffected_rows());+ for (InputStream stream : jdbc.streams) assertThrows(java.io.IOException.class, stream::read);+ }++ @Test void piecewiseDriverSeesRemainingBytesUntilEntireHexStreamIsSent() throws Exception {+ Fake jdbc=new Fake(); jdbc.piecewiseRead=true;+ String hex="00ff80".repeat(40000);+ BlobBoundStatement statement=new BlobBoundStatement(PREVIEW,"UPDATE t SET b=?",Arrays.asList(hex));+ run(jdbc,Arrays.asList(statement),false);+ assertEquals(Arrays.asList(hex),jdbc.boundHex);+ assertEquals(4,jdbc.pieces);+ assertEquals(0,jdbc.streams.get(0).available());+ }++ @Test void timeoutRollsBackClosesStreamsAndNeverFallsBackToText() throws Exception {+ Fake jdbc = new Fake(); jdbc.fail = true;+ RuntimeException failure = assertThrows(RuntimeException.class, () -> run(jdbc, Arrays.asList(bound()), true));+ assertInstanceOf(SQLTimeoutException.class, failure.getCause());+ assertEquals(1, jdbc.executions); assertEquals(1, jdbc.rollbacks); assertEquals(0, jdbc.commits);+ assertEquals(1, jdbc.closedStatements); assertTrue(jdbc.autoCommit);+ for (InputStream stream : jdbc.streams) assertThrows(java.io.IOException.class, stream::read);+ }++ @Test void manualFailureRollsBackOnlyBatchSavepoint() {+ Fake jdbc = new Fake(); jdbc.autoCommit = false; jdbc.fail = true;+ assertThrows(RuntimeException.class, () -> run(jdbc, Arrays.asList(bound()), false));+ assertEquals(1, jdbc.savepointRollbacks); assertEquals(0, jdbc.rollbacks);+ assertEquals(0, jdbc.commits); assertFalse(jdbc.autoCommit); assertEquals(1, jdbc.releases);+ }++ @Test void manualSuccessDoesNotCommitOrChangeAutoCommit() {+ Fake jdbc = new Fake(); jdbc.autoCommit = false;+ run(jdbc, Arrays.asList(bound()), false);+ assertEquals(1, jdbc.savepoints); assertEquals(1, jdbc.releases);+ assertEquals(0, jdbc.commits); assertEquals(0, jdbc.rollbacks); assertFalse(jdbc.autoCommit);+ }++ @Test void laterManualConflictRollsBackFirstWriteButPreservesPriorTransactionWork() {+ Fake jdbc = new Fake(); jdbc.autoCommit=false; jdbc.failAt=2;+ assertThrows(RuntimeException.class, () -> run(jdbc, Arrays.asList(bound(),bound()), false));+ assertEquals(2,jdbc.executions); assertEquals(42,jdbc.value);+ assertEquals(1,jdbc.savepointRollbacks); assertEquals(0,jdbc.rollbacks);+ assertEquals(0,jdbc.commits); assertFalse(jdbc.autoCommit);+ }++ @Test void failedManualRollbackQuarantinesConnectionWithUnknownOutcome() {+ Fake jdbc = new Fake(); jdbc.autoCommit=false; jdbc.failAt=1; jdbc.failRollback=true;+ RuntimeException failure=assertThrows(RuntimeException.class,()->run(jdbc,Arrays.asList(bound()),false));+ assertTrue(jdbc.connectionClosed); assertEquals(0,jdbc.commits);+ com.google.gson.JsonObject data=AgentRpcError.toJson(failure,"execute_batch","test").getAsJsonObject("data");+ assertEquals("quarantine",data.get("sessionDisposition").getAsString());+ assertEquals("unknown",data.get("operationOutcome").getAsString());+ assertEquals("connection",data.get("category").getAsString());+ assertEquals("08007",data.get("sqlState").getAsString());+ }++ @Test void confirmedObBusinessErrorKeepsPriorWorkButRollbackFailureStillQuarantines() {+ for (int cleanupFailure : new int[]{0,1,2}) {+ boolean cleanupFails=cleanupFailure!=0;+ Fake jdbc=new Fake(); jdbc.autoCommit=false; jdbc.failAt=2; jdbc.failRollback=cleanupFailure==1; jdbc.failRelease=cleanupFailure==2;+ jdbc.executionFailure=new java.sql.SQLTransientConnectionException("ORA-20001: stale target", "HY000", 20001);+ BlobBoundExecutor.PreparedStatementConfigurer configurer=new BlobBoundExecutor.PreparedStatementConfigurer() {+ public void configure(PreparedStatement statement) { }+ public boolean isRollbackConfirmedBusinessError(java.sql.SQLException error) { return error.getErrorCode()==20001; }+ };+ RuntimeException failure=assertThrows(RuntimeException.class,()->BlobBoundExecutor.execute(jdbc.connection(),+ Arrays.asList(PREVIEW,PREVIEW),Arrays.asList(bound(),bound()),null,s->s,()->null,7,false,configurer));+ var data=AgentRpcError.toJson(failure,"execute_batch","test").getAsJsonObject("data");+ assertEquals(cleanupFails?"quarantine":"keep",data.get("sessionDisposition").getAsString());+ assertEquals(cleanupFails?"connection":"sql",data.get("category").getAsString());+ assertEquals("unknown",data.get("operationOutcome").getAsString());+ assertEquals(0,jdbc.commits); assertEquals(0,jdbc.rollbacks);+ if(!cleanupFails) { assertEquals(42,jdbc.value); assertEquals(1,jdbc.savepointRollbacks); assertFalse(jdbc.connectionClosed); }+ else { assertTrue(jdbc.connectionClosed); assertEquals("08007",data.get("sqlState").getAsString()); }+ }+ }++ @Test void exactUnsupportedReleaseDoesNotCommitOrDiscardSuccessfulOrRolledBackManualBatch() {+ for(boolean conflict : new boolean[]{false,true}) {+ Fake jdbc=new Fake(); jdbc.autoCommit=false; jdbc.failRelease=true;+ jdbc.releaseFailure=new java.sql.SQLException("releaseSavepoint is not supported","99999",17023);+ if(conflict) { jdbc.failAt=2; jdbc.executionFailure=new java.sql.SQLTransientConnectionException("ORA-20001: stale", "HY000",20001); }+ BlobBoundExecutor.PreparedStatementConfigurer configurer=new BlobBoundExecutor.PreparedStatementConfigurer() {+ public void configure(PreparedStatement statement) { }+ public boolean isRollbackConfirmedBusinessError(java.sql.SQLException error) { return error.getErrorCode()==20001; }+ public boolean isUnsupportedSavepointRelease(java.sql.SQLException error) { return error.getErrorCode()==17023 && "99999".equals(error.getSQLState()); }+ };+ if(conflict) {+ RuntimeException failure=assertThrows(RuntimeException.class,()->BlobBoundExecutor.execute(jdbc.connection(),+ Arrays.asList(PREVIEW,PREVIEW),Arrays.asList(bound(),bound()),null,s->s,()->null,7,false,configurer));+ assertEquals("keep",AgentRpcError.toJson(failure,"execute_batch","test").getAsJsonObject("data").get("sessionDisposition").getAsString());+ assertEquals(42,jdbc.value); assertEquals(1,jdbc.savepointRollbacks);+ } else {+ BlobBoundExecutor.execute(jdbc.connection(),Arrays.asList(PREVIEW),Arrays.asList(bound()),null,s->s,()->null,7,false,configurer);+ assertEquals(43,jdbc.value); assertEquals(0,jdbc.savepointRollbacks);+ }+ assertEquals(0,jdbc.commits); assertFalse(jdbc.autoCommit); assertFalse(jdbc.connectionClosed);+ }+ }++ @Test void defaultTypedBatchCommitsOrRollsBackBeforeRestoringAutoCommit() {+ for(boolean conflict : new boolean[]{false,true}) {+ Fake jdbc=new Fake();+ if(conflict) { jdbc.failAt=2; jdbc.executionFailure=new java.sql.SQLTransientConnectionException("ORA-20001: stale", "HY000",20001); }+ BlobBoundExecutor.PreparedStatementConfigurer configurer=new BlobBoundExecutor.PreparedStatementConfigurer() {+ public void configure(PreparedStatement statement) { }+ public boolean isRollbackConfirmedBusinessError(java.sql.SQLException error) { return error.getErrorCode()==20001; }+ };+ if(conflict) {+ RuntimeException failure=assertThrows(RuntimeException.class,()->BlobBoundExecutor.execute(jdbc.connection(),+ Arrays.asList(PREVIEW,PREVIEW),Arrays.asList(bound(),bound()),null,s->s,()->null,7,false,configurer));+ assertEquals("keep",AgentRpcError.toJson(failure,"execute_batch","test").getAsJsonObject("data").get("sessionDisposition").getAsString());+ assertEquals(42,jdbc.value); assertEquals(1,jdbc.rollbacks); assertEquals(0,jdbc.commits);+ } else {+ BlobBoundExecutor.execute(jdbc.connection(),Arrays.asList(PREVIEW,PREVIEW),Arrays.asList(bound(),bound()),null,s->s,()->null,7,false,configurer);+ assertEquals(44,jdbc.value); assertEquals(1,jdbc.commits); assertEquals(0,jdbc.rollbacks);+ }+ assertTrue(jdbc.autoCommit); assertEquals(0,jdbc.savepoints);+ }+ Fake manual=new Fake(); manual.autoCommit=false;+ assertThrows(IllegalStateException.class,()->run(manual,Arrays.asList(bound()),true));+ assertEquals(0,manual.executions); assertFalse(manual.autoCommit);+ }++ @Test void typedDdlOrTransactionControlRejectsCompleteBatchBeforeOpeningConnection() {+ for(String sql : List.of("CREATE TABLE t (b BLOB)","BEGIN UPDATE t SET b=?; COMMIT; END;", "BEGIN EXECUTE IMMEDIATE 'DROP TABLE t'; END;")) {+ Fake jdbc=new Fake();+ BlobBoundStatement invalid=new BlobBoundStatement(sql,sql,sql.contains("?")?List.of("00"):List.of());+ assertThrows(IllegalArgumentException.class,()->run(jdbc,Arrays.asList(bound(),invalid),false));+ assertEquals(0,jdbc.executions); assertNull(jdbc.preparedSql); assertTrue(jdbc.autoCommit);+ }+ BlobBoundStatement.validate(List.of(PREVIEW),List.of(new BlobBoundStatement(PREVIEW,"UPDATE t SET b=? /* COMMIT */ WHERE note='CREATE TABLE x'",List.of("00"))));+ }++ @Test void defaultTypedCommitRollbackOrResetFailuresNeverBecomeKnownBusinessKeep() {+ for(String stage : List.of("commit","rollback","reset")) {+ Fake jdbc=new Fake(); jdbc.failCommit=stage.equals("commit"); jdbc.failReset=stage.equals("reset");+ if(stage.equals("rollback")) { jdbc.failAt=1; jdbc.failRollback=true; jdbc.executionFailure=new java.sql.SQLTransientConnectionException("stale", "HY000",20001); }+ BlobBoundExecutor.PreparedStatementConfigurer configurer=new BlobBoundExecutor.PreparedStatementConfigurer() {+ public void configure(PreparedStatement statement) { }+ public boolean isRollbackConfirmedBusinessError(java.sql.SQLException error) { return error.getErrorCode()==20001; }+ };+ RuntimeException failure=assertThrows(RuntimeException.class,()->BlobBoundExecutor.execute(jdbc.connection(),+ Arrays.asList(PREVIEW),Arrays.asList(bound()),null,s->s,()->null,7,false,configurer));+ var data=AgentRpcError.toJson(failure,"execute_batch","test").getAsJsonObject("data");+ assertEquals("quarantine",data.get("sessionDisposition").getAsString());+ assertEquals("unknown",data.get("operationOutcome").getAsString());+ }+ }++ @Test void unsupportedSavepointFailsBeforeAnyWrite() {+ Fake jdbc = new Fake(); jdbc.autoCommit = false; jdbc.unsupportedSavepoint = true;+ assertThrows(RuntimeException.class, () -> run(jdbc, Arrays.asList(bound()), false));+ assertEquals(0, jdbc.executions); assertEquals(0, jdbc.commits); assertEquals(0, jdbc.rollbacks);+ }++ @Test void rejectsInvalidLaterBindingBeforeOpeningAnyStatement() {+ Fake jdbc = new Fake();+ assertThrows(IllegalArgumentException.class, () -> run(jdbc,+ Arrays.asList(bound(), new BlobBoundStatement(PREVIEW, SQL, Arrays.asList("0x00"))), true));+ assertEquals(0, jdbc.executions); assertNull(jdbc.preparedSql); assertTrue(jdbc.autoCommit);+ assertThrows(IllegalArgumentException.class, () -> BlobBoundStatement.validate(Arrays.asList("edited"), Arrays.asList(bound())));+ }++ @Test void cancellationTracksStatementAndPreventsNextStatement() {+ Fake jdbc = new Fake(); jdbc.cancel = true;+ assertThrows(java.util.concurrent.CancellationException.class, () -> run(jdbc, Arrays.asList(bound(), bound()), true));+ assertEquals(2, jdbc.cancels); assertEquals(1, jdbc.executions);+ assertEquals(1, jdbc.rollbacks); assertEquals(2, jdbc.closedStatements);+ }++ @Test void invalidLaterParameterCountFailsBeforeAnyWriteAndIgnoresQuotedMarkers() {+ Fake jdbc=new Fake();+ assertThrows(IllegalArgumentException.class,()->run(jdbc,Arrays.asList(bound(),new BlobBoundStatement(PREVIEW,SQL,Arrays.asList("cafe"))),true));+ assertEquals(0,jdbc.executions); assertNull(jdbc.preparedSql);+ BlobBoundStatement.validate(Arrays.asList(PREVIEW),Arrays.asList(new BlobBoundStatement(PREVIEW,+ "BEGIN UPDATE t SET b=?; x:='?''?'; x:=q'[?]'; -- ?\n/* ? */ END;",Arrays.asList("cafe"))));+ }++ @Test void legacyAgentRejectsBindingBeforeCallingLegacyBatch() {+ DatabaseAgent agent = (DatabaseAgent) Proxy.newProxyInstance(DatabaseAgent.class.getClassLoader(), new Class<?>[]{DatabaseAgent.class},+ (p, m, a) -> { if (m.getName().equals("supportsBlobBindStatements")) return false;+ if (m.getName().equals("getConnection")) return new Fake().connection();+ if (m.getName().startsWith("execute")) throw new AssertionError("Must not execute unsupported payload"); return defaultValue(m.getReturnType()); });+ String response = new JsonRpcServer(agent).handleRequest("{\"id\":1,\"method\":\"execute_batch\",\"params\":{\"statements\":[],\"boundStatements\":[]}}");+ assertTrue(JsonParser.parseString(response).getAsJsonObject().getAsJsonObject("error").get("message").getAsString().contains("blob_bind_statements_v1"), response);+ }++ @Test void onlyOptedInServerAdvertisesBindingCapability() {+ com.google.gson.Gson gson = new com.google.gson.Gson();+ assertFalse(gson.toJson(AgentProtocol.multiSessionJdbcHandshakeResult()).contains("blob_bind_statements_v1"));+ assertTrue(gson.toJson(AgentProtocol.multiSessionJdbcHandshakeResult(true)).contains("blob_bind_statements_v1"));+ }++ @Test void laterSetterFailureOccursBeforeAnyWriteAndClosesAllResources() {+ Fake jdbc=new Fake(); jdbc.failBindAt=3;+ assertThrows(RuntimeException.class,()->run(jdbc,Arrays.asList(bound(),bound()),true));+ assertEquals(0,jdbc.executions); assertEquals(1,jdbc.rollbacks); assertEquals(2,jdbc.closedStatements);+ for(InputStream stream:jdbc.streams)assertThrows(java.io.IOException.class,stream::read);+ }++ @Test void cancellationDuringResourceCloseStillPreventsCommit() {+ Fake jdbc=new Fake();jdbc.cancelOnClose=true;+ assertThrows(java.util.concurrent.CancellationException.class,()->run(jdbc,Arrays.asList(bound()),true));+ assertEquals(1,jdbc.executions);assertEquals(0,jdbc.commits);assertEquals(1,jdbc.rollbacks);+ }++ @Test void connectionResetAfterCommitReportsUnknownInsteadOfClaimingNoWrite() {+ Fake jdbc=new Fake();jdbc.failReset=true;+ RuntimeException failure=assertThrows(RuntimeException.class,()->run(jdbc,Arrays.asList(bound()),true));+ assertEquals(1,jdbc.commits);assertTrue(jdbc.connectionClosed);+ com.google.gson.JsonObject data=AgentRpcError.toJson(failure,"execute_transaction","test").getAsJsonObject("data");+ assertEquals("quarantine",data.get("sessionDisposition").getAsString());+ assertEquals("unknown",data.get("operationOutcome").getAsString());+ }++ @Test void rpcRejectsNonStringHexRatherThanGsonCoercingIt() {+ DatabaseAgent agent=(DatabaseAgent)Proxy.newProxyInstance(DatabaseAgent.class.getClassLoader(),new Class<?>[]{DatabaseAgent.class},+ (p,m,a)->{if(m.getName().equals("supportsBlobBindStatements"))return true;+ if(m.getName().equals("getConnection"))return new Fake().connection();+ if(m.getName().startsWith("execute"))throw new AssertionError("Malformed payload must not execute");return defaultValue(m.getReturnType());});+ String response=new JsonRpcServer(agent).handleRequest("{\"id\":2,\"method\":\"execute_transaction\",\"params\":{\"statements\":[\"preview\"],\"boundStatements\":[{\"previewSql\":\"preview\",\"sql\":\"BEGIN x:=?; END;\",\"blobParameters\":[12]}]}}");+ assertTrue(response.contains("hexadecimal string"),response);+ }++ private static QueryResult run(Fake jdbc, List<BlobBoundStatement> statements, boolean transaction) {+ List<String> previews = new ArrayList<>(); for (BlobBoundStatement ignored : statements) previews.add(PREVIEW);+ return BlobBoundExecutor.execute(jdbc.connection(), previews, statements, null, schema -> null, () -> "", 7, transaction);+ }++ private static final class Fake {+ boolean autoCommit = true, fail, cancel, unsupportedSavepoint, failRollback, connectionClosed, failReset, cancelOnClose, piecewiseRead, failRelease, failCommit;+ int pieces;+ int value=42,savedValue=42,transactionStartValue=42,failAt,failBindAt;+ int commits, rollbacks, savepointRollbacks, savepoints, releases, executions, closedStatements, cancels, timeout;+ String preparedSql;+ java.sql.SQLException executionFailure;+ java.sql.SQLException releaseFailure;+ List<String> events = new ArrayList<>(), boundHex = new ArrayList<>();+ List<Long> lengths = new ArrayList<>(); List<InputStream> streams = new ArrayList<>();+ Connection connection() {+ return (Connection) Proxy.newProxyInstance(Connection.class.getClassLoader(), new Class<?>[]{Connection.class}, (p,m,a) -> {+ switch (m.getName()) {+ case "getAutoCommit": return autoCommit;+ case "isValid": return true;+ case "close": connectionClosed=true; return null;+ case "setAutoCommit": if(failReset && (boolean)a[0])throw new java.sql.SQLException("reset failed"); if(autoCommit && !(boolean)a[0])transactionStartValue=value; autoCommit = (boolean)a[0]; return null;+ case "getMetaData": return Proxy.newProxyInstance(DatabaseMetaData.class.getClassLoader(), new Class<?>[]{DatabaseMetaData.class}, (x,y,z) -> y.getName().equals("supportsTransactions") ? true : defaultValue(y.getReturnType()));+ case "setSavepoint": if (unsupportedSavepoint) throw new java.sql.SQLFeatureNotSupportedException(); savepoints++; savedValue=value; return Proxy.newProxyInstance(Savepoint.class.getClassLoader(),new Class<?>[]{Savepoint.class},(x,y,z)->defaultValue(y.getReturnType()));+ case "releaseSavepoint": releases++; if(failRelease)throw releaseFailure!=null?releaseFailure:new java.sql.SQLTransientConnectionException("release lost connection","08006"); return null;+ case "commit": commits++; events.add("commit"); if(failCommit)throw new java.sql.SQLTransientConnectionException("commit outcome unknown","HY000",20001); return null;+ case "rollback": if(failRollback)throw new java.sql.SQLException("rollback lost connection","08006"); if (a == null || a.length == 0) {rollbacks++;value=transactionStartValue;} else {savepointRollbacks++;value=savedValue;} return null;+ case "prepareCall": case "prepareStatement": preparedSql=(String)a[0]; return statement(m.getName().equals("prepareCall"));+ default: return defaultValue(m.getReturnType());+ }+ });+ }+ PreparedStatement statement(boolean callable) {+ Class<?> type = callable ? CallableStatement.class : PreparedStatement.class;+ return (PreparedStatement) Proxy.newProxyInstance(type.getClassLoader(), new Class<?>[]{type}, (p,m,a) -> {+ switch (m.getName()) {+ case "setQueryTimeout": timeout=(int)a[0]; return null;+ case "setBlob": assertInstanceOf(InputStream.class,a[1]); assertInstanceOf(Long.class,a[2]);+ InputStream stream=(InputStream)a[1]; streams.add(stream); lengths.add((Long)a[2]);+ if(streams.size()==failBindAt)throw new java.sql.SQLException("binding failed");+ byte[] bytes;+ if(piecewiseRead) {+ java.io.ByteArrayOutputStream sent=new java.io.ByteArrayOutputStream(); byte[] buffer=new byte[32768];+ int read;+ while((read=stream.read(buffer))!=-1) { sent.write(buffer,0,read); pieces++; if(stream.available()==0)break; }+ bytes=sent.toByteArray();+ } else bytes=stream.readAllBytes();+ StringBuilder hex=new StringBuilder(); for(byte b:bytes)hex.append(String.format("%02x",b&255)); boundHex.add(hex.toString()); return null;+ case "execute": executions++;value++; if(fail)throw new SQLTimeoutException("timed out","HYT00"); if(executions==failAt)throw executionFailure!=null?executionFailure:new java.sql.SQLException("stale target","23000"); if(cancel)JdbcExecutor.current().cancelActiveStatements(); return false;+ case "getUpdateCount": return 1;+ case "cancel": cancels++; return null;+ case "close": closedStatements++; events.add("close"); if(cancelOnClose)JdbcExecutor.current().cancelActiveStatements(); return null;+ case "hashCode": return System.identityHashCode(p);+ case "equals": return p==a[0];+ default: return defaultValue(m.getReturnType());+ }+ });+ }+ }+ private static Object defaultValue(Class<?> type) {+ if(type==boolean.class)return false;if(type==int.class)return 0;if(type==long.class)return 0L;return null;+ }+}diff --git a/agents/common/src/test/java/com/dbx/agent/JdbcConnectionPoolingTest.java b/agents/common/src/test/java/com/dbx/agent/JdbcConnectionPoolingTest.javaindex 7601c3287f..92a932747a 100644--- a/agents/common/src/test/java/com/dbx/agent/JdbcConnectionPoolingTest.java+++ b/agents/common/src/test/java/com/dbx/agent/JdbcConnectionPoolingTest.java@@ -37,6 +37,86 @@ import static org.junit.jupiter.api.Assertions.fail;class JdbcConnectionPoolingTest {private static final Gson GSON = new Gson();+ @Test+ void blobRollbackFailureCannotReturnDirtyConnectionToAnotherSession() throws Exception {+ for (boolean manual : List.of(false, true)) {+ AtomicInteger physicalOpens = new AtomicInteger();+ CountDownLatch batchFinished = new CountDownLatch(1);+ CountDownLatch finishRequest = new CountDownLatch(1);+ ExecutorService worker = Executors.newSingleThreadExecutor();+ String url = h2Url("blob_rollback");+ try (Connection setup = DriverManager.getConnection(url, "sa", "");+ Statement statement = setup.createStatement();+ JdbcConnectionPoolRegistry registry = new JdbcConnectionPoolRegistry(poolSettings(2))) {+ statement.execute("CREATE TABLE rollback_probe (id INT)");+ List<JsonRpcServer> sessions = new java.util.ArrayList<>();+ for (int index = 0; index < 2; index++) {+ H2TestAgent agent = new H2TestAgent(url, physicalOpens) {+ @Override public boolean supportsBlobBindStatements() { return true; }++ @Override protected Connection openConnection(ConnectParams params) throws Exception {+ Connection physical = openH2(url, physicalOpens);+ if (physicalOpens.get() != 1) return physical;+ return (Connection) Proxy.newProxyInstance(getClass().getClassLoader(),+ new Class<?>[]{Connection.class}, (proxy, method, args) -> {+ if (method.getName().equals("rollback")) {+ throw new SQLException("Rollback was not acknowledged", "HY000");+ }+ try { return method.invoke(physical, args); }+ catch (InvocationTargetException error) { throw error.getCause(); }+ });+ }++ @Override public QueryResult executeBlobBoundStatements(List<String> previews,+ List<BlobBoundStatement> statements, String schema, int timeoutSecs, boolean transaction) {+ try {+ return BlobBoundExecutor.execute(requireConnected(), previews, statements,+ schema, value -> null, () -> null, timeoutSecs, transaction,+ new BlobBoundExecutor.PreparedStatementConfigurer() {+ @Override public void configure(java.sql.PreparedStatement statement) { }+ @Override public void discardConnection(Connection connection) throws SQLException {+ agentDiscard(connection);+ }+ });+ } finally {+ batchFinished.countDown();+ awaitUninterruptibly(finishRequest);+ }+ }++ private void agentDiscard(Connection connection) throws SQLException {+ discardConnection(connection);+ }+ };+ agent.attachConnectionPoolRegistry(registry);+ JsonRpcServer server = new JsonRpcServer(agent);+ server.dispatchForRuntime(AgentProtocol.METHOD_CONNECT,+ JsonParser.parseString("{\"database\":\"pooling\",\"username\":\"sa\",\"password\":\"\"}").getAsJsonObject());+ sessions.add(server);+ }+ if (manual) sessions.get(0).dispatchForRuntime(AgentProtocol.METHOD_BEGIN_MANUAL_TRANSACTION, new JsonObject());+ List<String> sql = List.of("INSERT INTO rollback_probe VALUES (1)", "INSERT INTO missing_table VALUES (2)");+ JsonObject request = new JsonObject();+ request.add("statements", GSON.toJsonTree(sql));+ request.add("boundStatements", GSON.toJsonTree(sql.stream()+ .map(value -> new BlobBoundStatement(value, value, List.of())).toList()));+ Future<Exception> failure = worker.submit(() -> assertThrows(Exception.class,+ () -> sessions.get(0).dispatchForRuntime(AgentProtocol.METHOD_EXECUTE_BATCH, request)));+ try {+ assertTrue(batchFinished.await(3, TimeUnit.SECONDS));+ QueryResult result = (QueryResult) sessions.get(1).dispatchForRuntime(AgentProtocol.METHOD_EXECUTE_QUERY,+ JsonParser.parseString("{\"sql\":\"SELECT COUNT(*) FROM rollback_probe\"}").getAsJsonObject());+ assertEquals(0L, ((Number) result.getRows().get(0).get(0)).longValue(), "manual=" + manual);+ assertEquals(2, physicalOpens.get());+ } finally { finishRequest.countDown(); }+ assertTrue(failure.get(3, TimeUnit.SECONDS).toString().contains("rollback was not confirmed"));+ } finally {+ finishRequest.countDown();+ worker.shutdownNow();+ }+ }+ }+@Testvoid registryReusesOnePhysicalConnectionAcrossSequentialLeases() throws Exception {AtomicInteger physicalOpens = new AtomicInteger();diff --git a/agents/common/src/test/java/com/dbx/agent/JsonRpcLargeValueTest.java b/agents/common/src/test/java/com/dbx/agent/JsonRpcLargeValueTest.javanew file mode 100644index 0000000000..4e0ac74420--- /dev/null+++ b/agents/common/src/test/java/com/dbx/agent/JsonRpcLargeValueTest.java@@ -0,0 +1,75 @@+package com.dbx.agent;++import com.google.gson.JsonParser;+import org.junit.jupiter.api.Test;+import static org.junit.jupiter.api.Assertions.*;+import java.lang.reflect.Proxy;+import java.util.ArrayList;+import java.util.List;+import java.util.Map;++class JsonRpcLargeValueTest {+ @Test+ void dispatchesOpaqueLocatorAndCharacterOffsetAndReleasesItWithoutSql() throws Exception {+ List<String> calls = new ArrayList<>();+ DatabaseAgent agent = (DatabaseAgent) Proxy.newProxyInstance(DatabaseAgent.class.getClassLoader(),+ new Class<?>[]{DatabaseAgent.class}, (object, method, args) -> {+ if (method.getName().equals("supportsQueryTiming")) return false;+ if (method.getName().equals("permitsAutomaticReconnect")) return false;+ if (method.getName().equals("readLargeValueChunk")) {+ calls.add("read");+ assertArrayEquals(new Object[]{"opaque-original", 700L, 4096}, args);+ return Map.of("status", "ok", "data", "中文😀", "next_offset", 703L, "eof", false, "value_kind", "text");+ }+ if (method.getName().equals("releaseLargeValue")) { calls.add("release"); assertEquals("opaque-original", args[0]); return true; }+ return null;+ });+ JsonRpcServer server = new JsonRpcServer(agent);+ Object result = server.dispatchForRuntime(AgentProtocol.METHOD_READ_LARGE_VALUE_CHUNK,+ JsonParser.parseString("{\"valueRef\":\"opaque-original\",\"offset\":700,\"limit\":4096}").getAsJsonObject());+ assertEquals("中文😀", ((Map<?, ?>) result).get("data"));+ assertEquals(true, server.dispatchForRuntime(AgentProtocol.METHOD_RELEASE_LARGE_VALUE,+ JsonParser.parseString("{\"valueRef\":\"opaque-original\"}").getAsJsonObject()));+ assertEquals(List.of("read", "release"), calls);+ }++ @Test+ void invalidatesLocatorsBeforeTransactionBoundary() throws Exception {+ List<String> calls = new ArrayList<>();+ DatabaseAgent agent = (DatabaseAgent) Proxy.newProxyInstance(DatabaseAgent.class.getClassLoader(),+ new Class<?>[]{DatabaseAgent.class}, (object, method, args) -> {+ if (method.getName().equals("supportsQueryTiming")) return false;+ if (method.getName().equals("permitsAutomaticReconnect")) return false;+ if (method.getName().equals("invalidateLargeValues")) { calls.add("invalidate"); return null; }+ if (method.getName().equals("commitManualTransaction")) { calls.add("commit"); return Map.of("ok", true); }+ return null;+ });+ new JsonRpcServer(agent).dispatchForRuntime(AgentProtocol.METHOD_COMMIT_MANUAL_TRANSACTION,+ JsonParser.parseString("{}").getAsJsonObject());+ assertEquals(List.of("invalidate", "commit"), calls);+ }++ @Test+ void invalidatesBeforeFailedWriteAndRollbackAndOnCancellation() throws Exception {+ List<String> calls = new ArrayList<>();+ DatabaseAgent agent = (DatabaseAgent) Proxy.newProxyInstance(DatabaseAgent.class.getClassLoader(),+ new Class<?>[]{DatabaseAgent.class}, (object, method, args) -> {+ if (method.getName().equals("supportsQueryTiming")) return false;+ if (method.getName().equals("permitsAutomaticReconnect")) return false;+ if (method.getName().equals("invalidateLargeValues")) { calls.add("invalidate"); return null; }+ if (method.getName().equals("executeBatch")) { calls.add("write"); throw new java.sql.SQLException("concurrent row removed"); }+ if (method.getName().equals("rollbackManualTransaction")) { calls.add("rollback"); return Map.of("ok", true); }+ return null;+ });+ JsonRpcServer server = new JsonRpcServer(agent);+ assertThrows(Exception.class, () -> server.dispatchForRuntime(AgentProtocol.METHOD_EXECUTE_BATCH,+ JsonParser.parseString("{\"statements\":[\"UPDATE T SET C='full original value'\"]}").getAsJsonObject()));+ assertEquals(List.of("invalidate", "write"), calls);+ calls.clear();+ server.dispatchForRuntime(AgentProtocol.METHOD_ROLLBACK_MANUAL_TRANSACTION, JsonParser.parseString("{}").getAsJsonObject());+ assertEquals(List.of("invalidate", "rollback"), calls);+ calls.clear();+ server.cancelActiveStatements();+ assertEquals(List.of("invalidate"), calls);+ }+}diff --git a/agents/drivers/oceanbase-oracle/src/main/java/com/dbx/agent/oceanbaseoracle/OceanBaseLobStatements.java b/agents/drivers/oceanbase-oracle/src/main/java/com/dbx/agent/oceanbaseoracle/OceanBaseLobStatements.javanew file mode 100644index 0000000000..501b645242--- /dev/null+++ b/agents/drivers/oceanbase-oracle/src/main/java/com/dbx/agent/oceanbaseoracle/OceanBaseLobStatements.java@@ -0,0 +1,56 @@+package com.dbx.agent.oceanbaseoracle;++import com.oceanbase.jdbc.OceanBaseStatement;+import com.dbx.agent.BlobBoundExecutor;+import java.sql.SQLException;+import java.sql.Statement;++final class OceanBaseLobStatements {+ private OceanBaseLobStatements() { }++ @FunctionalInterface+ interface ConnectionDiscarder {+ void discard(java.sql.Connection connection) throws SQLException;+ }++ static final BlobBoundExecutor.PreparedStatementConfigurer BINDING = binding(java.sql.Connection::close);++ static BlobBoundExecutor.PreparedStatementConfigurer binding(ConnectionDiscarder discard) {+ return new BlobBoundExecutor.PreparedStatementConfigurer() {+ @Override public void discardConnection(java.sql.Connection connection) throws SQLException {+ discard.discard(connection);+ }+ @Override public void configure(java.sql.PreparedStatement statement) throws SQLException {+ OceanBaseLobStatements.configure(statement);+ }+ @Override public boolean isRollbackConfirmedBusinessError(SQLException error) {+ if (!(error instanceof java.sql.SQLTransientConnectionException)+ || error.getErrorCode() != 20001 || !"HY000".equals(error.getSQLState())) return false;+ for (Throwable cause = error.getCause(); cause != null; cause = cause.getCause()) {+ if (cause instanceof java.sql.SQLRecoverableException || cause instanceof java.sql.SQLTimeoutException+ || cause instanceof SQLException sql && sql.getSQLState() != null && sql.getSQLState().startsWith("08")) return false;+ }+ return true;+ }+ @Override public boolean isUnsupportedSavepointRelease(SQLException error) {+ // OB Oracle mode rejects release locally; the transaction end releases its savepoints.+ return error.getErrorCode() == 17023 && "99999".equals(error.getSQLState())+ && !(error instanceof java.sql.SQLTimeoutException)+ && !(error instanceof java.sql.SQLRecoverableException);+ }+ };+ }++ static void configure(Statement statement) throws SQLException {+ OceanBaseStatement vendor;+ try {+ vendor = statement instanceof OceanBaseStatement ? (OceanBaseStatement) statement+ : statement.unwrap(OceanBaseStatement.class);+ } catch (SQLException error) {+ throw new SQLException("Unsupported OceanBase LOB statement", error);+ }+ if (vendor == null) throw new SQLException("Unsupported OceanBase LOB statement");+ // Set only the native LOB mode; binding, cancellation and close retain the pool proxy.+ vendor.setInternal();+ }+}diff --git a/agents/drivers/oceanbase-oracle/src/main/java/com/dbx/agent/oceanbaseoracle/OceanBaseLobValues.java b/agents/drivers/oceanbase-oracle/src/main/java/com/dbx/agent/oceanbaseoracle/OceanBaseLobValues.javanew file mode 100644index 0000000000..7eb4c057b3--- /dev/null+++ b/agents/drivers/oceanbase-oracle/src/main/java/com/dbx/agent/oceanbaseoracle/OceanBaseLobValues.java@@ -0,0 +1,265 @@+package com.dbx.agent.oceanbaseoracle;++import com.dbx.agent.JdbcExecutor;+import com.oceanbase.jdbc.DbxLobResourceBytes;+import java.nio.ByteBuffer;+import java.nio.charset.CodingErrorAction;+import java.nio.charset.StandardCharsets;+import java.sql.CallableStatement;+import java.sql.Clob;+import java.sql.Blob;+import java.sql.Connection;+import java.sql.ResultSet;+import java.sql.SQLException;+import java.sql.Types;+import java.util.ArrayList;+import java.util.Iterator;+import java.util.LinkedHashMap;+import java.util.List;+import java.util.Locale;+import java.util.Map;+import java.util.UUID;++/** Captured locators belong to this agent's pinned connection, never to a new SELECT. */+final class OceanBaseLobValues {+ static final String MARKER_PREFIX = "__DBX_LARGE_VALUE_BYTES_";+ static final int PREVIEW_CHARACTERS = 256;+ static final int MAX_CHUNK_CHARACTERS = 4096;+ private static final int MAX_REFS = 4096;+ private static final long MAX_RETAINED_BYTES = 64L * 1024 * 1024;+ private static final long IDLE_MILLIS = 5 * 60_000L;+ private static final long MAX_AGE_MILLIS = 30 * 60_000L;+ private final Map<String, Entry> entries = new LinkedHashMap<>();+ private final BlockReader reader;+ private final java.util.function.ToLongFunction<Object> retainedBytes;+ private long retainedByteCount;++ @FunctionalInterface+ interface BlockReader {+ Chunk read(Connection connection, Object locator, long offset, int limit) throws SQLException;+ }++ OceanBaseLobValues() { this(OceanBaseLobValues::read, DbxLobResourceBytes::retainedBytes); }+ OceanBaseLobValues(BlockReader reader) { this(reader, ignored -> 0); }+ OceanBaseLobValues(BlockReader reader, java.util.function.ToLongFunction<Object> retainedBytes) { this.reader = reader; this.retainedBytes = retainedBytes; }++ record Preview(String text, String ref, String kind) {+ Preview(String text, String ref) { this(text, ref, "clob"); }+ }+ record Chunk(String status, String data, long next_offset, boolean eof, String value_kind) {}+ record MarkedRows(List<String> columns, List<String> types, List<List<Object>> rows) {}+ private static final class Entry {+ final Connection connection;+ final Object locator;+ final long retainedBytes;+ final long created = System.currentTimeMillis();+ long accessed = created;+ Entry(Connection connection, Object locator, long retainedBytes) {++ this.connection = connection;+ this.locator = locator;+ this.retainedBytes = retainedBytes;+ }+ }++ synchronized Object preview(ResultSet rs, int index, int sqlType, String typeName) throws SQLException {+ boolean binary = sqlType == Types.BLOB || "BLOB".equalsIgnoreCase(typeName);+ if ((!binary && !isCharacterLob(sqlType, typeName)) || hasMarkerCollision(rs)) return null;+ // NCLOB's charset form must be verified separately; retain the complete existing read.+ if (sqlType == Types.NCLOB || "NCLOB".equalsIgnoreCase(typeName)) return null;+ Object locator = binary ? rs.getBlob(index) : rs.getClob(index);+ String kind = binary ? "blob" : "clob";+ if (locator == null || rs.wasNull()) return new Preview(null, null, kind);+ Connection connection = rs.getStatement().getConnection();+ prune();+ long bytes = retainedBytes.applyAsLong(locator);+ if (bytes < 0 || bytes > MAX_RETAINED_BYTES - retainedByteCount || entries.size() >= MAX_REFS) {+ freeLocator(locator);++ throw new SQLException("LOB result resource limit reached; close older results and execute again", "HY001");+ }+ boolean retained = false;+ try {+ Chunk chunk = reader.read(connection, locator, 0, PREVIEW_CHARACTERS + 1);+ if (chunk.eof()) return new Preview(binary ? "0x" + chunk.data() : chunk.data(), null, kind);+ String text = chunk.data();+ int count = binary ? text.length() / 2 : text.codePointCount(0, text.length());+ if (count <= PREVIEW_CHARACTERS) return new Preview(binary ? "0x" + text : text, null, kind);+ String ref = UUID.randomUUID().toString();+ entries.put(ref, new Entry(connection, locator, bytes));+ retainedByteCount += bytes;+ retained = true;+ String preview = binary ? "0x" + text.substring(0, PREVIEW_CHARACTERS * 2)+ : text.substring(0, text.offsetByCodePoints(0, PREVIEW_CHARACTERS));+ return new Preview(preview, ref, kind);+ } finally {+ if (!retained) freeLocator(locator);+ }+ }++ synchronized Chunk fetch(Connection connection, String ref, long offset, int limit) throws SQLException {+ if (offset < 0 || offset == Long.MAX_VALUE || limit < 1 || limit > MAX_CHUNK_CHARACTERS) {+ throw new IllegalArgumentException("Invalid LOB chunk offset or limit");+ }+ prune();+ Entry entry = entries.get(ref);+ if (entry == null || entry.connection != connection || connection.isClosed()) {+ release(ref);+ return new Chunk("expired", "", offset, false, "text");+ }+ entry.accessed = System.currentTimeMillis();+ try {+ return reader.read(connection, entry.locator, offset, limit);+ } catch (SQLException error) {+ release(ref);+ throw error;+ }+ }++ synchronized boolean release(String ref) {+ Entry entry = entries.remove(ref);+ if (entry == null) return false;+ retainedByteCount -= entry.retainedBytes;+ free(entry);+ return true;+ }++ synchronized boolean hasValues() {+ prune();+ return !entries.isEmpty();+ }++ synchronized void clear() {+ entries.values().forEach(OceanBaseLobValues::free);+ entries.clear();+ retainedByteCount = 0;+ }++ synchronized java.util.Set<String> checkpoint() {+ return java.util.Set.copyOf(entries.keySet());+ }++ synchronized void releaseSince(java.util.Set<String> checkpoint) {+ for (String ref : List.copyOf(entries.keySet())) {+ if (!checkpoint.contains(ref)) release(ref);+ }+ }++ private void prune() {+ long now = System.currentTimeMillis();+ Iterator<Entry> iterator = entries.values().iterator();+ while (iterator.hasNext()) {+ Entry entry = iterator.next();+ if (now - entry.accessed >= IDLE_MILLIS || now - entry.created >= MAX_AGE_MILLIS) {+ iterator.remove();+ retainedByteCount -= entry.retainedBytes;+ free(entry);+ }+ }+ }++ private static void free(Entry entry) {+ try { freeLocator(entry.locator); } catch (SQLException ignored) { }+ }++ private static void freeLocator(Object locator) throws SQLException {+ if (locator instanceof Blob) ((Blob) locator).free();+ else ((Clob) locator).free();+ }++ static Chunk read(Connection connection, Object locator, long offset, int limit) throws SQLException {+ boolean binary = locator instanceof Blob;+ // OceanBase READ raises ORA-06502 for empty LOBs. Only zero is safe here:+ // JDBC CLOB length counts UTF-16 units while READ offsets count code points.+ long length = binary ? ((Blob) locator).length() : ((Clob) locator).length();+ if (length == 0) return new Chunk("ok", "", offset, true, binary ? "binary" : "text");+ try (CallableStatement call = connection.prepareCall(+ "DECLARE v_lob " + (binary ? "BLOB" : "CLOB") + " := ?; v_amount INTEGER := ?; v_offset INTEGER := ?; "+ + "v_buffer " + (binary ? "RAW(32767)" : "VARCHAR2(32767)") + "; v_length INTEGER; BEGIN v_length := DBMS_LOB.GETLENGTH(v_lob); "+ + "IF v_offset > v_length THEN v_amount := 0; ELSE DBMS_LOB.READ(v_lob,v_amount,v_offset,v_buffer); END IF; "+ + "? := v_amount; ? := v_buffer; ? := v_length; END;")) {+ OceanBaseLobStatements.configure(call);+ if (binary) call.setBlob(1, (Blob) locator);+ else call.setClob(1, (Clob) locator);+ call.setInt(2, limit);+ call.setLong(3, offset + 1);+ call.registerOutParameter(4, Types.INTEGER);+ call.registerOutParameter(5, binary ? Types.VARBINARY : Types.VARCHAR);+ call.registerOutParameter(6, Types.BIGINT);+ call.setQueryTimeout(20);+ JdbcExecutor.current().withActiveStatement(call, () -> { call.execute(); return null; });+ int amount = call.getInt(4);+ byte[] bytes = call.getBytes(5);+ long serverLength = call.getLong(6);+ long nextOffset = Math.addExact(offset, amount);+ if (amount < 0 || amount > limit || serverLength < 0 || bytes == null && amount != 0+ || offset < serverLength && (amount == 0 || nextOffset > serverLength)+ || offset >= serverLength && amount != 0) {+ throw new SQLException("Invalid OceanBase LOB chunk response");+ }+ if (binary) {+ if (bytes != null && bytes.length != amount) throw new SQLException("OceanBase BLOB byte count mismatch");+ String hex = bytes == null ? "" : JdbcExecutor.bytesToHex(bytes).substring(2);+ return new Chunk("ok", hex, nextOffset, nextOffset >= serverLength, "binary");+ }+ String text;+ try {+ text = bytes == null ? "" : StandardCharsets.UTF_8.newDecoder()+ .onMalformedInput(CodingErrorAction.REPORT).onUnmappableCharacter(CodingErrorAction.REPORT)+ .decode(ByteBuffer.wrap(bytes)).toString();+ } catch (java.nio.charset.CharacterCodingException error) {+ throw new SQLException("Invalid UTF-8 in OceanBase LOB chunk", error);+ }+ if (text.codePointCount(0, text.length()) != amount) throw new SQLException("OceanBase LOB character count mismatch");+ return new Chunk("ok", text, nextOffset, nextOffset >= serverLength, "text");+ }+ }++ static boolean isCharacterLob(int sqlType, String typeName) {+ return sqlType == Types.CLOB || sqlType == Types.NCLOB+ || "CLOB".equalsIgnoreCase(typeName) || "NCLOB".equalsIgnoreCase(typeName);+ }++ private static boolean hasMarkerCollision(ResultSet rs) throws SQLException {+ var metadata = rs.getMetaData();+ for (int index = 1; index <= metadata.getColumnCount(); index++) {+ if (metadata.getColumnLabel(index).toUpperCase(Locale.ROOT).startsWith(MARKER_PREFIX)) return true;+ }+ return false;+ }++ static MarkedRows mark(List<String> columns, List<String> types, List<List<Object>> rows) {+ List<String> expandedColumns = new ArrayList<>();+ List<String> expandedTypes = new ArrayList<>();+ boolean[] marked = new boolean[columns.size()];+ String[] kinds = new String[columns.size()];+ for (List<Object> row : rows) {+ for (int index = 0; index < row.size(); index++) {+ if (row.get(index) instanceof Preview preview) { marked[index] = true; kinds[index] = preview.kind(); }+ }+ }+ boolean anyMarked = false;+ for (boolean value : marked) anyMarked |= value;+ if (!anyMarked) return null;+ for (int index = 0; index < columns.size(); index++) {+ expandedColumns.add(columns.get(index));+ expandedTypes.add(index < types.size() ? types.get(index) : "");+ if (marked[index]) {+ expandedColumns.add(MARKER_PREFIX + ("blob".equals(kinds[index]) ? "L_" : "C_") + index);+ expandedTypes.add("VARCHAR");+ }+ }+ List<List<Object>> expandedRows = new ArrayList<>();+ for (List<Object> row : rows) {+ List<Object> expanded = new ArrayList<>();+ for (int index = 0; index < columns.size(); index++) {+ Object value = row.get(index);+ Preview preview = value instanceof Preview ? (Preview) value : null;+ expanded.add(preview == null ? value : preview.text());+ if (marked[index]) expanded.add(preview == null || preview.ref() == null ? null : "D:1:unknown:" + preview.ref());+ }+ expandedRows.add(expanded);+ }+ return new MarkedRows(expandedColumns, expandedTypes, expandedRows);+ }+}diff --git a/agents/drivers/oceanbase-oracle/src/main/java/com/dbx/agent/oceanbaseoracle/OceanBaseOracleAgent.java b/agents/drivers/oceanbase-oracle/src/main/java/com/dbx/agent/oceanbaseoracle/OceanBaseOracleAgent.javaindex 6008442b7a..2f326c73cc 100644--- a/agents/drivers/oceanbase-oracle/src/main/java/com/dbx/agent/oceanbaseoracle/OceanBaseOracleAgent.java+++ b/agents/drivers/oceanbase-oracle/src/main/java/com/dbx/agent/oceanbaseoracle/OceanBaseOracleAgent.java@@ -1,6 +1,8 @@package com.dbx.agent.oceanbaseoracle;import com.dbx.agent.ColumnInfo;+import com.dbx.agent.BlobBoundStatement;+import com.dbx.agent.BlobBoundExecutor;import com.dbx.agent.AgentProtocol;import com.dbx.agent.CompletionAssistantCandidate;import com.dbx.agent.CompletionAssistantCandidateKind;@@ -29,6 +31,7 @@ import com.dbx.agent.QueryPageOptions;import com.dbx.agent.QueryPageResult;import com.dbx.agent.QueryResult;import com.dbx.agent.QueryTiming;+import com.dbx.agent.SpatialColumn;import com.dbx.agent.TableInfo;import com.dbx.agent.TriggerInfo;@@ -67,6 +70,8 @@ public final class OceanBaseOracleAgent extends ConfiguredJdbcAgent {"GGSYS", "FLOWS_FILES", "APEX_PUBLIC_USER", "GSMROOTUSER", "SYSRAC");private boolean queryTimeoutChanged;+ private final OceanBaseLobValues lobValues = new OceanBaseLobValues();+ private boolean deferCharacterLobs;public static final JdbcAgentProfile OCEANBASE_ORACLE_PROFILE = new JdbcAgentProfile("com.oceanbase.jdbc.Driver",@@ -89,18 +94,47 @@ public final class OceanBaseOracleAgent extends ConfiguredJdbcAgent {@Overridepublic boolean supportsQueryTiming() { return true; }+ @Override+ public boolean supportsBlobBindStatements() { return true; }++ @Override+ public QueryResult executeBlobBoundStatements(List<String> previews, List<BlobBoundStatement> statements,+ String schema, int timeoutSecs, boolean transaction) {+ return BlobBoundExecutor.execute(requireConnected(), previews, statements, schema,+ this::setSchemaSQL, this::resetSchemaSQL, timeoutSecs, transaction, OceanBaseLobStatements.binding(this::discardConnection));+ }+@Overridepublic QueryResult executeQuery(String sql, String schema, ExecuteQueryOptions options) {+ var lobCheckpoint = lobValues.checkpoint();try (QueryTiming timing = QueryTiming.begin()) {+ prepareLobExecution(sql, options.getDeferLobs());QueryResult result = super.executeQuery(sql, schema, options);+ var marked = OceanBaseLobValues.mark(result.getColumns(), result.getColumn_types(), result.getRows());+ if (marked != null) {+ var spatialColumns = remapLobSpatialColumns(result.getSpatial_columns(), marked.columns());+ var spatialValues = remapLobSpatialValues(result.getSpatial_values(), marked.columns());+ result.setColumns(marked.columns());+ result.setColumn_types(marked.types());+ result.setRows(marked.rows());+ result.setSpatial_columns(spatialColumns);+ result.setSpatial_values(spatialValues);+ }result.setQuery_timings_ms(timing.finish());return result;+ } catch (RuntimeException error) {+ lobValues.releaseSince(lobCheckpoint);+ throw error;+ } finally {+ deferCharacterLobs = false;}}@Overridepublic QueryPageResult executeQueryPage(String sql, String schema, QueryPageOptions options) {+ var lobCheckpoint = lobValues.checkpoint();try (QueryTiming timing = QueryTiming.begin()) {+ prepareLobExecution(sql, options.getDeferLobs());long prepareStarted = System.nanoTime();Connection connection = requireConnected();uncheckedVoid(() -> beforeQueryExecution(connection, options.getTimeoutSecs()));@@ -108,8 +142,14 @@ public final class OceanBaseOracleAgent extends ConfiguredJdbcAgent {QueryPageResult result = JdbcExecutor.current().executeBoundedPage(connection, sql, schema, this::setSchemaSQL, this::resetSchemaSQL, options, resultValueReader());+ markLobPage(result);result.setQuery_timings_ms(timing.finish());return result;+ } catch (RuntimeException error) {+ lobValues.releaseSince(lobCheckpoint);+ throw error;+ } finally {+ deferCharacterLobs = false;}}@@ -117,11 +157,166 @@ public final class OceanBaseOracleAgent extends ConfiguredJdbcAgent {public QueryPageResult fetchQueryPage(String sessionId, int pageSize) {try (QueryTiming timing = QueryTiming.begin()) {QueryPageResult result = super.fetchQueryPage(sessionId, pageSize);+ markLobPage(result);result.setQuery_timings_ms(timing.finish());return result;}}+ @Override+ public QueryPageResult startTableRead(String sql, String schema, QueryPageOptions options) {+ var lobCheckpoint = lobValues.checkpoint();+ prepareLobExecution(sql, options.getDeferLobs());+ try {+ QueryPageResult result = super.startTableRead(sql, schema, options);+ markLobPage(result);+ return result;+ } catch (RuntimeException error) {+ lobValues.releaseSince(lobCheckpoint);+ throw error;+ } finally {+ deferCharacterLobs = false;+ }+ }++ @Override+ public QueryPageResult fetchTableReadPage(String sessionId, int pageSize) {+ QueryPageResult result = super.fetchTableReadPage(sessionId, pageSize);+ markLobPage(result);+ return result;+ }++ private static void markLobPage(QueryPageResult result) {+ var marked = OceanBaseLobValues.mark(result.getColumns(), result.getColumn_types(), result.getRows());+ if (marked == null) return;+ var spatialColumns = remapLobSpatialColumns(result.getSpatial_columns(), marked.columns());+ var spatialValues = remapLobSpatialValues(result.getSpatial_values(), marked.columns());+ result.setColumns(marked.columns());+ result.setColumn_types(marked.types());+ result.setRows(marked.rows());+ result.setSpatial_columns(spatialColumns);+ result.setSpatial_values(spatialValues);+ }++ private static List<SpatialColumn> remapLobSpatialColumns(List<SpatialColumn> spatial, List<String> columns) {+ List<Integer> retained = new ArrayList<>();+ for (int index = 0; index < columns.size(); index++) {+ if (!columns.get(index).startsWith(OceanBaseLobValues.MARKER_PREFIX)) retained.add(index);+ }+ List<SpatialColumn> remapped = new ArrayList<>();+ for (SpatialColumn column : spatial) remapped.add(new SpatialColumn(retained.get(column.getColumn_index()), column.getSrid()));+ return remapped;+ }++ private static List<List<Integer>> remapLobSpatialValues(List<List<Integer>> spatial, List<String> columns) {+ List<List<Integer>> remapped = new ArrayList<>();+ for (List<Integer> row : spatial) {+ List<Integer> expanded = new ArrayList<>();+ int sourceIndex = 0;+ for (String column : columns) {+ expanded.add(column.startsWith(OceanBaseLobValues.MARKER_PREFIX) ? null : row.get(sourceIndex++));+ }+ remapped.add(expanded);+ }+ return remapped;+ }++ private void prepareLobExecution(String sql, boolean requested) {+ // Unproven statements may end the transaction or replace an object. Fail closed.+ String leading = sql.replaceFirst("(?s)^(?:\\s|--[^\\r\\n]*(?:\\r?\\n|$)|/\\*.*?\\*/)*", "");+ if (!leading.matches("(?is)^SELECT\\b.*") && !isSelectWithClause(leading)) lobValues.clear();+ deferCharacterLobs = requested;+ }++ // Recognize ordinary subquery factoring only. PL/SQL declarations and unproven+ // WITH forms retain the conservative invalidation behavior.+ private static boolean isSelectWithClause(String sql) {+ if (!sql.matches("(?is)^WITH\\b.*")) return false;+ var matcher = java.util.regex.Pattern.compile("(?s)--[^\\r\\n]*|/\\*.*?\\*/|'(?:''|[^'])*+'|\"(?:\"\"|[^\"])*+\"|[A-Za-z_][A-Za-z0-9_$#]*|\\S").matcher(sql);+ List<String> tokens = new ArrayList<>();+ while (matcher.find()) {+ String token = matcher.group();+ int end = matcher.end();+ if ((token.equalsIgnoreCase("q") || token.equalsIgnoreCase("nq")) && end + 1 < sql.length() && sql.charAt(end) == '\'') {+ char opening = sql.charAt(end + 1);+ char closing = switch (opening) {+ case '[' -> ']';+ case '{' -> '}';+ case '(' -> ')';+ case '<' -> '>';+ default -> opening;+ };+ int close = sql.indexOf("" + closing + '\'', end + 2);+ if (Character.isWhitespace(opening) || close < 0) return false;+ tokens.add("'literal'");+ matcher.region(close + 2, sql.length());+ continue;+ }+ if (!token.startsWith("--") && !token.startsWith("/*")) tokens.add(token);+ }+ if (tokens.isEmpty() || !tokens.get(0).equalsIgnoreCase("WITH")) return false;+ int index = 1;+ while (index < tokens.size()) {+ String name = tokens.get(index++);+ if (!name.matches("[A-Za-z_][A-Za-z0-9_$#]*|\"(?:\"\"|[^\"])++\"")) return false;+ if (index < tokens.size() && tokens.get(index).equals("(")) {+ index = afterLobQueryParentheses(tokens, index);+ if (index < 0) return false;+ }+ if (index >= tokens.size() || !tokens.get(index++).equalsIgnoreCase("AS")) return false;+ if (index + 1 >= tokens.size() || !tokens.get(index).equals("(") || !tokens.get(index + 1).equalsIgnoreCase("SELECT")) return false;+ index = afterLobQueryParentheses(tokens, index);+ if (index < 0 || index >= tokens.size()) return false;+ if (tokens.get(index).equals(",")) {+ index++;+ continue;+ }+ if (!tokens.get(index).equalsIgnoreCase("SELECT")) return false;+ for (int rest = index + 1; rest < tokens.size(); rest++) {+ if (tokens.get(rest).equals(";") && rest != tokens.size() - 1) return false;+ }+ return true;+ }+ return false;+ }++ private static int afterLobQueryParentheses(List<String> tokens, int start) {+ int depth = 0;+ for (int index = start; index < tokens.size(); index++) {+ String token = tokens.get(index);+ if (token.equals(";")) return -1;+ if (token.equals("(")) depth++;+ else if (token.equals(")") && --depth == 0) return index + 1;+ }+ return -1;+ }++ @Override+ protected JdbcExecutor.ResultValueReader resultValueReader() {+ if (!deferCharacterLobs) return super.resultValueReader();+ return (JdbcExecutor.ColumnAwareResultValueReader) (rs, index, sqlType, typeName) -> {+ Object preview = lobValues.preview(rs, index, sqlType, typeName);+ return preview == null ? resultValue(rs, index, sqlType) : preview;+ };+ }++ @Override+ protected boolean hasRetainedResultResources() { return lobValues.hasValues(); }++ @Override+ protected void releaseRetainedResultResources() { lobValues.clear(); }++ @Override+ public void invalidateLargeValues() { lobValues.clear(); }++ @Override+ public Object readLargeValueChunk(String valueRef, long offset, int limit) {+ return unchecked(() -> lobValues.fetch(requireConnected(), valueRef, offset, limit));+ }++ @Override+ public boolean releaseLargeValue(String valueRef) { return lobValues.release(valueRef); }+@Overrideprotected String buildJdbcUrl(ConnectParams params) {return buildUrl(params);@@ -1891,6 +2086,6 @@ public final class OceanBaseOracleAgent extends ConfiguredJdbcAgent {}public static void main(String[] args) {- new MultiSessionJsonRpcServer(OceanBaseOracleAgent::new).run();+ MultiSessionJsonRpcServer.withBlobBindings(OceanBaseOracleAgent::new).run();}}diff --git a/agents/drivers/oceanbase-oracle/src/main/java/com/oceanbase/jdbc/DbxLobResourceBytes.java b/agents/drivers/oceanbase-oracle/src/main/java/com/oceanbase/jdbc/DbxLobResourceBytes.javanew file mode 100644index 0000000000..06eb4220f8--- /dev/null+++ b/agents/drivers/oceanbase-oracle/src/main/java/com/oceanbase/jdbc/DbxLobResourceBytes.java@@ -0,0 +1,22 @@+package com.oceanbase.jdbc;++/** Connector/J 2.4.18 payload accounting only; never reads or exposes LOB bytes. */+public final class DbxLobResourceBytes {+ private DbxLobResourceBytes() {}++ public static long retainedBytes(Object value) {+ if (!(value instanceof Lob lob)) return -1;+ long bytes = 256; // conservative entry/locator metadata allowance+ if (lob.data != null) bytes += lob.data.length;+ if (lob.charData != null) bytes += 2L * lob.charData.length();+ ObLobLocator locator = lob.getLocator();+ if (locator != null) {+ if (locator.binaryData != null) bytes += locator.binaryData.length;+ if (locator instanceof ObLobLocatorV1 v1) {+ if (v1.rowId != null) bytes += v1.rowId.length;+ if (v1.tableId != null) bytes += v1.tableId.length;+ }+ }+ return bytes;+ }+}diff --git a/agents/drivers/oceanbase-oracle/src/test/java/com/dbx/agent/oceanbaseoracle/OceanBaseBlobValuesTest.java b/agents/drivers/oceanbase-oracle/src/test/java/com/dbx/agent/oceanbaseoracle/OceanBaseBlobValuesTest.javanew file mode 100644index 0000000000..7edd14a914--- /dev/null+++ b/agents/drivers/oceanbase-oracle/src/test/java/com/dbx/agent/oceanbaseoracle/OceanBaseBlobValuesTest.java@@ -0,0 +1,102 @@+package com.dbx.agent.oceanbaseoracle;++import org.junit.jupiter.api.Test;+import static org.junit.jupiter.api.Assertions.*;+import java.lang.reflect.Proxy;+import java.sql.Blob;+import java.sql.Connection;+import java.sql.ResultSet;+import java.sql.ResultSetMetaData;+import java.sql.Statement;+import java.sql.Types;+import java.util.HexFormat;+import java.util.List;+import java.util.Random;+import java.util.concurrent.atomic.AtomicBoolean;++class OceanBaseBlobValuesTest {+ @Test+ void preservesAllByteValuesAndLargeRandomContentAcrossBoundedChunks() throws Exception {+ byte[] original = new byte[128 * 1024 + 7];+ new Random(11438).nextBytes(original);+ for (int index = 0; index < 256; index++) original[index] = (byte) index;+ Fixture fixture = new Fixture();+ OceanBaseLobValues values = new OceanBaseLobValues((connection, locator, offset, limit) -> {+ assertSame(fixture.blob, locator);+ assertTrue(limit <= 4096);+ int start = (int) Math.min(original.length, offset);+ int end = Math.min(original.length, start + limit);+ return new OceanBaseLobValues.Chunk("ok", HexFormat.of().formatHex(original, start, end),+ offset + end - start, end - start < limit, "binary");+ });+ var preview = (OceanBaseLobValues.Preview) values.preview(fixture.resultSet, 1, Types.BLOB, "BLOB");+ assertEquals("0x" + HexFormat.of().formatHex(original, 0, 256), preview.text());+ assertEquals("blob", preview.kind());+ StringBuilder complete = new StringBuilder();+ long offset = 0;+ while (true) {+ var chunk = values.fetch(fixture.connection, preview.ref(), offset, 4096);+ assertEquals("binary", chunk.value_kind());+ complete.append(chunk.data());+ if (chunk.eof()) break;+ offset = chunk.next_offset();+ }+ byte[] fetched = HexFormat.of().parseHex(complete.toString());+ assertArrayEquals(original, fetched);+ assertArrayEquals(java.security.MessageDigest.getInstance("SHA-256").digest(original),+ java.security.MessageDigest.getInstance("SHA-256").digest(fetched));+ var marked = OceanBaseLobValues.mark(List.of("PAYLOAD"), List.of("BLOB"), List.of(List.of(preview)));+ assertEquals("__DBX_LARGE_VALUE_BYTES_L_0", marked.columns().get(1));+ assertEquals(preview.text(), marked.rows().get(0).get(0));+ values.clear();+ assertTrue(fixture.freed.get());+ assertEquals("expired", values.fetch(fixture.connection, preview.ref(), 0, 4096).status());+ }++ @Test+ void distinguishesEmptyBinaryZeroByteAndNullWithoutDeferredRefs() throws Exception {+ for (byte[] bytes : List.of(new byte[0], new byte[]{0}, new byte[]{0, (byte) 255})) {+ Fixture fixture = new Fixture();+ OceanBaseLobValues values = new OceanBaseLobValues((connection, locator, offset, limit) ->+ new OceanBaseLobValues.Chunk("ok", HexFormat.of().formatHex(bytes), bytes.length, true, "binary"));+ var preview = (OceanBaseLobValues.Preview) values.preview(fixture.resultSet, 1, Types.BLOB, "BLOB");+ assertEquals("0x" + HexFormat.of().formatHex(bytes), preview.text());+ assertNull(preview.ref());+ assertTrue(fixture.freed.get());+ }+ Fixture fixture = new Fixture();+ fixture.nullValue = true;+ OceanBaseLobValues values = new OceanBaseLobValues((connection, locator, offset, limit) -> { fail("NULL must not be read"); return null; });+ var preview = (OceanBaseLobValues.Preview) values.preview(fixture.resultSet, 1, Types.BLOB, "BLOB");+ assertNull(preview.text());+ assertNull(preview.ref());+ }++ private static final class Fixture {+ final AtomicBoolean freed = new AtomicBoolean();+ boolean nullValue;+ final Connection connection = proxy(Connection.class, (method, args) -> method.equals("isClosed") ? false : null);+ final Blob blob = proxy(Blob.class, (method, args) -> {+ if (method.equals("free")) { freed.set(true); return null; }+ throw new AssertionError("Unexpected full BLOB API: " + method);+ });+ final Statement statement = proxy(Statement.class, (method, args) -> method.equals("getConnection") ? connection : null);+ final ResultSetMetaData metadata = proxy(ResultSetMetaData.class, (method, args) -> {+ if (method.equals("getColumnCount")) return 1;+ if (method.equals("getColumnLabel")) return "PAYLOAD";+ return null;+ });+ final ResultSet resultSet = proxy(ResultSet.class, (method, args) -> {+ if (method.equals("getMetaData")) return metadata;+ if (method.equals("getStatement")) return statement;+ if (method.equals("getBlob")) return nullValue ? null : blob;+ if (method.equals("wasNull")) return nullValue;+ throw new AssertionError("Unexpected result read: " + method);+ });+ }+ @FunctionalInterface interface Handler { Object call(String method, Object[] args) throws Throwable; }+ private static <T> T proxy(Class<T> type, Handler handler) {+ return type.cast(Proxy.newProxyInstance(type.getClassLoader(), new Class<?>[]{type},+ (object, method, args) -> handler.call(method.getName(), args)));+ }+}diff --git a/agents/drivers/oceanbase-oracle/src/test/java/com/dbx/agent/oceanbaseoracle/OceanBaseLobSnapshotIntegrationTest.java b/agents/drivers/oceanbase-oracle/src/test/java/com/dbx/agent/oceanbaseoracle/OceanBaseLobSnapshotIntegrationTest.javanew file mode 100644index 0000000000..63c6d62bf1--- /dev/null+++ b/agents/drivers/oceanbase-oracle/src/test/java/com/dbx/agent/oceanbaseoracle/OceanBaseLobSnapshotIntegrationTest.java@@ -0,0 +1,122 @@+package com.dbx.agent.oceanbaseoracle;++import org.junit.jupiter.api.Test;+import org.junit.jupiter.api.Assumptions;+import static org.junit.jupiter.api.Assertions.*;+import java.sql.DriverManager;+import java.sql.Types;+import java.util.UUID;++/** Opt-in isolated Oracle tenant only. Run during the unified acceptance phase. */+class OceanBaseLobSnapshotIntegrationTest {+ @Test+ void capturesOriginalBlobBytesAcrossCursorCloseAndConcurrentUpdate() throws Exception {+ String url = System.getenv("OB_LOB_INTEGRATION_URL");+ Assumptions.assumeTrue(url != null && !url.isBlank(), "Isolated OB LOB integration environment not configured");+ String user = System.getenv("OB_LOB_INTEGRATION_USER");+ String password = System.getenv("OB_LOB_INTEGRATION_PASSWORD");+ String table = "DBX_O13_" + UUID.randomUUID().toString().replace("-", "").substring(0, 20).toUpperCase();+ OceanBaseLobValues values = new OceanBaseLobValues();+ try (var connection = DriverManager.getConnection(url, user, password);+ var other = DriverManager.getConnection(url, user, password)) {+ try (var statement = connection.createStatement(); var tenant = statement.executeQuery("SELECT SYS_CONTEXT('USERENV','CON_NAME') FROM DUAL")) {+ assertTrue(tenant.next());+ assertEquals("oracletest", tenant.getString(1).toLowerCase(), "Refuse writes outside the authorized isolated tenant");+ }+ boolean created = false;+ try {+ try (var statement = connection.createStatement()) {+ statement.execute("CREATE TABLE " + table + " (ID NUMBER PRIMARY KEY, PAYLOAD BLOB)");+ created = true;+ }+ byte[] original = new byte[1024 * 1024 + 7];+ new java.util.Random(11438).nextBytes(original);+ for (int index = 0; index < 256; index++) original[index] = (byte) index;+ try (var insert = connection.prepareStatement("INSERT INTO " + table + " VALUES (1, ?)")) {+ insert.setBytes(1, original);+ insert.executeUpdate();+ }+ OceanBaseLobValues.Preview preview;+ try (var statement = connection.createStatement(); var result = statement.executeQuery("SELECT PAYLOAD FROM " + table + " WHERE ID = 1")) {+ assertTrue(result.next());+ preview = (OceanBaseLobValues.Preview) values.preview(result, 1, Types.BLOB, "BLOB");+ }+ assertNotNull(preview.ref());+ assertEquals("0x" + java.util.HexFormat.of().formatHex(original, 0, 256), preview.text());+ try (var update = other.prepareStatement("UPDATE " + table + " SET PAYLOAD = ? WHERE ID = 1")) {+ update.setBytes(1, new byte[]{1, 2, 3});+ assertEquals(1, update.executeUpdate());+ }+ StringBuilder complete = new StringBuilder();+ long offset = 0;+ while (true) {+ var chunk = values.fetch(connection, preview.ref(), offset, 4096);+ assertEquals("binary", chunk.value_kind());+ complete.append(chunk.data());+ if (chunk.eof()) break;+ offset = chunk.next_offset();+ }+ assertArrayEquals(original, java.util.HexFormat.of().parseHex(complete.toString()));+ } finally {+ values.clear();+ if (created) try (var statement = connection.createStatement()) { statement.execute("DROP TABLE " + table + " PURGE"); }+ }+ }+ }++ @Test+ void capturesOriginalClobAcrossCursorCloseAndConcurrentUpdateAndDelete() throws Exception {+ String url = System.getenv("OB_LOB_INTEGRATION_URL");+ Assumptions.assumeTrue(url != null && !url.isBlank(), "Isolated OB LOB integration environment not configured");+ String user = System.getenv("OB_LOB_INTEGRATION_USER");+ String password = System.getenv("OB_LOB_INTEGRATION_PASSWORD");+ String table = "DBX_O13_" + UUID.randomUUID().toString().replace("-", "").substring(0, 20).toUpperCase();+ OceanBaseLobValues values = new OceanBaseLobValues();+ try (var connection = DriverManager.getConnection(url, user, password);+ var other = DriverManager.getConnection(url, user, password)) {+ try (var statement = connection.createStatement(); var tenant = statement.executeQuery("SELECT SYS_CONTEXT('USERENV','CON_NAME') FROM DUAL")) {+ assertTrue(tenant.next());+ assertEquals("oracletest", tenant.getString(1).toLowerCase(), "Refuse writes outside the authorized isolated tenant");+ }+ boolean created = false;+ try {+ try (var statement = connection.createStatement()) {+ statement.execute("CREATE TABLE " + table + " (ID NUMBER PRIMARY KEY, PAYLOAD CLOB)");+ created = true;+ }+ String original = "中文😀完整原值".repeat(12_000);+ try (var insert = connection.prepareStatement("INSERT INTO " + table + " VALUES (1, ?)")) {+ insert.setString(1, original);+ insert.executeUpdate();+ }+ OceanBaseLobValues.Preview preview;+ try (var statement = connection.createStatement(); var result = statement.executeQuery("SELECT PAYLOAD FROM " + table + " WHERE ID = 1")) {+ assertTrue(result.next());+ preview = (OceanBaseLobValues.Preview) values.preview(result, 1, Types.CLOB, "CLOB");+ }+ assertNotNull(preview.ref());+ assertEquals(256, preview.text().codePointCount(0, preview.text().length()));+ try (var update = other.prepareStatement("UPDATE " + table + " SET PAYLOAD = ? WHERE ID = 1")) {+ update.setString(1, "已经变更😀".repeat(12_000));+ assertEquals(1, update.executeUpdate());+ }+ try (var statement = other.createStatement()) { assertEquals(1, statement.executeUpdate("DELETE FROM " + table + " WHERE ID = 1")); }+ StringBuilder complete = new StringBuilder();+ long offset = 0;+ while (true) {+ var chunk = values.fetch(connection, preview.ref(), offset, 4096);+ assertEquals("ok", chunk.status());+ complete.append(chunk.data());+ if (chunk.eof()) break;+ offset = chunk.next_offset();+ }+ assertEquals(original, complete.toString());+ values.clear();+ assertEquals("expired", values.fetch(connection, preview.ref(), 0, 4096).status());+ } finally {+ values.clear();+ if (created) try (var statement = connection.createStatement()) { statement.execute("DROP TABLE " + table + " PURGE"); }+ }+ }+ }+}diff --git a/agents/drivers/oceanbase-oracle/src/test/java/com/dbx/agent/oceanbaseoracle/OceanBaseLobStatementTest.java b/agents/drivers/oceanbase-oracle/src/test/java/com/dbx/agent/oceanbaseoracle/OceanBaseLobStatementTest.javanew file mode 100644index 0000000000..98f030e200--- /dev/null+++ b/agents/drivers/oceanbase-oracle/src/test/java/com/dbx/agent/oceanbaseoracle/OceanBaseLobStatementTest.java@@ -0,0 +1,268 @@+package com.dbx.agent.oceanbaseoracle;++import com.dbx.agent.JdbcExecutor;+import com.dbx.agent.BlobBoundExecutor;+import com.dbx.agent.BlobBoundStatement;+import com.oceanbase.jdbc.OceanBaseConnection;+import com.oceanbase.jdbc.OceanBaseStatement;+import com.oceanbase.jdbc.internal.protocol.Protocol;+import com.oceanbase.jdbc.util.Options;+import com.zaxxer.hikari.HikariDataSource;+import java.lang.reflect.Proxy;+import java.sql.Blob;+import java.sql.CallableStatement;+import java.sql.Clob;+import java.sql.Connection;+import java.sql.PreparedStatement;+import java.sql.SQLException;+import java.sql.Types;+import java.util.ArrayList;+import java.util.List;+import java.util.concurrent.locks.ReentrantLock;+import javax.sql.DataSource;+import org.junit.jupiter.api.Test;+import static org.junit.jupiter.api.Assertions.*;++class OceanBaseLobStatementTest {+ @Test void onlyConfirmedObBusinessErrorIsEligibleForSavepointKeep() {+ assertTrue(OceanBaseLobStatements.BINDING.isRollbackConfirmedBusinessError(new java.sql.SQLTransientConnectionException("ORA-20001: stale", "HY000", 20001)));+ assertFalse(OceanBaseLobStatements.BINDING.isRollbackConfirmedBusinessError(new java.sql.SQLTransientConnectionException("connection lost", "08006", 20001)));+ assertFalse(OceanBaseLobStatements.BINDING.isRollbackConfirmedBusinessError(new java.sql.SQLTransientConnectionException("other error", "HY000", 600)));+ assertFalse(OceanBaseLobStatements.BINDING.isRollbackConfirmedBusinessError(new java.sql.SQLRecoverableException("lost", "HY000", 20001)));+ assertFalse(OceanBaseLobStatements.BINDING.isRollbackConfirmedBusinessError(new java.sql.SQLTimeoutException("timeout", "HY000", 20001)));+ assertFalse(OceanBaseLobStatements.BINDING.isRollbackConfirmedBusinessError(new java.sql.SQLTransientConnectionException("stale", "HY000", 20001, new SQLException("lost", "08006"))));+ assertTrue(OceanBaseLobStatements.BINDING.isUnsupportedSavepointRelease(new SQLException("unsupported", "99999", 17023)));+ assertFalse(OceanBaseLobStatements.BINDING.isUnsupportedSavepointRelease(new java.sql.SQLTransientConnectionException("lost", "08006", 17023)));+ assertFalse(OceanBaseLobStatements.BINDING.isUnsupportedSavepointRelease(new java.sql.SQLTimeoutException("timeout", "99999", 17023)));+ }+ @Test+ void boundPreparedAndCallableInitializeNativeModeBeforeStreamBindingThroughPool() throws Exception {+ for (boolean callable : new boolean[]{false, true}) {+ List<String> calls = new ArrayList<>();+ Options options = new Options();+ Protocol protocol = proxy(Protocol.class, (object, method, args) -> {+ if (method.getName().equals("getOptions")) return options;+ if (method.getName().equals("getLock")) return new ReentrantLock();+ return defaultValue(method.getReturnType());+ });+ OceanBaseStatement vendor = new OceanBaseStatement(new OceanBaseConnection(protocol), 1003, 1007, null);+ java.lang.reflect.InvocationHandler handler = (object, method, args) -> {+ switch (method.getName()) {+ case "unwrap": return ((Class<?>) args[0]).cast(vendor);+ case "isWrapperFor": return ((Class<?>) args[0]).isInstance(vendor);+ case "setBlob":+ assertTrue(vendor.isInternal(), "native mode must precede the first stream binding");+ assertEquals(3L, args[2]);+ assertArrayEquals(new byte[]{0, (byte)255, (byte)128}, ((java.io.InputStream) args[1]).readAllBytes());+ calls.add("bind"); return null;+ case "execute": assertTrue(JdbcExecutor.current().hasActiveStatements()); calls.add("execute"); return false;+ case "getUpdateCount": return 1;+ case "close": calls.add("close"); return null;+ default: return defaultValue(method.getReturnType());+ }+ };+ PreparedStatement delegate = callable ? proxy(CallableStatement.class, handler) : proxy(PreparedStatement.class, handler);+ Connection physical = proxy(Connection.class, (object, method, args) -> {+ if (method.getName().equals(callable ? "prepareCall" : "prepareStatement")) return delegate;+ if (method.getName().equals("getMetaData")) return proxy(java.sql.DatabaseMetaData.class, (o,m,a) -> m.getName().equals("supportsTransactions") ? true : defaultValue(m.getReturnType()));+ if (method.getName().equals("getAutoCommit") || method.getName().equals("isValid")) return true;+ if (method.getName().equals("getTransactionIsolation")) return Connection.TRANSACTION_READ_COMMITTED;+ return defaultValue(method.getReturnType());+ });+ DataSource source = proxy(DataSource.class, (object, method, args) -> method.getName().equals("getConnection") ? physical : defaultValue(method.getReturnType()));+ String sql = callable ? "BEGIN UPDATE t SET b = ?; END;" : "UPDATE t SET b = ?";+ try (HikariDataSource pool = new HikariDataSource()) {+ pool.setDataSource(source); pool.setMaximumPoolSize(1); pool.setMinimumIdle(0);+ try (Connection connection = pool.getConnection()) {+ BlobBoundExecutor.execute(connection, List.of("preview"),+ List.of(new BlobBoundStatement("preview", sql, List.of("00ff80"))),+ null, ignored -> null, () -> null, 20, false, OceanBaseLobStatements::configure);+ }+ }+ assertEquals(List.of("bind", "execute", "close"), calls);+ assertFalse(JdbcExecutor.current().hasActiveStatements());+ }+ }++ @Test+ void boundNativeInitializationFailureClosesEntirePreparedBatchBeforeAnyWrite() {+ List<String> calls = new ArrayList<>();+ Options options = new Options();+ Protocol protocol = proxy(Protocol.class, (object, method, args) -> {+ if (method.getName().equals("getOptions")) return options;+ if (method.getName().equals("getLock")) return new ReentrantLock();+ return defaultValue(method.getReturnType());+ });+ OceanBaseStatement vendor = new OceanBaseStatement(new OceanBaseConnection(protocol), 1003, 1007, null);+ int[] prepared = {0};+ Connection connection = proxy(Connection.class, (object, method, args) -> {+ if (method.getName().equals("getAutoCommit")) return true;+ if (method.getName().equals("getMetaData")) return proxy(java.sql.DatabaseMetaData.class, (o,m,a) -> m.getName().equals("supportsTransactions") ? true : defaultValue(m.getReturnType()));+ if (method.getName().equals("prepareStatement")) {+ int index = ++prepared[0];+ return proxy(PreparedStatement.class, (o, m, a) -> {+ if (m.getName().equals("unwrap")) {+ if (index == 2) throw new SQLException("unsupported native wrapper");+ return vendor;+ }+ if (m.getName().equals("close")) calls.add("close" + index);+ if (m.getName().equals("execute")) calls.add("write" + index);+ return defaultValue(m.getReturnType());+ });+ }+ return defaultValue(method.getReturnType());+ });+ RuntimeException error = assertThrows(RuntimeException.class, () -> BlobBoundExecutor.execute(connection,+ List.of("first", "second"), List.of(new BlobBoundStatement("first", "UPDATE t SET b = ?", List.of("00")),+ new BlobBoundStatement("second", "UPDATE t SET b = ?", List.of("01"))),+ null, ignored -> null, () -> null, 20, false, OceanBaseLobStatements::configure));+ assertEquals("Unsupported OceanBase LOB statement", error.getCause().getMessage());+ assertEquals(2, calls.size());+ assertTrue(calls.containsAll(List.of("close1", "close2")));+ assertFalse(JdbcExecutor.current().hasActiveStatements());+ }++ @Test+ void serverLengthMarksExactLastChunkAndPastEndWithoutHidingReadErrors() throws Exception {+ for (boolean binary : new boolean[]{false, true}) {+ for (String scenario : List.of("exact", "past-end", "beyond-end", "full-interior", "read-error")) {+ Options options = new Options();+ Protocol protocol = proxy(Protocol.class, (object, method, args) -> {+ if (method.getName().equals("getOptions")) return options;+ if (method.getName().equals("getLock")) return new ReentrantLock();+ return defaultValue(method.getReturnType());+ });+ OceanBaseStatement vendor = new OceanBaseStatement(new OceanBaseConnection(protocol), 1003, 1007, null);+ // JDBC UTF-16 length deliberately differs from the server's code-point length.+ Object locator = binary ? proxy(Blob.class, (o, m, a) -> m.getName().equals("length") ? 10L : defaultValue(m.getReturnType()))+ : proxy(Clob.class, (o, m, a) -> m.getName().equals("length") ? 10L : defaultValue(m.getReturnType()));+ SQLException failure = new SQLException("ORA-06502: real read failure", "HY000", 6502);+ CallableStatement call = proxy(CallableStatement.class, (object, method, args) -> {+ switch (method.getName()) {+ case "unwrap": return vendor;+ case "execute": if (scenario.equals("read-error")) throw failure; return false;+ case "getInt": return scenario.equals("past-end") || scenario.equals("beyond-end") ? 0 : 3;+ case "getLong": return scenario.equals("full-interior") ? 9L : 8L;+ case "getBytes": return scenario.equals("past-end") || scenario.equals("beyond-end") ? null : binary ? new byte[]{0, (byte) 255, 1} : "中😀末".getBytes(java.nio.charset.StandardCharsets.UTF_8);+ default: return defaultValue(method.getReturnType());+ }+ });+ Connection connection = proxy(Connection.class, (object, method, args) -> method.getName().equals("prepareCall") ? call : defaultValue(method.getReturnType()));+ if (scenario.equals("read-error")) {+ assertSame(failure, assertThrows(SQLException.class, () -> OceanBaseLobValues.read(connection, locator, 5, 3)));+ } else {+ var chunk = OceanBaseLobValues.read(connection, locator, scenario.equals("beyond-end") ? 9 : scenario.equals("past-end") ? 8 : 5, 3);+ assertEquals(scenario.equals("past-end") || scenario.equals("beyond-end") ? "" : binary ? "00ff01" : "中😀末", chunk.data());+ assertEquals(scenario.equals("beyond-end") ? 9 : 8, chunk.next_offset());+ assertEquals(!scenario.equals("full-interior"), chunk.eof(), "EOF must use server length, not JDBC UTF-16 length");+ }+ assertFalse(JdbcExecutor.current().hasActiveStatements());+ }+ }+ }++ @Test+ void emptyLocatorReturnsEmptyEofWithoutCallingDbmsLobRead() throws Exception {+ for (boolean binary : new boolean[]{false, true}) {+ java.lang.reflect.InvocationHandler handler = (object, method, args) -> {+ if (method.getName().equals("length")) return 0L;+ throw new AssertionError("Empty LOB must not be materialized");+ };+ Object locator = binary ? proxy(Blob.class, handler) : proxy(Clob.class, handler);+ Connection connection = proxy(Connection.class, (object, method, args) -> {+ if (method.getName().equals("prepareCall")) throw new SQLException("ORA-06502: no data found", "HY000", 6502);+ throw new AssertionError("Empty LOB must not execute a statement");+ });+ var chunk = OceanBaseLobValues.read(connection, locator, 0, 257);+ assertEquals("", chunk.data());+ assertEquals(0, chunk.next_offset());+ assertTrue(chunk.eof());+ assertEquals(binary ? "binary" : "text", chunk.value_kind());+ assertFalse(JdbcExecutor.current().hasActiveStatements());+ }+ }++ @Test+ void pooledCallableUnwrapsVendorOnlyForInternalFlagAndKeepsLifecycleOnProxy() throws Exception {+ for (boolean binary : new boolean[]{false, true}) {+ List<String> calls = new ArrayList<>();+ Options options = new Options();+ Protocol protocol = proxy(Protocol.class, (object, method, args) -> {+ if (method.getName().equals("getOptions")) return options;+ if (method.getName().equals("getLock")) return new ReentrantLock();+ return defaultValue(method.getReturnType());+ });+ OceanBaseStatement vendor = new OceanBaseStatement(new OceanBaseConnection(protocol), 1003, 1007, null);+ Object locator = binary ? proxy(Blob.class, (o, m, a) -> m.getName().equals("length") ? 8L : defaultValue(m.getReturnType()))+ : proxy(Clob.class, (o, m, a) -> m.getName().equals("length") ? 8L : defaultValue(m.getReturnType()));+ CallableStatement delegate = proxy(CallableStatement.class, (object, method, args) -> {+ switch (method.getName()) {+ case "unwrap": return ((Class<?>) args[0]).cast(vendor);+ case "isWrapperFor": return ((Class<?>) args[0]).isInstance(vendor);+ case "setBlob", "setClob": assertSame(locator, args[1]); calls.add(method.getName()); return null;+ case "setInt": assertEquals(3, args[1]); return null;+ case "setLong": assertEquals(6L, args[1]); return null;+ case "setQueryTimeout": assertEquals(20, args[0]); return null;+ case "registerOutParameter": assertEquals((int) args[0] == 4 ? Types.INTEGER : (int) args[0] == 5 ? (binary ? Types.VARBINARY : Types.VARCHAR) : Types.BIGINT, args[1]); return null;+ case "execute":+ assertTrue(vendor.isInternal());+ assertTrue(JdbcExecutor.current().hasActiveStatements());+ JdbcExecutor.current().cancelActiveStatements();+ calls.add("execute"); return false;+ case "cancel", "close": calls.add(method.getName()); return null;+ case "getInt": return 2;+ case "getLong": return 7L;+ case "getBytes": return binary ? new byte[]{0, (byte) 255} : "中😀".getBytes(java.nio.charset.StandardCharsets.UTF_8);+ default: return defaultValue(method.getReturnType());+ }+ });+ Connection physical = proxy(Connection.class, (object, method, args) -> {+ if (method.getName().equals("prepareCall")) return delegate;+ if (method.getName().equals("getAutoCommit") || method.getName().equals("isValid")) return true;+ if (method.getName().equals("getTransactionIsolation")) return Connection.TRANSACTION_READ_COMMITTED;+ return defaultValue(method.getReturnType());+ });+ DataSource source = proxy(DataSource.class, (object, method, args) -> method.getName().equals("getConnection") ? physical : defaultValue(method.getReturnType()));+ try (HikariDataSource pool = new HikariDataSource()) {+ pool.setDataSource(source);+ pool.setMaximumPoolSize(1);+ pool.setMinimumIdle(0);+ try (Connection connection = pool.getConnection()) {+ var chunk = OceanBaseLobValues.read(connection, locator, 5, 3);+ assertEquals(binary ? "00ff" : "中😀", chunk.data());+ assertEquals(7, chunk.next_offset());+ assertTrue(chunk.eof());+ assertEquals(binary ? "binary" : "text", chunk.value_kind());+ }+ }+ assertEquals(List.of(binary ? "setBlob" : "setClob", "cancel", "execute", "close"), calls);+ assertFalse(JdbcExecutor.current().hasActiveStatements());+ }+ }++ @Test+ void nonOceanBaseCallableIsRejectedAndClosedBeforeExecuting() {+ List<String> calls = new ArrayList<>();+ CallableStatement call = proxy(CallableStatement.class, (object, method, args) -> {+ if (method.getName().equals("unwrap")) throw new SQLException("Not a vendor wrapper");+ if (method.getName().equals("close") || method.getName().equals("execute")) calls.add(method.getName());+ return defaultValue(method.getReturnType());+ });+ Connection connection = proxy(Connection.class, (object, method, args) -> method.getName().equals("prepareCall") ? call : defaultValue(method.getReturnType()));+ SQLException error = assertThrows(SQLException.class, () -> OceanBaseLobValues.read(connection, proxy(Clob.class, (o, m, a) -> m.getName().equals("length") ? 1L : null), 0, 1));+ assertEquals("Unsupported OceanBase LOB statement", error.getMessage());+ assertEquals(List.of("close"), calls);+ assertFalse(JdbcExecutor.current().hasActiveStatements());+ }++ private static Object defaultValue(Class<?> type) {+ if (type == boolean.class) return false;+ if (type == int.class) return 0;+ if (type == long.class) return 0L;+ return null;+ }++ private static <T> T proxy(Class<T> type, java.lang.reflect.InvocationHandler handler) {+ return type.cast(Proxy.newProxyInstance(type.getClassLoader(), new Class<?>[]{type}, handler));+ }+}diff --git a/agents/drivers/oceanbase-oracle/src/test/java/com/dbx/agent/oceanbaseoracle/OceanBaseLobValuesTest.java b/agents/drivers/oceanbase-oracle/src/test/java/com/dbx/agent/oceanbaseoracle/OceanBaseLobValuesTest.javanew file mode 100644index 0000000000..2aea022e01--- /dev/null+++ b/agents/drivers/oceanbase-oracle/src/test/java/com/dbx/agent/oceanbaseoracle/OceanBaseLobValuesTest.java@@ -0,0 +1,223 @@+package com.dbx.agent.oceanbaseoracle;++import org.junit.jupiter.api.Test;+import org.junit.jupiter.params.ParameterizedTest;+import org.junit.jupiter.params.provider.CsvSource;+import com.dbx.agent.ExecuteQueryOptions;+import com.dbx.agent.QueryPageOptions;+import com.dbx.agent.test.TestSupport;+import static org.junit.jupiter.api.Assertions.*;+import java.lang.reflect.Proxy;+import java.sql.Clob;+import java.sql.Connection;+import java.sql.ResultSet;+import java.sql.ResultSetMetaData;+import java.sql.Statement;+import java.sql.Types;+import java.util.ArrayList;+import java.util.List;+import java.util.concurrent.atomic.AtomicBoolean;++class OceanBaseLobValuesTest {+ @ParameterizedTest+ @org.junit.jupiter.params.provider.ValueSource(strings = {"query", "page", "table"})+ void longCteLiteralReachesJdbcAndRetainsPreviousLocator(String entryPoint) throws Exception {+ checkFailedStatement(entryPoint, false, "WITH x AS (SELECT '" + "a".repeat(4000) + "' AS s FROM dual) SELECT * FROM x", true);+ }++ @ParameterizedTest+ @CsvSource({"query,false", "query,true", "page,false", "page,true", "table,false", "table,true", "cte-query,false", "cte-page,true", "cte-table,true"})+ void failedReadReleasesOnlyItsNewLocators(String entryPoint, boolean capturePartial) throws Exception {+ String sql = entryPoint.startsWith("cte-") ? "WITH x AS (SELECT 1 AS n FROM dual) SELECT * FROM x" : "SELECT INVALID FROM DUAL";+ checkFailedStatement(entryPoint.replace("cte-", ""), capturePartial, sql, true);+ }++ @ParameterizedTest+ @CsvSource(delimiter = '|', quoteCharacter = '`', value = {+ "WITH x(n) AS (SELECT 1 FROM dual), y AS (SELECT n FROM x) SELECT * FROM y|true",+ "WITH c AS (SELECT q'[it's (]' txt FROM dual) SELECT txt FROM c|true",+ "WITH c AS (SELECT q'[it's ;]' txt FROM dual) SELECT txt FROM c|true",+ "WITH c AS (SELECT Q'!it's ; (!' txt FROM dual) SELECT txt FROM c|true",+ "WITH \"x\" AS (SELECT ') ; UPDATE' FROM dual /* ) */) SELECT * FROM \"x\"|true",+ "WITH x AS (SELECT 1 FROM dual) UPDATE target SET n = 1|false",+ "WITH x AS (DELETE FROM target RETURNING n) SELECT * FROM x|false",+ "WITH x AS (SELECT 1 FROM dual) SELECT * FROM x; COMMIT|false",+ "WITH FUNCTION f RETURN NUMBER IS BEGIN RETURN 1; END; SELECT f FROM dual|false",+ "COMMIT|false",+ "ROLLBACK|false"+ })+ void onlyConfirmedCteQueriesRetainOldLocators(String sql, boolean retain) throws Exception {+ checkFailedStatement("query", false, sql, retain);+ }++ private void checkFailedStatement(String entryPoint, boolean capturePartial, String sql, boolean retain) throws Exception {+ OceanBaseLobValues values = new OceanBaseLobValues((connection, locator, offset, limit) -> chunk("x".repeat(1000), offset, limit));+ Fixture old = new Fixture();+ var retained = (OceanBaseLobValues.Preview) values.preview(old.resultSet, 1, Types.CLOB, "CLOB");+ Fixture partial = new Fixture();+ OceanBaseOracleAgent agent = new OceanBaseOracleAgent();+ var field = OceanBaseOracleAgent.class.getDeclaredField("lobValues");+ field.setAccessible(true);+ field.set(agent, values);+ TestSupport.setPrivateConnection(agent, proxy(Connection.class, (method, args) -> {+ if (method.equals("isClosed")) return false;+ if (method.equals("createStatement")) {+ if (capturePartial) values.preview(partial.resultSet, 1, Types.CLOB, "CLOB");+ throw new java.sql.SQLException("failed request", "42000");+ }+ return null;+ }));+ assertThrows(RuntimeException.class, () -> {+ switch (entryPoint) {+ case "query" -> agent.executeQuery(sql, null, new ExecuteQueryOptions(10, null, 5));+ case "page" -> agent.executeQueryPage(sql, null, new QueryPageOptions(10, null, 10, 5));+ default -> agent.startTableRead(sql, null, new QueryPageOptions(10, null, 10, 5));+ }+ });+ assertEquals(!retain, old.freed.get());+ assertEquals(capturePartial, partial.freed.get());+ if (retain) assertEquals("ok", values.fetch(old.connection, retained.ref(), 0, 10).status());+ agent.invalidateLargeValues();+ assertTrue(old.freed.get());+ }++ @Test+ void refusesNewLocatorsWhenRetainedPayloadBudgetIsFullAndRestoresCapacityOnRelease() throws Exception {+ OceanBaseLobValues values = new OceanBaseLobValues((connection, locator, offset, limit) -> chunk("x".repeat(1000), offset, limit), ignored -> 40L * 1024 * 1024);+ Fixture first = new Fixture();+ var preview = (OceanBaseLobValues.Preview) values.preview(first.resultSet, 1, Types.CLOB, "CLOB");+ Fixture second = new Fixture();+ assertThrows(java.sql.SQLException.class, () -> values.preview(second.resultSet, 1, Types.CLOB, "CLOB"));+ assertTrue(second.freed.get());+ assertTrue(values.release(preview.ref()));+ Fixture third = new Fixture();+ assertNotNull(((OceanBaseLobValues.Preview) values.preview(third.resultSet, 1, Types.CLOB, "CLOB")).ref());+ values.clear();+ Fixture fourth = new Fixture();+ assertNotNull(((OceanBaseLobValues.Preview) values.preview(fourth.resultSet, 1, Types.CLOB, "CLOB")).ref());+ values.clear();+ }+ @Test+ void boundsPreviewAndReadsTheSameCapturedLocatorWithoutMaterializingItsStreams() throws Exception {+ String original = "中文😀".repeat(1000);+ List<Integer> amounts = new ArrayList<>();+ Fixture fixture = new Fixture();+ OceanBaseLobValues values = new OceanBaseLobValues((connection, locator, offset, limit) -> {+ assertSame(fixture.connection, connection);+ assertSame(fixture.clob, locator);+ amounts.add(limit);+ return chunk(original, offset, limit);+ });+ var preview = (OceanBaseLobValues.Preview) values.preview(fixture.resultSet, 1, Types.CLOB, "CLOB");+ assertEquals(256, preview.text().codePointCount(0, preview.text().length()));+ assertFalse(Character.isHighSurrogate(preview.text().charAt(preview.text().length() - 1)));+ assertNotNull(preview.ref());+ assertEquals(List.of(257), amounts);+ StringBuilder complete = new StringBuilder();+ long offset = 0;+ while (true) {+ var next = values.fetch(fixture.connection, preview.ref(), offset, 31);+ complete.append(next.data());+ if (next.eof()) break;+ assertTrue(next.next_offset() > offset);+ offset = next.next_offset();+ }+ assertEquals(original, complete.toString());+ assertFalse(fixture.freed.get());+ assertTrue(values.release(preview.ref()));+ assertTrue(fixture.freed.get());+ assertEquals("expired", values.fetch(fixture.connection, preview.ref(), 0, 31).status());+ }++ @Test+ void distinguishesNullEmptyShortAndDeferredValues() throws Exception {+ for (String text : List.of("", "短😀值", "x".repeat(257))) {+ Fixture fixture = new Fixture();+ OceanBaseLobValues values = new OceanBaseLobValues((connection, locator, offset, limit) -> chunk(text, offset, limit));+ var preview = (OceanBaseLobValues.Preview) values.preview(fixture.resultSet, 1, Types.CLOB, "CLOB");+ // A value exactly filling the look-ahead chunk remains deferred until EOF is known.+ if (text.length() < 257) {+ assertEquals(text, preview.text());+ assertNull(preview.ref());+ assertTrue(fixture.freed.get());+ } else assertNotNull(preview.ref());+ values.clear();+ }+ Fixture fixture = new Fixture();+ fixture.nullValue = true;+ OceanBaseLobValues values = new OceanBaseLobValues((connection, locator, offset, limit) -> { fail("NULL must not be read"); return null; });+ var preview = (OceanBaseLobValues.Preview) values.preview(fixture.resultSet, 1, Types.CLOB, "CLOB");+ assertNull(preview.text());+ assertNull(preview.ref());+ }++ @Test+ void rejectsWrongConnectionAndInvalidChunkBoundsAndInvalidatesOnClear() throws Exception {+ Fixture fixture = new Fixture();+ OceanBaseLobValues values = new OceanBaseLobValues((connection, locator, offset, limit) -> chunk("原值".repeat(1000), offset, limit));+ var preview = (OceanBaseLobValues.Preview) values.preview(fixture.resultSet, 1, Types.CLOB, "CLOB");+ assertThrows(IllegalArgumentException.class, () -> values.fetch(fixture.connection, preview.ref(), -1, 1));+ assertThrows(IllegalArgumentException.class, () -> values.fetch(fixture.connection, preview.ref(), 0, 4097));+ assertEquals("expired", values.fetch(new Fixture().connection, preview.ref(), 0, 1).status());+ Fixture nextFixture = new Fixture();+ var nextPreview = (OceanBaseLobValues.Preview) values.preview(nextFixture.resultSet, 1, Types.CLOB, "CLOB");+ values.clear();+ assertEquals("expired", values.fetch(nextFixture.connection, nextPreview.ref(), 0, 1).status());+ assertTrue(fixture.freed.get());+ assertTrue(nextFixture.freed.get());+ }++ @Test+ void markerCollisionFallsBackBeforeReadingOrTruncatingAndRefsStayOutOfValues() throws Exception {+ Fixture fixture = new Fixture();+ fixture.label = "__dbx_large_value_bytes_c_0";+ OceanBaseLobValues values = new OceanBaseLobValues((connection, locator, offset, limit) -> { fail("Collision must keep complete ordinary read"); return null; });+ assertNull(values.preview(fixture.resultSet, 1, Types.CLOB, "CLOB"));+ var marked = OceanBaseLobValues.mark(List.of("ID", "Payload"), List.of("NUMBER", "CLOB"),+ List.of(List.of(1, new OceanBaseLobValues.Preview("原始😀", "opaque-ref")),+ java.util.Arrays.asList(2, new OceanBaseLobValues.Preview(null, null))));+ assertEquals(List.of("ID", "Payload", "__DBX_LARGE_VALUE_BYTES_C_1"), marked.columns());+ assertEquals("原始😀", marked.rows().get(0).get(1));+ assertEquals("D:1:unknown:opaque-ref", marked.rows().get(0).get(2));+ assertNull(marked.rows().get(1).get(1));+ assertNull(marked.rows().get(1).get(2));+ }++ private static OceanBaseLobValues.Chunk chunk(String text, long offset, int limit) {+ int count = text.codePointCount(0, text.length());+ int start = Math.min(count, (int) offset);+ int end = Math.min(count, start + limit);+ String data = text.substring(text.offsetByCodePoints(0, start), text.offsetByCodePoints(0, end));+ return new OceanBaseLobValues.Chunk("ok", data, offset + end - start, end - start < limit, "text");+ }++ private static final class Fixture {+ final AtomicBoolean freed = new AtomicBoolean();+ boolean nullValue;+ String label = "PAYLOAD";+ final Connection connection = proxy(Connection.class, (method, args) -> method.equals("isClosed") ? false : null);+ final Clob clob = proxy(Clob.class, (method, args) -> {+ if (method.equals("free")) { freed.set(true); return null; }+ throw new AssertionError("Unexpected full LOB API: " + method);+ });+ final Statement statement = proxy(Statement.class, (method, args) -> method.equals("getConnection") ? connection : null);+ final ResultSetMetaData metadata = proxy(ResultSetMetaData.class, (method, args) -> {+ if (method.equals("getColumnCount")) return 1;+ if (method.equals("getColumnLabel")) return label;+ return null;+ });+ final ResultSet resultSet = proxy(ResultSet.class, (method, args) -> {+ if (method.equals("getMetaData")) return metadata;+ if (method.equals("getStatement")) return statement;+ if (method.equals("getClob")) return nullValue ? null : clob;+ if (method.equals("wasNull")) return nullValue;+ throw new AssertionError("Unexpected result read: " + method);+ });+ }++ @FunctionalInterface interface Handler { Object call(String method, Object[] args) throws Throwable; }+ private static <T> T proxy(Class<T> type, Handler handler) {+ return type.cast(Proxy.newProxyInstance(type.getClassLoader(), new Class<?>[]{type},+ (object, method, args) -> handler.call(method.getName(), args)));+ }+}diff --git a/agents/drivers/oceanbase-oracle/src/test/java/com/oceanbase/jdbc/DbxLobResourceBytesTest.java b/agents/drivers/oceanbase-oracle/src/test/java/com/oceanbase/jdbc/DbxLobResourceBytesTest.javanew file mode 100644index 0000000000..7ec583713c--- /dev/null+++ b/agents/drivers/oceanbase-oracle/src/test/java/com/oceanbase/jdbc/DbxLobResourceBytesTest.java@@ -0,0 +1,23 @@+package com.oceanbase.jdbc;++import org.junit.jupiter.api.Test;+import static org.junit.jupiter.api.Assertions.*;++class DbxLobResourceBytesTest {+ @Test+ void countsExistingDriverPayloadAndLocatorWithoutReadingTheServer() {+ Clob clob = new Clob("中文🙂".repeat(100), null);+ ObLobLocatorV1 locator = new ObLobLocatorV1();+ locator.binaryData = new byte[1200];+ locator.rowId = new byte[20];+ locator.tableId = new byte[8];+ clob.locator = locator;+ assertEquals(256 + 800 + 1200 + 20 + 8, DbxLobResourceBytes.retainedBytes(clob));+ locator.binaryData = new byte[96];+ clob.charData = null;+ clob.data = null;+ locator.payloadSize = 1024L * 1024 * 1024; // out-row length is not retained payload+ assertEquals(256 + 96 + 20 + 8, DbxLobResourceBytes.retainedBytes(clob));+ assertEquals(-1, DbxLobResourceBytes.retainedBytes(new Object()));+ }+}diff --git a/apps/desktop/src/components/grid/DataGrid.vue b/apps/desktop/src/components/grid/DataGrid.vueindex 9836efcff5..51a0b7be76 100644--- a/apps/desktop/src/components/grid/DataGrid.vue+++ b/apps/desktop/src/components/grid/DataGrid.vue@@ -333,6 +333,7 @@ import { translateBackendError } from "@/i18n/backend-errors";import { useNavigationTargets } from "@/composables/useNavigationTargets";import { useDataGridExport, type MongoCopyUpdateTarget } from "@/composables/useDataGridExport";import { isTauriRuntime } from "@/lib/backend/tauriRuntime";+import { promptExportSavePath } from "@/lib/export/exportPath";import { eventTargetAllowsNativeClipboard, isPlainClipboardShortcut, readTextFromClipboard } from "@/lib/common/clipboard";import { claimDataGridPaste, claimDataGridSelectAll, clearDataGridClipboardCopy, parseDataGridClipboard, parseDataGridClipboardInBatches, planDataGridPaste } from "@/lib/dataGrid/dataGridClipboard";import { parseInsertStatementPaste, parseInsertStatementPasteInBatches } from "@/lib/dataGrid/dataGridInsertPaste";@@ -413,7 +414,7 @@ import { SearchableSelect } from "@/components/ui/searchable-select";import { useDataGridColumnFormatter } from "@/composables/useDataGridColumnFormatter";import { useDataGridTableMetadataLoaders } from "@/composables/useDataGridTableMetadataLoaders";import { DATA_GRID_SERVER_COLUMN_FILTER_LIMIT, useDataGridColumnFilters } from "@/composables/useDataGridColumnFilters";-import { useDataGridLargeValues } from "@/composables/useDataGridLargeValues";+import { useDataGridLargeValues, type LargeValueSnapshotDownloadTarget } from "@/composables/useDataGridLargeValues";import { useDataGridSaveConfirmation } from "@/composables/useDataGridSaveConfirmation";const SqlPreviewPanel = defineAsyncComponent(() => import("@/components/editor/SqlPreviewPanel.vue"));@@ -4463,6 +4464,9 @@ const editor = useDataGridEditor({cacheKey: computed(() => props.pendingStateKey ?? props.cacheKey),onResultPayloadMutated: () => queryStore.invalidateResultEstimateForPayload(props.result),refreshSavedRows,+ prepareSaveBaseline: async (changes) => {+ await largeValueRuntime?.prepareSaveBaseline(changes);+ },onCellValueChanged: (rowId, columnIndex) => largeValueRuntime?.invalidateVisibleLargeValuePreviewCell(rowId, columnIndex),prepareFullReload,emit,@@ -8809,6 +8813,7 @@ const {},),completeLocalResult: computed(() => (hasCompleteLocalResult.value ? props.result : undefined)),+ snapshotResult: computed(() => props.result),allExportResults: computed(() => props.allExportResults),currentResultLabel: computed(() => props.result.sourceLabel),exportFileBaseName: computed(() => props.exportFileBaseName),@@ -10767,10 +10772,23 @@ function downloadCellBinaryValue(rowIndex: number, columnIndex: number, mode: Bivoid downloadDetailBinaryValue(cellDetailFor(rowIndex, columnIndex), mode);}-async function downloadDetailBinaryValue(detail: DataGridCellDetail | null, mode: BinaryCellDownloadMode) {+async function downloadDetailBinaryValue(detail: DataGridCellDetail | null, mode: BinaryCellDownloadMode, snapshotTarget?: LargeValueSnapshotDownloadTarget) {+ if (snapshotTarget && !largeValueRuntimeInstance.isSnapshotDownloadTargetCurrent(snapshotTarget)) return;if (!detail || !canDownloadDetailBinaryValue(detail)) return;try {const sourceResult = props.result;+ if (snapshotTarget || largeValueRuntimeInstance.snapshotReference(getRowItem(detail.rowId), detail.colIndex)) {+ const target = snapshotTarget ?? largeValueRuntimeInstance.captureSnapshotDownloadTarget(detail.rowId, detail.colIndex);+ if (!target) throw new Error("LOB snapshot is unavailable");+ if (!largeValueRuntimeInstance.isSnapshotDownloadTargetCurrent(target)) return;+ const extension = mode === "binary" ? binaryCellDownloadPayload(detail.value, mode, detail.type, resolvedDatabaseType.value).extension : "txt";+ const fileName = binaryCellDownloadFileName({ column: detail.column, rowNumber: detail.rowNumber, mode, extension });+ const path = isTauriRuntime() ? await promptExportSavePath({ defaultFileName: fileName, filters: [{ name: "LOB", extensions: [extension] }] }) : fileName;+ if (!path || !largeValueRuntimeInstance.isSnapshotDownloadTargetCurrent(target)) return;+ await largeValueRuntimeInstance.downloadSnapshotTarget(target, path, mode);+ toast(isTauriRuntime() ? t("grid.downloadSaved", { path }) : t("grid.downloadStarted", { fileName }));+ return;+ }if (!(await hydrateLargeValueCell(detail.rowId, detail.colIndex))) return;if (props.result !== sourceResult) return;const resolvedDetail = cellDetailFor(displayRowIndexById(detail.rowId), detail.colIndex);@@ -10794,6 +10812,26 @@ async function downloadDetailBinaryValue(detail: DataGridCellDetail | null, mode}function binaryDownloadSubmenu(detail: DataGridCellDetail | null): ContextMenuItem | null {+ const sourceResult = props.result;+ const snapshotTarget = detail ? largeValueRuntimeInstance.captureSnapshotDownloadTarget(detail.rowId, detail.colIndex) : undefined;+ if (detail && largeValueRuntimeInstance.snapshotReference(getRowItem(detail.rowId), detail.colIndex) && !isBinaryCellColumnType(detail.type)) {+ return {+ label: t("grid.downloadSnapshotValue"),+ icon: Download,+ action: async () => {+ if (!snapshotTarget || !largeValueRuntimeInstance.isSnapshotDownloadTargetCurrent(snapshotTarget)) return;+ const defaultFileName = `lob-row-${detail.rowNumber}.txt`;+ const path = isTauriRuntime() ? await promptExportSavePath({ defaultFileName, filters: [{ name: "Text", extensions: ["txt"] }] }) : defaultFileName;+ if (!path || !largeValueRuntimeInstance.isSnapshotDownloadTargetCurrent(snapshotTarget)) return;+ try {+ await largeValueRuntimeInstance.downloadSnapshotTarget(snapshotTarget, path);+ toast(isTauriRuntime() ? t("grid.downloadSaved", { path }) : t("grid.downloadStarted", { fileName: defaultFileName }));+ } catch (error) {+ reportLargeValueLoadError(error);+ }+ },+ };+ }if (!canDownloadDetailBinaryValue(detail)) return null;return {label: t("grid.downloadBinaryValue"),@@ -10801,7 +10839,8 @@ function binaryDownloadSubmenu(detail: DataGridCellDetail | null): ContextMenuItchildren: BINARY_CELL_DOWNLOAD_MODES.map((mode) => ({label: t(`grid.binaryDownload.${mode}`),action: () => {- void downloadDetailBinaryValue(detail, mode);+ if (props.result !== sourceResult) return;+ return downloadDetailBinaryValue(detail, mode, snapshotTarget);},})),};diff --git a/apps/desktop/src/components/grid/__tests__/DataGridBinaryDownload.spec.ts b/apps/desktop/src/components/grid/__tests__/DataGridBinaryDownload.spec.tsindex 947ce00c29..028542d115 100644--- a/apps/desktop/src/components/grid/__tests__/DataGridBinaryDownload.spec.ts+++ b/apps/desktop/src/components/grid/__tests__/DataGridBinaryDownload.spec.ts@@ -7,8 +7,13 @@ import i18n from "@/i18n";import { TooltipProvider } from "@/components/ui/tooltip";import type { QueryResult } from "@/types/database";import type { DataGridCellDetail } from "@/lib/dataGrid/dataGridDetail";+import type { ContextMenuItem } from "@/components/ui/customContextMenuRegistry";-const mocks = vi.hoisted(() => ({ hydrate: vi.fn(), save: vi.fn() }));+const mocks = vi.hoisted(() => ({ hydrate: vi.fn(), save: vi.fn(), native: vi.fn(() => false), prompt: vi.fn(), download: vi.fn() }));++vi.mock("@/lib/backend/tauriRuntime", () => ({ isTauriRuntime: mocks.native }));+vi.mock("@/lib/export/exportPath", async (importOriginal) => ({ ...(await importOriginal<typeof import("@/lib/export/exportPath")>()), promptExportSavePath: mocks.prompt }));+vi.mock("@/lib/backend/api", async (importOriginal) => ({ ...(await importOriginal<typeof import("@/lib/backend/api")>()), downloadLargeValue: mocks.download }));vi.mock("@/composables/useDataGridLargeValues", async (importOriginal) => {const actual = await importOriginal<typeof import("@/composables/useDataGridLargeValues")>();@@ -88,6 +93,7 @@ async function mountGrid() {setupState: {cellDetailFor: (row: number, column: number) => DataGridCellDetail;downloadDetailBinaryValue: (detail: DataGridCellDetail, mode: "binary") => Promise<void>;+ binaryDownloadSubmenu: (detail: DataGridCellDetail) => ContextMenuItem;localColumnFilters: Record<number, Set<string>>;};}@@ -104,6 +110,114 @@ async function mountGrid() {}describe("DataGrid binary download identity", () => {+ it.each(["CLOB", "BLOB"])("does not download from a stale %s menu after the result is replaced", async (columnType) => {+ const { result, state } = await mountGrid();+ result.value = {+ ...result.value,+ column_types: ["NUMBER", columnType],+ rows: [[1, columnType === "BLOB" ? "0x11" : "old preview"]],+ large_value_context: { connectionId: "ob", database: "APP", clientSessionId: "original-session" },+ large_value_cells: [{ row_index: 0, column_index: 1, original_bytes: 5000, value_ref: "original-locator" }],+ };+ await nextTick();+ const menu = state.binaryDownloadSubmenu(state.cellDetailFor(0, 1));+ result.value = { ...result.value, rows: [[2, columnType === "BLOB" ? "0x22" : "new preview"]], large_value_cells: [{ row_index: 0, column_index: 1, original_bytes: 5000, value_ref: "replacement-locator" }] };+ await nextTick();+ mocks.native.mockReturnValue(true);+ mocks.prompt.mockResolvedValue("/tmp/snapshot.txt");+ mocks.download.mockResolvedValue(undefined);+ await (columnType === "BLOB" ? menu.children![0]!.action!() : menu.action!());+ expect(mocks.prompt).not.toHaveBeenCalled();+ expect(mocks.download).not.toHaveBeenCalled();+ });++ it.each(["CLOB", "BLOB"])("downloads the original locator from an unchanged %s menu", async (columnType) => {+ const { result, state } = await mountGrid();+ result.value = {+ ...result.value,+ column_types: ["NUMBER", columnType],+ rows: [[1, columnType === "BLOB" ? "0x11" : "preview"]],+ large_value_context: { connectionId: "ob", database: "APP", clientSessionId: "original-session" },+ large_value_cells: [{ row_index: 0, column_index: 1, original_bytes: 5000, value_ref: "original-locator" }],+ };+ await nextTick();+ const menu = state.binaryDownloadSubmenu(state.cellDetailFor(0, 1));+ mocks.native.mockReturnValue(true);+ mocks.prompt.mockResolvedValue("/tmp/snapshot.txt");+ mocks.download.mockResolvedValue(undefined);+ await (columnType === "BLOB" ? menu.children![0]!.action!() : menu.action!());+ expect(mocks.download).toHaveBeenCalledWith(expect.objectContaining({ valueRef: "original-locator", clientSessionId: "original-session", downloadEncoding: columnType === "BLOB" ? "binary" : undefined }), "/tmp/snapshot.txt", expect.any(AbortSignal));+ });++ it.each(["CLOB", "BLOB"])("rejects a %s menu when its session changes during the save dialog", async (columnType) => {+ const { result, state } = await mountGrid();+ result.value = {+ ...result.value,+ column_types: ["NUMBER", columnType],+ rows: [[1, columnType === "BLOB" ? "0x11" : "preview"]],+ large_value_context: { connectionId: "ob", database: "APP", clientSessionId: "original-session" },+ large_value_cells: [{ row_index: 0, column_index: 1, original_bytes: 5000, value_ref: "original-locator" }],+ };+ await nextTick();+ const menu = state.binaryDownloadSubmenu(state.cellDetailFor(0, 1));+ let finish!: (path: string) => void;+ mocks.native.mockReturnValue(true);+ mocks.prompt.mockImplementation(+ () =>+ new Promise<string>((resolve) => {+ finish = resolve;+ }),+ );+ const pending = columnType === "BLOB" ? menu.children![0]!.action!() : menu.action!();+ result.value.large_value_context!.clientSessionId = "replacement-session";+ finish("/tmp/snapshot.txt");+ await pending;+ expect(mocks.download).not.toHaveBeenCalled();+ });++ it.each(["CLOB", "BLOB"])("keeps save-dialog cancellation for %s snapshot downloads", async (columnType) => {+ const { result, state } = await mountGrid();+ result.value = {+ ...result.value,+ column_types: ["NUMBER", columnType],+ rows: [[1, columnType === "BLOB" ? "0x11" : "preview"]],+ large_value_context: { connectionId: "ob", database: "APP" },+ large_value_cells: [{ row_index: 0, column_index: 1, original_bytes: 5000, value_ref: "original-locator" }],+ };+ await nextTick();+ const menu = state.binaryDownloadSubmenu(state.cellDetailFor(0, 1));+ mocks.native.mockReturnValue(true);+ mocks.prompt.mockResolvedValue(null);+ await (columnType === "BLOB" ? menu.children![0]!.action!() : menu.action!());+ expect(mocks.download).not.toHaveBeenCalled();+ });++ it("does not download a replacement CLOB result after the save dialog returns", async () => {+ const { result, state } = await mountGrid();+ result.value = {+ ...result.value,+ column_types: ["NUMBER", "CLOB"],+ rows: [[1, "preview"]],+ large_value_context: { connectionId: "ob", database: "APP", clientSessionId: "original-session" },+ large_value_cells: [{ row_index: 0, column_index: 1, value_ref: "original-locator", value_kind: "text" }],+ };+ await nextTick();+ let finish!: (path: string) => void;+ mocks.prompt.mockImplementation(+ () =>+ new Promise<string>((resolve) => {+ finish = resolve;+ }),+ );+ mocks.native.mockReturnValue(true);+ const pending = state.binaryDownloadSubmenu(state.cellDetailFor(0, 1)).action!();+ expect(mocks.prompt).toHaveBeenCalledOnce();+ result.value = { ...result.value, rows: [[2, "new preview"]], large_value_cells: [{ row_index: 0, column_index: 1, value_ref: "replacement-locator", value_kind: "text" }] };+ await nextTick();+ finish("C:/Temp/snapshot.txt");+ await pending;+ expect(mocks.download).not.toHaveBeenCalled();+ });it("downloads the selected record when local filtering changes the display position during hydration", async () => {const { result, state, finish } = await mountGrid();const detail = state.cellDetailFor(1, 1);diff --git a/apps/desktop/src/composables/__tests__/useDataGridEditor.spec.ts b/apps/desktop/src/composables/__tests__/useDataGridEditor.spec.tsindex b95cee729a..0a84e6c349 100644--- a/apps/desktop/src/composables/__tests__/useDataGridEditor.spec.ts+++ b/apps/desktop/src/composables/__tests__/useDataGridEditor.spec.ts@@ -1338,6 +1338,7 @@ describe("useDataGridEditor saveChanges reload", () => {databaseType?: import("@/types/database").DatabaseType;primaryKeys?: string[];onExecuteSql?: (sql: string) => Promise<void>;+ prepareSaveBaseline?: import("@/composables/useDataGridEditor").UseDataGridEditorOptions["prepareSaveBaseline"];} = {},) {const emit = vi.fn();@@ -1386,11 +1387,81 @@ describe("useDataGridEditor saveChanges reload", () => {getRowItem: () => undefined,prepareFullReload: options.prepareFullReload,refreshSavedRows: options.refreshSavedRows,+ prepareSaveBaseline: options.prepareSaveBaseline,emit,});return { editor, emit, currentPage, ensureManualTransactionSession };}+ it.each(["batch", "transaction", "manual"] as const)("passes reviewed BLOB bindings through the %s save entrypoint", async (route) => {+ const statements = route === "transaction" ? ["reviewed BLOB save", "ordinary update"] : ["reviewed BLOB save"];+ const boundStatements = statements.map((previewSql, index) => ({ previewSql, sql: index === 0 ? "UPDATE t SET b=?" : previewSql, blobParameters: index === 0 ? ["00ff80"] : [] }));+ mocks.prepareDataGridSave.mockResolvedValue({ statements, boundStatements, rollbackStatements: [] });+ mocks.executeBatch.mockResolvedValue({ affected_rows: 1 });+ mocks.executeInTransaction.mockResolvedValue({ affected_rows: 2 });+ mocks.executeInManualTransaction.mockResolvedValue([{ affected_rows: 1 }]);+ const { editor } = createSaveTestEditor({ databaseType: "oceanbase-oracle", manualTransactionSessionId: route === "manual" ? "session-1" : undefined });+ editor.dirtyRows.value.set(0, new Map([[1, "changed"]]));+ await editor.saveChanges();+ const call = route === "manual" ? mocks.executeInManualTransaction.mock.calls[0] : route === "transaction" ? mocks.executeInTransaction.mock.calls[0] : mocks.executeBatch.mock.calls[0];+ expect(call?.[route === "manual" ? 11 : route === "transaction" ? 5 : 6]).toEqual(boundStatements);+ expect(editor.saveError.value).toBe("");+ });++ it("keeps joined ordinary and BLOB statements aligned in their original execution order", async () => {+ const targets = [+ { tableMeta: { tableName: "users", primaryKeys: ["id"], columns: [] }, sourceColumns: ["id", "name", undefined, undefined] },+ { tableMeta: { tableName: "papers", primaryKeys: ["id"], columns: [] }, sourceColumns: [undefined, undefined, "id", "title"] },+ ];+ mocks.prepareDataGridSave.mockImplementation(async (options) =>+ options.tableMeta.tableName === "users" ? { statements: ["ordinary update"], rollbackStatements: [] } : { statements: ["reviewed BLOB save"], rollbackStatements: [], boundStatements: [{ previewSql: "reviewed BLOB save", sql: "UPDATE papers SET b=?", blobParameters: ["00ff80"] }] },+ );+ mocks.executeInTransaction.mockResolvedValue({ affected_rows: 2 });+ const { editor } = createSaveTestEditor({ databaseType: "oceanbase-oracle", joinedWriteTargets: targets, queryResult: { columns: ["id", "name", "paper_id", "title"], rows: [[1, "old", 20, "old"]] } });+ editor.dirtyRows.value.set(+ 0,+ new Map([+ [1, "new name"],+ [3, "new title"],+ ]),+ );+ await editor.saveChanges();+ expect(mocks.executeInTransaction.mock.calls[0]?.[2]).toEqual(["ordinary update", "reviewed BLOB save"]);+ expect(mocks.executeInTransaction.mock.calls[0]?.[5]).toEqual([+ { previewSql: "ordinary update", sql: "ordinary update", blobParameters: [] },+ { previewSql: "reviewed BLOB save", sql: "UPDATE papers SET b=?", blobParameters: ["00ff80"] },+ ]);+ });++ it("loads complete original baselines before generating forward and rollback SQL", async () => {+ const source = { columns: ["id", "status"], rows: [[1, "LOB preview"]] as CellValue[][] };+ const prepareSaveBaseline = vi.fn(async (changes: Parameters<NonNullable<import("@/composables/useDataGridEditor").UseDataGridEditorOptions["prepareSaveBaseline"]>>[0]) => {+ expect(changes.dirtyRows.get(0).get(1)).toBeNull();+ source.rows[0]![1] = "complete original LOB";+ });+ mocks.prepareDataGridSave.mockImplementation(async (options) => {+ expect(options.rows[0][1]).toBe("complete original LOB");+ expect(options.dirtyRows).toEqual([[0, [[1, null]]]]);+ return { statements: ["UPDATE orders_test SET status=NULL WHERE id=1"], rollbackStatements: ["UPDATE orders_test SET status='complete original LOB' WHERE id=1"] };+ });+ const { editor } = createSaveTestEditor({ queryResult: source, prepareSaveBaseline });+ editor.dirtyRows.value.set(0, new Map([[1, null]]));+ await expect(editor.previewChanges()).resolves.toEqual(["UPDATE orders_test SET status=NULL WHERE id=1"]);+ expect(prepareSaveBaseline).toHaveBeenCalledOnce();+ });++ it("blocks writes and keeps pending changes when the original LOB baseline expired", async () => {+ const { editor } = createSaveTestEditor({ prepareSaveBaseline: vi.fn().mockRejectedValue(new Error("LOB snapshot expired")) });+ editor.dirtyRows.value.set(0, new Map([[1, null]]));+ await editor.saveChanges();+ expect(mocks.prepareDataGridSave).not.toHaveBeenCalled();+ expect(mocks.executeBatch).not.toHaveBeenCalled();+ expect(mocks.executeInTransaction).not.toHaveBeenCalled();+ expect(mocks.executeInManualTransaction).not.toHaveBeenCalled();+ expect(editor.dirtyRows.value.get(0)!.get(1)).toBeNull();+ expect(editor.saveError.value).toContain("LOB snapshot expired");+ });+// https://github.com/t8y2/dbx/issues/8321: without a primary key the row is// addressed by matching every column value, and the loaded page cannot show// whether another physical row matches the same condition.diff --git a/apps/desktop/src/composables/__tests__/useDataGridExport.spec.ts b/apps/desktop/src/composables/__tests__/useDataGridExport.spec.tsindex 922df3148b..572ecb3693 100644--- a/apps/desktop/src/composables/__tests__/useDataGridExport.spec.ts+++ b/apps/desktop/src/composables/__tests__/useDataGridExport.spec.ts@@ -1,14 +1,14 @@-import { computed, ref } from "vue";+import { computed, effectScope, ref } from "vue";import { createPinia, setActivePinia } from "pinia";import { beforeEach, describe, expect, it, vi } from "vitest";import { useDataGridExport, type UseDataGridExportOptions } from "@/composables/useDataGridExport";-import type { DatabaseType } from "@/types/database";+import type { DatabaseType, QueryResult } from "@/types/database";import { buildDataGridCopyUpdateStatements } from "@/lib/dataGrid/dataGridSql";import { copyToClipboard } from "@/lib/common/clipboard";import type { DataGridTableMeta } from "@/lib/dataGrid/dataGridSql";import type { CellSelectionMatrix, SelectionData } from "@/lib/dataGrid/gridSelection";import type { CellValue } from "@/lib/dataGrid/cellValue";-import { extractDataGridSelection, exportQueryResultCsv, exportQueryResultJson } from "@/lib/backend/api";+import { cancelQuery, extractDataGridSelection, exportQueryResultCsv, exportQueryResultJson, exportQueryResultMarkdown, exportQueryResultXlsx, exportSnapshotResult, readLargeValueChunk } from "@/lib/backend/api";import { DEFAULT_DATA_GRID_EXTRACTOR_OPTIONS } from "@/lib/dataGrid/dataGridCopyExtractor";import { clearDataGridClipboardCopy, parseDataGridClipboard } from "@/lib/dataGrid/dataGridClipboard";import { MONGO_DOCUMENT_GRID_NULL, mongoDocumentGridExternalValue } from "@/lib/mongo/mongoDocumentValues";@@ -52,6 +52,11 @@ vi.mock("@/lib/backend/api", async (importOriginal) => {extractDataGridSelection: vi.fn(),exportQueryResultCsv: vi.fn(),exportQueryResultJson: vi.fn(),+ exportQueryResultMarkdown: vi.fn(),+ exportQueryResultXlsx: vi.fn(),+ exportSnapshotResult: vi.fn(),+ readLargeValueChunk: vi.fn(),+ cancelQuery: vi.fn(),};});@@ -143,6 +148,7 @@ function createExportState(contextColumn?: number,databaseType: DatabaseType = "mysql",displayValue?: (value: CellValue, columnIndex: number) => string,+ overrides: Partial<UseDataGridExportOptions> = {},) {const rows = (rowDataList ?? [rowData ?? columns.map((column, index) => (column === "id" ? 1 : `value-${index}`))]).map((data, index) => ({ ...row(data), id: index + 1 }));const resolvedContextRowId = contextRowId === undefined ? (rows[0]?.id ?? null) : contextRowId;@@ -175,9 +181,187 @@ function createExportState(selectedRowIds,hasRowSelection: computed(() => selectedRowIds.value.size > 0),};- return useDataGridExport(options);+ return { ...useDataGridExport({ ...options, ...overrides }), contextCell: options.contextCell };}+describe("original LOB result exports", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ setActivePinia(createPinia());+ vi.mocked(exportSnapshotResult).mockResolvedValue(undefined);+ });+ function snapshotState() {+ const original = {+ columns: ["id", "name"],+ rows: [[1, "preview"]],+ column_types: ["NUMBER", "CLOB"],+ large_value_context: { connectionId: "original-connection", database: "original-database", clientSessionId: "original-session" },+ large_value_cells: [{ row_index: 0, column_index: 1, value_ref: "original-locator", value_kind: "text" }],+ } as QueryResult;+ return {+ original,+ state: createExportState(editableTable, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, "oracle", undefined, {+ snapshotResult: computed(() => original),+ hasCompleteLocalResult: computed(() => true),+ completeLocalResult: computed(() => original),+ }),+ };+ }+ it.each(["csv", "json"] as const)("streams export-all %s from captured locators without frontend hydration or requery", async (format) => {+ const { state } = snapshotState();+ await (format === "csv" ? state.exportCsv() : state.exportJson());+ expect(exportSnapshotResult).toHaveBeenCalledWith(+ expect.objectContaining({+ format,+ context: expect.objectContaining({ connectionId: "original-connection", clientSessionId: "original-session" }),+ cells: [{ rowIndex: 0, columnIndex: 1, valueRef: "original-locator" }],+ }),+ expect.any(String),+ expect.any(AbortSignal),+ );+ expect(readLargeValueChunk).not.toHaveBeenCalled();+ expect(exportQueryResultCsv).not.toHaveBeenCalled();+ expect(exportQueryResultJson).not.toHaveBeenCalled();+ });+ it.each(["csv", "json"] as const)("preserves hidden-key filtering and the row limit for snapshot %s", async (format) => {+ const { state, original } = snapshotState();+ original.columns.push("__DBX_PK_0");+ original.rows = [+ [1, "preview", "rowid-1"],+ [2, "second preview", "rowid-2"],+ ];+ original.hidden_column_indexes = [2];+ original.large_value_cells!.push({ row_index: 1, column_index: 1, value_ref: "second-locator", value_kind: "text" });+ useSettingsStore().editorSettings.exportRowLimitEnabled = true;+ useSettingsStore().editorSettings.exportRowLimit = 1;+ await (format === "csv" ? state.exportCsv() : state.exportJson());+ expect(vi.mocked(exportSnapshotResult).mock.calls[0]?.[0]).toEqual(+ expect.objectContaining({+ columns: ["id", "name"],+ rows: [[1, "preview"]],+ cells: [{ rowIndex: 0, columnIndex: 1, valueRef: "original-locator" }],+ }),+ );+ });+ it("settles snapshot export on scope disposal even when backend cancellation fails", async () => {+ const scope = effectScope();+ const { state } = scope.run(snapshotState)!;+ vi.mocked(exportSnapshotResult).mockImplementation(() => new Promise(() => {}));+ vi.mocked(cancelQuery).mockRejectedValueOnce(new Error("backend unavailable"));+ let settled = false;+ const pending = state.exportJson().finally(() => {+ settled = true;+ });+ try {+ await vi.waitFor(() => expect(exportSnapshotResult).toHaveBeenCalledOnce());+ scope.stop();+ await vi.waitFor(() => expect(settled).toBe(true));+ await pending;+ expect(vi.mocked(exportSnapshotResult).mock.calls[0]?.[2]?.aborted).toBe(true);+ expect(cancelQuery).toHaveBeenCalledOnce();+ expect(exportQueryResultJson).not.toHaveBeenCalled();+ } finally {+ scope.stop();+ }+ });+ it("does not publish a legacy preview export when the snapshot backend fails", async () => {+ const { state, original } = snapshotState();+ vi.mocked(exportSnapshotResult).mockRejectedValue(new Error("LOB snapshot expired"));+ await state.exportJson();+ expect(exportQueryResultJson).not.toHaveBeenCalled();+ expect(original.rows[0]![1]).toBe("preview");+ expect(toast).toHaveBeenCalledWith(expect.stringContaining("LOB snapshot expired"), 5000);+ });+ it.each(["unselected column", "hidden column", "row beyond limit"])("does not read an expired LOB in an %s during bounded export", async (excluded) => {+ const { original } = snapshotState();+ if (excluded === "hidden column") original.hidden_column_indexes = [1];+ if (excluded === "row beyond limit") {+ original.rows = [+ [1, "plain text"],+ [2, "preview"],+ ];+ original.large_value_cells![0]!.row_index = 1;+ useSettingsStore().editorSettings.exportRowLimitEnabled = true;+ useSettingsStore().editorSettings.exportRowLimit = 1;+ }+ const state = createExportState(editableTable, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, "oracle", undefined, {+ context: computed(() => "results"),+ snapshotResult: computed(() => original),+ hasCompleteLocalResult: computed(() => true),+ completeLocalResult: computed(() => original),+ });+ vi.mocked(readLargeValueChunk).mockRejectedValue(new Error("excluded LOB expired"));+ await state.exportMarkdown(excluded === "unselected column" ? { columnIndexes: [0] } : undefined);+ expect(exportQueryResultMarkdown).toHaveBeenCalledWith(expect.any(String), excluded === "row beyond limit" ? ["id", "name"] : ["id"], excluded === "row beyond limit" ? [[1, "plain text"]] : [[1]]);+ expect(readLargeValueChunk).not.toHaveBeenCalled();+ });+ it("fails bounded export when the selected LOB snapshot has expired", async () => {+ const { original } = snapshotState();+ const state = createExportState(editableTable, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, "oracle", undefined, {+ context: computed(() => "results"),+ snapshotResult: computed(() => original),+ hasCompleteLocalResult: computed(() => true),+ completeLocalResult: computed(() => original),+ });+ vi.mocked(readLargeValueChunk).mockRejectedValue(new Error("selected LOB expired"));+ await state.exportMarkdown({ columnIndexes: [1] });+ expect(readLargeValueChunk).toHaveBeenCalledWith(expect.objectContaining({ valueRef: "original-locator" }));+ expect(exportQueryResultMarkdown).not.toHaveBeenCalled();+ expect(toast).toHaveBeenCalledWith(expect.stringContaining("selected LOB expired"), 5000);+ });+ it.each(["replacement", "disposal"])("settles pending XLSX snapshot reads on %s even if server cancellation fails", async (change) => {+ const scope = effectScope();+ const { original } = snapshotState();+ const current = ref(original);+ const state = scope.run(() =>+ createExportState(editableTable, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, "oracle", undefined, {+ context: computed(() => "results"),+ snapshotResult: computed(() => current.value),+ hasCompleteLocalResult: computed(() => true),+ completeLocalResult: computed(() => current.value),+ }),+ )!;+ let deliver!: (chunk: Awaited<ReturnType<typeof readLargeValueChunk>>) => void;+ vi.mocked(readLargeValueChunk).mockImplementation(+ () =>+ new Promise((resolve) => {+ deliver = resolve;+ }),+ );+ vi.mocked(cancelQuery).mockRejectedValueOnce(new Error("cancel unavailable"));+ let settled = false;+ const pending = state.exportXlsx().finally(() => {+ settled = true;+ });+ try {+ await vi.waitFor(() => expect(readLargeValueChunk).toHaveBeenCalledOnce());+ if (change === "replacement") current.value = { ...original, rows: [[2, "new result"]] };+ else scope.stop();+ await vi.waitFor(() => expect(settled).toBe(true));+ expect(cancelQuery).toHaveBeenCalledWith(expect.any(String));+ expect(vi.mocked(readLargeValueChunk).mock.calls[0]?.[0].executionId).toBe(vi.mocked(cancelQuery).mock.calls[0]?.[0]);+ } finally {+ deliver({ status: "ok", data: "late", next_offset: 4, eof: true, value_kind: "text" });+ await pending;+ scope.stop();+ }+ expect(exportQueryResultXlsx).not.toHaveBeenCalled();+ });+ it("materializes export-all for bounded formats rather than passing preview rows", async () => {+ const { original } = snapshotState();+ const localState = createExportState(editableTable, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, "oracle", undefined, {+ context: computed(() => "results"),+ snapshotResult: computed(() => original),+ hasCompleteLocalResult: computed(() => true),+ completeLocalResult: computed(() => original),+ });+ vi.mocked(readLargeValueChunk).mockResolvedValue({ status: "ok", data: "complete original text", next_offset: 22, eof: true, value_kind: "text" });+ await localState.exportMarkdown();+ expect(exportQueryResultMarkdown).toHaveBeenCalledWith(expect.any(String), original.columns, [[1, "complete original text"]]);+ expect(original.rows[0]![1]).toBe("preview");+ });+});+const editableTable: DataGridTableMeta = {tableName: "users",primaryKeys: ["id"],@@ -194,6 +378,19 @@ describe("useDataGridExport prepared row statements", () => {vi.mocked(saveTextFile).mockResolvedValue(true);});+ it.each(["closed", "retargeted"] as const)("copies the clicked cell when the context menu is %s before its async callback finishes", async (menuState) => {+ const state = createExportState(editableTable, ["id", "name"], undefined, [1, "clicked cell"]);+ state.contextCell.value = { rowId: 1, rowIndex: 0, col: 1 };++ const pendingCopy = state.copyCell();+ // The menu starts the action, then clears or replaces its target on close.+ state.contextCell.value = menuState === "closed" ? null : { rowId: 1, rowIndex: 0, col: 0 };++ await expect(pendingCopy).resolves.toBeUndefined();+ expect(copyToClipboard).toHaveBeenCalledWith("clicked cell");+ expect(parseDataGridClipboard("clicked cell")).toEqual([["clicked cell"]]);+ });+it("disables row copy when the result has no rows", () => {const state = createExportState(editableTable, ["id", "name"], undefined, undefined, undefined, [], [], DEFAULT_DATA_GRID_EXTRACTOR_OPTIONS, false, undefined, false, null);@@ -1287,7 +1484,7 @@ describe("useDataGridExport prepared row statements", () => {const request = vi.mocked(extractDataGridSelection).mock.calls[0]?.[0];expect(request).toEqual(expect.objectContaining({- columns: [{ displayName: "name", sourceName: "name", sourceIndex: 0 }],+ columns: [{ displayName: "name", sourceName: "name", sourceIndex: 0, dataType: "varchar" }],selectedColumnIndexes: [0],rows: [["Ada"]],selectionKind: "columns",diff --git a/apps/desktop/src/composables/__tests__/useDataGridExtractor.includeDatabaseName.spec.ts b/apps/desktop/src/composables/__tests__/useDataGridExtractor.includeDatabaseName.spec.tsindex b984e25219..b9322c2d6b 100644--- a/apps/desktop/src/composables/__tests__/useDataGridExtractor.includeDatabaseName.spec.ts+++ b/apps/desktop/src/composables/__tests__/useDataGridExtractor.includeDatabaseName.spec.ts@@ -10,16 +10,19 @@ vi.mock("@/lib/backend/api", () => ({ extractDataGridSelection: mocks.extract })vi.mock("@/composables/useToast", () => ({ useToast: () => ({ toast: vi.fn() }) }));vi.mock("vue-i18n", () => ({ useI18n: () => ({ t: (key: string) => key }) }));-function createState(databaseType: DatabaseType, tableMeta: DataGridTableMeta, extractorOptions?: DataGridExtractorOptions, includeDatabaseName = false) {- const items = [{ id: 1, data: [1, "Ada"], isDraft: false }];+function createState(databaseType: DatabaseType, tableMeta: DataGridTableMeta | undefined, extractorOptions?: DataGridExtractorOptions, includeDatabaseName = false, query?: { columns: string[]; values: unknown[]; visible: number[]; types: string[]; omitFullTypes?: boolean }) {+ const allColumns = query?.columns ?? ["id", "name"];+ const visible = query?.visible ?? [0, 1];+ const items = [{ id: 1, data: query?.values ?? [1, "Ada"], isDraft: false }];return useDataGridExtractor({- columns: computed(() => ["id", "name"]),- allColumns: computed(() => ["id", "name"]),+ columns: computed(() => visible.map((index) => allColumns[index]!)),+ allColumns: computed(() => allColumns),displayItems: computed(() => items),allDisplayItems: computed(() => items),allSourceColumns: computed(() => undefined),- visibleColumnIndexes: computed(() => [0, 1]),- columnTypes: computed(() => undefined),+ visibleColumnIndexes: computed(() => visible),+ columnTypes: computed(() => query && visible.map((index) => query.types[index])),+ allColumnTypes: query?.omitFullTypes ? undefined : computed(() => query?.types),extractorOptions: computed(() => extractorOptions ?? DEFAULT_DATA_GRID_EXTRACTOR_OPTIONS),databaseType: computed(() => databaseType),identifierQuote: computed(() => undefined),@@ -86,4 +89,42 @@ describe("useDataGridExtractor includeDatabaseName payload", () => {expect(request.tableMeta.database).toBe("mydb");expect(request.options.sql.includeDatabaseName).toBe(true);});++ it("passes real query types for reordered and hidden row columns without table metadata", async () => {+ const values = ["2026-10-10 13:14:15", "2026-10-10 13:14:15.123456", "2026-10-10 13:14:15.123456 -5:30", null];+ const state = createState("oceanbase-oracle", undefined, undefined, false, {+ columns: ["D", "T", "Z", "N"],+ values,+ visible: [2, 0],+ types: ["DATE", "TIMESTAMP", "TIMESTAMP WITH TIME ZONE", "VARCHAR2"],+ });+ expect(await state.extractWithExtractor("sql-inserts")).not.toBeNull();+ const request = mocks.extract.mock.calls.at(-1)![0];+ expect(request.tableMeta).toBeUndefined();+ expect(request.columns.map((column: { sourceName: string; dataType: string }) => [column.sourceName, column.dataType])).toEqual([+ ["Z", "TIMESTAMP WITH TIME ZONE"],+ ["D", "DATE"],+ ]);+ expect(request.rows).toEqual([[values[2], values[0]]]);+ expect(await state.extractWithExtractor("sql-select")).not.toBeNull();+ const fullRequest = mocks.extract.mock.calls.at(-1)![0];+ expect(fullRequest.columns.map((column: { dataType: string }) => column.dataType)).toEqual(["DATE", "TIMESTAMP", "TIMESTAMP WITH TIME ZONE", "VARCHAR2"]);+ expect(fullRequest.rows).toEqual([values]);+ });++ it("keeps reordered visible types aligned when a legacy caller has no full types", async () => {+ const state = createState("oracle", undefined, undefined, false, {+ columns: ["D", "T"],+ values: ["2026-10-10 13:14:15", "2026-10-10 13:14:15.123456"],+ visible: [1, 0],+ types: ["DATE", "TIMESTAMP"],+ omitFullTypes: true,+ });+ expect(await state.extractWithExtractor("sql-inserts")).not.toBeNull();+ const request = mocks.extract.mock.calls.at(-1)![0];+ expect(request.columns.map((column: { sourceName: string; dataType: string }) => [column.sourceName, column.dataType])).toEqual([+ ["T", "TIMESTAMP"],+ ["D", "DATE"],+ ]);+ });});diff --git a/apps/desktop/src/composables/__tests__/useDataGridLargeValues.spec.ts b/apps/desktop/src/composables/__tests__/useDataGridLargeValues.spec.tsindex 7d6e32a1af..644a995ba5 100644--- a/apps/desktop/src/composables/__tests__/useDataGridLargeValues.spec.ts+++ b/apps/desktop/src/composables/__tests__/useDataGridLargeValues.spec.ts@@ -1,9 +1,11 @@// @vitest-environment happy-dom-import { computed, createApp, defineComponent, h, ref, type Ref } from "vue";+import { computed, createApp, defineComponent, h, nextTick, ref, type Ref } from "vue";import { afterEach, describe, expect, it, vi } from "vitest";import { binaryCellDisplayText, binaryCellDownloadPayload } from "@/lib/dataGrid/binaryCellDownload";import { useDataGridLargeValues } from "@/composables/useDataGridLargeValues";+import { useDataGridEditor } from "@/composables/useDataGridEditor";+import { createDataGridRuntimeScope } from "@/lib/dataGrid/dataGridRuntime";import type { DatabaseType, QueryResult } from "@/types/database";const mocks = vi.hoisted(() => ({@@ -11,15 +13,27 @@ const mocks = vi.hoisted(() => ({buildTableSelectSql: vi.fn(),cancelQuery: vi.fn(),executeMulti: vi.fn(),+ readLargeValueChunk: vi.fn(),+ downloadLargeValue: vi.fn(),+ prepareDataGridSave: vi.fn(),+ executeBatch: vi.fn(),}));vi.mock("@/lib/backend/api", () => ({buildDataGridContextFilterCondition: mocks.buildDataGridContextFilterCondition,cancelQuery: mocks.cancelQuery,executeMulti: mocks.executeMulti,+ readLargeValueChunk: mocks.readLargeValueChunk,+ downloadLargeValue: mocks.downloadLargeValue,+ prepareDataGridSave: mocks.prepareDataGridSave,+ executeBatch: mocks.executeBatch,+ connectionWriteUnlockState: vi.fn().mockResolvedValue(0),}));vi.mock("@/lib/table/tableSelectSql", () => ({ buildTableSelectSql: mocks.buildTableSelectSql }));+vi.mock("@/stores/connectionStore", () => ({ useConnectionStore: () => ({ getConfig: () => undefined }) }));+vi.mock("@/stores/historyStore", () => ({ useHistoryStore: () => ({ add: vi.fn() }) }));+vi.mock("@/stores/productionSafetyStore", () => ({ useProductionSafetyStore: () => ({}) }));const disposers: Array<() => void> = [];@@ -28,11 +42,13 @@ afterEach(() => {vi.resetAllMocks();});-function mountLargeValues(databaseType: DatabaseType, result: Ref<QueryResult>) {+function mountLargeValues(databaseType: DatabaseType, result: Ref<QueryResult>, withEditor = false) {+ const runtimeScope = createDataGridRuntimeScope();const toast = vi.fn();const formatCell = (value: unknown, columnIndex?: number, originalBytes?: number) => binaryCellDisplayText(value, result.value.column_types?.[columnIndex ?? 0], originalBytes, databaseType) ?? String(value ?? "");const item = (rowId = 1) => ({ id: rowId, sourceIndex: rowId - 1, data: result.value.rows[rowId - 1]!, isNew: false, isDeleted: false, isDirtyCol: [false, false] });let largeValues: ReturnType<typeof useDataGridLargeValues> | undefined;+ let editor: ReturnType<typeof useDataGridEditor> | undefined;const app = createApp(defineComponent({setup() {@@ -68,7 +84,7 @@ function mountLargeValues(databaseType: DatabaseType, result: Ref<QueryResult>)globalQueryTimeoutSecs: computed(() => 30),resultLifecycle: { beginOperation: () => 1, isCurrent: () => true },largeValueResolutionVersion: ref(0),- runtimeScope: { disposed: false, addCleanup: () => () => undefined, dispose: () => undefined },+ runtimeScope,uuid: () => "execution-1",translate: (key) => key,translateBackendError: (error) => String(error),@@ -77,14 +93,46 @@ function mountLargeValues(databaseType: DatabaseType, result: Ref<QueryResult>)cloneRow: vi.fn(),cloneRows: vi.fn(),});+ if (withEditor)+ editor = useDataGridEditor({+ result: computed(() => result.value),+ editable: computed(() => true),+ databaseType: computed(() => databaseType),+ connectionId: computed(() => `${databaseType}-1`),+ database: computed(() => "MAXIMO"),+ tableMeta: computed(() => ({+ schema: "public",+ tableName: "APP_DATA",+ columns: result.value.columns.map((name, index) => ({ name, data_type: index === 0 ? "NUMBER" : "CLOB" })),+ primaryKeys: ["ID"],+ })),+ sourceColumns: computed(() => result.value.columns),+ onExecuteSql: computed(() => undefined),+ sql: computed(() => undefined),+ searchText: ref(""),+ dataGridQuickEntryEnabled: computed(() => false),+ whereFilterInput: ref(""),+ currentWhereInput: computed(() => undefined),+ orderByInput: ref(""),+ rowStatusFilter: ref("all"),+ confirmDangerousRowDeletion: computed(() => false),+ pageSize: ref(100),+ currentPage: ref(1),+ getRowItem: (rowId) => ({ id: rowId, sourceIndex: rowId, data: result.value.rows[rowId]!, isNew: false, isDeleted: false, isDirtyCol: [false, false], status: "normal" }),+ prepareSaveBaseline: (changes) => largeValues!.prepareSaveBaseline(changes),+ emit: vi.fn(),+ });return () => h("div");},}),);app.mount(document.createElement("div"));- disposers.push(() => app.unmount());+ disposers.push(() => {+ runtimeScope.dispose();+ app.unmount();+ });if (!largeValues) throw new Error("useDataGridLargeValues was not mounted");- return { largeValues, toast, item };+ return { largeValues, toast, item, editor, runtimeScope };}function previewResult(columnType = "bytea", value = "\\x00017f80ff...", originalBytes = 9645) {@@ -99,6 +147,280 @@ function previewResult(columnType = "bytea", value = "\\x00017f80ff...", origina}describe("useDataGridLargeValues", () => {+ it.each(["result", "locator", "clientSessionId", "txnSessionId", "catalog", "disposal"] as const)("rejects a captured download target after its %s changes", async (change) => {+ const result = previewResult("CLOB", "preview", 5000);+ result.value.large_value_context = { connectionId: "oceanbase-oracle-1", database: "MAXIMO", clientSessionId: "original-session" };+ result.value.large_value_cells![0]!.value_ref = "original-locator";+ const { largeValues, runtimeScope } = mountLargeValues("oceanbase-oracle", result);+ const target = largeValues.captureSnapshotDownloadTarget(1, 1)!;+ expect(largeValues.isSnapshotDownloadTargetCurrent(target)).toBe(true);+ if (change === "result") result.value = { ...result.value, rows: [[2, "new preview"]] };+ else if (change === "locator") result.value.large_value_cells![0]!.value_ref = "replacement-locator";+ else if (change === "disposal") runtimeScope.dispose();+ else result.value.large_value_context![change] = "replacement-context";+ expect(largeValues.isSnapshotDownloadTargetCurrent(target)).toBe(false);+ await expect(largeValues.downloadSnapshotTarget(target, "lob.txt")).rejects.toThrow("context changed");+ expect(mocks.downloadLargeValue).not.toHaveBeenCalled();+ expect(target.context.clientSessionId).toBe("original-session");+ expect(target.valueRef).toBe("original-locator");+ });++ it.each([undefined, "binary", "utf8", "gbk"] as const)("downloads a captured original target with %s encoding", async (encoding) => {+ const result = previewResult("BLOB", "0x11", 5000);+ result.value.large_value_context = { connectionId: "oceanbase-oracle-1", database: "MAXIMO", txnSessionId: "original-transaction" };+ result.value.large_value_cells![0]!.value_ref = "original-locator";+ const { largeValues } = mountLargeValues("oceanbase-oracle", result);+ mocks.downloadLargeValue.mockResolvedValue(undefined);+ const target = largeValues.captureSnapshotDownloadTarget(1, 1)!;+ await largeValues.downloadSnapshotTarget(target, "lob.bin", encoding);+ expect(mocks.downloadLargeValue).toHaveBeenCalledWith(expect.objectContaining({ valueRef: "original-locator", txnSessionId: "original-transaction", downloadEncoding: encoding }), "lob.bin", target.signal);+ });++ it("cancels a captured target's pending download on cleanup", async () => {+ const result = previewResult("CLOB", "preview", 5000);+ result.value.large_value_context = { connectionId: "oceanbase-oracle-1", database: "MAXIMO" };+ result.value.large_value_cells![0]!.value_ref = "original-locator";+ const { largeValues, runtimeScope } = mountLargeValues("oceanbase-oracle", result);+ mocks.downloadLargeValue.mockImplementation(() => new Promise(() => {}));+ mocks.cancelQuery.mockRejectedValue(new Error("cancel failed"));+ const target = largeValues.captureSnapshotDownloadTarget(1, 1)!;+ const pending = largeValues.downloadSnapshotTarget(target, "lob.txt");+ runtimeScope.dispose();+ await expect(pending).rejects.toThrow("cancelled locally");+ expect(target.signal.aborted).toBe(true);+ expect(mocks.cancelQuery).toHaveBeenCalledWith("execution-1");+ });++ it("retains a hydrated locator for release even when the result has no ref array", async () => {+ const result = previewResult("CLOB", "preview", 5000);+ result.value.large_value_context = { connectionId: "oceanbase-oracle-1", database: "MAXIMO" };+ result.value.large_value_cells![0]!.value_ref = "old-page-locator";+ mocks.readLargeValueChunk.mockResolvedValue({ status: "ok", data: "complete", next_offset: 8, eof: true, value_kind: "text" });+ const { largeValues } = mountLargeValues("oceanbase-oracle", result);+ expect(await largeValues.hydrateLargeValueCell(1, 1)).toBe(true);+ expect(result.value.large_value_cells).toEqual([]);+ expect(result.value.large_value_refs).toContain("old-page-locator");+ });++ it.each(["read", "download", "save baseline"] as const)("ends a stalled %s on grid cleanup without accepting late success", async (operation) => {+ const result = previewResult("CLOB", "original preview", 5000);+ result.value.large_value_context = { connectionId: "oceanbase-oracle-1", database: "MAXIMO" };+ result.value.large_value_cells![0]!.value_ref = "old-locator";+ let release!: (value: unknown) => void;+ const external = new Promise((resolve) => {+ release = resolve;+ });+ mocks.readLargeValueChunk.mockReturnValueOnce(external);+ mocks.downloadLargeValue.mockReturnValueOnce(external);+ mocks.cancelQuery.mockRejectedValue(new Error("cancel failed"));+ const { largeValues, runtimeScope } = mountLargeValues("oceanbase-oracle", result);+ const work = operation === "read" ? largeValues.resolveLargeValueCells([1], [1]) : operation === "download" ? largeValues.downloadSnapshotCell(1, 1, "lob.txt") : largeValues.prepareSaveBaseline({ dirtyRows: new Map([[0, new Map([[1, "edit"]])]]), deletedRows: new Set() });+ let outcome: unknown;+ const settled = work.then(+ (value) => {+ outcome = value;+ },+ (error) => {+ outcome = error;+ },+ );+ runtimeScope.dispose();+ await vi.waitFor(() => expect(outcome).toBeInstanceOf(Error), { timeout: 150 });+ await settled;+ release({ status: "ok", data: "late", next_offset: 4, eof: true, value_kind: "text" });+ await nextTick();+ expect(result.value.rows[0]![1]).toBe("original preview");+ expect(result.value.large_value_cells![0]!.value_ref).toBe("old-locator");+ });+ it("ends a stalled snapshot read locally when its result changes even if server cancellation fails", async () => {+ const result = previewResult("CLOB", "original preview", 5000);+ result.value.large_value_context = { connectionId: "oceanbase-oracle-1", database: "MAXIMO" };+ result.value.large_value_cells![0]!.value_ref = "old-locator";+ const oldResult = result.value;+ let release!: (chunk: unknown) => void;+ mocks.readLargeValueChunk.mockReturnValueOnce(+ new Promise((resolve) => {+ release = resolve;+ }),+ );+ mocks.cancelQuery.mockRejectedValue(new Error("cancel failed"));+ const { largeValues } = mountLargeValues("oceanbase-oracle", result);+ let outcome: unknown;+ const pending = largeValues.resolveLargeValueCells([1], [1]).then(+ (value) => {+ outcome = value;+ },+ (error) => {+ outcome = error;+ },+ );+ await nextTick();+ result.value = { ...oldResult, rows: [[1, "new preview"]] };+ await nextTick();+ await vi.waitFor(() => expect(outcome).toBeInstanceOf(Error), { timeout: 150 });+ await pending;+ release({ status: "ok", data: "late", next_offset: 4, eof: true, value_kind: "text" });+ await nextTick();+ expect(oldResult.rows[0]![1]).toBe("original preview");+ expect(result.value.rows[0]![1]).toBe("new preview");+ expect(mocks.executeMulti).not.toHaveBeenCalled();+ });+ it.each(["CLOB", "BLOB"])("keeps the first pending %s edit when loading a second complete LOB on the same row", async (columnType) => {+ const binary = columnType === "BLOB";+ const firstEdit = binary ? "0x00ff80" : "first pending edit";+ const secondEdit = binary ? "0xaabbcc" : "second pending edit";+ const firstData = (binary ? "11" : "a").repeat(2057);+ const secondData = (binary ? "22" : "b").repeat(2061);+ const result = previewResult(columnType, binary ? "0x11" : "first preview", 2057);+ result.value.columns.push("DOCUMENT");+ result.value.column_types!.push(columnType);+ result.value.rows[0]!.push(binary ? "0x22" : "second preview");+ result.value.large_value_context = { connectionId: "oceanbase-oracle-1", database: "MAXIMO" };+ result.value.large_value_cells = [+ { row_index: 0, column_index: 1, original_bytes: 2057, value_ref: "first" },+ { row_index: 0, column_index: 2, original_bytes: 2061, value_ref: "second" },+ ];+ mocks.readLargeValueChunk.mockImplementation(async (options) => {+ const bytes = options.valueRef === "first" ? 2057 : 2061;+ return { status: "ok", data: options.valueRef === "first" ? firstData : secondData, next_offset: bytes, eof: true, value_kind: binary ? "binary" : "text" };+ });+ const { largeValues, editor } = mountLargeValues("oceanbase-oracle", result, true);+ await expect(largeValues.hydrateLargeValueCell(1, 1)).resolves.toBe(true);+ editor!.applyCellValue(0, 1, firstEdit);+ await nextTick();+ const row = result.value.rows[0];+ await expect(largeValues.hydrateLargeValueCell(1, 2)).resolves.toBe(true);+ await nextTick();+ expect(editor!.dirtyRows.value.get(0)?.get(1)).toBe(firstEdit);+ expect(result.value.rows[0]).toBe(row);+ editor!.applyCellValue(0, 2, secondEdit);+ mocks.prepareDataGridSave.mockResolvedValue({ statements: [`both ${columnType} updates`], rollbackStatements: [] });+ await editor!.previewChanges();+ expect(mocks.prepareDataGridSave.mock.calls[0]![0].dirtyRows).toEqual([+ [+ 0,+ [+ [1, firstEdit],+ [2, secondEdit],+ ],+ ],+ ]);+ expect(result.value.rows[0]).toEqual([1, (binary ? "0x" : "") + firstData, (binary ? "0x" : "") + secondData]);+ editor!.undoPendingChange();+ expect(editor!.dirtyRows.value.get(0)?.get(1)).toBe(firstEdit);+ expect(editor!.dirtyRows.value.get(0)?.has(2)).toBe(false);+ });++ it.each([+ ["CLOB", "preview"],+ ["CLOB", "failed preparation"],+ ["BLOB", "preview"],+ ["BLOB", "failed preparation"],+ ])("keeps editor edits, deletes and undo after %s baseline reads during %s", async (columnType, action) => {+ const binary = columnType === "BLOB";+ const result = previewResult(columnType, binary ? "0x00" : "preview", 1);+ result.value.rows.push([2, "second preview"]);+ result.value.large_value_context = { connectionId: "oracle-1", database: "MAXIMO" };+ result.value.large_value_cells = [+ { row_index: 0, column_index: 1, original_bytes: 1, value_ref: "first" },+ { row_index: 1, column_index: 1, original_bytes: 1, value_ref: "second" },+ ];+ const { editor } = mountLargeValues("oracle", result, true);+ editor!.newRows.value = [[3, "pending insert"]];+ editor!.applyCellValue(0, 1, "pending edit");+ editor!.applyDeleteRow(1);+ const rows = result.value.rows;+ const first = rows[0];+ const second = rows[1];+ mocks.readLargeValueChunk.mockResolvedValue({ status: "ok", data: binary ? "00ff" : "complete", next_offset: binary ? 2 : 8, eof: true, value_kind: binary ? "binary" : "text" });+ if (action === "preview") {+ mocks.prepareDataGridSave.mockResolvedValue({ statements: ["UPDATE APP_DATA", "DELETE APP_DATA"], rollbackStatements: [] });+ await editor!.previewChanges();+ } else {+ mocks.prepareDataGridSave.mockRejectedValue(new Error("preparation failed"));+ await editor!.saveChanges();+ }+ await nextTick();+ expect(editor!.dirtyRows.value.get(0)?.get(1)).toBe("pending edit");+ expect(editor!.deletedRows.value.has(1)).toBe(true);+ expect(editor!.newRows.value).toEqual([[3, "pending insert"]]);+ expect(editor!.hasPendingChanges.value).toBe(true);+ expect(editor!.canUndoPendingChange.value).toBe(true);+ expect(result.value.rows).toBe(rows);+ expect(result.value.rows[0]).toBe(first);+ expect(result.value.rows[1]).toBe(second);+ expect(first![1]).toBe(binary ? "0x00ff" : "complete");+ expect(mocks.executeBatch).not.toHaveBeenCalled();+ editor!.undoPendingChange();+ expect(editor!.deletedRows.value.has(1)).toBe(false);+ expect(editor!.dirtyRows.value.get(0)?.get(1)).toBe("pending edit");+ });+ it("loads original LOB baselines before clear/delete SQL generation without replacing pending edits", async () => {+ const result = previewResult("CLOB", "preview", 1);+ result.value.large_value_context = { connectionId: "oracle-1", database: "MAXIMO", clientSessionId: "original-session" };+ result.value.large_value_cells![0]!.value_ref = "original-locator";+ const { largeValues } = mountLargeValues("oracle", result);+ const dirtyRows = new Map([[0, new Map([[1, null]])]]);+ mocks.readLargeValueChunk.mockResolvedValue({ status: "ok", data: "original complete", next_offset: 17, eof: true, value_kind: "text" });+ await largeValues.prepareSaveBaseline({ dirtyRows, deletedRows: new Set() });+ expect(result.value.rows[0]![1]).toBe("original complete");+ expect(dirtyRows.get(0)!.get(1)).toBeNull();+ expect(result.value.large_value_refs).toContain("original-locator");+ expect(result.value.large_value_cells).toEqual([]);+ expect(mocks.executeMulti).not.toHaveBeenCalled();+ expect(mocks.readLargeValueChunk).toHaveBeenCalledWith(expect.objectContaining({ valueRef: "original-locator", connectionId: "oracle-1", clientSessionId: "original-session" }));+ });++ it("blocks save on expired snapshots and keeps every original preview for retry", async () => {+ const result = previewResult("CLOB", "preview", 1);+ result.value.large_value_context = { connectionId: "oracle-1", database: "MAXIMO" };+ result.value.large_value_cells![0]!.value_ref = "expired-locator";+ const { largeValues } = mountLargeValues("oracle", result);+ const originalRows = result.value.rows;+ mocks.readLargeValueChunk.mockResolvedValue({ status: "expired" });+ await expect(largeValues.prepareSaveBaseline({ dirtyRows: new Map(), deletedRows: new Set([0]) })).rejects.toThrow("snapshot expired");+ expect(result.value.rows).toBe(originalRows);+ expect(result.value.large_value_cells![0]!.value_ref).toBe("expired-locator");+ expect(mocks.executeMulti).not.toHaveBeenCalled();+ });++ it("refuses a save baseline owned by another connection even after hydration", async () => {+ const result = previewResult("CLOB", "complete original", 1);+ result.value.large_value_cells = [];+ result.value.large_value_context = { connectionId: "different-connection", database: "MAXIMO" };+ result.value.large_value_refs = ["retained-original-locator"];+ const { largeValues } = mountLargeValues("oracle", result);+ await expect(largeValues.prepareSaveBaseline({ dirtyRows: new Map([[0, new Map([[1, null]])]]), deletedRows: new Set() })).rejects.toThrow("connection is unavailable");+ expect(mocks.readLargeValueChunk).not.toHaveBeenCalled();+ });++ it("preserves a concurrently hydrated cell when save baseline preparation finishes later", async () => {+ const result = previewResult("CLOB", "first preview", 1);+ result.value.columns.push("DOCUMENT");+ result.value.column_types!.push("CLOB");+ result.value.rows[0]!.push("second preview");+ result.value.large_value_context = { connectionId: "oracle-1", database: "MAXIMO" };+ result.value.large_value_cells = [+ { row_index: 0, column_index: 1, original_bytes: 1, value_ref: "first-locator" },+ { row_index: 0, column_index: 2, original_bytes: 1, value_ref: "second-locator" },+ ];+ result.value.large_value_refs = ["first-locator", "second-locator"];+ let finishFirst!: (chunk: unknown) => void;+ mocks.readLargeValueChunk.mockImplementation(({ valueRef }) =>+ valueRef === "first-locator"+ ? new Promise((resolve) => {+ finishFirst = resolve;+ })+ : Promise.resolve({ status: "ok", data: "second complete", next_offset: 15, eof: true, value_kind: "text" }),+ );+ const { largeValues } = mountLargeValues("oracle", result);+ const preparation = largeValues.prepareSaveBaseline({ dirtyRows: new Map([[0, new Map([[1, null]])]]), deletedRows: new Set() });+ await expect(largeValues.hydrateLargeValueCell(1, 2)).resolves.toBe(true);+ finishFirst({ status: "ok", data: "first complete", next_offset: 14, eof: true, value_kind: "text" });+ await preparation;+ expect(result.value.rows[0]).toEqual([1, "first complete", "second complete"]);+ expect(result.value.large_value_cells).toEqual([]);+ });it.each([["postgres", 3],["mysql", 1],diff --git a/apps/desktop/src/composables/useDataGridEditor.ts b/apps/desktop/src/composables/useDataGridEditor.tsindex 3f229b0965..cdf5cd4984 100644--- a/apps/desktop/src/composables/useDataGridEditor.ts+++ b/apps/desktop/src/composables/useDataGridEditor.ts@@ -155,6 +155,7 @@ export interface UseDataGridEditorOptions {cacheKey?: ComputedRef<string | undefined>;/** 保存成功后结果负载被原地修改时通知宿主,使缓存的字节估算失效。 */onResultPayloadMutated?: () => void;+ prepareSaveBaseline?: (changes: { dirtyRows: ReadonlyMap<number, ReadonlyMap<number, CellValue>>; deletedRows: ReadonlySet<number> }) => Promise<void>;refreshSavedRows?: (request: { dirtyRows: ReadonlyMap<number, ReadonlyMap<number, CellValue>>; columns: readonly string[]; rows: readonly (readonly CellValue[])[] }) => Promise<boolean>;onCellValueChanged?: (rowId: number, columnIndex: number) => void;prepareFullReload?: () => void;@@ -1753,6 +1754,10 @@ export function useDataGridEditor(options: UseDataGridEditorOptions) {for (const group of groups) {const part = await api.prepareDataGridSave(group, saveDriverProfile());if (part.validationError) return part;+ if (part.boundStatements?.length || prepared.boundStatements) {+ prepared.boundStatements ??= prepared.statements.map((sql) => ({ previewSql: sql, sql, blobParameters: [] }));+ prepared.boundStatements.push(...(part.boundStatements ?? part.statements.map((sql) => ({ previewSql: sql, sql, blobParameters: [] }))));+ }prepared.statements.push(...part.statements);prepared.rollbackStatements.unshift(...part.rollbackStatements);prepared.keylessGuards!.push(...(part.keylessGuards ?? []));@@ -2121,6 +2126,13 @@ export function useDataGridEditor(options: UseDataGridEditorOptions) {return;}+ try {+ if (options.prepareSaveBaseline) await options.prepareSaveBaseline(snapshot);+ } catch (error) {+ saveError.value = normalizeDataGridSaveError(databaseType.value, error);+ await finishInterruptedSaveChanges(snapshot);+ return;+ }const stmtOptions = saveStatementOptions(snapshot);let preparedSave: Awaited<ReturnType<typeof api.prepareDataGridSave>> | undefined;if (stmtOptions) {@@ -2223,7 +2235,9 @@ export function useDataGridEditor(options: UseDataGridEditorOptions) {if (txnSessionId && hasBackendSaveTarget.value) {options.onManualTransactionMutation?.();try {- const results = await api.executeInManualTransaction(txnSessionId, stmts.join(";\n"), database.value ?? "", preparedSave?.executionSchema);+ const results = preparedSave?.boundStatements?.length+ ? await api.executeInManualTransaction(txnSessionId, stmts.join(";\n"), database.value ?? "", preparedSave?.executionSchema, undefined, undefined, undefined, undefined, undefined, undefined, undefined, preparedSave.boundStatements)+ : await api.executeInManualTransaction(txnSessionId, stmts.join(";\n"), database.value ?? "", preparedSave?.executionSchema);apiResult = {affected_rows: results.reduce((total, result) => total + (result.affected_rows ?? 0), 0),};@@ -2234,7 +2248,9 @@ export function useDataGridEditor(options: UseDataGridEditorOptions) {}} else if (useTransaction.value && stmts.length > 1 && hasBackendSaveTarget.value) {try {- apiResult = await api.executeInTransaction(connectionId.value!, database.value ?? "", stmts, preparedSave?.executionSchema);+ apiResult = preparedSave?.boundStatements?.length+ ? await api.executeInTransaction(connectionId.value!, database.value ?? "", stmts, preparedSave?.executionSchema, undefined, preparedSave.boundStatements)+ : await api.executeInTransaction(connectionId.value!, database.value ?? "", stmts, preparedSave?.executionSchema);} catch (e: any) {saveError.value = await recordFailedDataGridHistory(stmts, rollbackStmts, start, snapshot, e);await finishInterruptedSaveChanges(snapshot);@@ -2242,7 +2258,9 @@ export function useDataGridEditor(options: UseDataGridEditorOptions) {}} else if (hasBackendSaveTarget.value) {try {- apiResult = await api.executeBatch(connectionId.value!, database.value ?? "", stmts, preparedSave?.executionSchema);+ apiResult = preparedSave?.boundStatements?.length+ ? await api.executeBatch(connectionId.value!, database.value ?? "", stmts, preparedSave?.executionSchema, undefined, undefined, preparedSave.boundStatements)+ : await api.executeBatch(connectionId.value!, database.value ?? "", stmts, preparedSave?.executionSchema);} catch (e: any) {saveError.value = await recordFailedDataGridHistory(stmts, rollbackStmts, start, snapshot, e);await finishInterruptedSaveChanges(snapshot);@@ -2433,7 +2451,9 @@ export function useDataGridEditor(options: UseDataGridEditorOptions) {if (preview) return await preview({ dirtyRows: dirtyRows.value, newRows: newRows.value, newRowMeta: cloneNewRowMeta(newRowMeta.value), deletedRows: deletedRows.value, columns: result.value.columns, rows: result.value.rows });return [];}- const stmtOptions = saveStatementOptions();+ const snapshot = snapshotPendingSaveChanges();+ if (options.prepareSaveBaseline) await options.prepareSaveBaseline(snapshot);+ const stmtOptions = saveStatementOptions(snapshot);if (!stmtOptions) return [];const prepared = await prepareSaveStatements(stmtOptions);if (prepared?.validationError) {diff --git a/apps/desktop/src/composables/useDataGridExport.ts b/apps/desktop/src/composables/useDataGridExport.tsindex 9f14bfbc1f..d6044af377 100644--- a/apps/desktop/src/composables/useDataGridExport.ts+++ b/apps/desktop/src/composables/useDataGridExport.ts@@ -1,4 +1,4 @@-import { computed, type ComputedRef, type Ref, createApp } from "vue";+import { computed, type ComputedRef, type Ref, createApp, watch, getCurrentScope, onScopeDispose } from "vue";import { useI18n } from "vue-i18n";import { useDataGridExtractor } from "@/composables/useDataGridExtractor";import { isTauriRuntime } from "@/lib/backend/tauriRuntime";@@ -13,6 +13,8 @@ import { useToast } from "@/composables/useToast";import { useExportTracker } from "@/composables/useExportTracker";import { clipboardCellValue, type CellValue } from "@/lib/dataGrid/cellValue";import { binaryCellClipboardText } from "@/lib/dataGrid/binaryCellDownload";+import { materializeSnapshotResultRows, waitForLargeValueSnapshot } from "@/lib/dataGrid/largeValueSnapshot";+import { snapshotExportSelection, assertSnapshotXlsxCellLengths } from "@/lib/dataGrid/snapshotExport";import { tryStartExclusiveActivation, type ActionActivationGuard } from "@/lib/connection/actionActivation";import { clipboardLineEndings, copyToClipboard } from "@/lib/common/clipboard";import { clearDataGridClipboardCopy, rememberDataGridClipboardCopy } from "@/lib/dataGrid/dataGridClipboard";@@ -172,6 +174,7 @@ export interface UseDataGridExportOptions {* silently change what "export all data" produces.*/completeLocalResult?: ComputedRef<QueryResult | undefined>;+ snapshotResult?: ComputedRef<QueryResult>;allExportResults?: ComputedRef<Array<{ sheetName: string; result: QueryResult; sql?: string }> | undefined>;currentResultLabel?: ComputedRef<string | undefined>;exportFileBaseName?: ComputedRef<string | undefined>;@@ -200,6 +203,13 @@ interface CopyInsertData {}export function useDataGridExport(options: UseDataGridExportOptions) {+ let activeSnapshotCancel: (() => Promise<void>) | undefined;+ let scopeDisposed = false;+ if (getCurrentScope())+ onScopeDispose(() => {+ scopeDisposed = true;+ void activeSnapshotCancel?.().catch(() => undefined);+ });const { t } = useI18n();const { toast } = useToast();const tracker = useExportTracker();@@ -308,6 +318,37 @@ export function useDataGridExport(options: UseDataGridExportOptions) {});}+ async function materializeExportSnapshot(result: QueryResult, isResultCurrent: () => boolean): Promise<QueryResult["rows"]> {+ if (!result.large_value_cells?.some((cell) => cell.value_ref)) return result.rows;+ const originalConnectionId = connectionId.value;+ const originalDatabase = database.value;+ const isCurrent = () => !scopeDisposed && isResultCurrent() && connectionId.value === originalConnectionId && database.value === originalDatabase;+ if (!isCurrent()) throw new Error("LOB result context changed");+ const executionId = uuid();+ const controller = new AbortController();+ const cancel = async () => {+ controller.abort(new Error("LOB export cancelled locally"));+ await api.cancelQuery(executionId);+ };+ activeSnapshotCancel = cancel;+ const previousCancel = exportCancelHandler?.value;+ if (exportCancelHandler) exportCancelHandler.value = cancel;+ const stop = watch(+ isCurrent,+ (current) => {+ if (!current) void cancel().catch(() => undefined);+ },+ { flush: "sync" },+ );+ try {+ return await materializeSnapshotResultRows(result, isCurrent, controller.signal, executionId);+ } finally {+ stop();+ if (activeSnapshotCancel === cancel) activeSnapshotCancel = undefined;+ if (exportCancelHandler?.value === cancel) exportCancelHandler.value = previousCancel ?? null;+ }+ }+function applyGlobalDateTimeExportFormat(result: { columns: string[]; columnTypes: string[]; rows: CellValue[][] }, enabled: boolean) {const pattern = enabled ? useSettingsStore().editorSettings.globalDateTimeExportFormat : "";return pattern ? { ...result, rows: formatTemporalRowsForExport(result.rows, result.columnTypes, pattern) } : result;@@ -527,7 +568,16 @@ export function useDataGridExport(options: UseDataGridExportOptions) {// client-side filters/search and unsaved edits, which would silently// change what the export contains.if (useFullExport && rowIds === undefined && hasCompleteLocalResult?.value && completeLocalResult?.value) {- const normalized = hasColumnSubset || databaseType.value === "mongodb" ? normalizeCompleteLocalResult(completeLocalResult.value, targetColumns, projectionSourceIndexes) : normalizeCompleteLocalResult(completeLocalResult.value);+ const original = completeLocalResult.value;+ const projected = hasColumnSubset || databaseType.value === "mongodb";+ const hiddenIndexes = new Set(original.hidden_column_indexes ?? []);+ const sourceIndexes = projected ? (projectionSourceIndexes ?? targetColumns.map((column) => original.columns.indexOf(column))) : original.columns.map((_, index) => index).filter((index) => !hiddenIndexes.has(index));+ const settings = useSettingsStore().editorSettings;+ const sourceRows = settings.exportRowLimitEnabled ? original.rows.slice(0, settings.exportRowLimit) : original.rows;+ const selected = { ...original, rows: sourceRows, large_value_cells: original.large_value_cells?.filter((cell) => cell.row_index < sourceRows.length && sourceIndexes.includes(cell.column_index)) };+ const rows = await materializeExportSnapshot(selected, () => completeLocalResult.value === original);+ const materialized = { ...original, rows };+ const normalized = hasColumnSubset || databaseType.value === "mongodb" ? normalizeCompleteLocalResult(materialized, targetColumns, projectionSourceIndexes) : normalizeCompleteLocalResult(materialized);const columnComments = buildXlsxHeaderOverrides(normalized.columns, normalized.columnComments, headerMode);return {...applyGlobalDateTimeExportFormat(@@ -541,9 +591,9 @@ export function useDataGridExport(options: UseDataGridExportOptions) {}const targetComments = commentsForExportColumns(targetColumns, false);const commentHeader = buildXlsxHeaderOverrides(targetColumns, targetComments, headerMode);- const exportItems = await resolveVisibleRowValues(rowsToExport(rowIds));const visibleIndexes = visibleColumnIndexesOption?.value ?? columns.value.map((_, index) => index);const targetSourceIndexes = validColumnIndexes.map((targetIdx) => visibleIndexes[targetIdx] ?? targetIdx);+ const exportItems = await resolveVisibleRowValues(rowsToExport(rowIds), targetSourceIndexes);const targetIndexBySource = new Map<number, number>();targetSourceIndexes.forEach((sourceIdx, targetIdx) => {targetIndexBySource.set(sourceIdx, targetIdx);@@ -593,6 +643,7 @@ export function useDataGridExport(options: UseDataGridExportOptions) {}async function writeXlsxResult(outputPath: string, result: { columns: string[]; columnTypes: string[]; columnComments?: (string | null)[]; rows: CellValue[][] }, includeSqlSheet: boolean, autoFilter: boolean, sqlOverride?: string, headerCommentRows = false) {+ if (options.snapshotResult?.value.large_value_refs?.length || options.snapshotResult?.value.large_value_cells?.some((cell) => cell.value_ref)) assertSnapshotXlsxCellLengths(result.rows);const effectiveSql = sqlOverride ?? currentExportSql();const sqlWorksheet = includeSqlSheet ? buildXlsxSqlWorksheet([{ sql: effectiveSql || "" }]) : undefined;const rightAlign = useSettingsStore().editorSettings.numericColumnRightAlign;@@ -730,15 +781,17 @@ export function useDataGridExport(options: UseDataGridExportOptions) {// --- Cell/row copy ---async function copyCell() {- if (!contextCell.value || contextCell.value.col < 0) return;- const item = getRowItem(contextCell.value.rowId);+ const target = contextCell.value;+ if (!target || target.col < 0) return;+ const columnIndex = target.col;+ const item = getRowItem(target.rowId);if (!item || item.isDraft) return;- const sourceIndex = visibleColumnIndexes.value[contextCell.value.col] ?? contextCell.value.col;+ const sourceIndex = visibleColumnIndexes.value[columnIndex] ?? columnIndex;const [resolvedItem] = await resolveVisibleRowValues([item], [sourceIndex]);- const val = resolvedItem?.data[contextCell.value.col] ?? null;+ const val = resolvedItem?.data[columnIndex] ?? null;// 外部剪贴板呈现文本型 MySQL VARBINARY(NULL 也按空串输出);内部网格副本仍保留原 hex,保证回粘无损。- const rawValue = options.cellClipboardText?.(val, sourceIndex) ?? clipboardCellValue(binaryClipboardCellValue(val, contextCell.value.col));- const copyValue = options.databaseType.value === "oracle" && isTemporalColumnType(options.columnTypes.value?.[contextCell.value.col]) ? (options.displayValue?.(val, sourceIndex) ?? rawValue) : rawValue;+ const rawValue = options.cellClipboardText?.(val, sourceIndex) ?? clipboardCellValue(binaryClipboardCellValue(val, columnIndex));+ const copyValue = options.databaseType.value === "oracle" && isTemporalColumnType(options.columnTypes.value?.[columnIndex]) ? (options.displayValue?.(val, sourceIndex) ?? rawValue) : rawValue;await copyText(copyValue, { rows: [[val]] });}@@ -861,6 +914,7 @@ export function useDataGridExport(options: UseDataGridExportOptions) {allSourceColumns,visibleColumnIndexes,columnTypes,+ allColumnTypes: allColumnTypesOption,extractorOptions: extractorOptionsOption,databaseType,identifierQuote,@@ -943,10 +997,101 @@ export function useDataGridExport(options: UseDataGridExportOptions) {return exported;}+ async function exportLocalSnapshot(format: "csv" | "json", rowIds: number[] | undefined, columnIndexes: number[] | undefined, full: boolean): Promise<boolean> {+ const original = options.snapshotResult?.value;+ const originalConnectionId = connectionId.value;+ const originalDatabase = database.value;+ const isCurrent = () => options.snapshotResult?.value === original && connectionId.value === originalConnectionId && database.value === originalDatabase;+ if (!original || (full && rowIds === undefined && !hasCompleteLocalResult?.value)) return false;+ const exportAll = full && rowIds === undefined && hasCompleteLocalResult?.value;+ const visibleIndexes = visibleColumnIndexesOption?.value ?? columns.value.map((_, index) => index);+ const indexes = columnIndexes?.filter((index) => index >= 0 && index < columns.value.length);+ const hiddenIndexes = new Set(original.hidden_column_indexes ?? []);+ const sourceIndexes = exportAll && !indexes ? original.columns.map((_, index) => index).filter((index) => !hiddenIndexes.has(index)) : (indexes ?? columns.value.map((_, index) => index)).map((index) => visibleIndexes[index] ?? index);+ const names = sourceIndexes.map((index) => original.columns[index]!);+ const editorSettings = useSettingsStore().editorSettings;+ const originalRows = editorSettings.exportRowLimitEnabled ? original.rows.slice(0, editorSettings.exportRowLimit) : original.rows;+ const items = exportAll+ ? originalRows.map((row, sourceIndex) => ({ sourceIndex, data: sourceIndexes.map((index) => row[index]) }))+ : rowsToExport(rowIds).map((item) => ({+ sourceIndex: item.sourceIndex,+ isNew: item.isNew,+ data: externalizeRows([item.data], indexes)[0]!,+ isDirtyCol: (indexes ?? columns.value.map((_, index) => index)).map((index) => item.isDirtyCol[index] ?? false),+ }));+ const selected = snapshotExportSelection(original, names, sourceIndexes, items);+ if (!selected) return false;+ const types = sourceIndexes.map((index) => original.column_types?.[index] ?? "");+ selected.rows = applyGlobalDateTimeExportFormat({ columns: names, columnTypes: types, rows: selected.rows as CellValue[][] }, true).rows;+ let outputPath = exportFileName(full ? "export" : "export-page", format, { page: !full });+ if (isTauriRuntime()) {+ const path = await promptExportSavePath({ defaultFileName: outputPath, filters: [{ name: FORMAT_META[format]!.label, extensions: [format] }], preferredPath: useSettingsStore().editorSettings.preferredExportPath });+ if (!path) return true;+ outputPath = path;+ }+ if (!isCurrent()) throw new Error("LOB result context changed");+ const executionId = uuid();+ const controller = new AbortController();+ const cancel = async () => {+ controller.abort(new Error("LOB export cancelled locally"));+ await api.cancelQuery(executionId);+ };+ activeSnapshotCancel = cancel;+ const title = currentExportTitle();+ tracker.addTask(title, format, outputPath, executionId);+ tracker.registerTaskCancelHandler(executionId, cancel);+ if (exportProgressState)+ exportProgressState.value = {+ title: t("exportProgress.title"),+ tableName: title,+ format,+ rowsExported: 0,+ totalRows: selected.rows.length,+ status: "Running",+ errorMessage: null,+ filePath: outputPath,+ startedAt: Date.now(),+ finishedAt: undefined,+ };+ if (exportProgressDialog) exportProgressDialog.value = true;+ if (exportCanMinimize) exportCanMinimize.value = true;+ const previousCancel = exportCancelHandler?.value;+ if (exportCancelHandler) exportCancelHandler.value = cancel;+ const stop = watch(+ () => [options.snapshotResult?.value, connectionId.value, database.value],+ () => {+ if (!isCurrent()) void cancel().catch(() => undefined);+ },+ );+ try {+ await waitForLargeValueSnapshot(+ api.exportSnapshotResult({ ...selected, context: { ...selected.context, executionId }, format, quoteMode: useSettingsStore().editorSettings.csvQuoteMode, nullLiteral: csvNullLiteralForMode(useSettingsStore().editorSettings.csvNullMode) }, outputPath, controller.signal),+ controller.signal,+ );+ if (!isCurrent()) throw new Error("LOB result context changed");+ tracker.updateTableExportTask(executionId, { exportId: executionId, tableName: title, rowsExported: selected.rows.length, totalRows: selected.rows.length, status: "Done" });+ if (exportProgressState) exportProgressState.value = { ...exportProgressState.value, status: "Done", rowsExported: selected.rows.length, finishedAt: Date.now() };+ notifyExportSuccess(outputPath);+ } catch (error) {+ const errorMessage = error instanceof Error ? error.message : String(error);+ tracker.updateTableExportTask(executionId, { exportId: executionId, tableName: title, rowsExported: 0, totalRows: selected.rows.length, status: "Error", errorMessage });+ if (exportProgressState) exportProgressState.value = { ...exportProgressState.value, status: "Error", errorMessage, finishedAt: Date.now() };+ throw error;+ } finally {+ stop();+ if (activeSnapshotCancel === cancel) activeSnapshotCancel = undefined;+ tracker.unregisterTaskCancelHandler(executionId);+ if (exportCanMinimize) exportCanMinimize.value = false;+ if (exportCancelHandler) exportCancelHandler.value = previousCancel ?? null;+ }+ return true;+ }+async function exportCsv(target?: ExportTargetParam, columnIndexesParam?: number[]) {const { rowIds, columnIndexes } = normalizeExportTarget(target, columnIndexesParam);await runExclusiveExport(async () => {try {+ if (await exportLocalSnapshot("csv", rowIds, columnIndexes, true)) return;if (await exportQueryResultViaBackend("csv", rowIds, false, "name", true, undefined, false, columnIndexes)) return;if (await exportFullTableDataViaBackend("csv", rowIds, "name", true, undefined, false, columnIndexes)) return;@@ -1029,6 +1174,7 @@ export function useDataGridExport(options: UseDataGridExportOptions) {async function exportCurrentPageCsv(columnIndexes?: number[]) {await runExclusiveExport(async () => {try {+ if (await exportLocalSnapshot("csv", undefined, columnIndexes, false)) return;let outputPath = exportFileName("export-page", "csv", { page: true });if (isTauriRuntime()) {const path = await promptExportSavePath({@@ -1052,6 +1198,7 @@ export function useDataGridExport(options: UseDataGridExportOptions) {const { rowIds, columnIndexes } = normalizeExportTarget(target, columnIndexesParam);await runExclusiveExport(async () => {try {+ if (await exportLocalSnapshot("json", rowIds, columnIndexes, true)) return;if (await exportFullTableDataViaBackend("json", rowIds, "name", true, undefined, false, columnIndexes)) return;if (await exportQueryResultViaBackend("json", rowIds, false, "name", true, undefined, false, columnIndexes)) return;@@ -1077,6 +1224,7 @@ export function useDataGridExport(options: UseDataGridExportOptions) {async function exportCurrentPageJson(columnIndexes?: number[]) {await runExclusiveExport(async () => {try {+ if (await exportLocalSnapshot("json", undefined, columnIndexes, false)) return;let outputPath = exportFileName("export-page", "json", { page: true });if (isTauriRuntime()) {const path = await promptExportSavePath({@@ -1384,16 +1532,22 @@ export function useDataGridExport(options: UseDataGridExportOptions) {const exportPattern = useSettingsStore().editorSettings.globalDateTimeExportFormat;const rightAlign = useSettingsStore().editorSettings.numericColumnRightAlign;- const worksheets = sheets.map((sheet) => ({- sheetName: sheet.sheetName,- columns: sheet.result.columns,- columnTypes: sheet.result.column_types ?? [],- columnComments: buildXlsxHeaderOverrides(sheet.result.columns, commentsForExportColumns(sheet.result.columns), exportOptions.headerMode),- rows: formatTemporalRowsForExport(sheet.result.rows, sheet.result.column_types ?? [], exportPattern),- numericColumnRightAlign: rightAlign,- autoFilter: exportOptions.autoFilter,- headerCommentRows: xlsxHeaderUsesCommentRows(exportOptions.headerMode),- }));+ const worksheets = [];+ for (const sheet of sheets) {+ const sourceRows = sheet.result.rows;+ const rows = await materializeExportSnapshot(sheet.result, () => sheet.result.rows === sourceRows && (sheetsToExport !== undefined || !!allExportResults?.value?.includes(sheet)));+ if (sheet.result.large_value_refs?.length || sheet.result.large_value_cells?.some((cell) => cell.value_ref)) assertSnapshotXlsxCellLengths(rows);+ worksheets.push({+ sheetName: sheet.sheetName,+ columns: sheet.result.columns,+ columnTypes: sheet.result.column_types ?? [],+ columnComments: buildXlsxHeaderOverrides(sheet.result.columns, commentsForExportColumns(sheet.result.columns), exportOptions.headerMode),+ rows: formatTemporalRowsForExport(rows, sheet.result.column_types ?? [], exportPattern),+ numericColumnRightAlign: rightAlign,+ autoFilter: exportOptions.autoFilter,+ headerCommentRows: xlsxHeaderUsesCommentRows(exportOptions.headerMode),+ });+ }const sqlWorksheet = includeSqlSheet ? buildXlsxSqlWorksheet(sheets.map((sheet) => ({ resultName: sheet.sheetName, sql: sheet.sql || sheet.result.sourceStatement || "" }))) : undefined;await api.exportQueryResultsXlsx(outputPath, sqlWorksheet ? [...worksheets, { ...sqlWorksheet, autoFilter: false }] : worksheets, exportOptions.autoFilter, exportPattern || undefined);notifyExportSuccess(outputPath);diff --git a/apps/desktop/src/composables/useDataGridExtractor.ts b/apps/desktop/src/composables/useDataGridExtractor.tsindex cf05479d9a..3ce44e7866 100644--- a/apps/desktop/src/composables/useDataGridExtractor.ts+++ b/apps/desktop/src/composables/useDataGridExtractor.ts@@ -57,6 +57,7 @@ interface UseDataGridExtractorOptions {allSourceColumns: ComputedRef<Array<string | undefined> | undefined>;visibleColumnIndexes: ComputedRef<number[]>;columnTypes: ComputedRef<Array<string | undefined> | undefined>;+ allColumnTypes?: ComputedRef<Array<string | undefined> | undefined>;extractorOptions?: ComputedRef<DataGridExtractorOptions>;databaseType: ComputedRef<DatabaseType | undefined>;identifierQuote?: ComputedRef<string | undefined>;@@ -217,6 +218,7 @@ export function useDataGridExtractor(options: UseDataGridExtractorOptions) {}const compactIndexBySource = new Map(requiredSourceIndexes.map((sourceIndex, compactIndex) => [sourceIndex, compactIndex]));const columnTypesBySource = new Map(visibleIndexes.map((sourceIndex, visibleIndex) => [sourceIndex, options.columnTypes.value?.[visibleIndex]]));+ const columnType = (sourceIndex: number) => options.allColumnTypes?.value?.[sourceIndex] ?? columnTypesBySource.get(sourceIndex);const columns = requiredSourceIndexes.map((sourceIndex, compactIndex) => ({displayName: fullColumns[sourceIndex],// Query results without source metadata still expose their database column@@ -224,10 +226,11 @@ export function useDataGridExtractor(options: UseDataGridExtractorOptions) {// availability check so SQL SELECT can use that safe fallback.sourceName: sourceNames?.[sourceIndex] ?? fullColumns[sourceIndex],sourceIndex: compactIndex,+ dataType: columnType(sourceIndex),}));const descriptor = DATA_GRID_COPY_EXTRACTOR_DESCRIPTORS[extractor];const selectedColumnIndexes = selectedSourceIndexes.map((sourceIndex) => compactIndexBySource.get(sourceIndex)).filter((index): index is number => index !== undefined);- const columnTypes = requiredSourceIndexes.map((sourceIndex) => columnTypesBySource.get(sourceIndex));+ const columnTypes = requiredSourceIndexes.map(columnType);const normalizeValues = descriptor.category === "json" || descriptor.category === "sql";const keepUnsafeJsonText = descriptor.category === "sql";const presentBinaryText = descriptor.category !== "sql";diff --git a/apps/desktop/src/composables/useDataGridLargeValues.ts b/apps/desktop/src/composables/useDataGridLargeValues.tsindex 931dcbd680..48dd537990 100644--- a/apps/desktop/src/composables/useDataGridLargeValues.ts+++ b/apps/desktop/src/composables/useDataGridLargeValues.ts@@ -5,6 +5,7 @@ import { buildDataGridContextFilterCondition } from "@/lib/dataGrid/dataGridSql"import { buildTableSelectSql } from "@/lib/table/tableSelectSql";import { shouldIncludeSyntheticRowId } from "@/lib/table/tableEditing";import { queryTimeoutSecsForConnection } from "@/lib/sql/queryTimeout";+import { materializeLargeValueSnapshot, waitForLargeValueSnapshot } from "@/lib/dataGrid/largeValueSnapshot";import type { ColumnInfo, ConnectionConfig, DatabaseType, QueryResult } from "@/types/database";import type { DataGridRuntimeScope } from "@/lib/dataGrid/dataGridRuntime";import {@@ -79,6 +80,19 @@ export interface UseDataGridLargeValuesOptions {}type ResolvedLargeValueCells = Map<number, Map<number, CellValue>>;+export interface LargeValueSnapshotDownloadTarget {+ readonly result: QueryResult;+ readonly rowId: number;+ readonly sourceIndex: number;+ readonly columnIndex: number;+ readonly valueRef: string;+ readonly context: Readonly<NonNullable<QueryResult["large_value_context"]>>;+ readonly connectionId: string | undefined;+ readonly database: string;+ readonly operation: number;+ readonly signal: AbortSignal;+}+const materializedSnapshotBytes = new WeakMap<QueryResult, Map<string, number>>();type LargeValueCellRequest = {item: LargeValueRowItem;sourceIndex: number;@@ -90,6 +104,16 @@ export function useDataGridLargeValues(options: UseDataGridLargeValuesOptions) {const LARGE_VALUE_FETCH_MAX_ROWS = 200;const LARGE_VALUE_FETCH_TARGET_BYTES = 64 * 1024 * 1024;const pendingLargeValueHydrations = createResultScopedPendingRequests<boolean>();+ const snapshotExecutionIds = new Set<string>();+ let snapshotController = new AbortController();+ const cancelSnapshotReads = () => {+ snapshotController.abort(new Error("LOB reading cancelled locally"));+ snapshotController = new AbortController();+ for (const executionId of snapshotExecutionIds) void api.cancelQuery(executionId).catch(() => {});+ snapshotExecutionIds.clear();+ };+ watch(() => [options.result.value, options.connectionId.value, options.executionDatabase.value], cancelSnapshotReads);+ options.runtimeScope.addCleanup(cancelSnapshotReads);const largeValueCellsByKey = computed(() => largeValueCellMap(options.result.value));type VisibleLargeValuePreviewRequest = {item: LargeValueRowItem;@@ -119,7 +143,58 @@ export function useDataGridLargeValues(options: UseDataGridLargeValuesOptions) {function formatGridItemCell(item: LargeValueRowItem, columnIndex: number): string {void visibleLargeValuePreviewVersion.value;- return options.formatCellCached(visibleLargeValuePreviewValue(item, columnIndex, item.data[columnIndex] ?? null), columnIndex, largeValueOriginalBytes(item, columnIndex));+ const text = options.formatCellCached(visibleLargeValuePreviewValue(item, columnIndex, item.data[columnIndex] ?? null), columnIndex, largeValueOriginalBytes(item, columnIndex));+ return snapshotReference(item, columnIndex) ? options.translate("grid.largeValueSnapshotPreview", { value: text }) : text;+ }++ function snapshotReference(item: LargeValueRowItem | undefined, columnIndex: number): string | undefined {+ if (!item || !isLargeValuePreview(item, columnIndex) || item.sourceIndex === undefined) return undefined;+ return largeValueCellsByKey.value.get(largeValueCellKey(item.sourceIndex, columnIndex))?.value_ref;+ }++ function captureSnapshotDownloadTarget(rowId: number, columnIndex: number): LargeValueSnapshotDownloadTarget | undefined {+ const result = options.result.value;+ const item = options.getRowItem(rowId);+ const valueRef = snapshotReference(item, columnIndex);+ const context = result.large_value_context;+ if (!valueRef || !context || item?.sourceIndex === undefined) return undefined;+ return {+ result,+ rowId,+ sourceIndex: item.sourceIndex,+ columnIndex,+ valueRef,+ context: { ...context },+ connectionId: options.connectionId.value,+ database: options.executionDatabase.value,+ operation: options.resultLifecycle.beginOperation(),+ signal: snapshotController.signal,+ };+ }++ function isSnapshotDownloadTargetCurrent(target: LargeValueSnapshotDownloadTarget): boolean {+ if (target.signal.aborted || options.runtimeScope.disposed || !options.resultLifecycle.isCurrent(target.operation) || options.result.value !== target.result || options.connectionId.value !== target.connectionId || options.executionDatabase.value !== target.database) return false;+ const item = options.getRowItem(target.rowId);+ const context = options.result.value.large_value_context;+ return item?.sourceIndex === target.sourceIndex && snapshotReference(item, target.columnIndex) === target.valueRef && !!context && (["connectionId", "database", "clientSessionId", "txnSessionId", "catalog"] as const).every((key) => context[key] === target.context[key]);+ }++ async function downloadSnapshotTarget(target: LargeValueSnapshotDownloadTarget, filePath: string, downloadEncoding?: "binary" | "utf8" | "gbk"): Promise<void> {+ if (!isSnapshotDownloadTargetCurrent(target)) throw new Error("LOB result context changed");+ const executionId = options.uuid();+ snapshotExecutionIds.add(executionId);+ try {+ await waitForLargeValueSnapshot(api.downloadLargeValue({ ...target.context, valueRef: target.valueRef, executionId, downloadEncoding }, filePath, target.signal), target.signal);+ if (!isSnapshotDownloadTargetCurrent(target)) throw new Error("LOB result context changed");+ } finally {+ snapshotExecutionIds.delete(executionId);+ }+ }++ async function downloadSnapshotCell(rowId: number, columnIndex: number, filePath: string, downloadEncoding?: "binary" | "utf8" | "gbk"): Promise<void> {+ const target = captureSnapshotDownloadTarget(rowId, columnIndex);+ if (!target) throw new Error("LOB snapshot is unavailable");+ await downloadSnapshotTarget(target, filePath, downloadEncoding);}function formatGridItemCellForConfirmation(item: LargeValueRowItem, columnIndex: number): string {@@ -477,7 +552,14 @@ export function useDataGridLargeValues(options: UseDataGridLargeValuesOptions) {}async function resolveLargeValueCells(rowIds: number[], columnIndexes: number[]): Promise<ResolvedLargeValueCells> {+ const signal = snapshotController.signal;+ const sourceResult = options.result.value;+ const connectionId = options.connectionId.value;+ const executionDatabase = options.executionDatabase.value;+ const operation = options.resultLifecycle.beginOperation();+ const isCurrent = () => !signal.aborted && options.result.value === sourceResult && options.connectionId.value === connectionId && options.executionDatabase.value === executionDatabase && options.resultLifecycle.isCurrent(operation);const resolved: ResolvedLargeValueCells = new Map();+ let snapshotBytes = 0;const requestedColumns = new Set(columnIndexes);const requestsByColumn = new Map<number, LargeValueCellRequest[]>();for (const rowId of new Set(rowIds)) {@@ -487,6 +569,25 @@ export function useDataGridLargeValues(options: UseDataGridLargeValuesOptions) {if (!isLargeValuePreview(item, columnIndex)) continue;const metadata = largeValueCellsByKey.value.get(largeValueCellKey(item.sourceIndex, columnIndex));if (!metadata) continue;+ if (metadata.value_ref) {+ const context = sourceResult.large_value_context;+ if (!context || context.connectionId !== connectionId || context.database !== executionDatabase) {+ throw new Error("LOB result connection is unavailable; execute the query again");+ }+ const executionId = options.uuid();+ snapshotExecutionIds.add(executionId);+ try {+ const value = await materializeLargeValueSnapshot({ ...context, valueRef: metadata.value_ref, executionId }, isCurrent, signal);+ snapshotBytes += new TextEncoder().encode(value).length;+ if (snapshotBytes > 64 * 1024 * 1024) throw new Error("LOB selection exceeds the 64 MiB view/copy limit; use CSV/JSON export or download individual complete values");+ const rowValues = resolved.get(item.id) ?? new Map<number, CellValue>();+ rowValues.set(columnIndex, value);+ resolved.set(item.id, rowValues);+ } finally {+ snapshotExecutionIds.delete(executionId);+ }+ continue;+ }const requests = requestsByColumn.get(columnIndex) ?? [];requests.push({ item, sourceIndex: item.sourceIndex, columnIndex, originalBytes: metadata.original_bytes });requestsByColumn.set(columnIndex, requests);@@ -507,6 +608,7 @@ export function useDataGridLargeValues(options: UseDataGridLargeValuesOptions) {for (const [columnIndex, requests] of requestsByColumn) {for (const chunk of chunkLargeValueRequests(requests)) {await fetchLargeValueRequestChunk(columnIndex, chunk, primaryKeyIndexes, resolved);+ if (!isCurrent()) throw new Error("LOB result context changed");}}return resolved;@@ -545,6 +647,8 @@ export function useDataGridLargeValues(options: UseDataGridLargeValuesOptions) {if (!isLargeValuePreview(item, columnIndex) || item?.sourceIndex === undefined) return true;const sourceResult = options.result.value;const hydrationKey = largeValueCellKey(item.sourceIndex, columnIndex);+ const valueRef = largeValueCellsByKey.value.get(hydrationKey)?.value_ref;+ const ownsSnapshot = !!valueRef;const operation = options.resultLifecycle.beginOperation();return pendingLargeValueHydrations.run(hydrationKey, sourceResult, async () => {try {@@ -552,11 +656,17 @@ export function useDataGridLargeValues(options: UseDataGridLargeValuesOptions) {if (!options.resultLifecycle.isCurrent(operation) || options.result.value !== sourceResult) return false;const value = resolved.get(rowId)?.get(columnIndex);if (value === undefined && !resolved.get(rowId)?.has(columnIndex)) return false;- const row = [...(sourceResult.rows[item.sourceIndex!] ?? [])];- row[columnIndex] = value ?? null;- const rows = sourceResult.rows.slice();- rows[item.sourceIndex!] = row;- sourceResult.rows = rows;+ if (ownsSnapshot && typeof value === "string") {+ const sizes = materializedSnapshotBytes.get(sourceResult) ?? new Map<string, number>();+ const bytes = new TextEncoder().encode(value).length;+ const total = [...sizes.values()].reduce((sum, size) => sum + size, 0) - (sizes.get(hydrationKey) ?? 0) + bytes;+ if (total > 64 * 1024 * 1024) throw new Error("LOB result exceeds the 64 MiB view/edit limit; use CSV/JSON export or download individual complete values");+ sizes.set(hydrationKey, bytes);+ materializedSnapshotBytes.set(sourceResult, sizes);+ }+ // Keep row identity so loading another LOB does not clear pending edits or undo history.+ sourceResult.rows[item.sourceIndex!]![columnIndex] = value ?? null;+ if (valueRef) sourceResult.large_value_refs = [...new Set([...(sourceResult.large_value_refs ?? []), valueRef])];visibleLargeValuePreviewCaches.get(sourceResult)?.forget(item.sourceIndex!, columnIndex);sourceResult.large_value_cells = sourceResult.large_value_cells?.filter((cell) => cell.row_index !== item.sourceIndex || cell.column_index !== columnIndex);options.largeValueResolutionVersion.value += 1;@@ -570,7 +680,60 @@ export function useDataGridLargeValues(options: UseDataGridLargeValuesOptions) {});}+ async function prepareSaveBaseline(changes: { dirtyRows: ReadonlyMap<number, ReadonlyMap<number, CellValue>>; deletedRows: ReadonlySet<number> }): Promise<void> {+ const snapshotSignal = snapshotController.signal;+ const source = options.result.value;+ const cells = (source.large_value_cells ?? []).filter((cell) => cell.value_ref && (changes.deletedRows.has(cell.row_index) || changes.dirtyRows.get(cell.row_index)?.has(cell.column_index)));+ const context = source.large_value_context;+ const connectionId = options.connectionId.value;+ const database = options.executionDatabase.value;+ if ((cells.length || source.large_value_refs?.length) && (!context || context.connectionId !== connectionId || context.database !== database)) throw new Error("LOB result connection is unavailable; execute the query again");+ if (!cells.length) return;+ if (!context) throw new Error("LOB result connection is unavailable; execute the query again");+ const operation = options.resultLifecycle.beginOperation();+ const isCurrent = () => !snapshotSignal.aborted && options.result.value === source && options.connectionId.value === connectionId && options.executionDatabase.value === database && options.resultLifecycle.isCurrent(operation);+ const executionId = options.uuid();+ snapshotExecutionIds.add(executionId);+ try {+ const sizes = new Map(materializedSnapshotBytes.get(source));+ const rows = source.rows.map((row) => [...row]);+ for (const cell of cells) {+ const value = await materializeLargeValueSnapshot({ ...context, valueRef: cell.value_ref!, executionId }, isCurrent, snapshotSignal);+ if (!rows[cell.row_index] || cell.column_index >= rows[cell.row_index]!.length) throw new Error("LOB result column is unavailable");+ sizes.set(largeValueCellKey(cell.row_index, cell.column_index), new TextEncoder().encode(value).length);+ if ([...sizes.values()].reduce((sum, size) => sum + size, 0) > 64 * 1024 * 1024) throw new Error("LOB save baseline exceeds the 64 MiB view/edit limit; reload and edit a smaller selection");+ rows[cell.row_index]![cell.column_index] = value;+ }+ if (!isCurrent()) throw new Error("LOB result context changed");+ // Other consumers can hydrate another cell while these requests await.+ // Merge only the requested baselines into the latest rows and budget.+ const mergedSizes = new Map(materializedSnapshotBytes.get(source));+ for (const cell of cells) {+ if (!source.rows[cell.row_index] || cell.column_index >= source.rows[cell.row_index]!.length) throw new Error("LOB result column is unavailable");+ const key = largeValueCellKey(cell.row_index, cell.column_index);+ mergedSizes.set(key, sizes.get(key)!);+ }+ if ([...mergedSizes.values()].reduce((sum, size) => sum + size, 0) > 64 * 1024 * 1024) throw new Error("LOB save baseline exceeds the 64 MiB view/edit limit; reload and edit a smaller selection");+ source.large_value_refs = [...new Set([...(source.large_value_refs ?? []), ...cells.map((cell) => cell.value_ref!)])];+ const resolved = new Set(cells.map((cell) => largeValueCellKey(cell.row_index, cell.column_index)));+ // Preserve row identity so the editor keeps pending edits, deletes and undo history.+ for (const cell of cells) source.rows[cell.row_index]![cell.column_index] = rows[cell.row_index]![cell.column_index];+ source.large_value_cells = source.large_value_cells?.filter((cell) => !resolved.has(largeValueCellKey(cell.row_index, cell.column_index)));+ materializedSnapshotBytes.set(source, mergedSizes);+ options.largeValueResolutionVersion.value += 1;+ options.clearCellFormatCache();+ options.invalidateResultEstimate(source);+ } finally {+ snapshotExecutionIds.delete(executionId);+ }+ }+return {+ snapshotReference,+ captureSnapshotDownloadTarget,+ isSnapshotDownloadTargetCurrent,+ downloadSnapshotTarget,+ downloadSnapshotCell,isLargeValuePreview,largeValueOriginalBytes,formatGridItemCell,@@ -578,6 +741,7 @@ export function useDataGridLargeValues(options: UseDataGridLargeValuesOptions) {visibleLargeValuePreviewValue,resolveLargeValueCells,hydrateLargeValueCell,+ prepareSaveBaseline,invalidateVisibleLargeValuePreviewCell,scheduleVisibleLargeValuePreviewHydration,reportLargeValueLoadError,diff --git a/apps/desktop/src/i18n/locales/en.ts b/apps/desktop/src/i18n/locales/en.tsindex d6a32c0069..4620f83bd5 100644--- a/apps/desktop/src/i18n/locales/en.ts+++ b/apps/desktop/src/i18n/locales/en.ts@@ -2911,6 +2911,8 @@ export default {binaryImportFailed: "Failed to import file: {message}",binaryImportTooLarge: "File is too large ({size}, limit {limit}). Importing large files into a single cell is not supported.",downloadBinaryValue: "Download Value",+ downloadSnapshotValue: "Download complete result snapshot",+ largeValueSnapshotPreview: "{value} (result snapshot preview)",downloadSaved: "Saved to {path}",downloadStarted: "Download started: {fileName}",binaryDownload: {diff --git a/apps/desktop/src/i18n/locales/es.ts b/apps/desktop/src/i18n/locales/es.tsindex 802e113eb7..eea97407e2 100644--- a/apps/desktop/src/i18n/locales/es.ts+++ b/apps/desktop/src/i18n/locales/es.ts@@ -2716,6 +2716,8 @@ export default withEnglishFallback({largeValueLocalSortUnavailable: "Esta columna contiene vistas previas de valores grandes y no se puede ordenar localmente por su contenido. Use la ordenación de la base de datos.",copyValue: "Copiar valor",downloadBinaryValue: "Descargar valor",+ downloadSnapshotValue: "Descargar la instantánea completa del resultado",+ largeValueSnapshotPreview: "{value} (vista previa de la instantánea del resultado)",downloadSaved: "Guardado en {path}",downloadStarted: "Descarga iniciada: {fileName}",binaryDownload: {diff --git a/apps/desktop/src/i18n/locales/it.ts b/apps/desktop/src/i18n/locales/it.tsindex 1df6e2f5a8..33c169edbe 100644--- a/apps/desktop/src/i18n/locales/it.ts+++ b/apps/desktop/src/i18n/locales/it.ts@@ -2610,6 +2610,8 @@ export default withEnglishFallback({largeValueLocalSortUnavailable: "Questa colonna contiene anteprime di valori di grandi dimensioni e non può essere ordinata localmente in base all'anteprima. Usa l'ordinamento del database.",copyValue: "Copia Valore",downloadBinaryValue: "Scarica Valore",+ downloadSnapshotValue: "Scarica l'istantanea completa del risultato",+ largeValueSnapshotPreview: "{value} (anteprima dell'istantanea del risultato)",downloadSaved: "Salvato in {path}",downloadStarted: "Download avviato: {fileName}",binaryDownload: {diff --git a/apps/desktop/src/i18n/locales/ja.ts b/apps/desktop/src/i18n/locales/ja.tsindex 0c7af30821..8a7342a951 100644--- a/apps/desktop/src/i18n/locales/ja.ts+++ b/apps/desktop/src/i18n/locales/ja.ts@@ -2615,6 +2615,8 @@ export default withEnglishFallback({largeValueLocalSortUnavailable: "この列には大きな値のプレビューが含まれるため、プレビュー内容による現在のページの並べ替えはできません。データベース並べ替えを使用してください。",copyValue: "値をコピー",downloadBinaryValue: "値をダウンロード",+ downloadSnapshotValue: "結果の完全なスナップショットをダウンロード",+ largeValueSnapshotPreview: "{value}(結果スナップショットのプレビュー)",downloadSaved: "{path} に保存しました",downloadStarted: "ダウンロード開始: {fileName}",binaryDownload: {diff --git a/apps/desktop/src/i18n/locales/ko.ts b/apps/desktop/src/i18n/locales/ko.tsindex d4e2f40c3b..60b211e770 100644--- a/apps/desktop/src/i18n/locales/ko.ts+++ b/apps/desktop/src/i18n/locales/ko.ts@@ -2655,6 +2655,8 @@ export default withEnglishFallback({largeValueLocalSortUnavailable: "이 열에는 큰 값 미리보기가 포함되어 있어 미리보기 내용으로 현재 페이지를 정렬할 수 없습니다. 데이터베이스 정렬을 사용하세요.",copyValue: "값 복사",downloadBinaryValue: "값 다운로드",+ downloadSnapshotValue: "전체 결과 스냅샷 다운로드",+ largeValueSnapshotPreview: "{value} (결과 스냅샷 미리보기)",binaryImportTooLarge: "파일이 너무 큽니다({size}, 상한 {limit}). 큰 파일을 단일 셀에 가져오는 것은 지원되지 않습니다.",downloadSaved: "{path}에 저장됨",downloadStarted: "다운로드 시작됨: {fileName}",diff --git a/apps/desktop/src/i18n/locales/pt-BR.ts b/apps/desktop/src/i18n/locales/pt-BR.tsindex baba8b1237..ade7fecc8a 100644--- a/apps/desktop/src/i18n/locales/pt-BR.ts+++ b/apps/desktop/src/i18n/locales/pt-BR.ts@@ -2610,6 +2610,8 @@ export default withEnglishFallback({largeValueLocalSortUnavailable: "Esta coluna contém visualizações de valores grandes e não pode ser ordenada localmente pelo conteúdo da visualização. Use a ordenação do banco de dados.",copyValue: "Copiar Valor",downloadBinaryValue: "Baixar Valor",+ downloadSnapshotValue: "Baixar o snapshot completo do resultado",+ largeValueSnapshotPreview: "{value} (prévia do snapshot do resultado)",downloadSaved: "Salvo em {path}",downloadStarted: "Download iniciado: {fileName}",binaryDownload: {diff --git a/apps/desktop/src/i18n/locales/ru.ts b/apps/desktop/src/i18n/locales/ru.tsindex 9802ddfc92..ff35d3be31 100644--- a/apps/desktop/src/i18n/locales/ru.ts+++ b/apps/desktop/src/i18n/locales/ru.ts@@ -2795,6 +2795,8 @@ export default withEnglishFallback({binaryImportFailed: "Не удалось импортировать файл: {message}",binaryImportTooLarge: "Файл слишком большой ({size}, предел {limit}). Импорт больших файлов в одну ячейку не поддерживается.",downloadBinaryValue: "Скачать значение",+ downloadSnapshotValue: "Скачать полный снимок результата",+ largeValueSnapshotPreview: "{value} (предпросмотр снимка результата)",downloadSaved: "Сохранено в {path}",downloadStarted: "Скачивание начато: {fileName}",binaryDownload: {diff --git a/apps/desktop/src/i18n/locales/zh-CN.ts b/apps/desktop/src/i18n/locales/zh-CN.tsindex b9ef121c28..a5feef39f8 100644--- a/apps/desktop/src/i18n/locales/zh-CN.ts+++ b/apps/desktop/src/i18n/locales/zh-CN.ts@@ -2846,6 +2846,8 @@ export default withEnglishFallback({binaryImportFailed: "导入文件失败:{message}",binaryImportTooLarge: "文件过大({size},上限 {limit})。不支持将大文件导入到单个单元格。",downloadBinaryValue: "下载值",+ downloadSnapshotValue: "下载完整结果快照",+ largeValueSnapshotPreview: "{value}(结果快照预览)",downloadSaved: "已保存到 {path}",downloadStarted: "已交给浏览器下载:{fileName}",binaryDownload: {diff --git a/apps/desktop/src/i18n/locales/zh-TW.ts b/apps/desktop/src/i18n/locales/zh-TW.tsindex f34eaab44e..5f1590c286 100644--- a/apps/desktop/src/i18n/locales/zh-TW.ts+++ b/apps/desktop/src/i18n/locales/zh-TW.ts@@ -2615,6 +2615,8 @@ export default withEnglishFallback({binaryImportFailed: "匯入檔案失敗:{message}",binaryImportTooLarge: "檔案過大({size},上限 {limit})。不支援將大檔案匯入到單一儲存格。",downloadBinaryValue: "下載值",+ downloadSnapshotValue: "下載完整結果快照",+ largeValueSnapshotPreview: "{value}(結果快照預覽)",downloadSaved: "已儲存到 {path}",downloadStarted: "已交給瀏覽器下載:{fileName}",binaryDownload: {diff --git a/apps/desktop/src/lib/__tests__/dataGrid/largeValueSnapshot.spec.ts b/apps/desktop/src/lib/__tests__/dataGrid/largeValueSnapshot.spec.tsnew file mode 100644index 0000000000..a1656ef4b0--- /dev/null+++ b/apps/desktop/src/lib/__tests__/dataGrid/largeValueSnapshot.spec.ts@@ -0,0 +1,88 @@+import { beforeEach, describe, expect, it, vi } from "vitest";+const mocks = vi.hoisted(() => ({ readLargeValueChunk: vi.fn() }));+vi.mock("@/lib/backend/api", () => mocks);+import { materializeLargeValueSnapshot, materializeSnapshotResultRows, readLargeValueSnapshot } from "@/lib/dataGrid/largeValueSnapshot";++const request = { connectionId: "ob", database: "APP", clientSessionId: "tab-original", valueRef: "original-ref" };+const response = (data: string, next_offset: number, eof = false) => ({ status: "ok", data, next_offset, eof, value_kind: "text" });+beforeEach(() => mocks.readLargeValueChunk.mockReset());++describe("original-result LOB snapshot consumption", () => {+ it("preserves every binary byte and prefixes the assembled value exactly once", async () => {+ const hex = Array.from({ length: 256 }, (_, index) => index.toString(16).padStart(2, "0")).join("");+ mocks.readLargeValueChunk.mockResolvedValueOnce({ ...response(hex.slice(0, 200), 100), value_kind: "binary" }).mockResolvedValueOnce({ ...response(hex.slice(200), 256, true), value_kind: "binary" });+ expect(await materializeLargeValueSnapshot(request, () => true)).toBe("0x" + hex);+ });++ it("distinguishes an empty BLOB from a zero byte and rejects malformed or incomplete hex", async () => {+ mocks.readLargeValueChunk.mockResolvedValueOnce({ ...response("", 0, true), value_kind: "binary" });+ expect(await materializeLargeValueSnapshot(request, () => true)).toBe("0x");+ mocks.readLargeValueChunk.mockResolvedValueOnce({ ...response("00", 1, true), value_kind: "binary" });+ expect(await materializeLargeValueSnapshot(request, () => true)).toBe("0x00");+ mocks.readLargeValueChunk.mockResolvedValueOnce({ ...response("0", 1, true), value_kind: "binary" });+ await expect(materializeLargeValueSnapshot(request, () => true)).rejects.toThrow("binary encoding");+ });+ it("uses server character offsets and preserves Chinese and emoji across chunks", async () => {+ mocks.readLargeValueChunk.mockResolvedValueOnce(response("中文😀", 3)).mockResolvedValueOnce(response("末尾😀", 6, true));+ expect(await materializeLargeValueSnapshot(request, () => true)).toBe("中文😀末尾😀");+ expect(mocks.readLargeValueChunk.mock.calls.map(([args]) => args.offset)).toEqual([0, 3]);+ expect(mocks.readLargeValueChunk.mock.calls[1]?.[0]).toMatchObject({ valueRef: "original-ref", clientSessionId: "tab-original" });+ });++ it("refuses an expired original locator without returning a preview or re-querying a row", async () => {+ mocks.readLargeValueChunk.mockResolvedValue({ ...response("", 0), status: "expired" });+ await expect(materializeLargeValueSnapshot(request, () => true)).rejects.toThrow("expired");+ expect(mocks.readLargeValueChunk).toHaveBeenCalledTimes(1);+ });++ it("rejects changed context after await before any consumer sees the value", async () => {+ let current = true;+ mocks.readLargeValueChunk.mockImplementation(async () => {+ current = false;+ return response("wrong context", 1, true);+ });+ const consume = vi.fn();+ await expect(readLargeValueSnapshot(request, () => current, consume)).rejects.toThrow("context changed");+ expect(consume).not.toHaveBeenCalled();+ });++ it("rejects non-progressing chunks instead of looping or copying partial data", async () => {+ mocks.readLargeValueChunk.mockResolvedValue(response("prefix", 0));+ await expect(materializeLargeValueSnapshot(request, () => true)).rejects.toThrow("offset");+ expect(mocks.readLargeValueChunk).toHaveBeenCalledTimes(1);+ });++ it("rejects expiry between chunks without returning the already fetched prefix", async () => {+ mocks.readLargeValueChunk.mockResolvedValueOnce(response("前缀😀", 3)).mockResolvedValueOnce({ ...response("", 3), status: "expired" });+ await expect(materializeLargeValueSnapshot(request, () => true)).rejects.toThrow("expired");+ expect(mocks.readLargeValueChunk).toHaveBeenCalledTimes(2);+ });++ it("validates character offsets rather than UTF-16 length", async () => {+ mocks.readLargeValueChunk.mockResolvedValue(response("😀", 2, true));+ await expect(materializeLargeValueSnapshot(request, () => true)).rejects.toThrow("character count");+ });++ it("uses each export result's original connection and column identity and leaves previews untouched", async () => {+ const result = {+ columns: ["Payload", "PAYLOAD"],+ column_types: ["CLOB", "CLOB"],+ rows: [["a-preview", "b-preview"]],+ affected_rows: 0,+ execution_time_ms: 0,+ large_value_cells: [{ row_index: 0, column_index: 1, original_bytes: 0, value_ref: "uppercase-column-ref" }],+ large_value_context: { connectionId: "other-ob", database: "OTHER", txnSessionId: "original-transaction" },+ };+ mocks.readLargeValueChunk.mockResolvedValue(response("完整😀", 3, true));+ expect(await materializeSnapshotResultRows(result, () => true)).toEqual([["a-preview", "完整😀"]]);+ expect(result.rows).toEqual([["a-preview", "b-preview"]]);+ expect(mocks.readLargeValueChunk).toHaveBeenCalledWith(+ expect.objectContaining({+ connectionId: "other-ob",+ database: "OTHER",+ txnSessionId: "original-transaction",+ valueRef: "uppercase-column-ref",+ }),+ );+ });+});diff --git a/apps/desktop/src/lib/__tests__/dataGrid/snapshotExport.spec.ts b/apps/desktop/src/lib/__tests__/dataGrid/snapshotExport.spec.tsnew file mode 100644index 0000000000..a676633bd9--- /dev/null+++ b/apps/desktop/src/lib/__tests__/dataGrid/snapshotExport.spec.ts@@ -0,0 +1,61 @@+import { describe, expect, it } from "vitest";+import { snapshotExportSelection, assertSnapshotXlsxCellLengths } from "@/lib/dataGrid/snapshotExport";+import type { QueryResult } from "@/types/database";++const result = {+ columns: ["ID", "Value", "value"],+ rows: [+ [1, "first preview", "second preview"],+ [2, "third preview", null],+ ],+ large_value_context: { connectionId: "original", database: "oracletest", clientSessionId: "original-session" },+ large_value_cells: [+ { row_index: 0, column_index: 1, value_ref: "first", value_kind: "text" },+ { row_index: 0, column_index: 2, value_ref: "second", value_kind: "text" },+ { row_index: 1, column_index: 1, value_ref: "third", value_kind: "text" },+ ],+} as QueryResult;++describe("snapshot export selection", () => {+ it("refuses XLSX truncation while retaining the complete value for other formats", () => {+ expect(() => assertSnapshotXlsxCellLengths([["a".repeat(32767)]])).not.toThrow();+ const value = "中🙂".repeat(20000);+ expect(() => assertSnapshotXlsxCellLengths([[value]])).toThrow("XLSX cannot preserve");+ expect(Array.from(value)).toHaveLength(40000);+ });+ it("remaps sorted rows and projected quoted columns by source positions", () => {+ const selected = snapshotExportSelection(+ result,+ ["value", "Value"],+ [2, 1],+ [+ { sourceIndex: 1, data: [null, "third preview"] },+ { sourceIndex: 0, data: ["second preview", "first preview"] },+ ],+ )!;+ expect(selected.cells).toEqual([+ { rowIndex: 0, columnIndex: 1, valueRef: "third" },+ { rowIndex: 1, columnIndex: 0, valueRef: "second" },+ { rowIndex: 1, columnIndex: 1, valueRef: "first" },+ ]);+ expect(selected.context).toEqual({ ...result.large_value_context, valueRef: "" });+ });+ it("preserves complete dirty values and new rows rather than substituting their original snapshots", () => {+ const selected = snapshotExportSelection(+ result,+ ["Value", "value"],+ [1, 2],+ [+ { sourceIndex: 0, data: ["edited complete", "second preview"], isDirtyCol: [true, false] },+ { isNew: true, data: ["new complete", "other complete"] },+ ],+ )!;+ expect(selected.cells).toEqual([{ rowIndex: 0, columnIndex: 1, valueRef: "second" }]);+ expect(selected.rows[0]![0]).toBe("edited complete");+ expect(result.rows[0]![1]).toBe("first preview");+ });+ it("fails before export when original connection context is missing", () => {+ expect(() => snapshotExportSelection({ ...result, large_value_context: undefined }, ["Value"], [1], [{ sourceIndex: 0, data: ["preview"] }])).toThrow("connection is unavailable");+ expect(snapshotExportSelection(result, ["ID"], [0], [{ sourceIndex: 0, data: [1] }])).toBeUndefined();+ });+});diff --git a/apps/desktop/src/lib/backend/__tests__/largeValueDownload.spec.ts b/apps/desktop/src/lib/backend/__tests__/largeValueDownload.spec.tsnew file mode 100644index 0000000000..1fcfcf16f4--- /dev/null+++ b/apps/desktop/src/lib/backend/__tests__/largeValueDownload.spec.ts@@ -0,0 +1,68 @@+// @vitest-environment happy-dom+import { afterEach, expect, it, vi } from "vitest";+import { downloadLargeValue, exportSnapshotResult } from "../http";++afterEach(() => {+ vi.restoreAllMocks();+ vi.unstubAllGlobals();+});++it("does not deliver a late snapshot export after local cancellation", async () => {+ let release!: (response: Response) => void;+ vi.stubGlobal(+ "fetch",+ vi.fn(+ () =>+ new Promise<Response>((resolve) => {+ release = resolve;+ }),+ ),+ );+ const click = vi.spyOn(HTMLAnchorElement.prototype, "click").mockImplementation(() => undefined);+ const controller = new AbortController();+ const pending = exportSnapshotResult({ context: { connectionId: "ob", database: "APP", valueRef: "locator" }, format: "json", columns: ["C"], rows: [["preview"]], cells: [{ rowIndex: 0, columnIndex: 0, valueRef: "locator" }] }, "snapshot.json", controller.signal);+ controller.abort(new Error("cancelled locally"));+ const outcome = pending.then(+ () => "delivered",+ () => "cancelled",+ );+ release(new Response(JSON.stringify({ downloadId: "prepared" }), { status: 200, headers: { "Content-Type": "application/json" } }));+ expect(await outcome).toBe("cancelled");+ expect(click).not.toHaveBeenCalled();+});++it("delivers an uncancelled browser download with the original filename", async () => {+ const fetch = vi.fn().mockResolvedValue(new Response(JSON.stringify({ downloadId: "prepared" }), { status: 200, headers: { "Content-Type": "application/json" } }));+ vi.stubGlobal("fetch", fetch);+ const filenames: string[] = [];+ vi.spyOn(HTMLAnchorElement.prototype, "click").mockImplementation(function (this: HTMLAnchorElement) {+ filenames.push(this.download);+ });+ await downloadLargeValue({ connectionId: "ob", database: "APP", valueRef: "locator" }, "lob.bin", new AbortController().signal);+ expect(filenames).toEqual(["lob.bin"]);+ expect(JSON.parse(fetch.mock.calls[0]![1].body)).toEqual({ request: { connectionId: "ob", database: "APP", valueRef: "locator" }, fileName: "lob.bin" });+});++it("does not deliver a browser download when cancelled while the server prepares it", async () => {+ let release!: (response: Response) => void;+ vi.stubGlobal(+ "fetch",+ vi.fn(+ () =>+ new Promise<Response>((resolve) => {+ release = resolve;+ }),+ ),+ );+ const click = vi.spyOn(HTMLAnchorElement.prototype, "click").mockImplementation(() => undefined);+ const controller = new AbortController();+ const pending = downloadLargeValue({ connectionId: "ob", database: "APP", valueRef: "locator" }, "lob.bin", controller.signal);+ controller.abort(new Error("cancelled locally"));+ const outcome = pending.then(+ () => "delivered",+ () => "cancelled",+ );+ release(new Response(JSON.stringify({ downloadId: "prepared" }), { status: 200, headers: { "Content-Type": "application/json" } }));+ expect(await outcome).toBe("cancelled");+ expect(click).not.toHaveBeenCalled();+});diff --git a/apps/desktop/src/lib/backend/api.ts b/apps/desktop/src/lib/backend/api.tsindex 11d9b61d58..8ff9ccd016 100644--- a/apps/desktop/src/lib/backend/api.ts+++ b/apps/desktop/src/lib/backend/api.ts@@ -282,6 +282,10 @@ export const cancelQuery = forward("cancelQuery");export const cancelQueryAndWait = forward("cancelQueryAndWait");export const cancelConditionalUpdate = forward("cancelConditionalUpdate");export const closeQuerySession = forward("closeQuerySession");+export const readLargeValueChunk = forward("readLargeValueChunk");+export const releaseLargeValue = forward("releaseLargeValue");+export const downloadLargeValue = forward("downloadLargeValue");+export const exportSnapshotResult = forward("exportSnapshotResult");export const closeClientConnectionSession = forward("closeClientConnectionSession");export const analyzeSqlReferences = forward("analyzeSqlReferences");export const findStatementAtCursor = forward("findStatementAtCursor");diff --git a/apps/desktop/src/lib/backend/http.ts b/apps/desktop/src/lib/backend/http.tsindex 0b511ce326..4902a1fc6c 100644--- a/apps/desktop/src/lib/backend/http.ts+++ b/apps/desktop/src/lib/backend/http.ts@@ -272,7 +272,7 @@ import type {PluginTrustedKey,PluginUiAssetPayload,} from "@/types/database";-import type { DataGridSavePreparation } from "@/lib/backend/tauri";+import type { BlobBoundStatement, DataGridSavePreparation } from "@/lib/backend/tauri";import type {NacosBatchPreview,NacosBatchReport,@@ -1594,6 +1594,67 @@ export async function executeMultiWithProgress(return results;}+export interface LargeValueRequest {+ connectionId: string;+ database: string;+ valueRef: string;+ offset?: number;+ limit?: number;+ executionId?: string;+ clientSessionId?: string;+ catalog?: string;+ txnSessionId?: string;+ downloadEncoding?: "binary" | "utf8" | "gbk";+}++export interface LargeValueChunk {+ status: string;+ data: string;+ next_offset: number;+ eof: boolean;+ value_kind: "text" | "binary";+}++export async function readLargeValueChunk(request: LargeValueRequest): Promise<LargeValueChunk> {+ return post("/api/query/large-value/chunk", request);+}++export async function releaseLargeValue(request: LargeValueRequest): Promise<boolean> {+ return post("/api/query/large-value/release", request);+}++export async function downloadLargeValue(request: LargeValueRequest, filePath: string, signal?: AbortSignal): Promise<void> {+ signal?.throwIfAborted();+ const fileName = filePath.split(/[\\/]/).pop() || "lob.txt";+ const prepared = await post<{ downloadId: string }>("/api/query/large-value/download", { request, fileName });+ signal?.throwIfAborted();+ const anchor = document.createElement("a");+ anchor.href = apiUrl(`/api/query/large-value/download/${encodeURIComponent(prepared.downloadId)}`);+ anchor.download = fileName;+ anchor.click();+}++export interface SnapshotExportRequest {+ context: LargeValueRequest;+ format: "csv" | "json";+ columns: string[];+ rows: unknown[][];+ cells: Array<{ rowIndex: number; columnIndex: number; valueRef: string }>;+ quoteMode?: "all" | "necessary";+ nullLiteral?: string | null;+}++export async function exportSnapshotResult(request: SnapshotExportRequest, filePath: string, signal?: AbortSignal): Promise<void> {+ signal?.throwIfAborted();+ const fileName = filePath.split(/[\\/]/).pop() || `result.${request.format}`;+ const prepared = await post<{ downloadId: string }>("/api/query/large-value/export", { request, fileName });+ signal?.throwIfAborted();+ const anchor = document.createElement("a");+ anchor.href = apiUrl(`/api/query/large-value/download/${encodeURIComponent(prepared.downloadId)}`);+ anchor.download = fileName;+ anchor.click();+}+export async function closeQuerySession(connectionId: string, database: string, sessionId: string, clientSessionId?: string, catalog?: string): Promise<boolean> {return post("/api/query/close-session", {connectionId,@@ -1613,7 +1674,7 @@ export async function closeClientConnectionSession(connectionId: string, databas});}-export async function executeBatch(connectionId: string, database: string, statements: string[], schema?: string, timeoutSecs?: number, useTransaction?: boolean): Promise<QueryResult> {+export async function executeBatch(connectionId: string, database: string, statements: string[], schema?: string, timeoutSecs?: number, useTransaction?: boolean, boundStatements?: BlobBoundStatement[]): Promise<QueryResult> {return post("/api/query/execute-batch", {connectionId,database,@@ -1621,6 +1682,7 @@ export async function executeBatch(connectionId: string, database: string, stateschema,timeoutSecs,useTransaction,+ boundStatements,});}@@ -1643,13 +1705,14 @@ export async function executeScriptWith2pc(connectionId: string, database: strin});}-export async function executeInTransaction(connectionId: string, database: string, statements: string[], schema?: string, catalog?: string): Promise<QueryResult> {+export async function executeInTransaction(connectionId: string, database: string, statements: string[], schema?: string, catalog?: string, boundStatements?: BlobBoundStatement[]): Promise<QueryResult> {return post("/api/query/execute-in-transaction", {connectionId,database,statements,schema,catalog,+ boundStatements,});}@@ -1669,6 +1732,7 @@ export async function executeInManualTransaction(_classificationSql?: string,_executionId?: string,_timeoutSecs?: number,+ _boundStatements?: BlobBoundStatement[],): Promise<QueryResult[]> {throw new Error("Manual transaction management is only available in the desktop app.");}diff --git a/apps/desktop/src/lib/backend/tauri.ts b/apps/desktop/src/lib/backend/tauri.tsindex c2c36ced6e..61ccfc1e94 100644--- a/apps/desktop/src/lib/backend/tauri.ts+++ b/apps/desktop/src/lib/backend/tauri.ts@@ -2032,6 +2032,27 @@ export async function cancelConditionalUpdate(executionId: string): Promise<Condreturn invoke("cancel_conditional_update", { executionId });}+export async function readLargeValueChunk(request: import("./http").LargeValueRequest): Promise<import("./http").LargeValueChunk> {+ return invoke("read_large_value_chunk", { request });+}++export async function releaseLargeValue(request: import("./http").LargeValueRequest): Promise<boolean> {+ return invoke("release_large_value", { request });+}++export async function downloadLargeValue(request: import("./http").LargeValueRequest, filePath: string, signal?: AbortSignal): Promise<void> {+ signal?.throwIfAborted();+ await invoke("download_large_value", { request, filePath });+ // A native command may already have persisted the file; this only retires its local caller.+ signal?.throwIfAborted();+}++export async function exportSnapshotResult(request: import("./http").SnapshotExportRequest, filePath: string, signal?: AbortSignal): Promise<void> {+ signal?.throwIfAborted();+ await invoke("export_snapshot_result", { request, filePath });+ signal?.throwIfAborted();+}+export async function closeQuerySession(connectionId: string, database: string, sessionId: string, clientSessionId?: string, catalog?: string): Promise<boolean> {return invoke("close_query_session", {connectionId,@@ -2051,7 +2072,7 @@ export async function closeClientConnectionSession(connectionId: string, databas});}-export async function executeBatch(connectionId: string, database: string, statements: string[], schema?: string, timeoutSecs?: number, useTransaction?: boolean): Promise<QueryResult> {+export async function executeBatch(connectionId: string, database: string, statements: string[], schema?: string, timeoutSecs?: number, useTransaction?: boolean, boundStatements?: BlobBoundStatement[]): Promise<QueryResult> {return invoke("execute_batch", {connectionId,database,@@ -2059,6 +2080,7 @@ export async function executeBatch(connectionId: string, database: string, stateschema,timeoutSecs,useTransaction,+ boundStatements,});}@@ -2076,13 +2098,14 @@ export async function executeScriptWith2pc(connectionId: string, database: strin});}-export async function executeInTransaction(connectionId: string, database: string, statements: string[], schema?: string, catalog?: string): Promise<QueryResult> {+export async function executeInTransaction(connectionId: string, database: string, statements: string[], schema?: string, catalog?: string, boundStatements?: BlobBoundStatement[]): Promise<QueryResult> {return invoke("execute_in_transaction", {connectionId,database,statements,schema,catalog,+ boundStatements,});}@@ -2102,6 +2125,7 @@ export async function executeInManualTransaction(classificationSql?: string,executionId?: string,timeoutSecs?: number,+ boundStatements?: BlobBoundStatement[],): Promise<QueryResult[]> {return invokeBackend("execute_in_manual_transaction", {txnSessionId,@@ -2115,6 +2139,7 @@ export async function executeInManualTransaction(classificationSql,executionId,timeoutSecs,+ boundStatements,});}@@ -2383,12 +2408,19 @@ export interface DataGridSaveGuard {message: string;}+export interface BlobBoundStatement {+ previewSql: string;+ sql: string;+ blobParameters: string[];+}+export interface DataGridSavePreparation {validationError?: string;statements: string[];rollbackStatements: string[];executionSchema?: string;keylessGuards?: DataGridSaveGuard[];+ boundStatements?: BlobBoundStatement[];}export async function prepareDataGridSave(options: DataGridSaveStatementOptions, driverProfile?: string): Promise<DataGridSavePreparation> {diff --git a/apps/desktop/src/lib/dataGrid/columnFormatter.ts b/apps/desktop/src/lib/dataGrid/columnFormatter.tsindex 295065d0fc..00fda24f8e 100644--- a/apps/desktop/src/lib/dataGrid/columnFormatter.ts+++ b/apps/desktop/src/lib/dataGrid/columnFormatter.ts@@ -446,7 +446,7 @@ export function formatTemporalRowsForExport<T extends CellValue>(rows: readonlyif (!normalizedPattern) return rows.map((row) => [...row]);return rows.map((row) =>row.map((value, index) => {- if (!isTemporalColumnType(columnTypes[index])) return value;+ if (value === null || !isTemporalColumnType(columnTypes[index])) return value;return formatTemporalValueForExport(value, normalizedPattern) as T;}),);diff --git a/apps/desktop/src/lib/dataGrid/dataGridCopyExtractor.ts b/apps/desktop/src/lib/dataGrid/dataGridCopyExtractor.tsindex 8107715a4b..7a9f01ee8f 100644--- a/apps/desktop/src/lib/dataGrid/dataGridCopyExtractor.ts+++ b/apps/desktop/src/lib/dataGrid/dataGridCopyExtractor.ts@@ -109,6 +109,7 @@ export interface DataGridExtractColumn {displayName: string;sourceName?: string;sourceIndex: number;+ dataType?: string;}export interface DataGridExtractRequest {diff --git a/apps/desktop/src/lib/dataGrid/largeValueSnapshot.ts b/apps/desktop/src/lib/dataGrid/largeValueSnapshot.tsnew file mode 100644index 0000000000..41f00a4b6e--- /dev/null+++ b/apps/desktop/src/lib/dataGrid/largeValueSnapshot.ts@@ -0,0 +1,90 @@+import * as api from "@/lib/backend/api";+import type { LargeValueRequest, LargeValueChunk } from "@/lib/backend/http";+import type { QueryResult } from "@/types/database";++const MAX_MATERIALIZED_BYTES = 16 * 1024 * 1024;++/** Abort only ends local waiting; the caller separately requests server cancellation. */+export async function waitForLargeValueSnapshot<T>(promise: Promise<T>, signal?: AbortSignal): Promise<T> {+ if (!signal) return promise;+ let abort!: () => void;+ try {+ return await Promise.race([+ promise,+ new Promise<never>((_, reject) => {+ abort = () => reject(signal.reason ?? new Error("LOB reading cancelled locally"));+ if (signal.aborted) abort();+ else signal.addEventListener("abort", abort, { once: true });+ }),+ ]);+ } finally {+ signal.removeEventListener("abort", abort);+ }+}++/** No cache: every request validates the original server locator's lifecycle. */+export async function readLargeValueSnapshot(request: LargeValueRequest, isCurrent: () => boolean, consume: (chunk: LargeValueChunk) => Promise<void> | void, signal?: AbortSignal): Promise<void> {+ let offset = 0;+ while (true) {+ signal?.throwIfAborted();+ if (!isCurrent()) throw new Error("LOB result context changed");+ const chunk = await waitForLargeValueSnapshot(api.readLargeValueChunk({ ...request, offset, limit: 4096 }), signal);+ signal?.throwIfAborted();+ if (!isCurrent()) throw new Error("LOB result context changed");+ if (chunk.status !== "ok") throw new Error(`LOB snapshot ${chunk.status}; execute the query again`);+ if (typeof chunk.data !== "string" || typeof chunk.eof !== "boolean" || (chunk.value_kind !== "text" && chunk.value_kind !== "binary")) throw new Error("Invalid LOB chunk payload");+ if (!Number.isSafeInteger(chunk.next_offset) || chunk.next_offset < offset || (!chunk.eof && chunk.next_offset === offset)) {+ throw new Error("Invalid LOB chunk offset");+ }+ const amount = chunk.next_offset - offset;+ if (amount > 4096 || (chunk.value_kind === "text" && Array.from(chunk.data).length !== amount)) {+ throw new Error("Invalid LOB chunk character count");+ }+ if (chunk.value_kind === "binary" && (!/^(?:[0-9a-f]{2})*$/i.test(chunk.data) || chunk.data.length / 2 !== amount)) {+ throw new Error("Invalid LOB chunk binary encoding");+ }+ await consume(chunk);+ signal?.throwIfAborted();+ if (!isCurrent()) throw new Error("LOB result context changed");+ if (chunk.eof) return;+ offset = chunk.next_offset;+ }+}++export async function materializeLargeValueSnapshot(request: LargeValueRequest, isCurrent: () => boolean, signal?: AbortSignal): Promise<string> {+ const chunks: string[] = [];+ let bytes = 0;+ let kind: LargeValueChunk["value_kind"] | undefined;+ await readLargeValueSnapshot(+ request,+ isCurrent,+ (chunk) => {+ if (kind && kind !== chunk.value_kind) throw new Error("LOB chunk type changed");+ kind = chunk.value_kind;+ bytes += chunk.value_kind === "binary" ? chunk.data.length / 2 : new TextEncoder().encode(chunk.data).length;+ if (bytes > MAX_MATERIALIZED_BYTES) throw new Error("LOB exceeds the 16 MiB view/copy limit; download the complete value instead");+ chunks.push(chunk.data);+ },+ signal,+ );+ return (kind === "binary" ? "0x" : "") + chunks.join("");+}++export async function materializeSnapshotResultRows(result: QueryResult, isCurrent: () => boolean, signal?: AbortSignal, executionId?: string): Promise<QueryResult["rows"]> {+ const cells = result.large_value_cells ?? [];+ if (!cells.some((cell) => cell.value_ref)) return result.rows;+ const context = result.large_value_context;+ if (!context) throw new Error("LOB result connection is unavailable; execute the query again");+ const rows = result.rows.map((row) => [...row]);+ let totalBytes = 0;+ for (const cell of cells) {+ if (!cell.value_ref) throw new Error("This result includes a value without a snapshot reference");+ const value = await materializeLargeValueSnapshot({ ...context, valueRef: cell.value_ref, executionId }, isCurrent, signal);+ totalBytes += new TextEncoder().encode(value).length;+ if (totalBytes > 64 * 1024 * 1024) throw new Error("LOB result exceeds the 64 MiB export limit; download individual complete values");+ const row = rows[cell.row_index];+ if (!row || cell.column_index >= row.length) throw new Error("LOB result column is unavailable");+ row[cell.column_index] = value;+ }+ return rows;+}diff --git a/apps/desktop/src/lib/dataGrid/snapshotExport.ts b/apps/desktop/src/lib/dataGrid/snapshotExport.tsnew file mode 100644index 0000000000..e00a0d22ce--- /dev/null+++ b/apps/desktop/src/lib/dataGrid/snapshotExport.ts@@ -0,0 +1,38 @@+import type { QueryResult } from "@/types/database";+import type { SnapshotExportRequest } from "@/lib/backend/http";++interface SnapshotExportRow {+ sourceIndex?: number;+ data: unknown[];+ isNew?: boolean;+ isDirtyCol?: boolean[];+}++/** Projection uses source positions, never labels, so quoted and repeated names remain distinct. */+export function snapshotExportSelection(result: QueryResult, columns: string[], sourceColumns: number[], items: SnapshotExportRow[]): Pick<SnapshotExportRequest, "columns" | "rows" | "cells" | "context"> | undefined {+ const refs = new Map((result.large_value_cells ?? []).filter((cell) => cell.value_ref).map((cell) => [`${cell.row_index}:${cell.column_index}`, cell.value_ref!]));+ const cells: SnapshotExportRequest["cells"] = [];+ items.forEach((item, rowIndex) => {+ if (item.isNew || item.sourceIndex === undefined) return;+ sourceColumns.forEach((sourceColumn, columnIndex) => {+ if (item.isDirtyCol?.[columnIndex]) return;+ const valueRef = refs.get(`${item.sourceIndex}:${sourceColumn}`);+ if (valueRef) cells.push({ rowIndex, columnIndex, valueRef });+ });+ });+ if (!cells.length) return undefined;+ if (!result.large_value_context) throw new Error("LOB result connection is unavailable; execute the query again");+ return { columns, rows: items.map((item) => item.data), cells, context: { ...result.large_value_context, valueRef: "" } };+}++export function assertSnapshotXlsxCellLengths(rows: unknown[][]): void {+ for (const row of rows)+ for (const value of row) {+ if (typeof value !== "string") continue;+ let count = 0;+ for (const _character of value)+ if (++count > 32767) {+ throw new Error("XLSX cannot preserve a LOB longer than 32,767 characters; use CSV/JSON or download the complete value");+ }+ }+}diff --git a/apps/desktop/src/stores/__tests__/queryStore.lobSessionRelease.spec.ts b/apps/desktop/src/stores/__tests__/queryStore.lobSessionRelease.spec.tsnew file mode 100644index 0000000000..02aae274f3--- /dev/null+++ b/apps/desktop/src/stores/__tests__/queryStore.lobSessionRelease.spec.ts@@ -0,0 +1,178 @@+import { createPinia, setActivePinia } from "pinia";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import type { ConnectionConfig, QueryResult } from "@/types/database";++const api = vi.hoisted(() => ({+ executeMulti: vi.fn(),+ closeQuerySession: vi.fn(),+ closeClientConnectionSession: vi.fn(),+ cancelQuery: vi.fn(),+ disconnectDb: vi.fn(),+ releaseLargeValue: vi.fn(),+}));++vi.mock("@/lib/backend/api", () => ({+ ...api,+ checkConnectionHealth: vi.fn().mockResolvedValue(undefined),+ analyzeEditableQueryEditability: vi.fn().mockResolvedValue({ editable: false, reason: "complex-query" }),+ prepareQueryPaginationExecutionPlan: vi.fn(async (options) => ({ sqlToExecute: options.sql, pageSql: options.sql, pageLimit: options.pagination.limit, pageOffset: options.pagination.offset, useAgentResultSession: true })),+ saveOpenTabsState: vi.fn().mockResolvedValue(undefined),+ deleteSchemaCachePrefix: vi.fn().mockResolvedValue(undefined),+ loadSchemaCache: vi.fn().mockResolvedValue(null),+ saveConnections: vi.fn().mockResolvedValue(undefined),+ saveSidebarLayout: vi.fn().mockResolvedValue(undefined),+}));++function result(session: string): QueryResult {+ return { columns: ["PAYLOAD"], rows: [["LOB preview"]], affected_rows: 0, execution_time_ms: 1, session_id: session, has_more: true };+}++describe("query Store LOB session release through public close and disconnect", () => {+ afterEach(() => vi.unstubAllGlobals());++ beforeEach(() => {+ vi.clearAllMocks();+ vi.stubGlobal("localStorage", { getItem: vi.fn(() => null), setItem: vi.fn(), removeItem: vi.fn() });+ setActivePinia(createPinia());+ api.closeQuerySession.mockResolvedValue(undefined);+ api.closeClientConnectionSession.mockResolvedValue(undefined);+ api.cancelQuery.mockResolvedValue(true);+ api.disconnectDb.mockResolvedValue(undefined);+ api.releaseLargeValue.mockResolvedValue(true);+ });++ it("preserves locator ownership from hydrated earlier pages when appending", async () => {+ const { appendQueryResultSegment } = await import("@/stores/queryStore");+ const context = { connectionId: "ob-page", database: "SYS", clientSessionId: "original-session" };+ const previous = { ...result("session"), large_value_context: context, large_value_refs: ["hydrated-old"], large_value_cells: [{ row_index: 0, column_index: 0, original_bytes: 5000, value_ref: "old-preview" }] };+ const segment = { ...result("session"), large_value_refs: ["new"] };+ const combined = appendQueryResultSegment(previous, segment, 100);+ expect(combined.large_value_refs).toEqual(expect.arrayContaining(["hydrated-old", "old-preview", "new"]));+ expect(combined.large_value_context).toEqual(context);+ });++ it.each([false, true, "toggled"] as const)("releases discarded refs but retains captured results (capture=%s)", async (capture) => {+ const { useQueryStore } = await import("@/stores/queryStore");+ const { useConnectionStore } = await import("@/stores/connectionStore");+ const { useSettingsStore } = await import("@/stores/settingsStore");+ const connections = useConnectionStore();+ useSettingsStore().editorSettings.autoCalculateTotalRows = false;+ connections.connections = [{ id: "ob-refresh", name: "OB", db_type: "oceanbase-oracle", database: "SYS", read_only: false } as ConnectionConfig];+ connections.connectedIds.add("ob-refresh");+ const store = useQueryStore();+ const id = store.createTab("ob-refresh", "SYS", "LOB", "query", "APP");+ const context = { connectionId: "ob-refresh", database: "SYS", clientSessionId: "old-client" };+ api.executeMulti.mockResolvedValueOnce([{ ...result("old"), large_value_context: context, large_value_refs: ["old-ref"] }]).mockResolvedValueOnce([result("new")]);+ await store.executeTabSql(id, "SELECT PAYLOAD FROM LOB_FIXTURE");+ const tab = store.tabs.find((entry) => entry.id === id)!;+ if (capture === "toggled") {+ expect(store.toggleResultAutoSave(id)).toBe(true);+ expect(store.toggleResultAutoSave(id)).toBe(false);+ expect(tab.activeResultRunId).toBeTruthy();+ } else tab.resultAutoSave = capture;+ await store.executeTabSql(id, "SELECT PAYLOAD FROM LOB_FIXTURE");+ if (capture === true) expect(api.releaseLargeValue).not.toHaveBeenCalled();+ else await vi.waitFor(() => expect(api.releaseLargeValue).toHaveBeenCalledWith(expect.objectContaining({ connectionId: "ob-refresh", database: "SYS", valueRef: "old-ref" })));+ await store.flushPendingPersist();+ });++ it.each(["failed-append", "shared-result", "history"] as const)("retains old locators still used after an autosave toggle (%s)", async (scenario) => {+ const { useQueryStore } = await import("@/stores/queryStore");+ const { useConnectionStore } = await import("@/stores/connectionStore");+ const { useSettingsStore } = await import("@/stores/settingsStore");+ const connections = useConnectionStore();+ useSettingsStore().editorSettings.autoCalculateTotalRows = false;+ connections.connections = [{ id: "ob-retain", name: "OB", db_type: "oceanbase-oracle", database: "SYS", read_only: false } as ConnectionConfig];+ connections.connectedIds.add("ob-retain");+ const store = useQueryStore();+ const id = store.createTab("ob-retain", "SYS", "LOB", "query", "APP");+ const old = { ...result("old"), large_value_context: { connectionId: "ob-retain", database: "SYS", clientSessionId: "old-client" }, large_value_refs: ["old-ref"] };+ api.executeMulti.mockResolvedValueOnce([old]);+ await store.executeTabSql(id, "SELECT PAYLOAD FROM LOB_FIXTURE");+ store.toggleResultAutoSave(id);+ store.toggleResultAutoSave(id);+ const tab = store.tabs.find((entry) => entry.id === id)!;+ if (scenario === "history") tab.resultRuns!.push({ ...tab.resultRuns![0], id: "other-retained-run" });+ if (scenario === "failed-append") api.executeMulti.mockRejectedValueOnce(new Error("query failed"));+ else api.executeMulti.mockResolvedValueOnce([scenario === "shared-result" ? { ...old, rows: [["new preview"]] } : result("new")]);+ await store.executeTabSql(id, "SELECT PAYLOAD FROM LOB_FIXTURE", scenario === "failed-append" ? { appendResult: true } : undefined);+ await store.flushPendingPersist();+ expect(api.releaseLargeValue).not.toHaveBeenCalled();+ if (scenario === "failed-append") expect(tab.result?.large_value_refs).toContain("old-ref");+ else expect(tab.result?.rows).toEqual(scenario === "shared-result" ? [["new preview"]] : [["LOB preview"]]);+ });++ it.each(["closeTab", "disconnect"] as const)("%s closes the original result and client sessions without touching another connection", async (action) => {+ const { useQueryStore } = await import("@/stores/queryStore");+ const { useConnectionStore } = await import("@/stores/connectionStore");+ const { useSettingsStore } = await import("@/stores/settingsStore");+ const connections = useConnectionStore();+ const settings = useSettingsStore();+ settings.editorSettings.disconnectTabHandlingMode = "keep-tabs-clear-results";+ settings.editorSettings.autoCalculateTotalRows = false;+ connections.connections = ["ob-a", "ob-b"].map((id) => ({ id, name: id, db_type: "oceanbase-oracle", host: "localhost", port: 2881, username: "fixture", password: "", database: "SYS", read_only: false }) as ConnectionConfig);+ connections.connectedIds.add("ob-a");+ connections.connectedIds.add("ob-b");+ const store = useQueryStore();+ const id = store.createTab("ob-a", "SYS", "LOB", "query", "APP");+ const otherId = store.createTab("ob-b", "SYS", "Other", "query", "APP");+ api.executeMulti.mockResolvedValueOnce([result("result-a")]).mockResolvedValueOnce([result("result-b")]);+ await store.executeTabSql(id, "SELECT PAYLOAD FROM LOB_FIXTURE");+ await store.executeTabSql(otherId, "SELECT PAYLOAD FROM LOB_FIXTURE");+ const originalSession = api.executeMulti.mock.calls[0][5].clientSessionId;+ const otherSession = api.executeMulti.mock.calls[1][5].clientSessionId;+ expect(originalSession).toEqual(expect.any(String));+ expect(originalSession).not.toBe(otherSession);+ expect(store.tabs.find((tab) => tab.id === id)?.result?.rows).toEqual([["LOB preview"]]);+ if (action === "closeTab") store.closeTab(id, { force: true });+ else await connections.disconnect("ob-a");+ await vi.waitFor(() => expect(api.closeClientConnectionSession).toHaveBeenCalledWith("ob-a", "SYS", originalSession));+ expect(api.closeQuerySession).toHaveBeenCalledWith("ob-a", "SYS", "result-a", originalSession);+ expect(api.closeClientConnectionSession.mock.calls.every((call) => call[0] === "ob-a")).toBe(true);+ expect(api.closeQuerySession.mock.calls.every((call) => call[0] === "ob-a")).toBe(true);+ expect(store.tabs.find((tab) => tab.id === id)?.result).toBeUndefined();+ expect(store.tabs.find((tab) => tab.id === otherId)?.result?.rows).toEqual([["LOB preview"]]);+ if (action === "disconnect") {+ expect(api.disconnectDb).toHaveBeenCalledWith("ob-a", undefined);+ expect(connections.connectedIds.has("ob-a")).toBe(false);+ expect(connections.connectedIds.has("ob-b")).toBe(true);+ expect(store.tabs.some((tab) => tab.id === id)).toBe(true);+ }+ await store.flushPendingPersist();+ });++ it.each(["closeTab", "disconnect"] as const)("%s cannot be undone by a late query result", async (action) => {+ const { useQueryStore } = await import("@/stores/queryStore");+ const { useConnectionStore } = await import("@/stores/connectionStore");+ const { useSettingsStore } = await import("@/stores/settingsStore");+ const connections = useConnectionStore();+ useSettingsStore().editorSettings.disconnectTabHandlingMode = "keep-tabs-clear-results";+ useSettingsStore().editorSettings.autoCalculateTotalRows = false;+ connections.connections = [{ id: "ob-late", name: "OB", db_type: "oceanbase-oracle", host: "localhost", port: 2881, username: "fixture", password: "", database: "SYS", read_only: false } as ConnectionConfig];+ connections.connectedIds.add("ob-late");+ const store = useQueryStore();+ const id = store.createTab("ob-late", "SYS", "Pending LOB", "query", "APP");+ let finish!: (results: QueryResult[]) => void;+ api.executeMulti.mockImplementationOnce(+ () =>+ new Promise<QueryResult[]>((resolve) => {+ finish = resolve;+ }),+ );+ const executing = store.executeTabSql(id, "SELECT PAYLOAD FROM LOB_FIXTURE");+ await vi.waitFor(() => expect(api.executeMulti).toHaveBeenCalledTimes(1));+ const originalSession = api.executeMulti.mock.calls[0][5].clientSessionId;+ if (action === "closeTab") store.closeTab(id, { force: true });+ else await connections.disconnect("ob-late");+ await vi.waitFor(() => expect(api.closeClientConnectionSession).toHaveBeenCalledWith("ob-late", "SYS", originalSession));+ finish([result("late-result")]);+ await executing;+ expect(store.tabs.find((tab) => tab.id === id)?.result).toBeUndefined();+ expect(store.tabs.find((tab) => tab.id === id)?.resultSessionId).toBeUndefined();+ expect(store.tabs.find((tab) => tab.id === id)?.isExecuting ?? false).toBe(false);+ expect(api.cancelQuery).toHaveBeenCalled();+ if (action === "closeTab") expect(store.tabs.some((tab) => tab.id === id)).toBe(false);+ else expect(connections.connectedIds.has("ob-late")).toBe(false);+ await store.flushPendingPersist();+ });+});diff --git a/apps/desktop/src/stores/queryStore.ts b/apps/desktop/src/stores/queryStore.tsindex 978f122f53..f2ed1a1bf3 100644--- a/apps/desktop/src/stores/queryStore.ts+++ b/apps/desktop/src/stores/queryStore.ts@@ -383,6 +383,10 @@ export function appendQueryResultSegment(previous: QueryResult, segment: QueryRespatial_columns: spatial_columns.length > 0 ? spatial_columns : undefined,spatial_values: appendParallelValues(previous.spatial_values, segment.spatial_values),large_value_cells: appendLargeValueCells(previous.large_value_cells, segment.large_value_cells, previous.rows.length, appendedRowCount),+ large_value_context: segment.large_value_context ?? previous.large_value_context,+ large_value_refs: [+ ...new Set([...(previous.large_value_refs ?? []), ...(segment.large_value_refs ?? []), ...(previous.large_value_cells ?? []).flatMap((cell) => (cell.value_ref ? [cell.value_ref] : [])), ...(segment.large_value_cells ?? []).flatMap((cell) => (cell.value_ref ? [cell.value_ref] : []))]),+ ],mongo_documents: appendParallelValues(previous.mongo_documents, segment.mongo_documents),mongo_copy_documents: appendParallelValues(previous.mongo_copy_documents, segment.mongo_copy_documents),execution_time_ms: (previous.execution_time_ms ?? 0) + (segment.execution_time_ms ?? 0),@@ -855,7 +859,7 @@ function projectsAllColumnsForSource(analysis: EditableQueryInfo, sourceKey: str}function queryProjectsDeferredLob(databaseType: DatabaseType, analysis: EditableQueryInfo, sourceKey: string, columns: readonly { name: string; data_type: string }[]): boolean {- const deferredTypes = databaseType === "oracle" ? ORACLE_DEFERRED_LOB_TYPES : databaseType === "db2" ? DB2_DEFERRED_LOB_TYPES : undefined;+ const deferredTypes = databaseType === "oracle" || databaseType === "oceanbase-oracle" ? ORACLE_DEFERRED_LOB_TYPES : databaseType === "db2" ? DB2_DEFERRED_LOB_TYPES : undefined;if (!deferredTypes) return false;const deferredColumns = new Set(columns@@ -2071,6 +2075,7 @@ export const useQueryStore = defineStore("query", () => {if (!tab || !tab.resultRuns || runIndex < 0) return false;const removedRun = tab.resultRuns[runIndex];+ if (removedRun) void releaseResultLargeValues(removedRun.result, ...(removedRun.results ?? []));if (removedRun?.resultSessionId) void closeResultRunSession(tab, removedRun);if (removedRun?.resultCacheKey) void deleteTabResultSnapshot(removedRun.resultCacheKey);if (removedRun) clearResultRunPayload(removedRun);@@ -2100,9 +2105,10 @@ export const useQueryStore = defineStore("query", () => {if (!tab.result && !tab.results?.length && !tab.resultEvicted) return false;const closeSession = closeResultSession(tab);+ const releaseValues = releaseResultLargeValues(tab.result, ...(tab.results ?? []));releaseTabResultObjectPayloads(tab);clearResultPayload(tab);- await closeSession;+ await Promise.all([closeSession, releaseValues]);return true;}@@ -2117,8 +2123,10 @@ export const useQueryStore = defineStore("query", () => {const currentSessionId = tab.resultSessionId ?? tab.result?.session_id;if (currentSessionId) closedSessionIds.add(currentSessionId);const closeOperations = [closeResultSession(tab)];+ closeOperations.push(releaseResultLargeValues(tab.result, ...(tab.results ?? [])));for (const run of resultRuns) {+ closeOperations.push(releaseResultLargeValues(run.result, ...(run.results ?? [])));if (run.resultCacheKey) void deleteTabResultSnapshot(run.resultCacheKey);if (!run.resultSessionId || closedSessionIds.has(run.resultSessionId)) continue;closedSessionIds.add(run.resultSessionId);@@ -2136,6 +2144,34 @@ export const useQueryStore = defineStore("query", () => {return (tab.resultRuns?.reduce((max, run) => Math.max(max, run.sequence), 0) ?? 0) + 1;}+ function resultLargeValueKey(result: QueryResult, valueRef: string): string {+ const context = result.large_value_context;+ return JSON.stringify([context?.connectionId, context?.database, context?.clientSessionId, context?.txnSessionId, context?.catalog, valueRef]);+ }++ function resultLargeValueKeys(result?: QueryResult): string[] {+ if (!result?.large_value_context) return [];+ return [...(result.large_value_refs ?? []), ...(result.large_value_cells ?? []).flatMap((cell) => (cell.value_ref ? [cell.value_ref] : []))].map((ref) => resultLargeValueKey(result, ref));+ }++ async function releaseResultLargeValues(...results: Array<QueryResult | undefined>) {+ const released = new Set<string>();+ for (const result of results) {+ const context = result?.large_value_context;+ if (!context) continue;+ const refs = new Set([...(result.large_value_refs ?? []), ...(result.large_value_cells ?? []).flatMap((cell) => (cell.value_ref ? [cell.value_ref] : []))]);+ for (const valueRef of refs) {+ if (released.has(valueRef)) continue;+ released.add(valueRef);+ try {+ await api.releaseLargeValue({ ...context, valueRef });+ } catch (error) {+ console.warn("[DBX][large-value:release:error]", error);+ }+ }+ }+ }+async function closeResultRunSession(tab: QueryTab, run: NonNullable<QueryTab["resultRuns"]>[number]) {if (!run.resultSessionId) return;const target = run.multiDbExecution?.target;@@ -2338,6 +2374,7 @@ export const useQueryStore = defineStore("query", () => {if (!tab.activeResultRunId || !tab.resultRuns?.length) return;const index = tab.resultRuns.findIndex((run) => run.id === tab.activeResultRunId);if (index < 0) return;+ const previousRun = tab.resultRuns[index];const run = {...tab.resultRuns[index],...(sql ? { sql } : {}),@@ -2385,6 +2422,14 @@ export const useQueryStore = defineStore("query", () => {};void persistResultRun(tab, run);tab.resultRuns[index] = run;+ const retainedResults = [tab.result, ...(tab.results ?? []), ...tab.resultRuns.flatMap((item) => [item.result, ...(item.results ?? [])])];+ const retainedRefs = new Set(retainedResults.flatMap((result) => resultLargeValueKeys(result)));+ const discardedResults = [previousRun.result, ...(previousRun.results ?? [])].map((result) => {+ if (!result) return undefined;+ const refs = [...(result.large_value_refs ?? []), ...(result.large_value_cells ?? []).flatMap((cell) => (cell.value_ref ? [cell.value_ref] : []))];+ return { ...result, large_value_cells: [], large_value_refs: refs.filter((valueRef) => !retainedRefs.has(resultLargeValueKey(result, valueRef))) };+ });+ void releaseResultLargeValues(...discardedResults);}function syncDisplayedResultRun(tab: QueryTab, sql: string, captureNewRun = false, options: ResultRunCaptureOptions = {}) {@@ -6430,8 +6475,13 @@ export const useQueryStore = defineStore("query", () => {function buildHiddenPrimaryKeyPreparation(tab: QueryTab, sql: string, databaseType: DatabaseType, loaded: LoadedEditableSource, primaryKeys: string[], declaredPrimaryKeys: string[], traceId: string, elapsed: () => string): EditableQueryExecutionPreparation {const metadataAnalysis = expandStarProjectionColumnsForSource(bindColumnsForSource(databaseType, loaded.analysis, loaded.source, loaded.tableMeta.columns), loaded.source, loaded.tableMeta.columns);- const stableLobSource = databaseType === "oracle" ? oracleRowIdIsSafeForQuery(tab, loaded) : databaseType === "db2";- const largeValuePreview = (databaseType === "oracle" || databaseType === "db2") && primaryKeys.length > 0 && stableLobSource && columnsAllowDeferredLobMarkers(loaded.tableMeta.columns) && queryProjectsDeferredLob(databaseType, metadataAnalysis, loaded.source.key, loaded.tableMeta.columns);+ const stableLobSource = databaseType === "oracle" || databaseType === "oceanbase-oracle" ? oracleRowIdIsSafeForQuery(tab, loaded) : databaseType === "db2";+ const largeValuePreview =+ (databaseType === "oracle" || databaseType === "oceanbase-oracle" || databaseType === "db2") &&+ primaryKeys.length > 0 &&+ stableLobSource &&+ columnsAllowDeferredLobMarkers(loaded.tableMeta.columns) &&+ queryProjectsDeferredLob(databaseType, metadataAnalysis, loaded.source.key, loaded.tableMeta.columns);const unchanged = { sql, metadataSql: sql, hiddenPrimaryKeys: [], largeValuePreview };if (hasTopLevelKeyword(sql, ["GROUP", "HAVING"], databaseType)) return unchanged;const missingPrimaryKeys =@@ -7176,6 +7226,7 @@ export const useQueryStore = defineStore("query", () => {tab.resultTotalRowCountLoading = false;const previousResultSessionClose = closeResultSession(tab, options?.pagination?.sessionId);if (!preserveResultDuringExecution || !tab.result) {+ if (!captureResultRun) void releaseResultLargeValues(tab.result, ...(tab.results ?? []));clearResultPayload(tab, { preserveCacheSnapshot: captureResultRun && pendingResultRunRestores.has(executionId) });}queryExecutionLog("info", "start", {@@ -8035,6 +8086,10 @@ export const useQueryStore = defineStore("query", () => {// would return the first page again (#8993).const isOffsetJumpPage = typeof pageOffset === "number" && pageOffset > 0 && !options?.pagination?.sessionId;const frontendTimeoutSecs = frontendQueryTimeoutSecsForSql(sqlToExecute, effectiveDbType, queryTimeoutSecs, sqlStatementParameterOptions);+ if (tab.mode === "data" && effectiveDbType === "oceanbase-oracle") {+ const meta = tableMetaForDataTab(tab);+ useLargeValuePreview = !!meta && /^(?:BASE )?TABLE$/i.test(meta.tableType ?? "") && columnsAllowDeferredLobMarkers(meta.columns) && meta.columns.some((column) => /^(N?CLOB|BLOB)$/i.test(column.data_type.trim()));+ }const sourceLabelDatabase = targetDatabase || conn?.database;const executionClientSessionId = options?.pagination?.clientSessionId ?? (tab.mode === "query" || tab.mode === "data" ? tabClientSessionId(tab) : undefined);const currentBeforeDispatch = findExecutionTab(id);@@ -8250,6 +8305,28 @@ export const useQueryStore = defineStore("query", () => {const responseResults = await withFrontendQueryTimeout(executionPromise, frontendTimeoutSecs, t("editor.queryTimeoutError", { seconds: frontendTimeoutSecs }), () => {void api.cancelQuery(executionId).catch((error) => queryExecutionLog("warn", "frontend-timeout:cancel-failed", { traceId, error }));});+ for (const result of responseResults) {+ if (effectiveDbType === "oceanbase-oracle" && !useLargeValuePreview && result.column_types?.some((type) => /^(N?CLOB|BLOB)$/i.test(type.trim()))) {+ result.messages = [+ ...(result.messages ?? []),+ {+ severity: "INFO",+ code: "LOB_COMPLETE_READ_FALLBACK",+ message: "LOB values were read completely because this result does not have a verified single-table preview source.",+ },+ ];+ }+ if (result.large_value_cells?.some((cell) => cell.value_ref)) {+ result.large_value_refs = result.large_value_cells.flatMap((cell) => (cell.value_ref ? [cell.value_ref] : []));+ result.large_value_context = {+ connectionId: executionConnectionId,+ database: executionDatabase,+ clientSessionId: executionClientSessionId,+ txnSessionId: tab.autoCommit === false ? tab.txnSessionId : undefined,+ catalog: executionCatalog,+ };+ }+ }if (findExecutionTab(id) !== tab || tab.executionId !== executionId || manualTransactionTargetEpoch(tab) !== executionTargetEpoch) return false;// A single result has an unambiguous request boundary. This includes fetch and// transport, but excludes SQL preparation and the grid's later render work.diff --git a/apps/desktop/src/types/database.ts b/apps/desktop/src/types/database.tsindex f05e7a614a..42c4d40e0d 100644--- a/apps/desktop/src/types/database.ts+++ b/apps/desktop/src/types/database.ts@@ -1392,7 +1392,11 @@ export interface QueryResult {total_is_exact?: boolean;truncated?: boolean;/** Variable-length cells represented by bounded previews in `rows`. */- large_value_cells?: Array<{ row_index: number; column_index: number; original_bytes: number }>;+ large_value_cells?: Array<{ row_index: number; column_index: number; original_bytes: number; value_ref?: string }>;+ /** Frontend-only original result connection, independent of the currently active tab. */+ large_value_context?: { connectionId: string; database: string; clientSessionId?: string; txnSessionId?: string; catalog?: string };+ /** Retained result refs also cover cells already hydrated into complete local values. */+ large_value_refs?: string[];session_id?: string | null;has_more?: boolean;/** For Elasticsearch REST search results parsed into a _source table,diff --git a/crates/dbx-core/assets/agent-protocol-v1.json b/crates/dbx-core/assets/agent-protocol-v1.jsonindex b363666a9e..af91085bbf 100644--- a/crates/dbx-core/assets/agent-protocol-v1.json+++ b/crates/dbx-core/assets/agent-protocol-v1.json@@ -32,6 +32,8 @@"execute_query_page","fetch_query_page","close_query_session",+ "read_large_value_chunk",+ "release_large_value","start_table_read","fetch_table_read_page","close_table_read_session",diff --git a/crates/dbx-core/src/connection/mod.rs b/crates/dbx-core/src/connection/mod.rsindex a199bd66e0..ca61dee6da 100644--- a/crates/dbx-core/src/connection/mod.rs+++ b/crates/dbx-core/src/connection/mod.rs@@ -1473,6 +1473,22 @@ impl AppState {self.connection_liveness.subscribe()}+ /// A locator belongs to its original workload session; never recreate it during lookup.+ pub(crate) async fn existing_workload_pool_for_session(+ &self,+ connection_id: &str,+ database: Option<&str>,+ client_session_id: Option<&str>,+ ) -> Option<(String, PoolKind)> {+ let config = self.configs.read().await.get(connection_id).cloned()?;+ let base_key = base_pool_key_for_config(Some(&config), connection_id, database, None, false);+ let key = pool_key_for_session_role(Some(&config), base_key, client_session_id, AgentSessionRole::Workload);+ if self.pool_credential_owner_mismatch(&config, &key).await {+ return None;+ }+ self.pool_handle(&key).await.map(|pool| (key, pool))+ }+/// Find an already-registered metadata/workload pool for a metadata read./// Unlike `get_or_create_metadata_pool_for_session`, this is a pure lookup:/// it never validates credentials, starts an agent, or opens a transport.diff --git a/crates/dbx-core/src/data/grid_clipboard_guard.rs b/crates/dbx-core/src/data/grid_clipboard_guard.rsindex 940e29a404..4fffa894b7 100644--- a/crates/dbx-core/src/data/grid_clipboard_guard.rs+++ b/crates/dbx-core/src/data/grid_clipboard_guard.rs@@ -139,6 +139,7 @@ mod tests {display_name: "value".to_string(),source_name: Some("value".to_string()),source_index: 0,+ data_type: None,}],selected_column_indexes: vec![0],rows,@@ -335,6 +336,7 @@ mod tests {display_name: "formula".to_string(),source_name: Some("formula".to_string()),source_index: 1,+ data_type: None,});let guarded = neutralize_spreadsheet_formulas(request);let result = dbx_sql::data_grid_extractors::extract_data_grid_selection(guarded)diff --git a/crates/dbx-core/src/query/mod.rs b/crates/dbx-core/src/query/mod.rsindex 916f82d0e0..d73b129953 100644--- a/crates/dbx-core/src/query/mod.rs+++ b/crates/dbx-core/src/query/mod.rs@@ -8,6 +8,7 @@ pub mod plugin_data;pub mod plugin_plan;pub mod query_cancel;pub mod redis_ops;+pub mod snapshot_export;mod sqlserver_agent_batch;pub mod sqlserver_manual_transaction;pub mod two_phase_commit;@@ -483,10 +484,11 @@ struct ServerLargeValueMarker {}#[derive(Clone, Copy)]-struct ServerLargeValueMarkerValue {+struct ServerLargeValueMarkerValue<'a> {kind: ServerLargeValuePreviewKind,preview_size: usize,original_bytes: Option<usize>,+ value_ref: Option<&'a str>,}/// Some PostgreSQL-compatible servers (for example KingbaseES instances with@@ -528,7 +530,7 @@ fn server_large_value_alias(Some((source_index, Some(preview_kind), source_type))}-fn server_large_value_marker(value: &serde_json::Value) -> Option<ServerLargeValueMarkerValue> {+fn server_large_value_marker(value: &serde_json::Value) -> Option<ServerLargeValueMarkerValue<'_>> {let mut parts = value.as_str()?.split(':');let kind = parts.next()?;let preview_size = parts.next()?;@@ -540,7 +542,13 @@ fn server_large_value_marker(value: &serde_json::Value) -> Option<ServerLargeVal_ => return None,};let original_bytes = parts.next().and_then(|value| value.parse::<usize>().ok());- Some(ServerLargeValueMarkerValue { kind, preview_size: preview_size.parse::<usize>().ok()?.max(1), original_bytes })+ let value_ref = parts.next().filter(|value| !value.is_empty());+ Some(ServerLargeValueMarkerValue {+ kind,+ preview_size: preview_size.parse::<usize>().ok()?.max(1),+ original_bytes,+ value_ref,+ })}fn truncate_server_large_value_preview(@@ -630,18 +638,26 @@ fn extract_server_large_value_markers(result: &mut db::QueryResult) -> Vec<db::L}for (row_index, row) in result.rows.iter_mut().enumerate() {for marker in &markers {- let marker_value = row.get(marker.result_index).and_then(server_large_value_marker);+ // Own the locator before mutating the preview in this row.+ let value_ref = row+ .get(marker.result_index)+ .and_then(server_large_value_marker)+ .and_then(|value| value.value_ref)+ .map(str::to_owned);+ let marker_value = row+ .get(marker.result_index)+ .and_then(server_large_value_marker)+ .map(|value| (value.kind, value.preview_size, value.original_bytes));let source_result_index = marker.result_index.saturating_sub(1);if marker_value.is_some_and(|value| {row.get_mut(source_result_index)- .is_some_and(|source| truncate_server_large_value_preview(source, value.kind, value.preview_size))+ .is_some_and(|source| truncate_server_large_value_preview(source, value.0, value.1))}) {large_value_cells.push(db::LargeValueCell {row_index,column_index: marker.source_index,- original_bytes: marker_value- .and_then(|value| value.original_bytes)- .unwrap_or(SERVER_LARGE_VALUE_UNKNOWN_BYTES),+ original_bytes: marker_value.and_then(|value| value.2).unwrap_or(SERVER_LARGE_VALUE_UNKNOWN_BYTES),+ value_ref,});}}@@ -3102,6 +3118,210 @@ fn parse_drop_database_target(sql: &str) -> Option<String> {parts[0].as_ident().map(|ident| ident.value.clone())}+#[derive(Debug, Clone, serde::Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct LargeValueRequest {+ pub connection_id: String,+ pub database: String,+ pub value_ref: String,+ #[serde(default)]+ pub offset: u64,+ #[serde(default)]+ pub limit: u32,+ pub execution_id: Option<String>,+ pub client_session_id: Option<String>,+ pub catalog: Option<String>,+ pub txn_session_id: Option<String>,+ pub download_encoding: Option<String>,+}++/// Fetches only the original captured locator; never retries by selecting the current row.+pub async fn request_large_value(+ state: &AppState,+ request: LargeValueRequest,+ release: bool,+) -> Result<serde_json::Value, String> {+ if request.value_ref.len() > 128 || (!release && (request.limit == 0 || request.limit > 4096)) {+ return Err("Invalid LOB chunk request".to_string());+ }+ let registered = request.execution_id.as_ref().map(|id| {+ state.running_queries.register_task(+ id.clone(),+ crate::query_cancel::RunningTaskMetadata::query(+ request.connection_id.clone(),+ request.database.clone(),+ request.client_session_id.clone(),+ ),+ )+ });+ let cancel_token = registered.as_ref().map(|task| task.token());+ request_large_value_with_cancel(state, request, release, cancel_token).await+}++async fn request_large_value_with_cancel(+ state: &AppState,+ request: LargeValueRequest,+ release: bool,+ cancel_token: Option<CancellationToken>,+) -> Result<serde_json::Value, String> {+ if request.value_ref.len() > 128 || (!release && (request.limit == 0 || request.limit > 4096)) {+ return Err("Invalid LOB chunk request".to_string());+ }+ let method = if release { "release_large_value" } else { "read_large_value_chunk" };+ let params = serde_json::json!({ "valueRef": request.value_ref, "offset": request.offset, "limit": request.limit });+ let timeout = Some(std::time::Duration::from_secs(30));+ if let Some(txn_id) = request.txn_session_id.as_deref() {+ let connection = {+ let mut sessions =+ wait_for_value_opt(cancel_token.clone(), timeout, state.transaction_sessions.write()).await?;+ let session = sessions.get_mut(txn_id).ok_or(MANUAL_TRANSACTION_SESSION_NOT_FOUND_ERROR)?;+ if session.connection_id != request.connection_id+ || session.busy+ || session.last_activity.elapsed().as_secs() >= MANUAL_TRANSACTION_IDLE_TIMEOUT_SECS+ {+ return Err("LOB transaction context expired or busy".to_string());+ }+ session.last_activity = std::time::Instant::now();+ Arc::clone(&session.connection)+ };+ let connection = wait_for_value_opt(cancel_token.clone(), timeout, connection.lock()).await?;+ let TxnConnection::Agent { client, .. } = &*connection else {+ return Err("LOB snapshot chunks require an agent transaction".to_string());+ };+ let result = wait_for_value_opt(cancel_token.clone(), timeout, client.lock())+ .await?+ .call_with_timeout_and_cancel(method, params, timeout, cancel_token.clone())+ .await;+ if !wait_for_value_opt(cancel_token, timeout, state.transaction_sessions.read()).await?.contains_key(txn_id) {+ return Err("LOB transaction context expired".to_string());+ }+ return result;+ }+ let pool_database = query_pool_database(&request.database, request.catalog.as_deref());+ let (pool_key, handle) = wait_for_value_opt(+ cancel_token.clone(),+ timeout,+ state.existing_workload_pool_for_session(+ &request.connection_id,+ pool_database,+ request.client_session_id.as_deref(),+ ),+ )+ .await?+ .ok_or_else(|| "LOB context has expired; rerun the query".to_string())?;+ let _activity = state.pool_activity_touch(pool_key.as_str());+ let PoolKind::Agent(client) = handle else {+ return Err("LOB snapshot chunks require an agent connection".to_string());+ };+ let mut client = wait_for_value_opt(cancel_token.clone(), timeout, client.lock()).await?;+ client.call_with_timeout_and_cancel(method, params, timeout, cancel_token).await+}++pub async fn write_large_value_snapshot(+ state: &AppState,+ mut request: LargeValueRequest,+ output: &mut std::fs::File,+) -> Result<u64, String> {+ use std::io::Write;+ let registered = request.execution_id.as_ref().map(|id| {+ state.running_queries.register_task(+ id.clone(),+ crate::query_cancel::RunningTaskMetadata::query(+ request.connection_id.clone(),+ request.database.clone(),+ request.client_session_id.clone(),+ ),+ )+ });+ let cancel = registered.as_ref().map(|task| task.token());+ request.offset = 0;+ request.limit = 4096;+ let mut written = 0;+ let mut value_kind: Option<String> = None;+ let mut decoder = match request.download_encoding.as_deref() {+ None | Some("binary") => None,+ Some("utf8") => Some(encoding_rs::UTF_8.new_decoder_without_bom_handling()),+ Some("gbk") => Some(encoding_rs::GBK.new_decoder_without_bom_handling()),+ Some(_) => return Err("Unsupported LOB download encoding".to_string()),+ };+ let mut first_decoded_output = request.download_encoding.as_deref() == Some("utf8");+ loop {+ if is_canceled(&cancel) {+ return Err(canceled_error());+ }+ let chunk = request_large_value_with_cancel(state, request.clone(), false, cancel.clone()).await?;+ if is_canceled(&cancel) {+ return Err(canceled_error());+ }+ let (data, next, eof, kind) = snapshot_export::checked_chunk(&chunk, request.offset)?;+ if value_kind.as_deref().is_some_and(|original| original != kind) {+ return Err("LOB chunk type changed".to_string());+ }+ value_kind = Some(kind.to_string());+ if next < request.offset || (!eof && next == request.offset) {+ return Err("Invalid LOB offset".to_string());+ }+ let bytes = if kind == "binary" {+ let bytes = decode_lob_hex_chunk(data)?;+ if bytes.len() as u64 != next - request.offset {+ return Err("Invalid LOB byte count".to_string());+ }+ if let Some(decoder) = decoder.as_mut() {+ let mut text = decode_lob_text_chunk(decoder, &bytes, eof)?;+ if first_decoded_output && !text.is_empty() {+ if text.starts_with('\u{feff}') {+ text.drain(..3);+ }+ first_decoded_output = false;+ }+ text.into_bytes()+ } else {+ bytes+ }+ } else if kind == "text" {+ if data.chars().count() as u64 != next - request.offset {+ return Err("Invalid LOB character count".to_string());+ }+ data.as_bytes().to_vec()+ } else {+ return Err("Invalid LOB type".to_string());+ };+ output.write_all(&bytes).map_err(|error| error.to_string())?;+ written += bytes.len() as u64;+ if eof {+ break;+ }+ request.offset = next;+ }+ if is_canceled(&cancel) {+ return Err(canceled_error());+ }+ output.flush().map_err(|error| error.to_string())?;+ Ok(written)+}++fn decode_lob_hex_chunk(hex: &str) -> Result<Vec<u8>, String> {+ if hex.len() > 8192 || !hex.len().is_multiple_of(2) || !hex.is_ascii() {+ return Err("Invalid LOB binary encoding".to_string());+ }+ hex.as_bytes()+ .chunks_exact(2)+ .map(|pair| {+ u8::from_str_radix(std::str::from_utf8(pair).map_err(|_| "Invalid LOB binary encoding".to_string())?, 16)+ .map_err(|_| "Invalid LOB binary encoding".to_string())+ })+ .collect()+}++fn decode_lob_text_chunk(decoder: &mut encoding_rs::Decoder, bytes: &[u8], eof: bool) -> Result<String, String> {+ let mut text = String::with_capacity(bytes.len() * 3 + 12);+ let (status, consumed, _) = decoder.decode_to_string(bytes, &mut text, eof);+ if status != encoding_rs::CoderResult::InputEmpty || consumed != bytes.len() {+ return Err("LOB download decoding did not consume the complete chunk".to_string());+ }+ Ok(text)+}+pub async fn close_query_session(state: &AppState,connection_id: &str,@@ -4527,6 +4747,53 @@ fn contains_standalone_concurrently_keyword(upper: &str) -> bool {false}+pub async fn execute_blob_bound_statements(+ state: &AppState,+ connection_id: &str,+ database: &str,+ previews: &[String],+ bound: &[dbx_types::types::BlobBoundStatement],+ schema: Option<&str>,+ use_transaction: bool,+ timeout_secs: Option<u64>,+) -> Result<db::QueryResult, String> {+ dbx_types::types::validate_blob_bound_statements(previews, bound)?;+ if connection_database_type(state, connection_id).await != Some(DatabaseType::OceanbaseOracle) {+ return Err("Bound BLOB saves are only supported for OceanBase Oracle.".into());+ }+ let pool_key = if database.is_empty() {+ connection_id.to_string()+ } else {+ state.get_or_create_pool(connection_id, Some(database)).await?+ };+ let sql = bound.iter().map(|statement| statement.sql.clone()).collect::<Vec<_>>();+ check_read_only_for_connection_multi(state, &pool_key, &sql).await?;+ let pool = state.pool_handle(&pool_key).await;+ let Some(PoolKind::Agent(source_client)) = pool.as_ref() else {+ return Err("Bound BLOB saves require an updated JDBC Agent.".into());+ };+ let mut client = source_client.lock().await;+ let result = client+ .execute_blob_bound_typed(+ if database.is_empty() { None } else { Some(database) },+ previews,+ bound,+ schema,+ use_transaction,+ resolve_query_timeout(timeout_secs),+ )+ .await;+ drop(client);+ match result {+ Ok(result) => Ok(result),+ Err(error) => {+ discard_agent_pool_after_typed_error(state, &pool_key, source_client, &error, RecoveryScope::UserOperation)+ .await;+ Err(error.into_legacy_string())+ }+ }+}+async fn execute_statements_inner(state: &AppState,connection_id: &str,@@ -6105,6 +6372,7 @@ pub async fn execute_in_manual_transaction(#[derive(Clone, Debug, Default)]pub struct ManualTransactionExecutionOptions {+ pub bound_statements: Option<Vec<dbx_types::types::BlobBoundStatement>>,pub max_rows: Option<usize>,pub table_data_preview: bool,pub execution_id: Option<String>,@@ -6128,6 +6396,9 @@ pub async fn execute_in_manual_transaction_with_options(options: ManualTransactionExecutionOptions,) -> Result<Vec<ExecuteMultiResult>, String> {if sqlserver_manual_transaction::is_session_id(txn_session_id) {+ if options.bound_statements.is_some() {+ return Err("Bound BLOB saves are only supported for OceanBase Oracle.".into());+ }return sqlserver_manual_transaction::execute(state, txn_session_id, sql, database, schema, options).await;}const TXN_IDLE_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(MANUAL_TRANSACTION_IDLE_TIMEOUT_SECS);@@ -6143,16 +6414,28 @@ pub async fn execute_in_manual_transaction_with_options(let db_type = connection_database_type(state, &connection_id).await;let compatibility_mode = connection_sql_compatibility_mode(state, &pool_key, db_type).await;- let statements = db_type.map_or_else(- || split_sql_statements(sql),- |db_type| {- crate::sql::split_sql_statements_for_database_with_compatibility(- sql,- db_type,- compatibility_mode.as_deref(),- )- },- );+ let statements = if let Some(bound) = options.bound_statements.as_ref() {+ if db_type != Some(DatabaseType::OceanbaseOracle) {+ return Err("Bound BLOB saves are only supported for OceanBase Oracle.".into());+ }+ let previews = bound.iter().map(|statement| statement.preview_sql.clone()).collect::<Vec<_>>();+ if sql != previews.join(";\n") {+ return Err("The reviewed SQL changed; regenerate the BLOB save preview before saving.".into());+ }+ dbx_types::types::validate_blob_bound_statements(&previews, bound)?;+ previews+ } else {+ db_type.map_or_else(+ || split_sql_statements(sql),+ |db_type| {+ crate::sql::split_sql_statements_for_database_with_compatibility(+ sql,+ db_type,+ compatibility_mode.as_deref(),+ )+ },+ )+ };if statements.is_empty() {// Sticky-dialect UX marker: the no-op is Core's decision that the script// (empty/whitespace/comments-only) has no statements, so the frontend@@ -6186,6 +6469,26 @@ pub async fn execute_in_manual_transaction_with_options(// Read-only check while the session is still in the map. If this fails the// session remains intact.check_read_only_for_connection_multi(state, &pool_key, &statements).await?;+ if let Some(bound) = options.bound_statements.as_ref() {+ check_read_only_for_connection_multi(+ state,+ &pool_key,+ &bound.iter().map(|statement| statement.sql.clone()).collect::<Vec<_>>(),+ )+ .await?;+ let connection = state+ .transaction_sessions+ .read()+ .await+ .get(txn_session_id)+ .map(|session| Arc::clone(&session.connection))+ .ok_or(MANUAL_TRANSACTION_SESSION_NOT_FOUND_ERROR)?;+ let connection = connection.lock().await;+ if !matches!(&*connection, TxnConnection::Agent { client, .. } if client.lock().await.supports_capability(crate::db::agent_driver::AgentCapability::BlobBindStatementsV1))+ {+ return Err("This Agent does not support bound BLOB saves; update the Agent before saving.".into());+ }+ }let classification: Vec<bool> =classify_manual_transaction_statements(db_type, statements.len(), options.classification_sql.as_deref());@@ -6227,7 +6530,11 @@ pub async fn execute_in_manual_transaction_with_options(let mut results = Vec::with_capacity(statements.len());let mut conn = connection.lock().await;+ let mut bound_failure_can_keep = false;for (i, statement) in statements.iter().enumerate() {+ if options.bound_statements.is_some() && i > 0 {+ break;+ }let result = match &mut *conn {TxnConnection::SqlServer { .. } => {return Err("SQL Server transaction must use its batch executor".to_string())@@ -6244,18 +6551,41 @@ pub async fn execute_in_manual_transaction_with_options(.await}TxnConnection::Agent { client, .. } => {- execute_manual_txn_agent_statement(- client,- db_type,- statement,- database,- schema,- row_limit,- options.table_data_preview,- options.page_size,- options.result_session_id.as_deref(),- )- .await+ if let Some(bound) = options.bound_statements.as_ref() {+ match client+ .lock()+ .await+ .execute_blob_bound_typed(+ if database.is_empty() { None } else { Some(database) },+ &statements,+ bound,+ schema,+ false,+ resolve_query_timeout(options.timeout_secs),+ )+ .await+ {+ Ok(result) => Ok(result),+ Err(error) => {+ bound_failure_can_keep = error.session_disposition()+ == Some(crate::db::agent_driver::AgentSessionDisposition::Keep);+ Err(error.into_legacy_string())+ }+ }+ } else {+ execute_manual_txn_agent_statement(+ client,+ db_type,+ statement,+ database,+ schema,+ row_limit,+ options.table_data_preview,+ options.page_size,+ options.result_session_id.as_deref(),+ )+ .await+ }}TxnConnection::ExternalDriver { session, config, .. } => {execute_manual_txn_external_driver_statement(session, config, statement, database, schema, row_limit)@@ -6274,6 +6604,13 @@ pub async fn execute_in_manual_transaction_with_options(results.push(executed);}Err(e) => {+ if bound_failure_can_keep {+ if let Some(session) = state.transaction_sessions.write().await.get_mut(txn_session_id) {+ session.busy = false;+ session.last_activity = std::time::Instant::now();+ }+ return Err(e);+ }// Statement failure ends the transaction. If another cleanup path// already removed the session, it owns the final rollback.let should_rollback = {@@ -6284,7 +6621,11 @@ pub async fn execute_in_manual_transaction_with_options(let _ = rollback_manual_txn_connection(&mut conn).await;release_manual_txn_session_pool(state, &connection_id, &mut conn).await;}- return Err(format!("Statement {} failed: {}. The manual transaction was rolled back.", i + 1, e));+ return Err(if options.bound_statements.is_some() {+ format!("Bound BLOB save failed: {e}. The transaction session was discarded; the operation outcome may be unknown.")+ } else {+ format!("Statement {} failed: {}. The manual transaction was rolled back.", i + 1, e)+ });}}}@@ -9926,7 +10267,7 @@ for line in sys.stdin:let result = ExecuteMultiResult::success_with_index_and_large_values(empty_query_result(1),0,- vec![db::LargeValueCell { row_index: 2, column_index: 3, original_bytes: 65_536 }],+ vec![db::LargeValueCell { row_index: 2, column_index: 3, original_bytes: 65_536, value_ref: None }],false,);@@ -9940,28 +10281,28 @@ for line in sys.stdin:#[test]fn large_value_cell_merge_replaces_driver_entries_and_appends_server_entries() {let driver_cells = vec![- db::LargeValueCell { row_index: 1, column_index: 2, original_bytes: 10 },- db::LargeValueCell { row_index: 3, column_index: 4, original_bytes: 20 },+ db::LargeValueCell { row_index: 1, column_index: 2, original_bytes: 10, value_ref: None },+ db::LargeValueCell { row_index: 3, column_index: 4, original_bytes: 20, value_ref: None },];let server_cells = vec![- db::LargeValueCell { row_index: 1, column_index: 2, original_bytes: 100 },- db::LargeValueCell { row_index: 5, column_index: 6, original_bytes: 200 },+ db::LargeValueCell { row_index: 1, column_index: 2, original_bytes: 100, value_ref: None },+ db::LargeValueCell { row_index: 5, column_index: 6, original_bytes: 200, value_ref: None },];assert_eq!(merge_large_value_cells(driver_cells, server_cells),vec![- db::LargeValueCell { row_index: 1, column_index: 2, original_bytes: 100 },- db::LargeValueCell { row_index: 3, column_index: 4, original_bytes: 20 },- db::LargeValueCell { row_index: 5, column_index: 6, original_bytes: 200 },+ db::LargeValueCell { row_index: 1, column_index: 2, original_bytes: 100, value_ref: None },+ db::LargeValueCell { row_index: 3, column_index: 4, original_bytes: 20, value_ref: None },+ db::LargeValueCell { row_index: 5, column_index: 6, original_bytes: 200, value_ref: None },]);}#[test]fn large_value_cell_merge_preserves_single_source_inputs() {- let driver_cell = db::LargeValueCell { row_index: 1, column_index: 2, original_bytes: 10 };- let server_cell = db::LargeValueCell { row_index: 3, column_index: 4, original_bytes: 20 };+ let driver_cell = db::LargeValueCell { row_index: 1, column_index: 2, original_bytes: 10, value_ref: None };+ let server_cell = db::LargeValueCell { row_index: 3, column_index: 4, original_bytes: 20, value_ref: None };assert_eq!(merge_large_value_cells(vec![driver_cell.clone()], Vec::new()), vec![driver_cell]);assert_eq!(merge_large_value_cells(Vec::new(), vec![server_cell.clone()]), vec![server_cell]);@@ -9971,10 +10312,10 @@ for line in sys.stdin:fn large_value_cell_merge_handles_large_disjoint_inputs() {const CELL_COUNT: usize = 100_000;let driver_cells = (0..CELL_COUNT)- .map(|row_index| db::LargeValueCell { row_index, column_index: 0, original_bytes: 10 })+ .map(|row_index| db::LargeValueCell { row_index, column_index: 0, original_bytes: 10, value_ref: None }).collect();let server_cells = (0..CELL_COUNT)- .map(|row_index| db::LargeValueCell { row_index, column_index: 1, original_bytes: 20 })+ .map(|row_index| db::LargeValueCell { row_index, column_index: 1, original_bytes: 20, value_ref: None }).collect();let merged = merge_large_value_cells(driver_cells, server_cells);@@ -10299,6 +10640,74 @@ for line in sys.stdin:));}+ #[test]+ fn original_lob_ref_survives_production_result_normalization_without_polluting_preview_values() {+ let mut result = empty_query_result(0);+ result.columns = vec!["Payload".to_string(), "__DBX_LARGE_VALUE_BYTES_C_0".to_string()];+ result.column_types = vec!["CLOB".to_string(), "VARCHAR".to_string()];+ result.rows = vec![+ vec![serde_json::json!("原😀值"), serde_json::json!("D:1:unknown:original-ref")],+ vec![serde_json::Value::Null, serde_json::Value::Null],+ vec![serde_json::json!(""), serde_json::Value::Null],+ ];+ let normalized = ExecuteMultiResult::success_with_optional_server_large_values(result, true);+ assert_eq!(normalized.result.columns, vec!["Payload"]);+ assert_eq!(+ normalized.result.rows,+ vec![vec![serde_json::json!("原😀值")], vec![serde_json::Value::Null], vec![serde_json::json!("")]]+ );+ assert_eq!(+ normalized.large_value_cells,+ vec![db::LargeValueCell {+ row_index: 0,+ column_index: 0,+ original_bytes: SERVER_LARGE_VALUE_UNKNOWN_BYTES,+ value_ref: Some("original-ref".to_string()),+ }]+ );+ let wire = serde_json::to_value(normalized).unwrap();+ assert_eq!(wire["large_value_cells"][0]["value_ref"], "original-ref");+ assert_eq!(wire["rows"][0][0], "原😀值");+ let legacy: db::LargeValueCell = serde_json::from_value(serde_json::json!({+ "row_index": 0, "column_index": 1, "original_bytes": 128,+ }))+ .unwrap();+ assert_eq!(legacy.value_ref, None);+ assert!(serde_json::to_value(legacy).unwrap().get("value_ref").is_none());+ }++ #[test]+ fn lob_binary_download_decodes_every_byte_without_text_conversion() {+ let original: Vec<u8> = (0..=255).collect();+ let hex: String = original.iter().map(|value| format!("{value:02x}")).collect();+ assert_eq!(decode_lob_hex_chunk(&hex).unwrap(), original);+ assert_eq!(decode_lob_hex_chunk("").unwrap(), Vec::<u8>::new());+ assert_eq!(decode_lob_hex_chunk("00FF").unwrap(), vec![0, 255]);+ assert!(decode_lob_hex_chunk("0").is_err());+ assert!(decode_lob_hex_chunk("zz").is_err());+ assert!(decode_lob_hex_chunk("00".repeat(4097).as_str()).is_err());+ }++ #[test]+ fn lob_download_text_modes_preserve_multibyte_characters_split_across_chunks() {+ let original = "中文😀末尾";+ let mut utf8 = encoding_rs::UTF_8.new_decoder_without_bom_handling();+ let bytes = original.as_bytes();+ let mut decoded = String::new();+ for (index, byte) in bytes.iter().enumerate() {+ decoded.push_str(&decode_lob_text_chunk(&mut utf8, &[*byte], index + 1 == bytes.len()).unwrap());+ }+ assert_eq!(decoded, original);+ let (bytes, _, errors) = encoding_rs::GBK.encode("中文末尾");+ assert!(!errors);+ let mut gbk = encoding_rs::GBK.new_decoder_without_bom_handling();+ let mut decoded = String::new();+ for (index, byte) in bytes.iter().enumerate() {+ decoded.push_str(&decode_lob_text_chunk(&mut gbk, &[*byte], index + 1 == bytes.len()).unwrap());+ }+ assert_eq!(decoded, "中文末尾");+ }+#[test]fn external_driver_preview_fallback_rewrites_generated_postgres_projections() {let sql = concat!(@@ -10457,6 +10866,7 @@ for line in sys.stdin:row_index: 0,column_index: 1,original_bytes: SERVER_LARGE_VALUE_UNKNOWN_BYTES,+ value_ref: None}]);@@ -12194,6 +12604,7 @@ for line in sys.stdin:row_index: 0,column_index: 1,original_bytes: SERVER_LARGE_VALUE_UNKNOWN_BYTES,+ value_ref: None}]);}@@ -12260,8 +12671,18 @@ for line in sys.stdin:assert_eq!(cells,vec![- db::LargeValueCell { row_index: 0, column_index: 1, original_bytes: SERVER_LARGE_VALUE_UNKNOWN_BYTES },- db::LargeValueCell { row_index: 0, column_index: 2, original_bytes: SERVER_LARGE_VALUE_UNKNOWN_BYTES },+ db::LargeValueCell {+ row_index: 0,+ column_index: 1,+ original_bytes: SERVER_LARGE_VALUE_UNKNOWN_BYTES,+ value_ref: None+ },+ db::LargeValueCell {+ row_index: 0,+ column_index: 2,+ original_bytes: SERVER_LARGE_VALUE_UNKNOWN_BYTES,+ value_ref: None+ },]);}@@ -12318,7 +12739,7 @@ for line in sys.stdin:cells,[3, 7, 11].into_iter()- .map(|row_index| db::LargeValueCell { row_index, column_index: 0, original_bytes: 5 })+ .map(|row_index| db::LargeValueCell { row_index, column_index: 0, original_bytes: 5, value_ref: None }).collect::<Vec<_>>());}@@ -12419,9 +12840,9 @@ for line in sys.stdin:sizes.into_iter().enumerate()- .filter_map(|(row_index, size)| size- .filter(|size| *size > preview_size)- .map(|original_bytes| { db::LargeValueCell { row_index, column_index: 1, original_bytes } }))+ .filter_map(|(row_index, size)| size.filter(|size| *size > preview_size).map(|original_bytes| {+ db::LargeValueCell { row_index, column_index: 1, original_bytes, value_ref: None }+ })).collect::<Vec<_>>());}@@ -12466,6 +12887,7 @@ for line in sys.stdin:row_index: 0,column_index: 1,original_bytes: SERVER_LARGE_VALUE_UNKNOWN_BYTES,+ value_ref: None}]);}diff --git a/crates/dbx-core/src/query/snapshot_export.rs b/crates/dbx-core/src/query/snapshot_export.rsnew file mode 100644index 0000000000..0c347ce637--- /dev/null+++ b/crates/dbx-core/src/query/snapshot_export.rs@@ -0,0 +1,518 @@+use super::{canceled_error, is_canceled, request_large_value_with_cancel, LargeValueRequest};+use crate::connection::AppState;+use serde::Deserialize;+use serde_json::Value;+use std::collections::HashMap;+use std::io::{BufReader, Read, Seek, SeekFrom, Write};++#[derive(Debug, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct SnapshotExportCell {+ pub row_index: usize,+ pub column_index: usize,+ pub value_ref: String,+}++#[derive(Debug, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct SnapshotExportRequest {+ pub context: LargeValueRequest,+ pub format: String,+ pub columns: Vec<String>,+ pub rows: Vec<Vec<Value>>,+ pub cells: Vec<SnapshotExportCell>,+ #[serde(default)]+ pub quote_mode: dbx_formats::csv_export::CsvQuoteMode,+ pub null_literal: Option<String>,+}++/// Original result references only. A temporary cell file bounds memory even for+/// formula-guard inspection; callers publish the output only after success.+pub async fn write_snapshot_export(+ state: &AppState,+ request: SnapshotExportRequest,+ output: &mut std::fs::File,+) -> Result<(), String> {+ let registered = request.context.execution_id.as_ref().map(|id| {+ state.running_queries.register_task(+ id.clone(),+ crate::query_cancel::RunningTaskMetadata::query(+ request.context.connection_id.clone(),+ request.context.database.clone(),+ request.context.client_session_id.clone(),+ ),+ )+ });+ let cancel = registered.as_ref().map(|task| task.token());+ write_snapshot_export_with_fetch(request, output, cancel.clone(), |chunk_request| {+ request_large_value_with_cancel(state, chunk_request, false, cancel.clone())+ })+ .await+}++async fn write_snapshot_export_with_fetch<F, Fut>(+ request: SnapshotExportRequest,+ output: &mut std::fs::File,+ cancel: Option<tokio_util::sync::CancellationToken>,+ mut fetch: F,+) -> Result<(), String>+where+ F: FnMut(LargeValueRequest) -> Fut,+ Fut: std::future::Future<Output = Result<Value, String>>,+{+ let mut buffered = std::io::BufWriter::new(output);+ let output = &mut buffered;+ if request.format != "csv" && request.format != "json" {+ return Err("Unsupported snapshot export format".into());+ }+ if request.rows.iter().any(|row| row.len() != request.columns.len()) {+ return Err("Invalid snapshot export row".into());+ }+ let mut refs = HashMap::new();+ for cell in &request.cells {+ if cell.row_index >= request.rows.len()+ || cell.column_index >= request.columns.len()+ || cell.value_ref.is_empty()+ || cell.value_ref.len() > 128+ || refs.insert((cell.row_index, cell.column_index), cell.value_ref.as_str()).is_some()+ {+ return Err("Invalid snapshot export cell".into());+ }+ }+ // JSON objects cannot preserve duplicate labels. Reject rather than dropping a column.+ if request.format == "json" {+ let mut names = std::collections::HashSet::new();+ if request.columns.iter().any(|name| !names.insert(name)) {+ return Err("JSON export requires unique column names; use CSV".into());+ }+ }+ let json = request.format == "json";+ if json {+ output.write_all(b"[").map_err(|e| e.to_string())?;+ } else {+ let mut header = String::new();+ for (index, name) in request.columns.iter().enumerate() {+ if index > 0 {+ header.push(',');+ }+ dbx_formats::csv_export::push_csv_field(&mut header, name, request.quote_mode);+ }+ output.write_all(header.as_bytes()).map_err(|e| e.to_string())?;+ }+ for (row_index, row) in request.rows.iter().enumerate() {+ if is_canceled(&cancel) {+ return Err(canceled_error());+ }+ output+ .write_all(if json {+ if row_index == 0 {+ b"{"+ } else {+ b",{"+ }+ } else {+ b"\n"+ })+ .map_err(|e| e.to_string())?;+ for (column_index, value) in row.iter().enumerate() {+ if column_index > 0 {+ output.write_all(b",").map_err(|e| e.to_string())?;+ }+ if json {+ serde_json::to_writer(&mut *output, &request.columns[column_index]).map_err(|e| e.to_string())?;+ output.write_all(b":").map_err(|e| e.to_string())?;+ }+ if let Some(value_ref) = refs.get(&(row_index, column_index)) {+ let mut cell_file = tempfile::tempfile().map_err(|e| e.to_string())?;+ let mut chunk_request = request.context.clone();+ chunk_request.value_ref = (*value_ref).to_string();+ chunk_request.offset = 0;+ chunk_request.limit = 4096;+ let mut original_kind: Option<String> = None;+ loop {+ if is_canceled(&cancel) {+ return Err(canceled_error());+ }+ let chunk = fetch(chunk_request.clone()).await?;+ let (data, next, eof, kind) = checked_chunk(&chunk, chunk_request.offset)?;+ if original_kind.as_deref().is_some_and(|original| original != kind) {+ return Err("LOB chunk type changed".into());+ }+ if original_kind.is_none() && kind == "binary" {+ cell_file.write_all(b"0x").map_err(|e| e.to_string())?;+ }+ original_kind = Some(kind.to_string());+ cell_file.write_all(data.as_bytes()).map_err(|e| e.to_string())?;+ if eof {+ break;+ }+ chunk_request.offset = next;+ }+ cell_file.seek(SeekFrom::Start(0)).map_err(|e| e.to_string())?;+ let guard = !json+ && stream_formula_guard(BufReader::new(CancelableReader {+ reader: &mut cell_file,+ cancel: &cancel,+ }))?;+ cell_file.seek(SeekFrom::Start(0)).map_err(|e| e.to_string())?;+ let quoted = json+ || request.quote_mode == dbx_formats::csv_export::CsvQuoteMode::All+ || csv_needs_quotes(CancelableReader { reader: &mut cell_file, cancel: &cancel })?;+ cell_file.seek(SeekFrom::Start(0)).map_err(|e| e.to_string())?;+ if quoted {+ output.write_all(b"\"").map_err(|e| e.to_string())?;+ }+ if guard {+ output.write_all(b"'").map_err(|e| e.to_string())?;+ }+ let mut buffer = [0_u8; 8192];+ loop {+ if is_canceled(&cancel) {+ return Err(canceled_error());+ }+ let count = cell_file.read(&mut buffer).map_err(|e| e.to_string())?;+ if count == 0 {+ break;+ }+ write_escaped(output, &buffer[..count], json)?;+ }+ if quoted {+ output.write_all(b"\"").map_err(|e| e.to_string())?;+ }+ } else if json {+ serde_json::to_writer(&mut *output, value).map_err(|e| e.to_string())?;+ } else {+ let mut cell = String::new();+ dbx_formats::csv_export::push_query_result_csv_row_with_options(+ &mut cell,+ std::slice::from_ref(value),+ request.quote_mode,+ request.null_literal.as_deref(),+ );+ output.write_all(cell.as_bytes()).map_err(|e| e.to_string())?;+ }+ }+ if json {+ output.write_all(b"}").map_err(|e| e.to_string())?;+ }+ }+ if is_canceled(&cancel) {+ return Err(canceled_error());+ }+ if json {+ output.write_all(b"]").map_err(|e| e.to_string())?;+ }+ output.flush().map_err(|e| e.to_string())+}++struct CancelableReader<'a, R> {+ reader: R,+ cancel: &'a Option<tokio_util::sync::CancellationToken>,+}+impl<R: Read> Read for CancelableReader<'_, R> {+ fn read(&mut self, buffer: &mut [u8]) -> std::io::Result<usize> {+ if is_canceled(self.cancel) {+ return Err(std::io::Error::other(canceled_error()));+ }+ self.reader.read(buffer)+ }+}++pub(super) fn checked_chunk(chunk: &Value, offset: u64) -> Result<(&str, u64, bool, &str), String> {+ if chunk.get("status").and_then(Value::as_str) != Some("ok") {+ return Err("LOB snapshot expired; execute the query again".into());+ }+ let data = chunk.get("data").and_then(Value::as_str).ok_or("Invalid LOB data")?;+ let next = chunk.get("next_offset").and_then(Value::as_u64).ok_or("Invalid LOB offset")?;+ let eof = chunk.get("eof").and_then(Value::as_bool).ok_or("Invalid LOB EOF")?;+ let kind = chunk.get("value_kind").and_then(Value::as_str).ok_or("Invalid LOB type")?;+ if next < offset || next - offset > 4096 || (!eof && next == offset) {+ return Err("Invalid LOB offset".into());+ }+ let amount = match kind {+ "text" => data.chars().count(),+ "binary" if data.len() <= 8192 && data.len() % 2 == 0 && data.bytes().all(|b| b.is_ascii_hexdigit()) => {+ data.len() / 2+ }+ _ => return Err("Invalid LOB chunk encoding".into()),+ };+ if amount as u64 != next - offset {+ return Err("Invalid LOB chunk length".into());+ }+ Ok((data, next, eof, kind))+}++fn write_escaped(output: &mut impl Write, bytes: &[u8], json: bool) -> Result<(), String> {+ for &byte in bytes {+ match byte {+ b'"' => output.write_all(if json { b"\\\"" } else { b"\"\"" }),+ b'\\' if json => output.write_all(b"\\\\"),+ 0..=31 if json => write!(output, "\\u{byte:04x}"),+ _ => output.write_all(&[byte]),+ }+ .map_err(|e| e.to_string())?;+ }+ Ok(())+}++fn csv_needs_quotes(mut reader: impl Read) -> Result<bool, String> {+ let mut buffer = [0_u8; 8192];+ loop {+ let count = reader.read(&mut buffer).map_err(|e| e.to_string())?;+ if count == 0 {+ return Ok(false);+ }+ if buffer[..count].iter().any(|&byte| matches!(byte, b',' | b'"' | b'\n' | b'\r')) {+ return Ok(true);+ }+ }+}++// Same cell-level guard as dbx-formats, including negative decimals and literal+// apostrophes, without retaining leading spaces/zeroes or the complete cell.+fn stream_formula_guard(reader: impl Read) -> Result<bool, String> {+ let mut bytes = BufReader::new(reader).bytes();+ let mut next = || bytes.next().transpose().map_err(|e| e.to_string());+ let mut byte = next()?;+ if byte == Some(b'\'') {+ byte = next()?;+ if byte == Some(b'\'') {+ return Ok(true);+ }+ }+ while byte == Some(b' ') {+ byte = next()?;+ }+ if byte != Some(b'-') {+ return Ok(byte.is_some_and(|b| b"=+@\t\r".contains(&b)));+ }+ byte = next()?;+ if matches!(byte, Some(b'+') | Some(b'-')) {+ byte = next()?;+ }+ let mut digits = 0_usize;+ let mut significant = 0;+ let mut dot = false;+ loop {+ match byte {+ Some(b'0'..=b'9') => {+ digits += 1;+ if byte != Some(b'0') || significant > 0 {+ significant += 1;+ }+ if significant > 15 {+ return Ok(true);+ }+ }+ Some(b'.') if !dot && digits > 0 => {+ dot = true;+ digits = 0;+ significant = 0;+ }+ None => return Ok(digits == 0),+ _ => return Ok(true),+ }+ byte = next()?;+ }+}++#[cfg(test)]+mod tests {+ use super::*;+ #[test]+ fn streamed_guard_matches_existing_cell_semantics() {+ for value in [+ "",+ "plain",+ "=cmd",+ " +86",+ "-1",+ "-1.25",+ "-00000000000000000000000000001",+ "-1.00000000000000001",+ "-2+cmd",+ "-",+ "'-1",+ "'=cmd",+ "''text",+ "'plain",+ " --1",+ "-.1",+ "\ttext",+ ] {+ let mut expected = String::new();+ dbx_formats::csv_export::push_formula_guard(&mut expected, value);+ assert_eq!(stream_formula_guard(value.as_bytes()).unwrap(), !expected.is_empty(), "{value}");+ }+ }+ #[test]+ fn streamed_guard_buffers_reads_and_preserves_long_cell_boundaries() {+ struct CountingReader<'a> {+ data: &'a [u8],+ reads: usize,+ }+ impl Read for CountingReader<'_> {+ fn read(&mut self, buffer: &mut [u8]) -> std::io::Result<usize> {+ self.reads += 1;+ self.data.read(buffer)+ }+ }+ for value in [+ format!("{}=cmd", " ".repeat(16385)),+ format!("-{}1", "0".repeat(16385)),+ format!("{}中🙂", " ".repeat(16385)),+ ] {+ let mut reader = CountingReader { data: value.as_bytes(), reads: 0 };+ let mut expected = String::new();+ dbx_formats::csv_export::push_formula_guard(&mut expected, &value);+ assert_eq!(stream_formula_guard(&mut reader).unwrap(), !expected.is_empty());+ assert!(reader.reads < 16, "reader performed {} reads", reader.reads);+ }+ struct FailingReader;+ impl Read for FailingReader {+ fn read(&mut self, _: &mut [u8]) -> std::io::Result<usize> {+ Err(std::io::Error::other("snapshot read failed"))+ }+ }+ assert_eq!(stream_formula_guard(FailingReader).unwrap_err(), "snapshot read failed");+ }+ #[test]+ fn escapes_chunk_boundaries_without_changing_utf8_or_binary_hex() {+ let text = "中🙂\"\\\n\0";+ for split in 0..=text.len() {+ let mut out = Vec::new();+ write_escaped(&mut out, &text.as_bytes()[..split], true).unwrap();+ write_escaped(&mut out, &text.as_bytes()[split..], true).unwrap();+ assert_eq!(serde_json::from_slice::<String>(&[b"\"".as_slice(), &out, b"\""].concat()).unwrap(), text);+ }+ }+ #[test]+ fn rejects_expiry_invalid_offsets_and_incomplete_hex() {+ for chunk in [+ serde_json::json!({"status":"expired"}),+ serde_json::json!({"status":"ok","data":"0","next_offset":1,"eof":true,"value_kind":"binary"}),+ serde_json::json!({"status":"ok","data":"a","next_offset":5000,"eof":true,"value_kind":"text"}),+ ] {+ assert!(checked_chunk(&chunk, 0).is_err());+ }+ let chunk = serde_json::json!({"status":"ok","data":"🙂","next_offset":1,"eof":true,"value_kind":"text"});+ assert_eq!(checked_chunk(&chunk, 0).unwrap().1, 1);+ }++ fn request(format: &str) -> SnapshotExportRequest {+ serde_json::from_value(serde_json::json!({+ "context": {"connectionId":"original-connection","database":"oracletest","valueRef":"","clientSessionId":"original-session"},+ "format":format,"columns":["ID","PAYLOAD"],"rows":[[1,"preview"]],+ "cells":[{"rowIndex":0,"columnIndex":1,"valueRef":"original-locator"}],"nullLiteral":"\\N"+ })).unwrap()+ }++ #[tokio::test]+ async fn production_writer_preserves_unicode_quotes_and_original_context_in_multiple_chunks() {+ let original = format!(" =cmd{}\"\\\n", "中🙂".repeat(3000));+ let chars: Vec<char> = original.chars().collect();+ for format in ["csv", "json"] {+ let mut file = tempfile::tempfile().unwrap();+ let mut offsets = Vec::new();+ write_snapshot_export_with_fetch(request(format), &mut file, None, |chunk_request| {+ assert_eq!(chunk_request.value_ref, "original-locator");+ assert_eq!(chunk_request.connection_id, "original-connection");+ assert_eq!(chunk_request.client_session_id.as_deref(), Some("original-session"));+ assert_eq!(chunk_request.limit, 4096);+ offsets.push(chunk_request.offset);+ let begin = chunk_request.offset as usize;+ let end = (begin + 4096).min(chars.len());+ std::future::ready(Ok(serde_json::json!({"status":"ok","data":chars[begin..end].iter().collect::<String>(),"next_offset":end,"eof":end==chars.len(),"value_kind":"text"})))+ }).await.unwrap();+ assert_eq!(offsets, vec![0, 4096]);+ file.seek(SeekFrom::Start(0)).unwrap();+ let mut text = String::new();+ file.read_to_string(&mut text).unwrap();+ if format == "json" {+ assert_eq!(serde_json::from_str::<Value>(&text).unwrap()[0]["PAYLOAD"], original);+ } else {+ assert_eq!(+ text,+ dbx_formats::csv_export::format_query_result_csv_with_options(+ &["ID".into(), "PAYLOAD".into()],+ &[vec![Value::from(1), Value::from(original.clone())]],+ dbx_formats::csv_export::CsvQuoteMode::All,+ Some("\\N")+ )+ );+ }+ }+ }++ #[tokio::test]+ async fn production_writer_never_completes_on_mid_read_expiry_or_cancel() {+ for cancel_read in [false, true] {+ let token = tokio_util::sync::CancellationToken::new();+ let mut file = tempfile::tempfile().unwrap();+ let mut calls = 0;+ let error = write_snapshot_export_with_fetch(request("json"), &mut file, Some(token.clone()), |chunk_request| {+ calls += 1;+ if cancel_read { token.cancel(); }+ std::future::ready(Ok(if chunk_request.offset == 0 {+ serde_json::json!({"status":"ok","data":"first","next_offset":5,"eof":false,"value_kind":"text"})+ } else { serde_json::json!({"status":"expired"}) }))+ }).await.unwrap_err();+ assert_eq!(calls, if cancel_read { 1 } else { 2 });+ assert!(!error.is_empty());+ }+ }++ #[tokio::test]+ async fn production_writer_keeps_blob_hex_prefix_once_and_all_byte_values() {+ let hex: String = (0..=255_u8).map(|byte| format!("{byte:02x}")).collect();+ let mut file = tempfile::tempfile().unwrap();+ write_snapshot_export_with_fetch(request("json"), &mut file, None, |chunk_request| {+ let begin = chunk_request.offset as usize;+ let end = (begin + 127).min(256);+ std::future::ready(Ok(serde_json::json!({"status":"ok","data":&hex[begin*2..end*2],"next_offset":end,"eof":end==256,"value_kind":"binary"})))+ }).await.unwrap();+ file.seek(SeekFrom::Start(0)).unwrap();+ let result: Value = serde_json::from_reader(file).unwrap();+ assert_eq!(result[0]["PAYLOAD"], format!("0x{hex}"));+ }++ #[tokio::test]+ async fn necessary_quotes_and_formula_guard_match_existing_export() {+ for value in ["plain", "", "-000000000000000000001", " =cmd", "'plain", "'=cmd", "a,b", "a\"b"] {+ let mut req = request("csv");+ req.quote_mode = dbx_formats::csv_export::CsvQuoteMode::Necessary;+ let mut file = tempfile::tempfile().unwrap();+ write_snapshot_export_with_fetch(req, &mut file, None, |_| {+ std::future::ready(Ok(serde_json::json!({+ "status":"ok","data":value,"next_offset":value.chars().count(),"eof":true,"value_kind":"text"+ })))+ })+ .await+ .unwrap();+ file.seek(SeekFrom::Start(0)).unwrap();+ let mut output = String::new();+ file.read_to_string(&mut output).unwrap();+ assert_eq!(+ output,+ dbx_formats::csv_export::format_query_result_csv_with_options(+ &["ID".into(), "PAYLOAD".into()],+ &[vec![Value::from(1), Value::from(value)]],+ dbx_formats::csv_export::CsvQuoteMode::Necessary,+ Some("\\N")+ )+ );+ }+ }++ #[test]+ fn cancelled_formula_scan_stops_instead_of_retrying_forever() {+ let token = tokio_util::sync::CancellationToken::new();+ token.cancel();+ let cancel = Some(token);+ assert!(stream_formula_guard(BufReader::new(CancelableReader {+ reader: b" -0000".as_slice(),+ cancel: &cancel+ }))+ .is_err());+ }+}diff --git a/crates/dbx-core/tests/fixtures/lob_cancel_wait_agent.py b/crates/dbx-core/tests/fixtures/lob_cancel_wait_agent.pynew file mode 100644index 0000000000..4ecf6ba334--- /dev/null+++ b/crates/dbx-core/tests/fixtures/lob_cancel_wait_agent.py@@ -0,0 +1,18 @@+import json+import pathlib+import sys++log_path = pathlib.Path(sys.argv[1])+print(json.dumps({"ready": True}), flush=True)+for line in sys.stdin:+ request = json.loads(line)+ method = request["method"]+ with log_path.open("a", encoding="utf-8") as log:+ log.write(method + "\n")+ if method == "handshake":+ result = {"protocolVersion": 2, "agentProtocolVersion": 2, "capabilities": ["multi_session"]}+ elif method == "read_large_value_chunk":+ result = {"data": "fixture", "nextOffset": 7, "eof": True, "kind": "text"}+ else:+ result = {"ok": True}+ print(json.dumps({"jsonrpc": "2.0", "id": request["id"], "result": result}), flush=True)diff --git a/crates/dbx-core/tests/lob_cancel_wait.rs b/crates/dbx-core/tests/lob_cancel_wait.rsnew file mode 100644index 0000000000..d8f1c48d4a--- /dev/null+++ b/crates/dbx-core/tests/lob_cancel_wait.rs@@ -0,0 +1,220 @@+use dbx_core::connection::{AppState, PoolKind, TransactionSession, TxnConnection};+use dbx_core::db::agent_driver::{AgentDriverClient, AgentLaunchSpec, AgentRuntimeClient};+use dbx_core::models::connection::ConnectionConfig;+use dbx_core::query::{request_large_value, LargeValueRequest};+use serde_json::json;+use std::sync::Arc;+use std::time::{Duration, Instant};+use tokio::sync::Mutex;++struct Fixture {+ state: AppState,+ runtime: Arc<AgentRuntimeClient>,+ directory: tempfile::TempDir,+}++impl Drop for Fixture {+ fn drop(&mut self) {+ self.runtime.kill();+ }+}++impl Fixture {+ async fn new() -> Self {+ let directory = tempfile::tempdir().unwrap();+ let script = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/lob_cancel_wait_agent.py");+ let log_path = directory.path().join("methods.log");+ let python = if cfg!(windows) { "python" } else { "python3" };+ let runtime = AgentRuntimeClient::spawn(+ AgentLaunchSpec::new(python)+ .with_args([script.to_string_lossy().to_string(), log_path.to_string_lossy().to_string()]),+ "test",+ )+ .await+ .unwrap();+ runtime.increment_session_count();+ let storage = dbx_core::persistence::test_storage::open(&directory.path().join("state.db")).await.unwrap();+ let state = AppState::new(storage);+ let config: ConnectionConfig = serde_json::from_value(json!({+ "id":"lob", "name":"LOB wait fixture", "db_type":"oceanbase-oracle",+ "host":"127.0.0.1", "port":1, "username":"fixture", "password":"", "connect_timeout_secs":1+ }))+ .unwrap();+ state.configs.write().await.insert("lob".into(), config);+ state+ .update_connection_pools(|pools| {+ pools.insert(+ "lob".into(),+ PoolKind::agent(AgentDriverClient::shared_session(runtime.clone(), "lob-fixture".into())),+ )+ })+ .await;+ Self { state, runtime, directory }+ }++ fn assert_no_lob_rpc(&self) {+ let methods = std::fs::read_to_string(self.directory.path().join("methods.log")).unwrap_or_default();+ assert!(+ !methods.lines().any(|method| method == "read_large_value_chunk" || method == "release_large_value"),+ "A cancelled lock wait sent a LOB RPC"+ );+ }+}++fn request(transaction: bool) -> LargeValueRequest {+ serde_json::from_value(json!({+ "connectionId":"lob", "database":"", "valueRef":"captured-locator", "offset":0, "limit":4096,+ "executionId":"lob-wait", "txnSessionId":if transaction { Some("txn") } else { None }+ }))+ .unwrap()+}++async fn assert_local_cancel(fixture: &Fixture, transaction: bool, release: bool) {+ let mut pending = Box::pin(request_large_value(&fixture.state, request(transaction), release));+ assert!(+ tokio::time::timeout(Duration::from_millis(20), &mut pending).await.is_err(),+ "Fixture must hold the actual entry pending"+ );+ assert!(fixture.state.running_queries.diagnostics().active_execution_ids.iter().any(|id| id == "lob-wait"));+ assert!(fixture.state.running_queries.cancel("lob-wait"));+ let result = tokio::time::timeout(Duration::from_secs(1), &mut pending).await;+ assert!(result.is_ok(), "Cancelling must end local waiting while the lock remains held");+ assert_eq!(result.unwrap().unwrap_err(), "Query canceled");+ assert!(fixture.state.running_queries.diagnostics().active_execution_ids.is_empty());+ fixture.assert_no_lob_rpc();+}++#[tokio::test]+async fn public_lob_request_cancels_while_waiting_for_transaction_registry() {+ for release in [false, true] {+ let fixture = Fixture::new().await;+ let _held = fixture.state.transaction_sessions.write().await;+ assert_local_cancel(&fixture, true, release).await;+ }+}++#[tokio::test]+async fn public_lob_request_cancels_while_waiting_for_transaction_connection() {+ for release in [false, true] {+ let fixture = Fixture::new().await;+ let connection = Arc::new(Mutex::new(TxnConnection::Mysql(None)));+ fixture.state.transaction_sessions.write().await.insert(+ "txn".into(),+ TransactionSession {+ sqlserver: None,+ connection: connection.clone(),+ pool_key: "lob".into(),+ last_activity: Instant::now(),+ busy: false,+ snapshot_rotation_safe: false,+ connection_id: "lob".into(),+ database: "".into(),+ schema: None,+ },+ );+ let _held = connection.lock().await;+ assert_local_cancel(&fixture, true, release).await;+ }+}++#[tokio::test]+async fn public_lob_request_cancels_while_waiting_for_agent_client() {+ for release in [false, true] {+ let fixture = Fixture::new().await;+ let Some(PoolKind::Agent(client)) = fixture.state.pool_handle("lob").await else {+ panic!("Agent fixture missing")+ };+ let _held = client.lock().await;+ assert_local_cancel(&fixture, false, release).await;+ }+}++#[tokio::test]+async fn public_lob_request_cancels_while_preparing_its_pool() {+ for release in [false, true] {+ let fixture = Fixture::new().await;+ let _held = fixture.state.configs.write().await;+ assert_local_cancel(&fixture, false, release).await;+ }+}++#[tokio::test]+async fn public_lob_request_does_not_recreate_a_missing_locator_session() {+ for release in [false, true] {+ let directory = tempfile::tempdir().unwrap();+ let storage = dbx_core::persistence::test_storage::open(&directory.path().join("state.db")).await.unwrap();+ let state = AppState::new_with_plugin_and_agent_dir_and_app_version(+ storage,+ directory.path().join("plugins"),+ directory.path().join("agents"),+ "test",+ );+ let launch = state.agent_manager.driver_launch_config_path("oceanbase-oracle");+ std::fs::create_dir_all(launch.parent().unwrap()).unwrap();+ let script = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/lob_cancel_wait_agent.py");+ let log = directory.path().join("methods.log");+ std::fs::write(+ launch,+ serde_json::to_vec(&json!({+ "command":if cfg!(windows) { "python" } else { "python3" }, "args":[script, log]+ }))+ .unwrap(),+ )+ .unwrap();+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();+ let config: ConnectionConfig = serde_json::from_value(json!({+ "id":"lob", "name":"Missing locator fixture", "db_type":"oceanbase-oracle",+ "host":"127.0.0.1", "port":listener.local_addr().unwrap().port(),+ "username":"fixture", "password":"", "save_password":true,+ "keepalive_interval_secs":0, "idle_timeout_secs":0+ }))+ .unwrap();+ state.configs.write().await.insert("lob".into(), config);+ let result = request_large_value(&state, request(false), release).await;+ let methods = std::fs::read_to_string(log).unwrap_or_default();+ state.shutdown(Duration::from_secs(2)).await;+ assert_eq!(result.unwrap_err(), "LOB context has expired; rerun the query");+ assert!(methods.is_empty(), "Missing locator session must not start an Agent: {methods}");+ assert!(state.running_queries.diagnostics().active_execution_ids.is_empty());+ }+}++#[tokio::test]+async fn public_lob_request_uses_only_its_original_workload_scope() {+ for release in [false, true] {+ let fixture = Fixture::new().await;+ for (database, catalog, client_session) in [("", None, Some("other-tab")), ("other-database", None, None)] {+ let mut req = request(false);+ req.database = database.into();+ req.catalog = catalog.map(str::to_string);+ req.client_session_id = client_session.map(str::to_string);+ assert_eq!(+ request_large_value(&fixture.state, req, release).await.unwrap_err(),+ "LOB context has expired; rerun the query"+ );+ }+ fixture.assert_no_lob_rpc();+ let mut req = request(false);+ // A catalog query uses the connection workload pool, matching query_pool_database.+ req.database = "catalog-display-database".into();+ req.catalog = Some("catalog".into());+ assert!(request_large_value(&fixture.state, req, release).await.is_ok());+ }+}++#[tokio::test]+async fn public_lob_request_does_not_fall_back_to_metadata_role() {+ let fixture = Fixture::new().await;+ fixture+ .state+ .update_connection_pools(|pools| {+ let pool = pools.remove("lob").unwrap();+ pools.insert("lob:role:metadata".into(), pool);+ })+ .await;+ assert_eq!(+ request_large_value(&fixture.state, request(false), false).await.unwrap_err(),+ "LOB context has expired; rerun the query"+ );+ fixture.assert_no_lob_rpc();+}diff --git a/crates/dbx-driver-agent/assets/agent-protocol-v2.json b/crates/dbx-driver-agent/assets/agent-protocol-v2.jsonindex 8cd5f4e230..76d831bce7 100644--- a/crates/dbx-driver-agent/assets/agent-protocol-v2.json+++ b/crates/dbx-driver-agent/assets/agent-protocol-v2.json@@ -2,7 +2,7 @@"protocolVersion": 2,"handshakeMethod": "handshake","handshakeResponseFields": ["protocolVersion", "agentProtocolVersion", "capabilities"],- "allCapabilities": ["connect", "test_connection", "metadata", "query", "paged_query", "transaction", "ddl", "kv", "kv_ttl", "kv_cas", "kv_list_values", "kv_status", "kv_history", "etcd_compaction", "etcd_defrag", "etcd_watch", "etcd_lease", "etcd_auth", "mongo_drop_database", "mongo_clone_collection", "mongo_run_command", "mongo_insert_documents", "mongo_replace_document", "mongo_bulk_write", "mongo_rename_collection", "mongo_find_cursor", "multi_session", "structured_error_v1"],+ "allCapabilities": ["connect", "test_connection", "metadata", "query", "paged_query", "transaction", "ddl", "kv", "kv_ttl", "kv_cas", "kv_list_values", "kv_status", "kv_history", "etcd_compaction", "etcd_defrag", "etcd_watch", "etcd_lease", "etcd_auth", "mongo_drop_database", "mongo_clone_collection", "mongo_run_command", "mongo_insert_documents", "mongo_replace_document", "mongo_bulk_write", "mongo_rename_collection", "mongo_find_cursor", "multi_session", "structured_error_v1", "blob_bind_statements_v1"],"capabilities": ["connect", "test_connection", "metadata", "query", "paged_query", "transaction", "ddl", "multi_session"],"defaultSqlCapabilities": ["connect", "test_connection", "metadata", "query", "paged_query", "transaction", "ddl", "multi_session", "structured_error_v1"],"commonMethods": [@@ -36,6 +36,8 @@"execute_query_page","fetch_query_page","close_query_session",+ "read_large_value_chunk",+ "release_large_value","start_table_read","fetch_table_read_page","close_table_read_session",@@ -51,5 +53,15 @@"mongoLegacyMethods": ["list_databases", "list_collections", "find_documents", "find_one", "explain_find", "aggregate_documents", "find_documents_extended_json", "count_documents", "server_version", "create_index", "create_user", "drop_indexes", "drop_collection", "clone_collection", "drop_database", "insert_document", "insert_documents", "update_document", "update_documents", "replace_document", "bulk_write", "rename_collection", "delete_document", "delete_documents", "run_command", "start_find_cursor", "fetch_find_cursor", "close_find_cursor"],"kvMethods": ["kv_list_prefix", "kv_get", "kv_put", "kv_delete", "kv_rename", "kv_history", "kv_status", "etcd_compact", "etcd_defrag", "etcd_watch_start", "etcd_watch_poll", "etcd_watch_stop", "etcd_lease_list", "etcd_lease_get", "etcd_lease_grant", "etcd_lease_keepalive_once", "etcd_lease_revoke", "etcd_auth_user_list", "etcd_auth_user_get", "etcd_auth_user_add", "etcd_auth_user_delete", "etcd_auth_user_change_password", "etcd_auth_user_grant_role", "etcd_auth_user_revoke_role", "etcd_auth_role_list", "etcd_auth_role_get", "etcd_auth_role_add", "etcd_auth_role_delete", "etcd_auth_role_grant_permission", "etcd_auth_role_revoke_permission"],"sessionField": "agentSessionId",- "cursorSessionField": "sessionId"+ "cursorSessionField": "sessionId",+ "blobBindStatementsV1": {+ "capability": "blob_bind_statements_v1",+ "methods": ["execute_batch", "execute_transaction"],+ "optionalFields": ["boundStatements", "queryTimeoutSecs"],+ "statementFields": ["previewSql", "sql", "blobParameters"],+ "blobEncoding": "even-length hexadecimal without 0x",+ "previewRule": "complete array length and each previewSql must exactly match statements; unbound sql equals previewSql",+ "manualTransaction": "same connection, per-batch savepoint, no implicit commit; rollback to savepoint on failure",+ "unsupported": "reject complete request before executing any statement; no SQL-text fallback"+ }}diff --git a/crates/dbx-driver-agent/src/agent_driver.rs b/crates/dbx-driver-agent/src/agent_driver.rsindex e04adb2216..7a27b399e4 100644--- a/crates/dbx-driver-agent/src/agent_driver.rs+++ b/crates/dbx-driver-agent/src/agent_driver.rs@@ -1022,6 +1022,7 @@ impl AgentHandshake {#[derive(Debug, Clone, Copy, PartialEq, Eq)]pub enum AgentCapability {+ BlobBindStatementsV1,Connect,TestConnection,Metadata,@@ -1130,7 +1131,7 @@ fn parse_agent_rpc_error_header(header: &str) -> (Option<i64>, String) {}impl AgentCapability {- pub const ALL: [Self; 28] = [+ pub const ALL: [Self; 29] = [Self::Connect,Self::TestConnection,Self::Metadata,@@ -1159,10 +1160,12 @@ impl AgentCapability {Self::MongoFindCursor,Self::MultiSession,Self::StructuredErrorV1,+ Self::BlobBindStatementsV1,];pub fn as_str(self) -> &'static str {match self {+ Self::BlobBindStatementsV1 => "blob_bind_statements_v1",Self::Connect => "connect",Self::TestConnection => "test_connection",Self::Metadata => "metadata",@@ -1229,6 +1232,8 @@ pub enum AgentMethod {ExecuteQueryPage,FetchQueryPage,CloseQuerySession,+ ReadLargeValueChunk,+ ReleaseLargeValue,StartTableRead,FetchTableReadPage,CloseTableReadSession,@@ -1243,7 +1248,7 @@ pub enum AgentMethod {}impl AgentMethod {- pub const ALL: [Self; 41] = [+ pub const ALL: [Self; 43] = [Self::Handshake,Self::Connect,Self::OpenSession,@@ -1274,6 +1279,8 @@ impl AgentMethod {Self::ExecuteQueryPage,Self::FetchQueryPage,Self::CloseQuerySession,+ Self::ReadLargeValueChunk,+ Self::ReleaseLargeValue,Self::StartTableRead,Self::FetchTableReadPage,Self::CloseTableReadSession,@@ -1324,6 +1331,8 @@ impl AgentMethod {Self::StartTableRead => "start_table_read",Self::FetchTableReadPage => "fetch_table_read_page",Self::CloseTableReadSession => "close_table_read_session",+ Self::ReadLargeValueChunk => "read_large_value_chunk",+ Self::ReleaseLargeValue => "release_large_value",Self::GetExplainInfo => "get_explain_info",Self::ExecuteBatch => "execute_batch",Self::ExecuteTransaction => "execute_transaction",@@ -2888,6 +2897,32 @@ impl AgentDriverClient {.await}+ pub async fn execute_blob_bound_typed<T: DeserializeOwned + Send + 'static>(+ &mut self,+ database: Option<&str>,+ previews: &[String],+ bound: &[dbx_types::types::BlobBoundStatement],+ schema: Option<&str>,+ use_transaction: bool,+ timeout_duration: Option<Duration>,+ ) -> Result<T, AgentCallError> {+ dbx_types::types::validate_blob_bound_statements(previews, bound)?;+ if !self.handshake.as_ref().is_some_and(|handshake| handshake.supports(AgentCapability::BlobBindStatementsV1)) {+ return Err("This Agent does not support bound BLOB saves; update the Agent before saving.".into());+ }+ self.invalidate_cached_query();+ let mut params = agent_transaction_params(database, previews, schema);+ params["boundStatements"] = serde_json::to_value(bound).map_err(|error| error.to_string())?;+ params["queryTimeoutSecs"] =+ serde_json::json!(timeout_duration.map(|duration| duration.as_secs().max(1)).unwrap_or(30));+ self.call_method_typed_with_timeout(+ if use_transaction { AgentMethod::ExecuteTransaction } else { AgentMethod::ExecuteBatch },+ params,+ timeout_duration,+ )+ .await+ }+fn invalidate_cached_query(&mut self) {self.cached_query = None;}@@ -3235,7 +3270,8 @@ pub fn is_unsupported_handshake_error(error: &str) -> bool {pub fn agent_supports_capability(handshake: Option<&AgentHandshake>, capability: AgentCapability) -> bool {if matches!(capability,- AgentCapability::Kv+ AgentCapability::BlobBindStatementsV1+ | AgentCapability::Kv| AgentCapability::KvTtl| AgentCapability::KvCas| AgentCapability::KvListValues@@ -5725,8 +5761,53 @@ for line in sys.stdin:assert_eq!(handshake.capabilities, vec!["connect", "query", "metadata"]);}+ #[tokio::test]+ async fn bound_blob_execution_rejects_unsupported_agents_and_edited_previews_before_rpc() {+ let mut client = AgentDriverClient::test_stub();+ let previews = vec!["reviewed BLOB save".to_string()];+ let bound = vec![dbx_types::types::BlobBoundStatement {+ preview_sql: previews[0].clone(),+ sql: "UPDATE t SET b=?".into(),+ blob_parameters: vec!["00ff80".into()],+ }];+ let error = client+ .execute_blob_bound_typed::<serde_json::Value>(None, &previews, &bound, None, false, None)+ .await+ .unwrap_err();+ assert!(error.into_legacy_string().contains("does not support bound BLOB"));+ assert_eq!(client.next_id, 0);+ client.handshake = Some(AgentHandshake {+ protocol_version: AGENT_PROTOCOL_VERSION,+ agent_protocol_version: AGENT_PROTOCOL_VERSION,+ capabilities: vec!["blob_bind_statements_v1".into()],+ });+ let error = client+ .execute_blob_bound_typed::<serde_json::Value>(None, &["edited SQL".into()], &bound, None, true, None)+ .await+ .unwrap_err();+ assert!(error.into_legacy_string().contains("changed"));+ assert_eq!(client.next_id, 0);+ }+#[test]fn defines_agent_protocol_capabilities() {+ assert!(!agent_supports_capability(None, AgentCapability::BlobBindStatementsV1));+ assert!(!agent_supports_capability(+ Some(&AgentHandshake {+ protocol_version: AGENT_PROTOCOL_VERSION,+ agent_protocol_version: AGENT_PROTOCOL_VERSION,+ capabilities: vec!["query".into()]+ }),+ AgentCapability::BlobBindStatementsV1+ ));+ assert!(agent_supports_capability(+ Some(&AgentHandshake {+ protocol_version: AGENT_PROTOCOL_VERSION,+ agent_protocol_version: AGENT_PROTOCOL_VERSION,+ capabilities: vec!["blob_bind_statements_v1".into()]+ }),+ AgentCapability::BlobBindStatementsV1+ ));assert_eq!(AgentCapability::Connect.as_str(), "connect");assert_eq!(AgentCapability::TestConnection.as_str(), "test_connection");assert_eq!(AgentCapability::Metadata.as_str(), "metadata");@@ -5755,7 +5836,8 @@ for line in sys.stdin:assert_eq!(AgentCapability::MongoFindCursor.as_str(), "mongo_find_cursor");assert_eq!(AgentCapability::MultiSession.as_str(), "multi_session");assert_eq!(AgentCapability::StructuredErrorV1.as_str(), "structured_error_v1");- assert_eq!(AgentCapability::ALL.len(), 28);+ assert_eq!(AgentCapability::BlobBindStatementsV1.as_str(), "blob_bind_statements_v1");+ assert_eq!(AgentCapability::ALL.len(), 29);}#[test]diff --git a/crates/dbx-driver-mysql/src/mysql.rs b/crates/dbx-driver-mysql/src/mysql.rsindex 5594e1d9cc..3d22942132 100644--- a/crates/dbx-driver-mysql/src/mysql.rs+++ b/crates/dbx-driver-mysql/src/mysql.rs@@ -1288,7 +1288,12 @@ fn mysql_row_to_json_with_srids_and_previews(if let Some((preview, original_bytes)) =preview_bytes.and_then(|limit| mysql_bounded_value_preview(row, index, limit, protected_indexes)){- large_value_cells.push(LargeValueCell { row_index, column_index: index, original_bytes });+ large_value_cells.push(LargeValueCell {+ row_index,+ column_index: index,+ original_bytes,+ value_ref: None,+ });return preview;}mysql_value_to_json_with_effective_type(row, index, effective_types.get(index).map(String::as_str))@@ -9158,7 +9163,10 @@ mod tests {assert_eq!(values[0], serde_json::json!("k".repeat(2048)));assert_eq!(values[1].as_str().map(str::len), Some(1027));assert!(values[1].as_str().is_some_and(|value| value.ends_with("...")));- assert_eq!(cells, vec![LargeValueCell { row_index: 7, column_index: 1, original_bytes: 32 * 1024 }]);+ assert_eq!(+ cells,+ vec![LargeValueCell { row_index: 7, column_index: 1, original_bytes: 32 * 1024, value_ref: None }]+ );}#[test]@@ -9183,7 +9191,10 @@ mod tests {mysql_row_to_json_with_srids_and_previews(&row, &mut spatial_columns, 0, Some(512), &protected, &[]);assert_eq!(values[0], serde_json::json!("k".repeat(2048)));- assert_eq!(cells, vec![LargeValueCell { row_index: 0, column_index: 1, original_bytes: 4096 }]);+ assert_eq!(+ cells,+ vec![LargeValueCell { row_index: 0, column_index: 1, original_bytes: 4096, value_ref: None }]+ );}#[test]@@ -9223,7 +9234,10 @@ mod tests {assert!(values[1].as_str().is_some_and(|value| value.ends_with("...")));assert_eq!(values[2].as_str().map(str::len), Some(2 + 420 * 2));assert_eq!(values[3], serde_json::json!("B:419:25143"));- assert_eq!(cells, vec![LargeValueCell { row_index: 0, column_index: 1, original_bytes: 10_000 }]);+ assert_eq!(+ cells,+ vec![LargeValueCell { row_index: 0, column_index: 1, original_bytes: 10_000, value_ref: None }]+ );}#[test]diff --git a/crates/dbx-sql-data/src/data_grid_extractors/contract.rs b/crates/dbx-sql-data/src/data_grid_extractors/contract.rsindex b3c3a99897..3c2683a7c3 100644--- a/crates/dbx-sql-data/src/data_grid_extractors/contract.rs+++ b/crates/dbx-sql-data/src/data_grid_extractors/contract.rs@@ -156,6 +156,8 @@ pub struct DataGridExtractColumn {#[serde(default, skip_serializing_if = "Option::is_none")]pub source_name: Option<String>,pub source_index: usize,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub data_type: Option<String>,}#[derive(Debug, Clone, Serialize, Deserialize)]diff --git a/crates/dbx-sql-data/src/data_grid_extractors/sql.rs b/crates/dbx-sql-data/src/data_grid_extractors/sql.rsindex a6d09e600b..db4d84255f 100644--- a/crates/dbx-sql-data/src/data_grid_extractors/sql.rs+++ b/crates/dbx-sql-data/src/data_grid_extractors/sql.rs@@ -381,7 +381,11 @@ fn sql_selected_data(context: &ExtractContext<'_>, for_update: bool) -> Result<S.collect();let column_types = included_indexes.iter()- .map(|index| context.selected_column_info[*index].map(|info| info.data_type.clone()))+ .map(|index| {+ context.selected_column_info[*index]+ .map(|info| info.data_type.clone())+ .or_else(|| context.selected_columns[*index].data_type.clone())+ }).collect();let rows = context.requestdiff --git a/crates/dbx-sql-data/src/data_grid_extractors/tests.rs b/crates/dbx-sql-data/src/data_grid_extractors/tests.rsindex 86c069d3fc..3766235db5 100644--- a/crates/dbx-sql-data/src/data_grid_extractors/tests.rs+++ b/crates/dbx-sql-data/src/data_grid_extractors/tests.rs@@ -4,7 +4,12 @@ use crate::models::connection::DatabaseType;use serde_json::json;fn column(name: &str, source_index: usize) -> DataGridExtractColumn {- DataGridExtractColumn { display_name: name.to_string(), source_name: Some(name.to_string()), source_index }+ DataGridExtractColumn {+ display_name: name.to_string(),+ source_name: Some(name.to_string()),+ source_index,+ data_type: None,+ }}fn request(extractor: DataGridExtractorId) -> DataGridExtractRequest {@@ -51,6 +56,57 @@ fn temporal_insert_request() -> DataGridExtractRequest {native}+#[test]+fn oracle_query_insert_uses_real_result_types_without_table_metadata() {+ for database_type in [DatabaseType::Oracle, DatabaseType::OceanbaseOracle] {+ let mut value = serde_json::to_value(request(DataGridExtractorId::SqlInserts)).unwrap();+ value["databaseType"] = serde_json::to_value(database_type).unwrap();+ value["columns"] = json!([+ {"displayName":"D","sourceIndex":0,"dataType":"DATE"},+ {"displayName":"T","sourceIndex":1,"dataType":"TIMESTAMP"},+ {"displayName":"Z","sourceIndex":2,"dataType":"TIMESTAMP WITH TIME ZONE"},+ {"displayName":"TEXT","sourceIndex":3,"dataType":"VARCHAR2"}+ ]);+ value["selectedColumnIndexes"] = json!([2, 0, 1, 3]);+ value["rows"] = json!([+ [+ "2026-10-10 13:14:15",+ "2026-10-10 13:14:15.123456",+ "2026-10-10 13:14:15.123456 -5:30",+ "2026-10-10 13:14:15"+ ],+ [null, null, null, null]+ ]);+ let request = serde_json::from_value(value).unwrap();+ let sql = extract_data_grid_selection(request).unwrap().text;+ assert!(+ sql.contains("TO_TIMESTAMP_TZ('2026-10-10 13:14:15.123456 -05:30', 'YYYY-MM-DD HH24:MI:SS.FF TZH:TZM')")+ );+ assert!(sql.contains("TO_DATE('2026-10-10 13:14:15', 'YYYY-MM-DD HH24:MI:SS')"));+ assert!(sql.contains("TO_TIMESTAMP('2026-10-10 13:14:15.123456', 'YYYY-MM-DD HH24:MI:SS.FF')"));+ assert!(sql.contains(", '2026-10-10 13:14:15')"));+ assert!(sql.contains("VALUES (NULL, NULL, NULL, NULL)"));+ }+}++#[test]+fn query_insert_result_types_preserve_metadata_priority_and_unknown_strings() {+ let mut native = temporal_insert_request();+ let mut value = serde_json::to_value(&native).unwrap();+ value["columns"][1]["dataType"] = json!("DATE");+ native = serde_json::from_value(value).unwrap();+ let sql = extract_data_grid_selection(native).unwrap().text;+ assert!(sql.contains("'it''s text'"));+ let mut value = serde_json::to_value(request(DataGridExtractorId::SqlInserts)).unwrap();+ value["databaseType"] = serde_json::to_value(DatabaseType::OceanbaseOracle).unwrap();+ value["columns"][1]["dataType"] = json!("UNKNOWN");+ value["rows"] = json!([[1, "2026-10-10 13:14:15"]]);+ assert!(extract_data_grid_selection(serde_json::from_value(value).unwrap())+ .unwrap()+ .text+ .contains("'2026-10-10 13:14:15'"));+}+#[test]fn sql_insert_temporal_format_contract_and_output() {let native = temporal_insert_request();@@ -1254,7 +1310,7 @@ fn select_cells_falls_back_to_display_name_like_where_clause() {columns: None,});request.columns = vec![- DataGridExtractColumn { display_name: "id".to_string(), source_name: None, source_index: 0 },+ DataGridExtractColumn { display_name: "id".to_string(), source_name: None, source_index: 0, data_type: None },column("name", 1),];let mut where_request = request.clone();diff --git a/crates/dbx-sql-data/src/data_grid_sql.rs b/crates/dbx-sql-data/src/data_grid_sql.rsindex 0f13637fcc..de4891dd3b 100644--- a/crates/dbx-sql-data/src/data_grid_sql.rs+++ b/crates/dbx-sql-data/src/data_grid_sql.rs@@ -387,6 +387,8 @@ pub struct DataGridSavePreparation {/// Checks the caller must run — and pass — before executing `statements`.#[serde(default, skip_serializing_if = "Vec::is_empty")]pub keyless_guards: Vec<DataGridSaveGuard>,+ #[serde(default, skip_serializing_if = "Vec::is_empty")]+ pub bound_statements: Vec<dbx_types::types::BlobBoundStatement>,}pub fn prepare_data_grid_save(options: DataGridSaveStatementOptions) -> DataGridSavePreparation {@@ -409,6 +411,7 @@ pub fn prepare_data_grid_save_for_driver_profile(&options.table_meta,),keyless_guards: Vec::new(),+ bound_statements: Vec::new(),};}@@ -427,15 +430,22 @@ pub fn prepare_data_grid_save_for_driver_profile(rollback_statements,execution_schema: None,keyless_guards,+ bound_statements: Vec::new(),};}- let statements = build_data_grid_save_statements(&options, driver_profile, &mut keyless_guards);+ let mut bound_statements = Vec::new();+ let statements =+ build_data_grid_save_statements(&options, driver_profile, &mut keyless_guards, &mut bound_statements);+ if !bound_statements.iter().any(|statement| !statement.blob_parameters.is_empty()) {+ bound_statements.clear();+ }DataGridSavePreparation {validation_error: None,statements,rollback_statements: build_data_grid_rollback_statements(&options, driver_profile),execution_schema: data_grid_save_execution_schema(options.database_type, driver_profile, &options.table_meta),keyless_guards,+ bound_statements,}}@@ -488,6 +498,14 @@ pub fn build_data_grid_copy_update_statements(options: DataGridCopyUpdateStatemeif writable_indexes.is_empty() {return Vec::new();}+ if options.rows.iter().any(|row| {+ writable_indexes.iter().any(|(_, index, info)| {+ is_oceanbase_blob_column(options.database_type, *info)+ && row.get(*index).is_some_and(|value| !value.is_null() && oceanbase_blob_hex(value).is_none())+ })+ }) {+ return Vec::new();+ }let table = data_grid_generated_table_name(options.database_type,@@ -606,6 +624,14 @@ pub(crate) fn build_data_grid_copy_insert_statement_with_formatters(if insert_columns.is_empty() || options.rows.is_empty() {return None;}+ if options.rows.iter().any(|row| {+ insert_columns.iter().any(|(_, index, info)| {+ is_oceanbase_blob_column(options.database_type, info.as_ref())+ && row.get(*index).is_some_and(|value| !value.is_null() && oceanbase_blob_hex(value).is_none())+ })+ }) {+ return None;+ }let table = options.table_meta.as_ref().map_or_else(|| "table_name".to_string(),@@ -697,7 +723,17 @@ pub(crate) fn build_data_grid_copy_insert_statement_with_formatters(let statements = if options.insert_mode == DataGridCopyInsertMode::RowByRow|| options.database_type.is_some_and(uses_single_row_insert_statements){- value_rows.iter().map(|values| format!("INSERT INTO {table} ({columns}) VALUES {values};")).collect::<Vec<_>>()+ value_rows+ .iter()+ .map(|values| {+ let sql = format!("INSERT INTO {table} ({columns}) VALUES {values}");+ if options.database_type == Some(DatabaseType::OceanbaseOracle) {+ data_grid_statement(options.database_type, sql)+ } else {+ format!("{sql};")+ }+ })+ .collect::<Vec<_>>()} else {vec![format!("INSERT INTO {table} ({columns}) VALUES{}{};",@@ -1287,6 +1323,9 @@ fn build_neo4j_data_grid_column_distinct_values_sql(options: &DataGridColumnDist}fn validate_data_grid_save(options: &DataGridSaveStatementOptions) -> Option<String> {+ if let Some(error) = validate_oceanbase_blob_save(options) {+ return Some(error);+ }if let Some(error) = validate_opaque_aggregate_state_write(options) {return Some(error);}@@ -1632,6 +1671,7 @@ fn build_data_grid_save_statements(options: &DataGridSaveStatementOptions,driver_profile: Option<&str>,keyless_guards: &mut Vec<DataGridSaveGuard>,+ bound_statements: &mut Vec<dbx_types::types::BlobBoundStatement>,) -> Vec<String> {if options.database_type == Some(DatabaseType::Tdengine) {return build_tdengine_data_grid_save_statements(options);@@ -1701,7 +1741,7 @@ fn build_data_grid_save_statements(if sets.is_empty() {continue;}- let where_clause = build_primary_key_where(+ let mut where_clause = build_primary_key_where(options.database_type,&options.table_meta.primary_keys,&save_columns,@@ -1709,6 +1749,13 @@ fn build_data_grid_save_statements(column_info,options.identifier_quote.as_deref(),);+ let guarded_lob = append_oceanbase_lob_save_guards(+ options,+ &save_columns,+ row,+ changes.iter().map(|(index, _)| *index),+ &mut where_clause,+ );guard_predicate(&where_clause, &mut guarded_predicates);if batch_mysql_writes {if update_sets.as_deref().is_some_and(|current| current != sets) {@@ -1722,10 +1769,8 @@ fn build_data_grid_save_statements(update_sets = Some(sets);update_predicates.push(where_clause);} else {- statements.push(data_grid_statement(- options.database_type,- data_grid_update_sql(options.database_type, &table, &sets, &where_clause),- ));+ let statement = data_grid_update_sql(options.database_type, &table, &sets, &where_clause);+ statements.push(data_grid_save_statement(options.database_type, statement, guarded_lob, bound_statements));}}if let Some(sets) = update_sets {@@ -1737,7 +1782,7 @@ fn build_data_grid_save_statements(let Some(row) = options.rows.get(*row_index) else {continue;};- let where_clause = build_primary_key_where(+ let mut where_clause = build_primary_key_where(options.database_type,&options.table_meta.primary_keys,&save_columns,@@ -1745,14 +1790,14 @@ fn build_data_grid_save_statements(column_info,options.identifier_quote.as_deref(),);+ let guarded_lob =+ append_oceanbase_lob_save_guards(options, &save_columns, row, 0..save_columns.len(), &mut where_clause);guard_predicate(&where_clause, &mut guarded_predicates);if batch_mysql_writes {delete_predicates.push(where_clause);} else {- statements.push(data_grid_statement(- options.database_type,- data_grid_delete_sql(options.database_type, &table, &where_clause),- ));+ let statement = data_grid_delete_sql(options.database_type, &table, &where_clause);+ statements.push(data_grid_save_statement(options.database_type, statement, guarded_lob, bound_statements));}}if !delete_predicates.is_empty() {@@ -1809,13 +1854,15 @@ fn build_data_grid_save_statements(}).collect::<Vec<_>>().join(", ");- statements.push(data_grid_statement(+ statements.push(data_grid_save_statement(options.database_type,if options.database_type == Some(DatabaseType::Transwarp) {format!("INSERT INTO {table} ({columns}) SELECT {values}")} else {format!("INSERT INTO {table} ({columns}) VALUES ({values})")},+ false,+ bound_statements,));}@@ -2450,9 +2497,22 @@ fn format_grid_assignment_sql_literal(column_info: Option<&DataGridColumnInfo>,identifier_quote: Option<&str>,) -> String {+ if is_oceanbase_blob_column(database_type, column_info) {+ if value.is_null() {+ return "NULL".to_string();+ }+ if let Some(hex) = oceanbase_blob_hex(value) {+ return if hex.is_empty() { "EMPTY_BLOB()".to_string() } else { format!("TO_BLOB(HEXTORAW('{hex}'))") };+ }+ // Invalid input must fail in SQL rather than storing the display text as bytes.+ return "TO_BLOB(HEXTORAW('invalid BLOB hex'))".to_string();+ }if matches!(database_type, Some(DatabaseType::Oracle | DatabaseType::OceanbaseOracle)) {if let Some(constructor) = column_info.and_then(|column| oracle_character_lob_constructor(&column.data_type)) {if let Some(text) = value.as_str() {+ if database_type == Some(DatabaseType::OceanbaseOracle) && text.is_empty() && constructor == "TO_CLOB" {+ return "EMPTY_CLOB()".to_string();+ }return format_oracle_lob_assignment_literal(text, constructor);}}@@ -2933,6 +2993,27 @@ fn regex_like_oracle_temporal(text: &str) -> Option<Rfc3339Parts> {if let Some(parts) = regex_like_rfc3339(text) {return Some(parts);}+ if let Some((datetime, zone)) = text.rsplit_once(' ') {+ let bytes = zone.as_bytes();+ let normalized_zone = if is_timezone_offset(zone) {+ Some(zone.to_string())+ } else if bytes.len() == 5+ && matches!(bytes[0], b'+' | b'-')+ && bytes[1].is_ascii_digit()+ && bytes[2] == b':'+ && bytes[3].is_ascii_digit()+ && bytes[4].is_ascii_digit()+ {+ Some(format!("{}0{}", &zone[..1], &zone[1..]))+ } else {+ None+ };+ if let Some(zone) = normalized_zone {+ let mut parts = regex_like_local_datetime(datetime)?;+ parts.zone = zone;+ return Some(parts);+ }+ }regex_like_local_datetime(text)}@@ -3412,6 +3493,8 @@ pub fn build_column_predicate(let ident = predicate_ident(database_type, column, identifier_quote);if value.is_null() {format!("{ident} IS NULL")+ } else if let Some(predicate) = oceanbase_lob_predicate(database_type, &ident, value, column_info) {+ predicate} else if use_binary_text_comparison && uses_mysql_binary_text_predicate(database_type, value, column_info) {format!("BINARY {ident} = {}",@@ -3439,6 +3522,8 @@ fn build_save_column_predicate(let ident = predicate_ident(database_type, column, identifier_quote);if value.is_null() || empty_string_saves_as_null(value, column_info) {format!("{ident} IS NULL")+ } else if let Some(predicate) = oceanbase_lob_predicate(database_type, &ident, value, column_info) {+ predicate} else if use_binary_text_comparison && uses_mysql_binary_text_predicate(database_type, value, column_info) {format!("BINARY {ident} = {}",@@ -3455,6 +3540,137 @@ fn build_save_column_predicate(}}+fn oceanbase_lob_predicate(+ database_type: Option<DatabaseType>,+ ident: &str,+ value: &Value,+ column_info: Option<&DataGridColumnInfo>,+) -> Option<String> {+ if is_oceanbase_blob_column(database_type, column_info) {+ if value.is_null() {+ return Some(format!("{ident} IS NULL"));+ }+ let Some(hex) = oceanbase_blob_hex(value) else {+ return Some("1 = 0".to_string());+ };+ if hex.len() > 4000 {+ // Reuse the temporary BLOB bind in oceanbase_blob_statement instead of+ // compiling one RAW predicate per 1000 bytes of the original value.+ return Some(format!(+ "(DBMS_LOB.GETLENGTH({ident}) = {} AND DBMS_LOB.COMPARE({ident}, TO_BLOB(HEXTORAW('{hex}'))) = 0)",+ hex.len() / 2+ ));+ }+ let mut predicates = vec![format!("DBMS_LOB.GETLENGTH({ident}) = {}", hex.len() / 2)];+ for (index, chunk) in hex.as_bytes().chunks(2000).enumerate() {+ let chunk = std::str::from_utf8(chunk).expect("validated ASCII hex");+ predicates.push(format!(+ "DBMS_LOB.SUBSTR({ident}, {}, {}) = HEXTORAW('{chunk}')",+ chunk.len() / 2,+ index * 1000 + 1+ ));+ }+ return Some(format!("({})", predicates.join(" AND ")));+ }+ if database_type != Some(DatabaseType::OceanbaseOracle)+ || column_info.and_then(|column| oracle_character_lob_constructor(&column.data_type)) != Some("TO_CLOB")+ {+ return None;+ }+ if value.is_null() {+ return Some(format!("{ident} IS NULL"));+ }+ let text = value.as_str()?;+ let mut predicates = vec![format!("DBMS_LOB.GETLENGTH({ident}) = {}", text.chars().count())];+ let mut offset = 1;+ let mut chunk = String::new();+ let mut count = 0;+ for ch in text.chars() {+ if chunk.len() + oracle_sql_literal_char_len(ch) > 2000 {+ predicates.push(format!(+ "UTL_RAW.CAST_TO_RAW(DBMS_LOB.SUBSTR({ident}, {count}, {offset})) = UTL_RAW.CAST_TO_RAW('{chunk}')"+ ));+ offset += count;+ chunk.clear();+ count = 0;+ }+ append_oracle_sql_literal_char(&mut chunk, ch);+ count += 1;+ }+ if count > 0 {+ predicates.push(format!(+ "UTL_RAW.CAST_TO_RAW(DBMS_LOB.SUBSTR({ident}, {count}, {offset})) = UTL_RAW.CAST_TO_RAW('{chunk}')"+ ));+ }+ Some(format!("({})", predicates.join(" AND ")))+}++fn append_oceanbase_lob_save_guards(+ options: &DataGridSaveStatementOptions,+ columns: &[Option<String>],+ row: &[Value],+ indexes: impl Iterator<Item = usize>,+ where_clause: &mut String,+) -> bool {+ let mut guarded = false;+ let column_info = options.table_meta.columns.as_deref().unwrap_or(&[]);+ for index in indexes {+ let Some(column) = columns.get(index).and_then(|column| column.as_deref()) else {+ continue;+ };+ let ident = predicate_ident(options.database_type, column, options.identifier_quote.as_deref());+ if let Some(predicate) = oceanbase_lob_predicate(+ options.database_type,+ &ident,+ row.get(index).unwrap_or(&Value::Null),+ column_info_for(column_info, column),+ ) {+ if !where_clause.is_empty() {+ where_clause.push_str(" AND ");+ }+ where_clause.push_str(&predicate);+ guarded = true;+ }+ }+ guarded+}++fn data_grid_save_statement(+ database_type: Option<DatabaseType>,+ sql: String,+ guard_row_count: bool,+ bound: &mut Vec<dbx_types::types::BlobBoundStatement>,+) -> String {+ let preview = if guard_row_count {+ oceanbase_guarded_lob_statement(sql.clone())+ } else {+ data_grid_statement(database_type, sql.clone())+ };+ if database_type == Some(DatabaseType::OceanbaseOracle) {+ let (rewritten, blobs) = oceanbase_blob_literals(&sql, true);+ let execution_sql = if blobs.is_empty() {+ preview.clone()+ } else if guard_row_count {+ format!("BEGIN\n{rewritten};\nIF SQL%ROWCOUNT <> 1 THEN RAISE_APPLICATION_ERROR(-20001, 'LOB target changed or missing; reload before saving'); END IF;\nEND;")+ } else {+ rewritten+ };+ bound.push(dbx_types::types::BlobBoundStatement {+ preview_sql: preview.clone(),+ sql: execution_sql,+ blob_parameters: blobs.into_iter().map(str::to_string).collect(),+ });+ }+ preview+}++fn oceanbase_guarded_lob_statement(sql: String) -> String {+ if let Some(statement) = oceanbase_blob_statement(&sql, true) {+ return statement;+ }+ format!("BEGIN\n{sql};\nIF SQL%ROWCOUNT <> 1 THEN\nRAISE_APPLICATION_ERROR(-20001, 'LOB target changed or missing; reload before saving');\nEND IF;\nEND;")+}+fn postgres_keyless_json_predicate(database_type: Option<DatabaseType>,ident: &str,@@ -3488,6 +3704,11 @@ fn mysql_json_predicate_literal(}fn data_grid_statement(database_type: Option<DatabaseType>, sql: String) -> String {+ if database_type == Some(DatabaseType::OceanbaseOracle) {+ if let Some(statement) = oceanbase_blob_statement(&sql, false) {+ return statement;+ }+ }if database_type == Some(DatabaseType::ManticoreSearch) {sql} else {@@ -3495,6 +3716,137 @@ fn data_grid_statement(database_type: Option<DatabaseType>, sql: String) -> Stri}}+fn is_oceanbase_blob_column(database_type: Option<DatabaseType>, column_info: Option<&DataGridColumnInfo>) -> bool {+ database_type == Some(DatabaseType::OceanbaseOracle)+ && column_info.is_some_and(|column| column.data_type.trim().eq_ignore_ascii_case("BLOB"))+}++fn oceanbase_blob_hex(value: &Value) -> Option<&str> {+ let hex = value.as_str()?.strip_prefix("0x")?;+ (hex.len() % 2 == 0 && hex.bytes().all(|byte| byte.is_ascii_hexdigit())).then_some(hex)+}++fn validate_oceanbase_blob_save(options: &DataGridSaveStatementOptions) -> Option<String> {+ if options.database_type != Some(DatabaseType::OceanbaseOracle) {+ return None;+ }+ let columns = effective_columns(options);+ let info = options.table_meta.columns.as_deref().unwrap_or(&[]);+ let valid = |index: usize, value: &Value| {+ !is_oceanbase_blob_column(+ options.database_type,+ columns.get(index).and_then(|column| column.as_deref()).and_then(|column| column_info_for(info, column)),+ ) || value.is_null()+ || oceanbase_blob_hex(value).is_some()+ };+ for (row_index, changes) in &options.dirty_rows {+ for (index, value) in changes {+ if !valid(*index, value)+ || options+ .rows+ .get(*row_index)+ .is_some_and(|row| !valid(*index, row.get(*index).unwrap_or(&Value::Null)))+ {+ return Some("OceanBase BLOB values must be NULL or 0x followed by complete hexadecimal byte pairs; reload the original value before saving.".to_string());+ }+ }+ }+ for row in options.deleted_rows.iter().filter_map(|index| options.rows.get(*index)).chain(options.new_rows.iter()) {+ if row.iter().enumerate().any(|(index, value)| !valid(index, value)) {+ return Some("OceanBase BLOB values must be NULL or 0x followed by complete hexadecimal byte pairs; reload the original value before saving.".to_string());+ }+ }+ None+}++// Only rewrite our generated BLOB literal outside quoted strings/identifiers. The SQL text+// uses binds so temporary PL variables cannot resolve to an identically named table column.+fn oceanbase_blob_statement(sql: &str, guard_row_count: bool) -> Option<String> {+ let (rewritten, blobs) = oceanbase_blob_literals(sql, false);+ if blobs.is_empty() {+ return None;+ }+ oceanbase_temporary_blob_statement(&rewritten, &blobs, guard_row_count)+}++fn oceanbase_blob_literals(sql: &str, positional: bool) -> (String, Vec<&str>) {+ const PREFIX: &str = "TO_BLOB(HEXTORAW('";+ let sql = sql.trim_end_matches(';');+ let mut rewritten = String::new();+ let mut blobs = Vec::new();+ let mut index = 0;+ while index < sql.len() {+ let rest = &sql[index..];+ if let Some(hex_start) = rest.strip_prefix(PREFIX) {+ if let Some(end) = hex_start.find("'))") {+ let hex = &hex_start[..end];+ if hex.len() > 4000 && hex.len() % 2 == 0 && hex.bytes().all(|byte| byte.is_ascii_hexdigit()) {+ rewritten.push_str(&if positional { "?".to_string() } else { format!(":dbx_lob_{}", blobs.len()) });+ blobs.push(hex);+ index += PREFIX.len() + end + 3;+ continue;+ }+ }+ }+ let ch = rest.chars().next().expect("nonempty SQL remainder");+ rewritten.push(ch);+ index += ch.len_utf8();+ if ch == '\'' || ch == '"' {+ while index < sql.len() {+ let quoted = sql[index..].chars().next().expect("nonempty quoted remainder");+ rewritten.push(quoted);+ index += quoted.len_utf8();+ if quoted == ch {+ if sql[index..].starts_with(ch) {+ rewritten.push(ch);+ index += ch.len_utf8();+ } else {+ break;+ }+ }+ }+ }+ }+ (rewritten, blobs)+}++fn oceanbase_temporary_blob_statement(rewritten: &str, blobs: &[&str], guard_row_count: bool) -> Option<String> {+ let mut statement = "DECLARE\ndbx_sql CLOB;\n".to_string();+ let mut cleanup = String::new();+ for index in 0..blobs.len() {+ statement.push_str(&format!("dbx_lob_{index} BLOB;\n"));+ cleanup.push_str(&format!(+ "IF DBMS_LOB.ISTEMPORARY(dbx_lob_{index}) = 1 THEN DBMS_LOB.FREETEMPORARY(dbx_lob_{index}); END IF;\n"+ ));+ }+ statement.push_str("BEGIN\ndbx_sql := ");+ statement.push_str(&format_oracle_lob_assignment_literal(rewritten, "TO_CLOB"));+ statement.push_str(";\n");+ for (index, hex) in blobs.iter().enumerate() {+ statement.push_str(&format!("DBMS_LOB.CREATETEMPORARY(dbx_lob_{index}, TRUE, DBMS_LOB.CALL);\n"));+ for chunk in hex.as_bytes().chunks(2000) {+ let chunk = std::str::from_utf8(chunk).expect("validated ASCII hex");+ statement.push_str(&format!(+ "DBMS_LOB.WRITEAPPEND(dbx_lob_{index}, {}, HEXTORAW('{chunk}'));\n",+ chunk.len() / 2+ ));+ }+ }+ statement.push_str(&format!(+ "EXECUTE IMMEDIATE dbx_sql USING {};\n",+ (0..blobs.len()).map(|index| format!("dbx_lob_{index}")).collect::<Vec<_>>().join(", ")+ ));+ if guard_row_count {+ statement.push_str("IF SQL%ROWCOUNT <> 1 THEN RAISE_APPLICATION_ERROR(-20001, 'LOB target changed or missing; reload before saving'); END IF;\n");+ }+ cleanup.push_str("IF DBMS_LOB.ISTEMPORARY(dbx_sql) = 1 THEN DBMS_LOB.FREETEMPORARY(dbx_sql); END IF;\n");+ statement.push_str(&cleanup);+ statement.push_str("EXCEPTION WHEN OTHERS THEN\n");+ statement.push_str(&cleanup);+ statement.push_str("RAISE;\nEND;");+ Some(statement)+}+fn data_grid_update_sql(database_type: Option<DatabaseType>, table: &str, sets: &str, where_clause: &str) -> String {if database_type == Some(DatabaseType::ClickHouse) {format!("ALTER TABLE {table} UPDATE {sets} WHERE {where_clause}")@@ -7307,6 +7659,60 @@ mod tests {);}+ #[test]+ fn copy_insert_preserves_oracle_agent_timezone_values_and_nulls() {+ for database_type in [DatabaseType::Oracle, DatabaseType::OceanbaseOracle] {+ for (data_type, value, literal) in [+ (+ "TIMESTAMP WITH TIME ZONE",+ "2026-10-09 13:14:15 +8:00",+ "TO_TIMESTAMP_TZ('2026-10-09 13:14:15 +08:00', 'YYYY-MM-DD HH24:MI:SS TZH:TZM')",+ ),+ (+ "TIMESTAMP(6) WITH TIME ZONE",+ "2026-10-09 13:14:15.123456 +8:00",+ "TO_TIMESTAMP_TZ('2026-10-09 13:14:15.123456 +08:00', 'YYYY-MM-DD HH24:MI:SS.FF TZH:TZM')",+ ),+ (+ "timestamp(9) with time zone",+ "2026-10-09 13:14:15.123456789 -5:30",+ "TO_TIMESTAMP_TZ('2026-10-09 13:14:15.123456789 -05:30', 'YYYY-MM-DD HH24:MI:SS.FF TZH:TZM')",+ ),+ (+ "TIMESTAMP(3) WITH TIME ZONE",+ "2026-10-09 13:14:15.123 +00:00",+ "TO_TIMESTAMP_TZ('2026-10-09 13:14:15.123 +00:00', 'YYYY-MM-DD HH24:MI:SS.FF TZH:TZM')",+ ),+ ] {+ for has_table_columns in [true, false] {+ let statement = build_data_grid_copy_insert_statement(DataGridCopyInsertStatementOptions {+ database_type: Some(database_type),+ identifier_quote: None,+ table_meta: Some(DataGridTableMeta {+ catalog: None,+ database: None,+ schema: None,+ table_name: "tz_roundtrip".to_string(),+ primary_keys: vec![],+ columns: has_table_columns.then(|| vec![column("Z", data_type, true, None)]),+ }),+ columns: vec!["Z".to_string()],+ column_types: Some(vec![Some(data_type.to_string())]),+ source_columns: None,+ rows: vec![vec![json!(value)], vec![Value::Null]],+ exclude_primary_keys: false,+ include_computed_columns: false,+ include_database_name: false,+ insert_mode: DataGridCopyInsertMode::RowByRow,+ })+ .unwrap();+ assert!(statement.contains(literal), "{database_type:?}: {statement}");+ assert!(statement.contains("VALUES (NULL)"), "{statement}");+ }+ }+ }+ }+#[test]fn formats_oracle_temporal_literals_from_editor_values_without_nls_parsing() {let timestamp = column("created_at", "TIMESTAMP(6)", true, None);@@ -7338,6 +7744,208 @@ mod tests {);}+ #[test]+ fn prepares_oceanbase_blob_bytes_and_snapshot_guards() {+ let blob = column("CONTENT", "BLOB", true, None);+ let database_type = Some(DatabaseType::OceanbaseOracle);+ assert_eq!(format_grid_assignment_sql_literal(&json!("0x"), database_type, Some(&blob), None), "EMPTY_BLOB()");+ assert_eq!(format_grid_assignment_sql_literal(&Value::Null, database_type, Some(&blob), None), "NULL");+ assert_eq!(+ format_grid_assignment_sql_literal(&json!("0x00ff"), database_type, Some(&blob), None),+ "TO_BLOB(HEXTORAW('00ff'))"+ );+ assert_eq!(+ build_column_predicate(database_type, "CONTENT", &json!("0x"), Some(&blob), true, None),+ "(DBMS_LOB.GETLENGTH(\"CONTENT\") = 0)"+ );+ let original = format!("0x{}ff", "00".repeat(1000));+ let new_value = format!("0x{}80", "00ff".repeat(1500));+ let mut options = DataGridSaveStatementOptions {+ database_type,+ identifier_quote: None,+ server_version: None,+ table_meta: DataGridTableMeta {+ catalog: None,+ database: None,+ schema: Some("APP".into()),+ table_name: "FILES".into(),+ primary_keys: vec!["ID".into()],+ columns: Some(vec![column("ID", "NUMBER", false, None), blob]),+ },+ columns: vec!["ID".into(), "CONTENT".into()],+ source_columns: None,+ rows: vec![vec![json!(1), json!(original)]],+ dirty_rows: vec![(0, vec![(1, json!(new_value))])],+ deleted_rows: vec![],+ new_rows: vec![],+ include_database_name: false,+ };+ let prepared = prepare_data_grid_save(options.clone());+ assert_eq!(prepared.validation_error, None);+ let sql = &prepared.statements[0];+ assert!(sql.starts_with("DECLARE\n"));+ assert!(sql.contains("CREATETEMPORARY(dbx_lob_0"));+ assert_eq!(sql.matches("WRITEAPPEND(dbx_lob_0").count(), 4);+ assert!(sql.contains("WRITEAPPEND(dbx_lob_0, 1, HEXTORAW('80'))"));+ assert!(sql.contains("EXECUTE IMMEDIATE dbx_sql USING dbx_lob_0"));+ assert!(sql.contains("DBMS_LOB.SUBSTR(\"CONTENT\", 1, 1001) = HEXTORAW(''ff'')"));+ assert!(sql.contains("SQL%ROWCOUNT <> 1"));+ assert_eq!(sql.matches("FREETEMPORARY(dbx_lob_0)").count(), 2);+ assert!(prepared.rollback_statements[0].contains("DBMS_LOB.GETLENGTH(\"CONTENT\") = 3001"));+ options.dirty_rows[0].1[0].1 = json!("0x123");+ let invalid = prepare_data_grid_save(options);+ assert!(invalid.validation_error.is_some());+ assert!(invalid.statements.is_empty());+ }++ #[test]+ fn oceanbase_large_blob_baseline_uses_one_exact_bound_comparison() {+ let original = format!("0x{}80", "00ff".repeat(524291)); // 1 MiB + 7 bytes+ let prepared = prepare_data_grid_save(DataGridSaveStatementOptions {+ database_type: Some(DatabaseType::OceanbaseOracle),+ identifier_quote: None,+ server_version: None,+ table_meta: DataGridTableMeta {+ catalog: None,+ database: None,+ schema: Some("APP".into()),+ table_name: "FILES".into(),+ primary_keys: vec!["ID".into()],+ columns: Some(vec![column("ID", "NUMBER", false, None), column("CONTENT", "BLOB", true, None)]),+ },+ columns: vec!["ID".into(), "CONTENT".into()],+ source_columns: None,+ rows: vec![vec![json!(6), json!(original)]],+ dirty_rows: vec![(0, vec![(1, json!("0x00ff80"))])],+ deleted_rows: vec![],+ new_rows: vec![],+ include_database_name: false,+ });+ assert_eq!(prepared.validation_error, None);+ let sql = &prepared.statements[0];+ assert_eq!(sql.matches("DBMS_LOB.COMPARE").count(), 1);+ assert!(!sql.contains("DBMS_LOB.SUBSTR"));+ assert!(sql.contains("DBMS_LOB.COMPARE(\"CONTENT\", :dbx_lob_0) = 0"));+ assert!(sql.contains("DBMS_LOB.GETLENGTH(\"CONTENT\") = 1048583"));+ assert!(sql.contains("EXECUTE IMMEDIATE dbx_sql USING dbx_lob_0"));+ assert!(sql.contains("SQL%ROWCOUNT <> 1"));+ assert_eq!(sql.matches("FREETEMPORARY(dbx_lob_0)").count(), 2);+ let bound = &prepared.bound_statements[0];+ assert_eq!(bound.preview_sql, *sql);+ assert!(bound.sql.len() < 512);+ assert!(!bound.sql.contains("WRITEAPPEND"));+ assert!(bound.sql.contains("DBMS_LOB.COMPARE(\"CONTENT\", ?) = 0"));+ assert_eq!(bound.blob_parameters.len(), 1);+ assert_eq!(bound.blob_parameters[0].len(), 1048583 * 2);+ }++ #[test]+ fn oceanbase_blob_statement_keeps_literal_text_and_identifiers_opaque() {+ let hex = "abcd".repeat(1001);+ let sql = format!("UPDATE \"TO_BLOB(HEXTORAW('fake'))\" SET \"B\" = TO_BLOB(HEXTORAW('{hex}')), \"T\" = 'TO_BLOB(HEXTORAW(''{hex}''))' WHERE \"ID\" = 1");+ let statement = oceanbase_blob_statement(&sql, false).unwrap();+ assert_eq!(statement.matches("CREATETEMPORARY(").count(), 1);+ assert!(statement.contains("USING dbx_lob_0"));+ assert!(!statement.contains("dbx_lob_1"));+ assert!(!statement.contains("SQL%ROWCOUNT <> 1"));+ assert_eq!(oceanbase_blob_statement("UPDATE T SET B = TO_BLOB(HEXTORAW('00ff'))", false), None);+ assert_eq!(+ oceanbase_blob_statement(&format!("UPDATE T SET TXT = 'TO_BLOB(HEXTORAW(''{hex}''))'"), false),+ None+ );+ }++ #[test]+ fn oceanbase_bound_blobs_keep_new_and_original_values_in_sql_order() {+ let old_a = "11".repeat(2049);+ let old_b = "22".repeat(2050);+ let new_a = "33".repeat(2051);+ let new_b = "44".repeat(2052);+ let mut options = DataGridSaveStatementOptions {+ database_type: Some(DatabaseType::OceanbaseOracle),+ identifier_quote: None,+ server_version: None,+ table_meta: DataGridTableMeta {+ catalog: None,+ database: None,+ schema: Some("APP".into()),+ table_name: "FILES".into(),+ primary_keys: vec!["ID".into()],+ columns: Some(vec![+ column("ID", "NUMBER", false, None),+ column("A", "BLOB", true, None),+ column("B", "BLOB", true, None),+ ]),+ },+ columns: vec!["ID".into(), "A".into(), "B".into()],+ source_columns: None,+ rows: vec![vec![json!(1), json!(format!("0x{old_a}")), json!(format!("0x{old_b}"))]],+ dirty_rows: vec![(0, vec![(1, json!(format!("0x{new_a}"))), (2, json!(format!("0x{new_b}")))])],+ deleted_rows: vec![],+ new_rows: vec![],+ include_database_name: false,+ };+ let prepared = prepare_data_grid_save(options.clone());+ let bound = &prepared.bound_statements[0];+ assert_eq!(bound.blob_parameters, vec![new_a, new_b, old_a.clone(), old_b.clone()]);+ assert_eq!(bound.sql.matches('?').count(), 4);+ assert!(bound.sql.contains("SQL%ROWCOUNT <> 1"));+ for (value, literal) in [(Value::Null, "NULL"), (json!("0x"), "EMPTY_BLOB()")] {+ options.dirty_rows = vec![(0, vec![(1, value)])];+ let prepared = prepare_data_grid_save(options.clone());+ assert_eq!(prepared.bound_statements[0].blob_parameters, vec![old_a.clone()]);+ assert!(prepared.bound_statements[0].sql.contains(&format!("\"A\" = {literal}")));+ }+ }++ #[test]+ fn prepares_oceanbase_clob_guards_and_preserves_empty_lob() {+ let clob = column("BODY", "CLOB", true, None);+ let database_type = Some(DatabaseType::OceanbaseOracle);+ assert_eq!(format_grid_assignment_sql_literal(&json!(""), database_type, Some(&clob), None), "EMPTY_CLOB()");+ assert_eq!(+ build_column_predicate(database_type, "BODY", &json!(""), Some(&clob), true, None),+ "(DBMS_LOB.GETLENGTH(\"BODY\") = 0)"+ );+ assert_eq!(+ build_column_predicate(database_type, "BODY", &Value::Null, Some(&clob), true, None),+ "\"BODY\" IS NULL"+ );+ let text = format!("{}'尾", "😀".repeat(501));+ let predicate = build_column_predicate(database_type, "BODY", &json!(text), Some(&clob), true, None);+ assert!(predicate.contains("GETLENGTH(\"BODY\") = 503"));+ assert!(predicate.contains("SUBSTR(\"BODY\", 500, 1)"));+ assert!(predicate.contains("SUBSTR(\"BODY\", 3, 501)"));+ assert!(predicate.contains("😀''尾"));+ assert!(!predicate.contains("DBMS_LOB.COMPARE"));++ let result = prepare_data_grid_save(DataGridSaveStatementOptions {+ database_type,+ identifier_quote: None,+ server_version: None,+ table_meta: DataGridTableMeta {+ catalog: None,+ database: None,+ schema: Some("APP".into()),+ table_name: "DOCS".into(),+ primary_keys: vec!["ID".into()],+ columns: Some(vec![column("ID", "NUMBER", false, None), clob]),+ },+ columns: vec!["ID".into(), "BODY".into()],+ source_columns: None,+ rows: vec![vec![json!(1), json!("original")]],+ dirty_rows: vec![(0, vec![(1, json!("edited"))])],+ deleted_rows: vec![],+ new_rows: vec![],+ include_database_name: false,+ });+ assert_eq!(result.validation_error, None);+ assert!(result.statements[0].contains("\"BODY\" = 'edited'"));+ assert!(result.statements[0].contains("UTL_RAW.CAST_TO_RAW('original')"));+ assert!(result.statements[0].contains("SQL%ROWCOUNT <> 1"));+ assert!(result.rollback_statements[0].contains("UTL_RAW.CAST_TO_RAW('edited')"));+ }+#[test]fn prepares_oracle_clob_update_without_oversized_string_literals() {let clob = column("body", "CLOB", true, None);@@ -8593,7 +9201,13 @@ mod tests {],source_columns: None,rows: vec![- vec![json!("*AAABk1AAEAAAAAgAAA"), json!("task-1"), json!("response"), json!("0011"), json!("archive")],+ vec![+ json!("*AAABk1AAEAAAAAgAAA"),+ json!("task-1"),+ json!("response"),+ json!("0x0011"),+ json!("archive"),+ ],vec![json!("*AAABk1AAEAAAAAgAAB"), json!("task-2"), Value::Null, Value::Null, Value::Null],],dirty_rows: vec![],@@ -8603,13 +9217,13 @@ mod tests {});assert_eq!(result.validation_error, None);- assert_eq!(- result.statements,- vec![- "DELETE FROM \"APP\".\"DATA_REPORT_SUB_TASK\" WHERE ROWIDTOCHAR(ROWID) = '*AAABk1AAEAAAAAgAAA';",- "DELETE FROM \"APP\".\"DATA_REPORT_SUB_TASK\" WHERE ROWIDTOCHAR(ROWID) = '*AAABk1AAEAAAAAgAAB';",- ]- );+ assert_eq!(result.statements.len(), 2);+ assert!(result.statements[0].contains("ROWIDTOCHAR(ROWID) = '*AAABk1AAEAAAAAgAAA'"));+ assert!(result.statements[0].contains("DBMS_LOB.GETLENGTH(\"SMC_RESPONSE\") = 8"));+ assert!(result.statements[0].contains("UTL_RAW.CAST_TO_RAW('response')"));+ assert!(result.statements[1].contains("ROWIDTOCHAR(ROWID) = '*AAABk1AAEAAAAAgAAB'"));+ assert!(result.statements[1].contains("\"SMC_RESPONSE\" IS NULL"));+ assert!(result.statements.iter().all(|statement| statement.contains("SQL%ROWCOUNT <> 1")));}#[test]@@ -8641,7 +9255,9 @@ mod tests {});assert_eq!(result.validation_error, None);- assert_eq!(result.statements, vec!["DELETE FROM \"APP\".\"DOCUMENTS\" WHERE \"ID\" = 42;"]);+ assert_eq!(result.statements.len(), 1);+ assert!(result.statements[0].contains("WHERE \"ID\" = 42 AND (DBMS_LOB.GETLENGTH(\"BODY\") = 4"));+ assert!(result.statements[0].contains("SQL%ROWCOUNT <> 1"));}#[test]diff --git a/crates/dbx-types/src/types.rs b/crates/dbx-types/src/types.rsindex 2059acf2ea..25e7dd7b50 100644--- a/crates/dbx-types/src/types.rs+++ b/crates/dbx-types/src/types.rs@@ -1,5 +1,34 @@use serde::{Deserialize, Serialize};+/// A data-grid statement whose BLOB values travel outside the executable SQL.+/// The preview must match the caller's reviewed SQL before any statement runs.+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct BlobBoundStatement {+ pub preview_sql: String,+ pub sql: String,+ pub blob_parameters: Vec<String>,+}++pub fn validate_blob_bound_statements(previews: &[String], bound: &[BlobBoundStatement]) -> Result<(), String> {+ if previews.len() != bound.len()+ || previews.iter().zip(bound).any(|(preview, statement)| preview != &statement.preview_sql)+ {+ return Err("The reviewed SQL changed; regenerate the BLOB save preview before saving.".into());+ }+ if bound.iter().any(|statement| {+ statement.sql.trim().is_empty()+ || statement.blob_parameters.is_empty() && statement.sql != statement.preview_sql+ || statement+ .blob_parameters+ .iter()+ .any(|hex| hex.len() % 2 != 0 || !hex.bytes().all(|byte| byte.is_ascii_hexdigit()))+ }) {+ return Err("Invalid BLOB statement parameters.".into());+ }+ Ok(())+}+pub use crate::mysql_event::MysqlEventInfo;#[derive(Debug, Clone, Default, Serialize, Deserialize)]@@ -547,6 +576,9 @@ pub struct LargeValueCell {pub row_index: usize,pub column_index: usize,pub original_bytes: usize,+ /// Opaque original-result locator. Absent for legacy preview/re-query drivers.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub value_ref: Option<String>,}#[derive(Debug, Clone, Deserialize)]@@ -1115,6 +1147,25 @@ pub struct CustomTypeDetails {#[cfg(test)]mod tests {+ #[test]+ fn blob_bindings_refuse_edited_previews_and_invalid_later_parameters() {+ let previews = vec!["first reviewed save".to_string(), "second reviewed save".to_string()];+ let mut bound = previews+ .iter()+ .map(|preview| super::BlobBoundStatement {+ preview_sql: preview.clone(),+ sql: "BEGIN UPDATE T SET B=?; END;".into(),+ blob_parameters: vec!["00ff".into()],+ })+ .collect::<Vec<_>>();+ assert!(super::validate_blob_bound_statements(&previews, &bound).is_ok());+ bound[1].blob_parameters[0] = "xyz".into();+ assert!(super::validate_blob_bound_statements(&previews, &bound).is_err());+ bound[1].blob_parameters[0] = "00ff".into();+ bound[1].preview_sql = "user edited SQL".into();+ assert!(super::validate_blob_bound_statements(&previews, &bound).is_err());+ assert!(super::validate_blob_bound_statements(&previews, &bound[..1]).is_err());+ }use super::{is_opaque_aggregate_state_type, CompletionAssistantCandidate, CompletionAssistantCandidateKind, ObjectInfo,ObjectSource, ObjectSourceKind, QueryMessage, RoutineParameterMode, SpatialColumn, SpatialColumnBuilder,diff --git a/crates/dbx-web/src/main.rs b/crates/dbx-web/src/main.rsindex 499d08d9e0..0b3b419d02 100644--- a/crates/dbx-web/src/main.rs+++ b/crates/dbx-web/src/main.rs@@ -916,6 +916,11 @@ async fn serve() -> Result<(), String> {.route("/query/cancel", post(routes::query::cancel_query)).route("/query/cancel-conditional-update", post(routes::query::cancel_conditional_update)).route("/query/close-session", post(routes::query::close_query_session))+ .route("/query/large-value/chunk", post(routes::query::read_large_value_chunk))+ .route("/query/large-value/release", post(routes::query::release_large_value))+ .route("/query/large-value/download", post(routes::query::prepare_large_value_download))+ .route("/query/large-value/export", post(routes::query::prepare_snapshot_export))+ .route("/query/large-value/download/{id}", get(routes::query::download_large_value)).route("/query/close-client-session", post(routes::query::close_client_connection_session)).route("/export/query-result-json", post(routes::text_export::export_query_result_json)).route("/export/query-result-markdown", post(routes::text_export::export_query_result_markdown))diff --git a/crates/dbx-web/src/routes/query.rs b/crates/dbx-web/src/routes/query.rsindex 2e3b07f591..7c85b7a362 100644--- a/crates/dbx-web/src/routes/query.rs+++ b/crates/dbx-web/src/routes/query.rs@@ -73,6 +73,8 @@ pub struct CloseClientConnectionSessionRequest {#[derive(Deserialize)]#[serde(rename_all = "camelCase")]pub struct ExecuteBatchRequest {+ #[serde(default)]+ pub bound_statements: Option<Vec<dbx_core::db::BlobBoundStatement>>,pub connection_id: String,pub database: String,pub statements: Vec<String>,@@ -659,6 +661,25 @@ pub async fn execute_batch(for statement in &req.statements {super::mcp_policy::ensure_sql(&state, &headers, &req.connection_id, &database, statement, false).await?;}+ if let Some(bound) = req.bound_statements.as_ref() {+ for statement in bound {+ super::mcp_policy::ensure_sql(&state, &headers, &req.connection_id, &database, &statement.sql, false)+ .await?;+ }+ return dbx_core::query::execute_blob_bound_statements(+ &state.app,+ &req.connection_id,+ &database,+ &req.statements,+ bound,+ req.schema.as_deref(),+ req.use_transaction == Some(true),+ req.timeout_secs,+ )+ .await+ .map(Json)+ .map_err(AppError::from);+ }tracing::debug!(connection_id = %req.connection_id, "execute_batch");let result = dbx_core::query::execute_statements_with_transaction_option(&state.app,@@ -690,6 +711,106 @@ pub async fn cancel_conditional_update(Json(state.app.running_queries.cancel_and_wait(&req.execution_id, CONDITIONAL_UPDATE_CANCEL_WAIT).await)}+pub async fn read_large_value_chunk(+ State(state): State<Arc<WebState>>,+ Json(req): Json<dbx_core::query::LargeValueRequest>,+) -> Result<Json<serde_json::Value>, AppError> {+ dbx_core::query::request_large_value(&state.app, req, false).await.map(Json).map_err(AppError::from)+}++pub async fn release_large_value(+ State(state): State<Arc<WebState>>,+ Json(req): Json<dbx_core::query::LargeValueRequest>,+) -> Result<Json<serde_json::Value>, AppError> {+ dbx_core::query::request_large_value(&state.app, req, true).await.map(Json).map_err(AppError::from)+}++#[derive(Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct LargeValueDownloadRequest {+ pub request: dbx_core::query::LargeValueRequest,+ pub file_name: String,+}++pub async fn prepare_large_value_download(+ State(state): State<Arc<WebState>>,+ Json(req): Json<LargeValueDownloadRequest>,+) -> Result<Json<serde_json::Value>, AppError> {+ let mut temporary = tempfile::NamedTempFile::new().map_err(|error| AppError::from(error.to_string()))?;+ dbx_core::query::write_large_value_snapshot(&state.app, req.request, temporary.as_file_mut())+ .await+ .map_err(AppError::from)?;+ let (_, path) = temporary.keep().map_err(|error| AppError::from(error.to_string()))?;+ let download_id = uuid::Uuid::new_v4().to_string();+ state.export_files.write().await.insert(+ download_id.clone(),+ crate::state::WebExportFile {+ file_path: path.to_string_lossy().into_owned(),+ download_filename: req.file_name,+ format: "lob".to_string(),+ },+ );+ let cleanup_state = state.clone();+ let cleanup_id = download_id.clone();+ tokio::spawn(async move {+ tokio::time::sleep(std::time::Duration::from_secs(300)).await;+ if let Some(file) = cleanup_state.export_files.write().await.remove(&cleanup_id) {+ let _ = tokio::fs::remove_file(file.file_path).await;+ }+ });+ Ok(Json(serde_json::json!({ "downloadId": download_id })))+}++pub async fn download_large_value(+ State(state): State<Arc<WebState>>,+ axum::extract::Path(id): axum::extract::Path<String>,+) -> Result<axum::response::Response, AppError> {+ let file = state+ .export_files+ .write()+ .await+ .remove(&id)+ .ok_or_else(|| AppError::from("LOB download expired".to_string()))?;+ super::mongodb_import_export::export_file_response(file).await+}++#[derive(Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct SnapshotExportDownloadRequest {+ pub request: dbx_core::query::snapshot_export::SnapshotExportRequest,+ pub file_name: String,+}++pub async fn prepare_snapshot_export(+ State(state): State<Arc<WebState>>,+ Json(req): Json<SnapshotExportDownloadRequest>,+) -> Result<Json<serde_json::Value>, AppError> {+ let mut temporary = tempfile::NamedTempFile::new().map_err(|error| AppError::from(error.to_string()))?;+ let format = req.request.format.clone();+ dbx_core::query::snapshot_export::write_snapshot_export(&state.app, req.request, temporary.as_file_mut())+ .await+ .map_err(AppError::from)?;+ let (_, path) = temporary.keep().map_err(|error| AppError::from(error.to_string()))?;+ let download_id = uuid::Uuid::new_v4().to_string();+ state.export_files.write().await.insert(+ download_id.clone(),+ crate::state::WebExportFile {+ file_path: path.to_string_lossy().into_owned(),+ download_filename: req.file_name,+ format,+ },+ );+ let cleanup_state = state.clone();+ let cleanup_id = download_id.clone();+ tokio::spawn(async move {+ tokio::time::sleep(std::time::Duration::from_secs(300)).await;+ if let Some(file) = cleanup_state.export_files.write().await.remove(&cleanup_id) {+ let _ = tokio::fs::remove_file(file.file_path).await;+ }+ });+ Ok(Json(serde_json::json!({ "downloadId": download_id })))+}+pub async fn close_query_session(State(state): State<Arc<WebState>>,Json(req): Json<CloseSessionRequest>,@@ -759,6 +880,21 @@ pub async fn execute_in_transaction(State(state): State<Arc<WebState>>,Json(req): Json<ExecuteBatchRequest>,) -> Result<Json<dbx_core::db::QueryResult>, AppError> {+ if let Some(bound) = req.bound_statements.as_ref() {+ return dbx_core::query::execute_blob_bound_statements(+ &state.app,+ &req.connection_id,+ &req.database,+ &req.statements,+ bound,+ req.schema.as_deref(),+ true,+ req.timeout_secs,+ )+ .await+ .map(Json)+ .map_err(AppError::from);+ }tracing::debug!(connection_id = %req.connection_id, "execute_in_transaction");let result = dbx_core::query::execute_statements_in_transaction(&state.app,@@ -778,6 +914,9 @@ pub async fn execute_script_with_2pc(State(state): State<Arc<WebState>>,Json(req): Json<ExecuteBatchRequest>,) -> Result<Json<dbx_core::query::SchemaDiffDeployResult>, AppError> {+ if req.bound_statements.is_some() {+ return Err(AppError::from("Bound BLOB saves must use a supported save execution endpoint.".to_string()));+ }tracing::debug!(connection_id = %req.connection_id, "execute_script_with_2pc");// Single-connection real transaction (not per-statement auto-commit 2PC).let result = dbx_core::query::execute_schema_diff_deploy(@@ -1381,6 +1520,7 @@ mod tests {async fn execute_script_with_2pc_returns_structured_result() {let (state, _dir) = test_web_state().await;let req = ExecuteBatchRequest {+ bound_statements: None,connection_id: "conn-1".to_string(),database: "testdb".to_string(),statements: vec!["SELECT 1".to_string()],@@ -1407,6 +1547,7 @@ mod tests {async fn execute_script_with_2pc_empty_statements_succeeds() {let (state, _dir) = test_web_state().await;let req = ExecuteBatchRequest {+ bound_statements: None,connection_id: "conn-empty".to_string(),database: "testdb".to_string(),statements: vec![],@@ -1430,6 +1571,7 @@ mod tests {async fn execute_script_with_2pc_propagates_structured_failure_fields() {let (state, _dir) = test_web_state().await;let req = ExecuteBatchRequest {+ bound_statements: None,connection_id: "missing-conn".to_string(),database: "testdb".to_string(),statements: vec!["CREATE TABLE t1 (id INT)".to_string(), "CREATE TABLE t2 (id INT)".to_string()],@@ -1455,6 +1597,7 @@ mod tests {async fn execute_script_with_2pc_blocks_unconfirmed_destructive_sql() {let (state, _dir) = test_web_state().await;let req = ExecuteBatchRequest {+ bound_statements: None,connection_id: "missing-conn".to_string(),database: "testdb".to_string(),statements: vec!["DROP INDEX idx_old ON users".to_string()],diff --git a/docs/testing/oceanbase-lob-reading.md b/docs/testing/oceanbase-lob-reading.mdnew file mode 100644index 0000000000..e0bb3852b4--- /dev/null+++ b/docs/testing/oceanbase-lob-reading.md@@ -0,0 +1,28 @@+# OceanBase Oracle LOB regression acceptance++This batch covers result-snapshot CLOB/BLOB reading, writing, copying and exporting. Target database acceptance uses OceanBase Oracle 4.2.5.7 and Connector/J 2.4.18. Automated tests with JDBC and transport fixtures do not establish support on other database versions.++## Reproduction and expected behavior++Use an authorized isolated table with a primary key, CLOB, BLOB and nullable temporal columns. Include SQL NULL, empty LOBs, Unicode text longer than the grid preview and binary data containing all byte values. Keep fixture credentials and connection details outside the PR.++1. Query the fixture, then update or delete its rows through a second connection. Read, copy and export the original result. The full value must come from its original retained locator and session; it must not use the preview or re-query the changed row. Expired references must report an error instead of opening another session.+2. Export selected cells and rows to CSV, JSON and XLSX. Compare complete values with the original fixture, including NULL versus empty text and empty binary data. Preserve selection, column order, header comments and existing spreadsheet formula protection. An incomplete snapshot must fail the operation instead of producing a successful truncated file.+3. Edit CLOB/BLOB cells and save. Read back exact content. Test empty values, NULL, multibyte text and binary values larger than one bind chunk. Concurrent changes must fail the old-value guard and retain the draft. Failed multi-statement writes must roll back; manual transactions must retain their existing ownership.+4. Start an asynchronous full-value copy, then change the focused cell. The original cell and column remain the copy target. Start another read, replace the result or dispose the grid while the backend remains pending, and reject the cancellation request. Local waiting must settle, late chunks must not modify either result, and a late HTTP preparation response must not start a download.+5. Close the result tab or disconnect one connection while a query is pending. Its result and client sessions must be released; other connections must remain usable. A late result must not restore the closed tab or its runtime state.+6. Hold the original session's registry, transaction or Agent lock, then cancel a LOB request. Core must finish local waiting and remove its task registration. Missing original pools, wrong client sessions and metadata-only pools must not create replacement locator sessions.+7. Render and export NULL date/time cells and explicit timezone values. NULL stays NULL; SQL extraction preserves the explicit timezone information.++## Automated coverage++- Frontend tests call the real editor, exporter, large-value composable, snapshot helpers and query/connection stores, with external backend calls controlled by fixtures.+- Agent tests cover chunk boundaries, retained locator lifetime, resource limits, typed BLOB bindings and RPC dispatch. Opt-in database tests must be reported as skipped when their environment is absent.+- Core tests cover snapshot export, original-session lookup and cancellation while waiting for locks. Transport tests cover late browser-download responses.+- Tests, type checking, compilation, database acceptance and GUI acceptance are separate evidence layers. Record the exact candidate and results in the PR.++## Limits and remaining acceptance++Local cancellation settles client waiting. It does not prove database-side statement termination or physical server cursor release. Native delivery may already have persisted its destination before cancellation reaches the caller; browser late-response checks do not establish atomic native-file cancellation.++The independent candidate still requires database and GUI readback against its own verified build. Historical integration-worktree results are not current-candidate acceptance. Exercise success, error, cancellation, close/reopen and disconnect with the loaded Agent JAR hash recorded. Verify exact fixture cleanup separately, and keep native delivery, clipboard content and untested database versions explicitly unverified until checked.diff --git a/packages/app-tests/columnFormatter.test.ts b/packages/app-tests/columnFormatter.test.tsindex 0cde19af8a..5127bf87e9 100644--- a/packages/app-tests/columnFormatter.test.ts+++ b/packages/app-tests/columnFormatter.test.ts@@ -81,6 +81,21 @@ test("formats only typed temporal cells for export", async () => {assert.deepEqual(rows, [[1, "2024/02/25 05:02:15.000+00:00", "2024-02-25T05:02:15Z", "2024/02/25 05:02:15.123+08:00", "2024/02/25 13:02:15.987+08:00"]]);});+test("preserves temporal nulls and literal NULL text when formatting exports", async () => {+ const { formatTemporalRowsForExport } = await import("../../apps/desktop/src/lib/dataGrid/columnFormatter.ts");+ const types = ["DATE", "TIMESTAMP(6)", "TIMESTAMP WITH TIME ZONE", "TIMESTAMP WITH LOCAL TIME ZONE", "VARCHAR2"];+ const rows = [+ [null, null, null, null, "NULL"],+ ["NULL", "NULL", "NULL", "NULL", null],+ ];+ assert.deepEqual(formatTemporalRowsForExport(rows, types, "YYYY/MM/DD HH:mm:ss.SSSZ"), rows);+ assert.deepEqual(formatTemporalRowsForExport(rows, types, ""), rows);+ assert.deepEqual(rows, [+ [null, null, null, null, "NULL"],+ ["NULL", "NULL", "NULL", "NULL", null],+ ]);+});+test("formats Oracle timestamp fractional precision in the data grid", () => {assert.equal(applyColumnFormatter("2024-02-25 13:02:15.123456", { kind: "datetime", unit: "auto", pattern: "YYYY/MM/DD HH:mm:ss.SSS", timezone: undefined }), "2024/02/25 13:02:15.123");});diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.tomlindex 4cd5f1b1ac..314c0a2e34 100644--- a/src-tauri/Cargo.toml+++ b/src-tauri/Cargo.toml@@ -31,6 +31,7 @@ tauri-build = { version = "2.5.6", features = [] }[dependencies]serde = { version = "1.0", features = ["derive"] }serde_json = "1.0"+tempfile = "3"serde_yaml_ng = "0.10"base64 = "0.22"log = "0.4"@@ -85,7 +86,6 @@ sysinfo = { version = "0.32", features = ["system"] }[dev-dependencies]dbx-core = { path = "../crates/dbx-core", default-features = false, features = ["test-support"] }tauri = { version = "2.10.3", features = ["test"] }-tempfile = "3"[target.'cfg(target_os = "macos")'.dependencies]objc2 = { version = "0.6.4", default-features = false, features = ["std"] }diff --git a/src-tauri/src/commands/query.rs b/src-tauri/src/commands/query.rsindex 4e9b8a23ea..88cb1f52c6 100644--- a/src-tauri/src/commands/query.rs+++ b/src-tauri/src/commands/query.rs@@ -354,6 +354,36 @@ pub async fn close_query_session(.await}+#[tauri::command]+pub async fn read_large_value_chunk(+ state: State<'_, Arc<AppState>>,+ request: dbx_core::query::LargeValueRequest,+) -> Result<serde_json::Value, String> {+ dbx_core::query::request_large_value(&state, request, false).await+}++#[tauri::command]+pub async fn release_large_value(+ state: State<'_, Arc<AppState>>,+ request: dbx_core::query::LargeValueRequest,+) -> Result<serde_json::Value, String> {+ dbx_core::query::request_large_value(&state, request, true).await+}++#[tauri::command]+pub async fn download_large_value(+ state: State<'_, Arc<AppState>>,+ request: dbx_core::query::LargeValueRequest,+ file_path: String,+) -> Result<u64, String> {+ let path = std::path::Path::new(&file_path);+ let parent = path.parent().filter(|parent| !parent.as_os_str().is_empty()).unwrap_or(std::path::Path::new("."));+ let mut temporary = tempfile::NamedTempFile::new_in(parent).map_err(|error| error.to_string())?;+ let written = dbx_core::query::write_large_value_snapshot(&state, request, temporary.as_file_mut()).await?;+ temporary.persist(path).map_err(|error| error.to_string())?;+ Ok(written)+}+#[tauri::command]pub async fn close_client_connection_session(state: State<'_, Arc<AppState>>,@@ -366,6 +396,20 @@ pub async fn close_client_connection_session(state.close_client_session_pool(&connection_id, database, &client_session_id).await}+#[tauri::command]+pub async fn export_snapshot_result(+ state: State<'_, Arc<AppState>>,+ request: dbx_core::query::snapshot_export::SnapshotExportRequest,+ file_path: String,+) -> Result<(), String> {+ let path = std::path::Path::new(&file_path);+ let parent = path.parent().filter(|parent| !parent.as_os_str().is_empty()).unwrap_or(std::path::Path::new("."));+ let mut temporary = tempfile::NamedTempFile::new_in(parent).map_err(|error| error.to_string())?;+ dbx_core::query::snapshot_export::write_snapshot_export(&state, request, temporary.as_file_mut()).await?;+ temporary.persist(path).map_err(|error| error.to_string())?;+ Ok(())+}+fn query_session_database<'a>(database: &'a str, catalog: Option<&str>) -> Option<&'a str> {if database.trim().is_empty() || catalog.is_some() {None@@ -383,7 +427,21 @@ pub async fn execute_batch(schema: Option<String>,timeout_secs: Option<u64>,use_transaction: Option<bool>,+ bound_statements: Option<Vec<db::BlobBoundStatement>>,) -> Result<db::QueryResult, String> {+ if let Some(bound) = bound_statements.as_ref() {+ return dbx_core::query::execute_blob_bound_statements(+ &state,+ &connection_id,+ &database,+ &statements,+ bound,+ schema.as_deref(),+ use_transaction == Some(true),+ timeout_secs,+ )+ .await;+ }dbx_core::query::execute_statements_with_transaction_option(&state,&connection_id,@@ -431,7 +489,21 @@ pub async fn execute_in_transaction(statements: Vec<String>,schema: Option<String>,catalog: Option<String>,+ bound_statements: Option<Vec<db::BlobBoundStatement>>,) -> Result<db::QueryResult, String> {+ if let Some(bound) = bound_statements.as_ref() {+ return dbx_core::query::execute_blob_bound_statements(+ &state,+ &connection_id,+ &database,+ &statements,+ bound,+ schema.as_deref(),+ true,+ None,+ )+ .await;+ }dbx_core::query::execute_statements_in_transaction(&state,&connection_id,@@ -517,6 +589,7 @@ pub async fn execute_in_manual_transaction(classification_sql: Option<String>,execution_id: Option<String>,timeout_secs: Option<u64>,+ bound_statements: Option<Vec<db::BlobBoundStatement>>,) -> Result<Vec<dbx_core::query::ExecuteMultiResult>, ManualTransactionCommandError> {let messages = query_messages_callback(&app, execution_id.as_deref());dbx_core::query::query_messages::with_query_messages(@@ -528,6 +601,7 @@ pub async fn execute_in_manual_transaction(&database,schema.as_deref(),dbx_core::query::ManualTransactionExecutionOptions {+ bound_statements,max_rows,table_data_preview: table_data_preview.unwrap_or(false),page_size,diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rsindex 39a41565f6..801a46c010 100644--- a/src-tauri/src/lib.rs+++ b/src-tauri/src/lib.rs@@ -2137,6 +2137,10 @@ pub fn run() {commands::query::cancel_query,commands::query::cancel_conditional_update,commands::query::close_query_session,+ commands::query::read_large_value_chunk,+ commands::query::release_large_value,+ commands::query::download_large_value,+ commands::query::export_snapshot_result,commands::query::close_client_connection_session,commands::query::execute_batch,commands::query::execute_script,