diff --git a/client-v2/src/main/java/com/clickhouse/client/api/Client.java b/client-v2/src/main/java/com/clickhouse/client/api/Client.java index f7dc49519..31c1e6c7a 100644 --- a/client-v2/src/main/java/com/clickhouse/client/api/Client.java +++ b/client-v2/src/main/java/com/clickhouse/client/api/Client.java @@ -1762,23 +1762,26 @@ public CompletableFuture insert(String tableName, throw new IllegalArgumentException("Buffer size must be greater than 0"); } - return insert(tableName, columnNames, new DataStreamWriter() { - @Override - public void onOutput(OutputStream out) throws IOException { - byte[] buffer = new byte[writeBufferSize]; - int bytesRead; - while ((bytesRead = data.read(buffer)) > 0) { - out.write(buffer, 0, bytesRead); - } - out.close(); - } + return insert(tableName, columnNames, inputStreamWriter(data, writeBufferSize), format, settings); + } - @Override - public void onRetry() throws IOException { - data.reset(); - } - }, - format, settings); + private static DataStreamWriter inputStreamWriter(InputStream data, int writeBufferSize) { + return new DataStreamWriter() { + @Override + public void onOutput(OutputStream out) throws IOException { + byte[] buffer = new byte[writeBufferSize]; + int bytesRead; + while ((bytesRead = data.read(buffer)) > 0) { + out.write(buffer, 0, bytesRead); + } + out.close(); + } + + @Override + public void onRetry() throws IOException { + data.reset(); + } + }; } /** @@ -1812,11 +1815,142 @@ public CompletableFuture insert(String tableName, DataStreamWriter writer, ClickHouseFormat format, InsertSettings settings) { + StringBuilder sqlStmt = new StringBuilder("INSERT INTO ").append(tableName); + if (columnNames != null && !columnNames.isEmpty()) { + sqlStmt.append(" ("); + for (String columnName : columnNames) { + sqlStmt.append(columnName).append(", "); + } + sqlStmt.deleteCharAt(sqlStmt.length() - 2); + sqlStmt.append(")"); + } + sqlStmt.append(" FORMAT ").append(format.name()); + return executeInsert(sqlStmt.toString(), tableName, null, writer, format, settings); + } + + /** + *

Sends an insert request with an application-defined {@code INSERT} statement. Input data is read from + * the input stream.

+ * + * @param sql - {@code INSERT} statement without the data. See + * {@link #insertQuery(String, Map, DataStreamWriter, ClickHouseFormat, InsertSettings)} + * @param data - data stream to insert + * @param format - format of the data in the stream. When {@code null}, {@code sql} must have a + * {@code FORMAT} clause + * @param settings - insert operation settings + * @return {@code CompletableFuture} - a promise to insert response + */ + public CompletableFuture insertQuery(String sql, + InputStream data, + ClickHouseFormat format, + InsertSettings settings) { + if (settings == null) { + throw new IllegalArgumentException("Settings cannot be null"); + } + final int writeBufferSize = settings.getInputStreamCopyBufferSize() <= 0 ? + (int) configuration.get(ClientConfigProperties.CLIENT_NETWORK_BUFFER_SIZE.getKey()) : + settings.getInputStreamCopyBufferSize(); + + if (writeBufferSize <= 0) { + throw new IllegalArgumentException("Buffer size must be greater than 0"); + } + return insertQuery(sql, null, inputStreamWriter(data, writeBufferSize), format, settings); + } + + /** + *

Sends an insert request with an application-defined {@code INSERT} statement. Data is pushed when + * a {@link DataStreamWriter#onOutput(OutputStream)} is called.

+ * + * @param sql - {@code INSERT} statement without the data. See + * {@link #insertQuery(String, Map, DataStreamWriter, ClickHouseFormat, InsertSettings)} + * @param writer - {@link DataStreamWriter} implementation + * @param format - source format. When {@code null}, {@code sql} must have a {@code FORMAT} clause + * @param settings - operation settings + * @return {@code CompletableFuture} - a promise to insert response + */ + public CompletableFuture insertQuery(String sql, + DataStreamWriter writer, + ClickHouseFormat format, + InsertSettings settings) { + return insertQuery(sql, null, writer, format, settings); + } + + /** + *

Sends an insert request with an application-defined {@code INSERT} statement. Data is pushed when + * a {@link DataStreamWriter#onOutput(OutputStream)} is called.

+ * + *

Use this method when {@link #insert(String, List, DataStreamWriter, ClickHouseFormat, InsertSettings)} + * cannot express the statement. For example: + * {@code INSERT INTO t (a, b) SELECT a, sum(b) FROM input('a String, b UInt64') GROUP BY a}.

+ * + *
    + *
  • The client sends {@code sql} to the server as it is: the client does not parse, validate or + * escape it. Do not put untrusted values into {@code sql}; use {@code queryParams} for them.
  • + *
  • When {@code format} is not {@code null}, the client appends a new line and {@code FORMAT } + * to {@code sql}. In this case {@code sql} must not have a {@code FORMAT} clause.
  • + *
  • When {@code format} is {@code null}, {@code sql} must end with a {@code FORMAT} clause.
  • + *
  • The data in the stream must be in the format of the statement.
  • + *
  • The operation does not report a target table to the metrics and the spans.
  • + *
+ * + * @param sql - {@code INSERT} statement without the data + * @param queryParams - values of the server-side query parameters ({@code {name:Type}}) in {@code sql}. + * May be {@code null} + * @param writer - {@link DataStreamWriter} implementation + * @param format - source format. When {@code null}, {@code sql} must have a {@code FORMAT} clause + * @param settings - operation settings + * @return {@code CompletableFuture} - a promise to insert response + */ + public CompletableFuture insertQuery(String sql, + Map queryParams, + DataStreamWriter writer, + ClickHouseFormat format, + InsertSettings settings) { + if (sql == null || sql.trim().isEmpty()) { + throw new IllegalArgumentException("SQL statement cannot be null or empty"); + } + if (writer == null) { + throw new IllegalArgumentException("Writer cannot be null"); + } + // A new line keeps the FORMAT clause out of a line comment at the end of the statement. + String sqlStmt = format == null ? sql : sql + "\nFORMAT " + format.name(); + return executeInsert(sqlStmt, null, queryParams, writer, format, settings); + } + + /** + * Formats the values of the query parameters here, so that the transport layer gets the text to send: + * Array/Map values are quoted as the {@code param_} parser of the server expects + * (e.g. {@code {dates:Array(Date)}} from {@code List} becomes {@code ['2026-05-13']}, not + * {@code [2026-05-13]}). + */ + private static Map formatQueryParams(Map queryParams) { + Map formattedParams = new LinkedHashMap<>(); + for (Map.Entry param : queryParams.entrySet()) { + formattedParams.put(param.getKey(), + DataTypeConverter.INSTANCE.convertParameterToString(param.getValue())); + } + return formattedParams; + } + + private CompletableFuture executeInsert(String sqlStmt, + String tableName, + Map queryParams, + DataStreamWriter writer, + ClickHouseFormat format, + InsertSettings settings) { if (settings == null) { throw new IllegalArgumentException("Settings cannot be null"); } final InsertSettings requestSettings = new InsertSettings(buildRequestSettings(settings.getAllSettings())); - requestSettings.setOption(ClientConfigProperties.INPUT_OUTPUT_FORMAT.getKey(), format); + if (format != null) { + requestSettings.setOption(ClientConfigProperties.INPUT_OUTPUT_FORMAT.getKey(), format); + } else { + // The FORMAT clause of the statement sets the format. The default of the client must not get to the request. + requestSettings.resetOption(ClientConfigProperties.INPUT_OUTPUT_FORMAT.getKey()); + } + if (queryParams != null) { + requestSettings.setOption(HttpAPIClientHelper.KEY_STATEMENT_PARAMS, formatQueryParams(queryParams)); + } String operationId = requestSettings.getOperationId(); ClientStatisticsHolder clientStats = null; @@ -1843,17 +1977,7 @@ public CompletableFuture insert(String tableName, throw new IllegalArgumentException("Buffer size must be greater than 0"); } - StringBuilder sqlStmt = new StringBuilder("INSERT INTO ").append(tableName); - if (columnNames != null && !columnNames.isEmpty()) { - sqlStmt.append(" ("); - for (String columnName : columnNames) { - sqlStmt.append(columnName).append(", "); - } - sqlStmt.deleteCharAt(sqlStmt.length() - 2); - sqlStmt.append(")"); - } - sqlStmt.append(" FORMAT ").append(format.name()); - requestSettings.serverSetting(ClickHouseHttpProto.QPARAM_QUERY_STMT, sqlStmt.toString()); + requestSettings.serverSetting(ClickHouseHttpProto.QPARAM_QUERY_STMT, sqlStmt); if (requestSettings.getQueryId() == null && queryIdGenerator != null) { requestSettings.setQueryId(queryIdGenerator.get()); } @@ -2000,15 +2124,7 @@ public CompletableFuture query(String sqlQuery, Map parser expects - // (e.g. {dates:Array(Date)} <- List becomes ['2026-05-13'], not [2026-05-13]). - Map formattedParams = new LinkedHashMap<>(); - for (Map.Entry param : queryParams.entrySet()) { - formattedParams.put(param.getKey(), - DataTypeConverter.INSTANCE.convertParameterToString(param.getValue())); - } - requestSettings.setOption(HttpAPIClientHelper.KEY_STATEMENT_PARAMS, formattedParams); + requestSettings.setOption(HttpAPIClientHelper.KEY_STATEMENT_PARAMS, formatQueryParams(queryParams)); } if (requestSettings.getQueryId() == null && queryIdGenerator != null) { diff --git a/client-v2/src/main/java/com/clickhouse/client/api/observability/MetricsRecorder.java b/client-v2/src/main/java/com/clickhouse/client/api/observability/MetricsRecorder.java index 12bb4c950..6a03bc8b0 100644 --- a/client-v2/src/main/java/com/clickhouse/client/api/observability/MetricsRecorder.java +++ b/client-v2/src/main/java/com/clickhouse/client/api/observability/MetricsRecorder.java @@ -61,7 +61,8 @@ public interface MetricsRecorder { * Reports that an insert operation completed successfully. * * @param settings - resolved settings of the operation; source of the target database - * @param tableName - target table + * @param tableName - target table, or {@code null} when the client does not know it (an insert with an + * application-defined statement) * @param metrics - metrics of the completed operation; source of the operation and serialization * durations and of what the server wrote. May be {@code null} */ @@ -82,7 +83,8 @@ public interface MetricsRecorder { * {@link #recordInsertSuccess(InsertSettings, String, OperationMetrics)}. * * @param settings - resolved settings of the operation - * @param tableName - target table + * @param tableName - target table, or {@code null} when the client does not know it (an insert with an + * application-defined statement) * @param duration - time the operation took before it failed, measured by the client * @param t - failure the caller receives */ @@ -103,7 +105,8 @@ public interface MetricsRecorder { * per retried attempt. * * @param settings - resolved settings of the operation - * @param tableName - target table + * @param tableName - target table, or {@code null} when the client does not know it (an insert with an + * application-defined statement) * @param cause - failure of the attempt that is retried */ void recordInsertRetry(InsertSettings settings, String tableName, Throwable cause); diff --git a/client-v2/src/main/java/com/clickhouse/client/api/observability/MetricsSupport.java b/client-v2/src/main/java/com/clickhouse/client/api/observability/MetricsSupport.java index 89c6779a5..deb5196c1 100644 --- a/client-v2/src/main/java/com/clickhouse/client/api/observability/MetricsSupport.java +++ b/client-v2/src/main/java/com/clickhouse/client/api/observability/MetricsSupport.java @@ -68,7 +68,8 @@ public Map queryAttributes(QuerySettings settings, Throwable fai * Returns the attributes of an insert operation. * * @param settings - resolved settings of the operation - * @param tableName - target table + * @param tableName - target table, or {@code null} when the client does not know it (an insert with an + * application-defined statement) * @param failure - failure of the operation, or {@code null} when it succeeded * @return attributes, keyed by {@link MetricAttribute#getKey()} */ diff --git a/client-v2/src/main/java/com/clickhouse/client/api/observability/SpanRecorder.java b/client-v2/src/main/java/com/clickhouse/client/api/observability/SpanRecorder.java index 2d97275f8..9ba202156 100644 --- a/client-v2/src/main/java/com/clickhouse/client/api/observability/SpanRecorder.java +++ b/client-v2/src/main/java/com/clickhouse/client/api/observability/SpanRecorder.java @@ -63,7 +63,8 @@ public interface SpanRecorder { * * @param settings - resolved settings of the operation; source of the target database and the * query id - * @param tableName - target table + * @param tableName - target table, or {@code null} when the client does not know it (an insert with an + * application-defined statement) * @param batchSize - number of items in the batch, or {@link #BATCH_SIZE_UNKNOWN} when the client * does not know it * @param endpoint - first configured endpoint, which the operation is expected to use; the endpoint diff --git a/client-v2/src/main/java/com/clickhouse/client/api/observability/SpanSupport.java b/client-v2/src/main/java/com/clickhouse/client/api/observability/SpanSupport.java index 7ecbd4548..b5abb5918 100644 --- a/client-v2/src/main/java/com/clickhouse/client/api/observability/SpanSupport.java +++ b/client-v2/src/main/java/com/clickhouse/client/api/observability/SpanSupport.java @@ -66,7 +66,8 @@ public String querySpanName(QuerySettings settings) { * naming convention. * * @param settings - settings of the operation - * @param tableName - target table + * @param tableName - target table, or {@code null} when the client does not know it (an insert with an + * application-defined statement) * @return span name */ public String insertSpanName(InsertSettings settings, String tableName) { @@ -105,7 +106,8 @@ public void fillQueryAttributes(Span span, QuerySettings settings, String sqlQue * * @param span - span of the operation * @param settings - resolved settings of the operation - * @param tableName - target table + * @param tableName - target table, or {@code null} when the client does not know it (an insert with an + * application-defined statement) * @param batchSize - number of items in the batch, or {@link SpanRecorder#BATCH_SIZE_UNKNOWN} * when the client does not know it * @param endpoint - endpoint the operation is expected to use; may be {@code null} diff --git a/client-v2/src/test/java/com/clickhouse/client/insert/InsertTests.java b/client-v2/src/test/java/com/clickhouse/client/insert/InsertTests.java index 9939e5202..ed099b3e6 100644 --- a/client-v2/src/test/java/com/clickhouse/client/insert/InsertTests.java +++ b/client-v2/src/test/java/com/clickhouse/client/insert/InsertTests.java @@ -40,8 +40,10 @@ import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; +import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; +import java.math.BigDecimal; import java.nio.charset.StandardCharsets; import java.time.Instant; import java.time.LocalDate; @@ -53,7 +55,10 @@ import java.util.Arrays; import java.util.Collections; import java.util.List; +import java.util.Map; import java.util.UUID; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ExecutionException; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import java.util.zip.GZIPOutputStream; @@ -906,4 +911,147 @@ public void testInsertSettingsNotChanged() throws Exception { Mockito.verifyNoMoreInteractions(settings); } } + + private static final String INSERT_QUERY_TABLE = "insert_query_table"; + private static final String INSERT_QUERY_SELECT = "INSERT INTO " + INSERT_QUERY_TABLE + " (id, name, total)" + + " SELECT id, upper(name), sum(v) * %s FROM input('id UInt32, name String, v UInt64') GROUP BY id, name"; + private static final String INSERT_QUERY_DATA = "1,a,10\n2,b,7\n1,a,5\n"; + + @DataProvider(name = "insertQueryDataProvider") + public static Object[][] insertQueryDataProvider() { + return new Object[][] { + {String.format(INSERT_QUERY_SELECT, "1"), null, ClickHouseFormat.CSV, false, 1}, + {String.format(INSERT_QUERY_SELECT, "1") + " FORMAT CSV", null, null, false, 1}, + {String.format(INSERT_QUERY_SELECT, "1") + " -- comment", null, ClickHouseFormat.CSV, false, 1}, + {String.format(INSERT_QUERY_SELECT, "{k:UInt64}"), Collections.singletonMap("k", 10), ClickHouseFormat.CSV, false, 10}, + {String.format(INSERT_QUERY_SELECT, "1"), null, ClickHouseFormat.CSV, true, 1}, + }; + } + + @Test(groups = { "integration" }, dataProvider = "insertQueryDataProvider") + public void testInsertQuery(String sql, Map queryParams, ClickHouseFormat format, + boolean useInputStream, int factor) throws Exception { + initTable(INSERT_QUERY_TABLE, "CREATE TABLE " + INSERT_QUERY_TABLE + + " (id UInt32, name String, total UInt64, flag UInt8 DEFAULT 7) ENGINE = MergeTree ORDER BY id"); + + byte[] data = INSERT_QUERY_DATA.getBytes(StandardCharsets.UTF_8); + CompletableFuture future = useInputStream + ? client.insertQuery(sql, new ByteArrayInputStream(data), format, new InsertSettings()) + : client.insertQuery(sql, queryParams, out -> out.write(data), format, new InsertSettings()); + try (InsertResponse response = future.get(EXECUTE_CMD_TIMEOUT, TimeUnit.SECONDS)) { + assertEquals(response.getWrittenRows(), 2); + } + + List records = client.queryAll("SELECT * FROM " + INSERT_QUERY_TABLE + " ORDER BY id"); + assertEquals(records.size(), 2); + Object[][] expected = {{1L, "A", 15L * factor, 7}, {2L, "B", 7L * factor, 7}}; + for (int i = 0; i < expected.length; i++) { + GenericRecord r = records.get(i); + assertEquals(new Object[] {r.getLong("id"), r.getString("name"), r.getLong("total"), r.getInteger("flag")}, + expected[i]); + } + } + + @Test(groups = { "integration" }) + public void testInsertQueryServerError() throws Exception { + initTable(INSERT_QUERY_TABLE, "CREATE TABLE " + INSERT_QUERY_TABLE + + " (id UInt32, name String, total UInt64, flag UInt8 DEFAULT 7) ENGINE = MergeTree ORDER BY id"); + byte[] data = INSERT_QUERY_DATA.getBytes(StandardCharsets.UTF_8); + + // The statement has a FORMAT clause and the client appends one more + String sql = String.format(INSERT_QUERY_SELECT, "1") + " FORMAT CSV"; + try { + client.insertQuery(sql, out -> out.write(data), ClickHouseFormat.CSV, new InsertSettings()) + .get(EXECUTE_CMD_TIMEOUT, TimeUnit.SECONDS); + fail("Expected a server error"); + } catch (Exception e) { + Throwable cause = e instanceof ExecutionException ? e.getCause() : e; + assertTrue(cause instanceof ServerException, "Unexpected exception: " + cause); + } + assertEquals(client.queryAll("SELECT * FROM " + INSERT_QUERY_TABLE).size(), 0); + } + + @Test(groups = { "integration" }) + public void testInsertQueryCompressedParquet() throws Exception { + String tableName = "insert_query_parquet_table"; + initTable(tableName, "CREATE TABLE " + tableName + + " (id Int64, str String, dcml Decimal64(9), time DateTime('UTC')) ENGINE = MergeTree ORDER BY id"); + + // test_sample.parquet.gz: 100 rows (int, str, flt, dcml, time), compressed with gzip + String sql = "INSERT INTO " + tableName + " (id, str, dcml, time)" + + " SELECT int * 2, concat('s', str), dcml, time" + + " FROM input('int Int64, str String, dcml Decimal64(9), time DateTime(\\'UTC\\')')"; + InsertSettings insertSettings = new InsertSettings().appCompressedData(true, "gzip"); + try (InputStream data = InsertTests.class.getResourceAsStream("/data_samples/test_sample.parquet.gz"); + InsertResponse response = client.insertQuery(sql, data, ClickHouseFormat.Parquet, insertSettings) + .get(EXECUTE_CMD_TIMEOUT, TimeUnit.SECONDS)) { + assertEquals(response.getWrittenRows(), 100); + } + + GenericRecord r = client.queryAll("SELECT count() AS cnt, sum(id) AS sum_id, uniqExact(str) AS uniq_str," + + " countIf(startsWith(str, 's')) AS s_cnt, max(dcml) AS max_dcml, toString(min(time)) AS min_time," + + " toString(max(time)) AS max_time FROM " + tableName).get(0); + assertEquals(new Object[] {r.getLong("cnt"), r.getLong("sum_id"), r.getLong("uniq_str"), r.getLong("s_cnt"), + r.getBigDecimal("max_dcml"), r.getString("min_time"), r.getString("max_time")}, + new Object[] {100L, 9900L, 100L, 100L, new BigDecimal("1.000000000"), + "2020-01-01 00:00:00", "2020-01-01 00:01:39"}); + } + + @Test(groups = { "integration" }) + public void testInsertQueryIntoTableFunction() throws Exception { + if (isCloud()) { + throw new SkipException("The file() table function is not available in ClickHouse Cloud"); + } + String fileName = "insert_query_" + UUID.randomUUID().toString().replace('-', '_') + ".csv.gz"; + String structure = "'id UInt32, name String, v UInt64'"; + + String sql = "INSERT INTO FUNCTION file('" + fileName + "', 'CSV', " + structure + ")"; + byte[] data = INSERT_QUERY_DATA.getBytes(StandardCharsets.UTF_8); + try (InsertResponse response = client.insertQuery(sql, out -> out.write(data), ClickHouseFormat.CSV, + new InsertSettings()).get(EXECUTE_CMD_TIMEOUT, TimeUnit.SECONDS)) { + assertEquals(response.getWrittenRows(), 3); + } + + // The server compresses the file because of the .gz extension + List magic = client.queryAll("SELECT hex(substring(raw_blob, 1, 2)) AS magic FROM file('" + + fileName + "', 'RawBLOB', 'raw_blob String', 'none')"); + assertEquals(magic.get(0).getString("magic"), "1F8B"); + + List records = client.queryAll("SELECT id, name, v FROM file('" + fileName + "', 'CSV', " + + structure + ")"); + Object[][] expected = {{1L, "a", 10L}, {2L, "b", 7L}, {1L, "a", 5L}}; + assertEquals(records.size(), expected.length); + for (int i = 0; i < expected.length; i++) { + GenericRecord r = records.get(i); + assertEquals(new Object[] {r.getLong("id"), r.getString("name"), r.getLong("v")}, expected[i]); + } + } + + @Test(groups = { "integration" }) + public void testInsertQueryIntoNullFunction() throws Exception { + String sql = "INSERT INTO FUNCTION null('id UInt32, name String, v UInt64')"; + byte[] data = INSERT_QUERY_DATA.getBytes(StandardCharsets.UTF_8); + try (InsertResponse response = client.insertQuery(sql, out -> out.write(data), ClickHouseFormat.CSV, + new InsertSettings()).get(EXECUTE_CMD_TIMEOUT, TimeUnit.SECONDS)) { + assertEquals(response.getWrittenRows(), 3); + } + } + + @DataProvider(name = "insertQueryInvalidArgumentsDataProvider") + public static Object[][] insertQueryInvalidArgumentsDataProvider() { + DataStreamWriter writer = out -> { }; + InsertSettings settings = new InsertSettings(); + return new Object[][] { + {null, writer, settings}, + {" ", writer, settings}, + {"INSERT INTO t", null, settings}, + {"INSERT INTO t", writer, null}, + }; + } + + @Test(groups = { "integration" }, dataProvider = "insertQueryInvalidArgumentsDataProvider") + public void testInsertQueryInvalidArguments(String sql, DataStreamWriter writer, InsertSettings settings) { + Assert.assertThrows(IllegalArgumentException.class, + () -> client.insertQuery(sql, writer, ClickHouseFormat.CSV, settings)); + } } diff --git a/client-v2/src/test/resources/data_samples/test_sample.parquet.gz b/client-v2/src/test/resources/data_samples/test_sample.parquet.gz new file mode 100644 index 000000000..eab2be518 Binary files /dev/null and b/client-v2/src/test/resources/data_samples/test_sample.parquet.gz differ diff --git a/docs/features.md b/docs/features.md index ef27f4018..e2826f183 100644 --- a/docs/features.md +++ b/docs/features.md @@ -28,6 +28,7 @@ This document lists stable, user-visible behavior in `client-v2` and `jdbc-v2` t - MultiPoint type support: For ClickHouse `26.8+`, reads and writes the `MultiPoint` geo type, which is transmitted exactly like `Ring` and `LineString` (`Array(Point)`) and is represented as `double[][]` through generic records, binary readers, POJO binding, and SQL parameter formatting. A `MultiPoint` held in a `Dynamic` column is decoded on read; it cannot be written into a `Dynamic` column, because the client infers the type from the Java value and `double[][]` resolves to `Ring`. - Nested type support: Un-flattened `Nested(f1 T1, ..., fN TN)` columns (tables created with `flatten_nested = 0`) can be written through the insert path (`Client#insert`) using `RowBinaryFormatWriter#setValue`, and are read back through the binary readers and generic records. The column is serialized the same way it is read — identically to `Array(Tuple(T1, ..., TN))`, a var-uint row count followed by one tuple per nested row — so the value supplied for the column is a `List` (or array) of tuples, one tuple per nested row, each carrying the N field values in declaration order. - Insert APIs: Supports inserting registered POJOs, raw streams, and callback-driven writers, with optional column lists and format selection. +- Custom insert statement: `Client#insertQuery` sends an `INSERT` statement that the application writes (for example `INSERT ... SELECT ... FROM input(...)`) with data from a `DataStreamWriter` or an `InputStream`. The client does not parse the statement. It appends `FORMAT ` when a format is given; otherwise the statement must have a `FORMAT` clause. The statement can have query parameters - `{name:Type}` placeholders, for example `INSERT INTO t SELECT a * {k:UInt64} FROM input('a UInt64')` - and their values come from the `queryParams` map of `insertQuery(sql, queryParams, writer, format, settings)`; the client sends each value as the `param_` URL parameter, as `Client#query` does, and the server substitutes it. The statement goes in the `query` URL parameter, as for the other insert methods. Metrics and spans of the operation have no target table (`db.collection.name`). - Insert controls: Supports insert-specific settings such as deduplication token, query id, compression behavior, and request headers. - Command execution: Executes DDL or other non-result commands and exposes response summaries and operation metrics. - Session handling: Supports client-wide and per-operation HTTP sessions, operation-level session overrides, runtime updates of client `session_id`, and server-side session validation through `session_check`. diff --git a/history/latest/2071.md b/history/latest/2071.md new file mode 100644 index 000000000..aa2eecbb9 --- /dev/null +++ b/history/latest/2071.md @@ -0,0 +1,8 @@ +- **[client-v2]** Added `Client#insertQuery` to insert data with an `INSERT` statement that the application writes, + for example `INSERT INTO t (a, b) SELECT a, sum(b) FROM input('a String, b UInt64') GROUP BY a`. Before, the + insert methods could only make `INSERT INTO [(columns)] FORMAT `. The client sends the statement + as it is. When the format argument is not `null`, the client appends `FORMAT `. When it is `null`, the + statement must have its own `FORMAT` clause. The data can come from a `DataStreamWriter` or an `InputStream`, and + server-side query parameters (`{name:Type}`) are supported. The operation reports no target table to metrics and + spans. The existing `insert` methods do not change. + (https://github.com/ClickHouse/clickhouse-java/issues/2071)