Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
72 changes: 63 additions & 9 deletions client-v2/src/main/java/com/clickhouse/client/api/Client.java
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,7 @@
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.stream.Collectors;

Expand Down Expand Up @@ -1992,13 +1993,6 @@ public CompletableFuture<QueryResponse> query(String sqlQuery, Map<String, Objec
}
final QuerySettings requestSettings = new QuerySettings(buildRequestSettings(settings.getAllSettings()));

applyFormatSpecificSettings(requestSettings);
ClientStatisticsHolder clientStats = new ClientStatisticsHolder();
// Origin of the duration of a failed operation. Taken where the client starts OP_DURATION, which is
// the duration reported for a successful operation, so that both outcomes measure the same work.
final long operationStartNanos = System.nanoTime();
clientStats.start(ClientMetrics.OP_DURATION);

if (queryParams != null) {
// Format parameter values here so the transport layer receives ready-to-send text:
// Array/Map values are quoted the way the server's param_<name> parser expects
Expand All @@ -2011,6 +2005,58 @@ public CompletableFuture<QueryResponse> query(String sqlQuery, Map<String, Objec
requestSettings.setOption(HttpAPIClientHelper.KEY_STATEMENT_PARAMS, formattedParams);
}

return queryInternal(sqlQuery, requestSettings,
endpoint -> httpClientHelper.createRequest(endpoint, requestSettings.getAllSettings(), sqlQuery),
null);
}

/**
* Sends a SQL request whose body is written directly to the HTTP output stream through {@link DataStreamWriter}.
* Use this when the SQL request body is large (for example a batched {@code INSERT ... VALUES} statement) to avoid
* building the full SQL text as one {@link String} in memory.
*
* @param sqlWriter writer that emits the UTF-8 SQL request body
* @param settings query operation settings (optional)
* @return {@code CompletableFuture<QueryResponse>} - a promise to query response
*/
public CompletableFuture<QueryResponse> queryStream(DataStreamWriter sqlWriter, QuerySettings settings) {
return queryStream(null, sqlWriter, settings);
}

/**
* Sends a SQL request whose body is written directly to the HTTP output stream through {@link DataStreamWriter}.
*
* @param queryDescription optional short SQL template or description for diagnostics and spans
* @param sqlWriter writer that emits the UTF-8 SQL request body
* @param settings query operation settings (optional)
* @return {@code CompletableFuture<QueryResponse>} - a promise to query response
*/
public CompletableFuture<QueryResponse> queryStream(String queryDescription, DataStreamWriter sqlWriter, QuerySettings settings) {
Objects.requireNonNull(sqlWriter, "sqlWriter cannot be null");
if (settings == null) {
settings = new QuerySettings();
}
final QuerySettings requestSettings = new QuerySettings(buildRequestSettings(settings.getAllSettings()));

return queryInternal(queryDescription, requestSettings,
endpoint -> httpClientHelper.createRequest(endpoint, requestSettings.getAllSettings(), out -> {
sqlWriter.onOutput(out);
out.close();
}),
sqlWriter);
}

private CompletableFuture<QueryResponse> queryInternal(String sqlForSpan,
QuerySettings requestSettings,
Function<Endpoint, TransportRequest> requestFactory,
DataStreamWriter retryCallback) {
applyFormatSpecificSettings(requestSettings);
ClientStatisticsHolder clientStats = new ClientStatisticsHolder();
// Origin of the duration of a failed operation. Taken where the client starts OP_DURATION, which is
// the duration reported for a successful operation, so that both outcomes measure the same work.
final long operationStartNanos = System.nanoTime();
clientStats.start(ClientMetrics.OP_DURATION);

if (requestSettings.getQueryId() == null && queryIdGenerator != null) {
requestSettings.setQueryId(queryIdGenerator.get());
}
Expand All @@ -2019,7 +2065,7 @@ public CompletableFuture<QueryResponse> query(String sqlQuery, Map<String, Objec
final int maxAttempts = Math.max(maxRetries, endpoints.size() - 1);
// Started on the calling thread so that the span joins the caller's ambient trace even when
// the operation itself runs on the shared operation executor.
final Span operationSpan = orNoop(spanRecorder.startQuerySpan(requestSettings, sqlQuery, endpoints.get(0)));
final Span operationSpan = orNoop(spanRecorder.startQuerySpan(requestSettings, sqlForSpan, endpoints.get(0)));
Supplier<QueryResponse> responseSupplier = () -> {
long startTime = System.nanoTime();
// Selecting some node
Expand All @@ -2029,7 +2075,7 @@ public CompletableFuture<QueryResponse> query(String sqlQuery, Map<String, Objec
try {
for (int i = 0; i <= maxAttempts; i++) {
failIfCancelled(queryId, i, lastException);
TransportRequest request = httpClientHelper.createRequest(selectedEndpoint, requestSettings.getAllSettings(), sqlQuery);
TransportRequest request = requestFactory.apply(selectedEndpoint);
registerTransportReq(queryId, request);
TransportResponse transportResp = null;
try {
Expand Down Expand Up @@ -2060,6 +2106,14 @@ public CompletableFuture<QueryResponse> query(String sqlQuery, Map<String, Objec
throw lastException;
}
}

if (retryCallback != null && i < maxAttempts) {
try {
retryCallback.onRetry();
} catch (IOException ioe) {
throw new ClientException("Failed to reset stream before next attempt", ioe);
}
}
}

String errMsg = requestExMsg("Query", maxAttempts + 1, durationSince(startTime).toMillis(), requestSettings.getQueryId());
Expand Down
4 changes: 2 additions & 2 deletions docs/features.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ This document lists stable, user-visible behavior in `client-v2` and `jdbc-v2` t
- Runtime credential updates: Existing `Client` instances can update username/password or bearer-token credentials for subsequent requests without rebuilding the client.
- Proxy support: Can send requests through configured HTTP proxies, including proxy credentials.
- Connection and socket tuning: Exposes pool sizing, keep-alive, reuse strategy, connect/request/socket timeouts, and low-level socket options. `Client#setNetworkTimeout(int)` (or the `long`/`ChronoUnit` overload) changes the socket-operation timeout for subsequent requests at runtime; requests already created keep their captured value, and an operation-level timeout overrides the client value. The socket buffer options `socket_rcvbuf` and `socket_sndbuf` (`Client.Builder#setSocketRcvbuf`/`#setSocketSndbuf`) have no default value: unless the application sets one, the buffers are left to the operating system, which sizes and auto-tunes them. Setting a fixed size disables that auto-tuning and is capped by the operating system limits, so it is not recommended unless a measurement shows a benefit.
- Query execution: Executes SQL asynchronously and returns streaming query responses with response metadata and metrics.
- Query execution: Executes SQL asynchronously and returns streaming query responses with response metadata and metrics. `Client#queryStream(DataStreamWriter, QuerySettings)` (and its `queryDescription` overload) streams the SQL request body directly through a `DataStreamWriter` callback without materializing the full SQL string in memory.
- Query settings: Supports per-query database selection, output format, execution limits, roles, log comments, headers, reusable `Session` objects, session settings, server settings, and network timeout overrides. Settings explicitly set to `null` or empty string will not be sent to the server. The default format (`RowBinaryWithNamesAndTypes`) is configured at the client level (`ClientConfigProperties.INPUT_OUTPUT_FORMAT`), sending the `X-ClickHouse-Format` request header. ClickHouse `26.8+` uses that request header in preference to a `FORMAT` clause in the SQL query. Configuring `format=` (empty) or `null` omits the format request header, allowing explicit SQL `FORMAT` clauses to take effect; however, on a JDBC connection this is an expert setting, as queries without a `FORMAT` clause fall back to server `default_format` (`TabSeparated`), which JDBC rejects.
- Parameterized SQL: Accepts named query parameters and can send them through supported HTTP request encodings.
- Result materialization helpers: Provides streaming `Records`, generic row access, and convenience APIs that materialize all rows into generic records or typed POJOs. A `Nullable(T)` column may be bound to a POJO field of a primitive type (e.g. `long`), which reads any non-`NULL` value without boxing; a value that is actually `NULL` cannot be held by such a field and is reported with a `NullValueException` (use the boxed type to accept `NULL`).
Expand Down Expand Up @@ -86,7 +86,7 @@ Compatibility-sensitive traits:
- Statement execution: Supports `execute`, `executeQuery`, `executeUpdate`, large update counts, and forward-only/read-only statements.
- Query cancellation and timeout: Supports JDBC query timeout handling and query cancellation through server-side `KILL QUERY`, with optional JDBC `cluster_name` property support to add `ON CLUSTER '<name>'` for cluster-wide cancellation.
- Batch execution: Supports batched statements and prepared-statement batches, including multi-row rewrite for eligible `INSERT ... VALUES` statements.
- Prepared statements: Supports `?` parameters through client-side SQL rendering and validates that all parameters are bound before execution.
- Prepared statements: Supports `?` parameters through client-side SQL rendering and validates that all parameters are bound before execution. When `WriterStatementImpl` is not selected, `StreamingPreparedStatementImpl` is enabled by default (`jdbc_streaming_prepared_statement=true`): it uses `FastSqlBatchWriter` and `SqlParameterBinder` to stream UTF-8 SQL bytes through `Client.queryStream(...)` (and fixed-size byte chunks for batches) without constructing a full SQL string in memory. Set `jdbc_streaming_prepared_statement=false` to use the legacy `PreparedStatementImpl` string-building path.
- SQL parsing and classification: Classifies SQL to distinguish queries, updates, inserts, `USE`, and role-changing statements, with selectable parser backends.
- JDBC escape processing: Translates supported JDBC escape syntax for dates, timestamps, and functions before execution. Escape sequences are only recognized outside of quoted text, so string literals and quoted identifiers — including inlined parameter values that contain `{fn `, `{d '...'}`, or `{ts '...'}` — are passed through unchanged.
- Result set streaming: Streams result sets from ClickHouse binary formats and `FORMAT JSONEachRow`, enforces max-row limits, and manages result-set lifecycle correctly.
Expand Down
2 changes: 1 addition & 1 deletion docs/source-map.md
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ parser areas (v1 and v2) also have a detail label: `jdbc-metadata` and `sql-pars
`ClientException`, `ServerException`, `ClickHouseException`, `ClientFaultCause`,
`DataTransferException`; jdbc `SqlExceptionUtils` (v1); data `ClickHouseChecker`.
- **JDBC insert** — `jdbc-v2/.../jdbc/` `PreparedStatementImpl`,
`WriterStatementImpl`. v1: `clickhouse-jdbc/.../jdbc/ClickHousePreparedStatement`.
`StreamingPreparedStatementImpl`, `WriterStatementImpl`. v1: `clickhouse-jdbc/.../jdbc/ClickHousePreparedStatement`.
- **JDBC read** — `jdbc-v2/.../jdbc/` `ResultSetImpl`, `StatementImpl`.
v1: `ClickHouseResultSet`, `ClickHouseStatement`.
- **JDBC metadata** — `jdbc-v2/.../jdbc/metadata/` (`DatabaseMetaDataImpl`,
Expand Down
11 changes: 11 additions & 0 deletions history/latest/3523.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
- **[client-v2]** Added `Client#queryStream(DataStreamWriter, QuerySettings)` and
`Client#queryStream(String, DataStreamWriter, QuerySettings)` to stream a UTF-8 SQL request body directly to the HTTP
output stream instead of assembling the full SQL text as one `String` in memory.
(https://github.com/ClickHouse/clickhouse-java/issues/3523)
- **[jdbc-v2]** Reduced memory allocations and improved throughput for large parameterized SQL queries and
`INSERT ... VALUES (...)` batches (for example, batches with SQL functions where `beta.row_binary_for_simple_insert`
cannot be used). `Connection#prepareStatement` now returns `StreamingPreparedStatementImpl` by default
(`jdbc_streaming_prepared_statement=true`), which writes parameters directly as UTF-8 bytes to the HTTP request
stream or fixed-size 64 KB batch chunks instead of building and copying intermediate `StringBuilder` and `String`
buffers. Set `jdbc_streaming_prepared_statement=false` to revert to the legacy `PreparedStatementImpl` string path.
(https://github.com/ClickHouse/clickhouse-java/issues/3523)
Original file line number Diff line number Diff line change
Expand Up @@ -479,6 +479,9 @@ public PreparedStatement prepareStatement(String sql, int resultSetType, int res
return new WriterStatementImpl(this, sql, tableSchema, parsedStatement);
}
}
if (config.isFlagSet(DriverProperties.STREAMING_PREPARED_STATEMENT)) {
return new StreamingPreparedStatementImpl(this, sql, parsedStatement);
}
return new PreparedStatementImpl(this, sql, parsedStatement);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -221,6 +221,15 @@ public enum DriverProperties {
+ "array level. Set to false to return the innermost type that is not an array.")
MULTI_DIMENSIONAL_ARRAY_ELEMENT_TYPE("jdbc_multi_dimensional_array_element_type", String.valueOf(Boolean.TRUE)),

/**
* Uses the streaming {@link java.sql.PreparedStatement} implementation ({@link StreamingPreparedStatementImpl}) for
* parameterized SQL statements instead of building full SQL strings in memory.
* Default: true
*/
@ConfigDescription("Uses the streaming PreparedStatement implementation for parameterized queries and writes, "
+ "serializing parameters directly to UTF-8 bytes instead of building large SQL strings in memory.")
STREAMING_PREPARED_STATEMENT("jdbc_streaming_prepared_statement", String.valueOf(Boolean.TRUE)),

;


Expand Down
Loading
Loading