From 04fe0eb2b08fead649a21ba22d26c2446754677d Mon Sep 17 00:00:00 2001 From: Polyglot AI <293096396+polyglotAI-bot@users.noreply.github.com> Date: Tue, 17 Nov 2026 19:47:00 +0000 Subject: [PATCH 1/5] [client-v2] Native reader: check each block against the first block The Native reader decodes some nested types (for example Array(Array(Int8)) or Map(String, Array(Nullable(Float64)))) with the RowBinary layout and reads a wrong number of bytes. It then read the next bytes as a block header, for example a block with no columns and some rows, and hasNext()/next() returned the rows of that block. NativeFormatReaderDataSetTest failed for these two types with "More rows than in the data set". All blocks of one Native result have the same columns. The reader now keeps the header of the first block and fails with ClientException if a later block has other columns. It compares the length of each name and type before it reads the bytes, so a length from wrong bytes cannot cause a large allocation. Also: - The schema is created only from the first block. Before, each block replaced the row buffers, so hasNext() at the end of a block changed the values that the getters returned for the current row. - hasNext(), readRecord(Map) and readRecord(Object[]) use one method to move to the next row. readRecord(Map) no longer throws NullPointerException for an empty result or IndexOutOfBoundsException for a block without rows. - A stream that ends inside the column count of a block now fails. Before, it was the end of the result. - Javadoc explains the stream layout and how the reader reads rows. Part of: https://github.com/ClickHouse/clickhouse-java/issues/3365 Co-Authored-By: Claude Opus 5.5 --- .../api/data_formats/NativeFormatReader.java | 211 +++++++++++++----- .../data_formats/NativeFormatReaderTest.java | 165 ++++++++++++++ history/latest/3365.md | 16 ++ 3 files changed, 340 insertions(+), 52 deletions(-) create mode 100644 history/latest/3365.md diff --git a/client-v2/src/main/java/com/clickhouse/client/api/data_formats/NativeFormatReader.java b/client-v2/src/main/java/com/clickhouse/client/api/data_formats/NativeFormatReader.java index 024f47bcf..69b4362ce 100644 --- a/client-v2/src/main/java/com/clickhouse/client/api/data_formats/NativeFormatReader.java +++ b/client-v2/src/main/java/com/clickhouse/client/api/data_formats/NativeFormatReader.java @@ -8,24 +8,75 @@ import com.clickhouse.data.ClickHouseColumn; import com.clickhouse.data.ClickHouseDataType; -import java.io.EOFException; +import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; +import java.io.SequenceInputStream; +import java.nio.charset.StandardCharsets; import java.util.ArrayList; +import java.util.Arrays; import java.util.List; import java.util.Map; /** - * For the backward compatibility server will not send TZ id in column type. Client should send version to a server + * Reads a result in the {@code Native} format. + * + *

Stream layout. A Native result is a sequence of blocks. There is no header and no trailer. The server + * sends an empty result as an empty stream, but the reader also accepts blocks without rows. One block is: + *

+ * VarUInt   number of columns
+ * VarUInt   number of rows
+ * for each column:
+ *   String  column name
+ *   String  column type
+ *   bytes   values of all rows of the column, in the Native (column-oriented) layout of the type
+ * 
+ * All blocks of one result have the same columns: the same number, in the same order, with the same names and + * types. + * + *

How rows are read. + *

+ * This reader does not use the one-row read-ahead of {@link AbstractBinaryFormatReader}. + * + *

For the backward compatibility server will not send TZ id in column type. Client should send version to a server * to get the correct column type. * (see: https://github.com/ClickHouse/ClickHouse/issues/38209) */ public class NativeFormatReader extends AbstractBinaryFormatReader { + /** Block that rows are taken from. {@code null} at the end of the result and after a read failure. */ private Block currentBlock; + /** Index of the next row to take from {@link #currentBlock}. */ private int blockRowIndex; + /** Column names of the first block. The rows of all blocks use these names. */ + private List columnNames; + + /** + * Column names and types of the first block, as the UTF-8 bytes that the server wrote: name, type, name, type, + * and so on. All later blocks must have the same bytes. + */ + private List firstBlockHeader; + public NativeFormatReader(InputStream inputStream, QuerySettings settings, BinaryStreamReader.ByteBufferAllocator byteBufferAllocator, Map> typeHintMapping) { @@ -44,10 +95,8 @@ public NativeFormatReader(InputStream inputStream, QuerySettings settings, @Override public boolean readRecord(Map record) throws IOException { - if (blockRowIndex >= currentBlock.getnRows()) { - if (!readBlock()) { - return false; - } + if (!hasRowInBlock()) { + return false; } currentBlock.fillRecord(blockRowIndex, record); @@ -55,27 +104,13 @@ public boolean readRecord(Map record) throws IOException { return true; } - // A Native block is fully in memory, so rows are taken from it directly instead of through the - // one-row read-ahead of the base class. Each block re-publishes the schema, which replaces the row - // buffers, so the next block is read only when no row of the current one is still pending. @Override public boolean hasNext() { - while (currentBlock != null && blockRowIndex >= currentBlock.getnRows()) { - try { - if (!readBlock()) { - currentBlock = null; - } - } catch (IOException e) { - currentBlock = null; - endReached(); - throw new ClientException("Failed to read block", e); - } - } - if (currentBlock == null) { - endReached(); - return false; + try { + return hasRowInBlock(); + } catch (IOException e) { + throw new ClientException("Failed to read block", e); } - return true; } @Override @@ -90,10 +125,8 @@ public Map next() { @Override protected boolean readRecord(Object[] record) throws IOException { - if (blockRowIndex >= currentBlock.getnRows()) { - if (!readBlock()) { - return false; - } + if (!hasRowInBlock()) { + return false; } currentBlock.fillRecord(blockRowIndex, record); @@ -101,28 +134,80 @@ protected boolean readRecord(Object[] record) throws IOException { return true; } - private boolean readBlock() throws IOException { - int nColumns; + /** + * Makes sure that {@link #currentBlock} has a row at {@link #blockRowIndex} that was not taken yet. Reads the next + * block only when all rows of the current block were taken, and skips blocks without rows. If the current block + * has a row, this method reads nothing. Thus, it gives the same result for each call until the row is taken. + * + * @return {@code true} if there is a row to take, {@code false} at the end of the result + * @throws IOException if the next block cannot be read. The reader is then at the end of the result. + * @throws ClientException if the next block has other columns than the first block, or a column that this reader + * does not decode. The reader is then at the end of the result. + */ + private boolean hasRowInBlock() throws IOException { try { - nColumns = BinaryStreamReader.readVarInt(input); - } catch (EOFException e) { + while (currentBlock != null && blockRowIndex >= currentBlock.getnRows()) { + readBlock(); + } + } catch (IOException | RuntimeException e) { + currentBlock = null; endReached(); - return false; + throw e; + } + return currentBlock != null; + } + + /** + * Reads the next block into {@link #currentBlock} and sets {@link #blockRowIndex} to its first row. If the stream + * ends before the block, sets {@link #currentBlock} to {@code null}. The first block sets the schema. A later block + * must have the same columns as the first block. + * + * @throws IOException if the stream cannot be read or ends inside the block + * @throws ClientException if the block has other columns than the first block (the reader is then not at a block + * boundary), or a column that this reader does not decode + */ + private void readBlock() throws IOException { + int firstByte = input.read(); + if (firstByte < 0) { + currentBlock = null; + endReached(); + return; + } + int nColumns = firstByte; + if ((firstByte & 0x80) != 0) { + // 128 or more columns: the VarUInt continues in the next bytes. + nColumns = BinaryStreamReader.readVarInt(new SequenceInputStream( + new ByteArrayInputStream(new byte[] {(byte) firstByte}), input)); } int nRows = BinaryStreamReader.readVarInt(input); - List names = new ArrayList<>(nColumns); - List types = new ArrayList<>(nColumns); - currentBlock = new Block(names, types, nRows); - List columns = new ArrayList<>(nColumns); + boolean firstBlock = firstBlockHeader == null; + if (!firstBlock && nColumns != columnNames.size()) { + throw blockOutOfSync("it has " + nColumns + " columns, but the first block has " + columnNames.size()); + } + List columns = firstBlock ? new ArrayList<>(nColumns) : getSchema().getColumns(); + if (firstBlock) { + columnNames = new ArrayList<>(nColumns); + firstBlockHeader = new ArrayList<>(nColumns * 2); + } + Block block = new Block(columnNames, nRows); for (int i = 0; i < nColumns; i++) { - - ClickHouseColumn column = ClickHouseColumn.of(BinaryStreamReader.readString(input), - BinaryStreamReader.readString(input)); - columns.add(column); - - names.add(column.getColumnName()); - types.add(column.getDataType().name()); + ClickHouseColumn column; + if (firstBlock) { + byte[] name = readStringBytes(); + byte[] type = readStringBytes(); + column = ClickHouseColumn.of(new String(name, StandardCharsets.UTF_8), + new String(type, StandardCharsets.UTF_8)); + columns.add(column); + columnNames.add(column.getColumnName()); + firstBlockHeader.add(name); + firstBlockHeader.add(type); + } else if (readsString(firstBlockHeader.get(2 * i)) && readsString(firstBlockHeader.get(2 * i + 1))) { + column = columns.get(i); + } else { + // Do not put the name and the type into the message: they were read from wrong bytes. + throw blockOutOfSync("column " + (i + 1) + " has a different name or type than in the first block"); + } List values; if (isNativeDecodableQBit(column)) { @@ -190,14 +275,37 @@ private boolean readBlock() throws IOException { values.add(value); } } - currentBlock.add(values); + block.add(values); + } + if (firstBlock) { + // Later blocks have the same columns, so the schema and the row buffers that it creates stay the same. + setSchema(new TableSchema(columns)); } - TableSchema schema = new TableSchema(columns); - - setSchema(schema); + currentBlock = block; blockRowIndex = 0; - return true; + } + + private byte[] readStringBytes() throws IOException { + return BinaryStreamReader.readStringBytes(input, BinaryStreamReader.readVarInt(input)); + } + + /** + * Reads a String and compares it with {@code expected}. Reads the bytes of the String only if its length is the + * same. Thus, a length read from wrong bytes cannot cause a large allocation. + */ + private boolean readsString(byte[] expected) throws IOException { + int length = BinaryStreamReader.readVarInt(input); + return length == expected.length + && Arrays.equals(BinaryStreamReader.readStringBytes(input, length), expected); + } + + private static ClientException blockOutOfSync(String reason) { + return new ClientException("Failed to read block: " + reason + ". All blocks of a Native result have the " + + "same columns, so the reader is not at a block boundary. Usually a column of the previous block " + + "uses a Native layout that this reader does not decode (for example, LowCardinality or some nested " + + "Array, Map and Tuple types), or the server wrote an error message into the stream. Use a RowBinary " + + "format (e.g. RowBinaryWithNamesAndTypes) to read such columns"); } /** @@ -267,16 +375,15 @@ private static boolean containsQBit(ClickHouseColumn column) { return false; } + /** Decoded values of one block: one list of {@code nRows} values for each column. */ private static class Block { final List names; - final List types; final List> values = new ArrayList<>(); final int nRows; - Block(List names, List types, int nRows) { + Block(List names, int nRows) { this.names = names; - this.types = types; this.nRows = nRows; } diff --git a/client-v2/src/test/java/com/clickhouse/client/api/data_formats/NativeFormatReaderTest.java b/client-v2/src/test/java/com/clickhouse/client/api/data_formats/NativeFormatReaderTest.java index bd24bd746..83d16adbb 100644 --- a/client-v2/src/test/java/com/clickhouse/client/api/data_formats/NativeFormatReaderTest.java +++ b/client-v2/src/test/java/com/clickhouse/client/api/data_formats/NativeFormatReaderTest.java @@ -19,8 +19,12 @@ import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; +import java.io.EOFException; import java.io.IOException; import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.TimeUnit; @@ -61,6 +65,148 @@ public void testReadsEveryRowAcrossBlocks() throws Exception { } } + // 0 rows: the server sends an empty stream. 25 rows with max_block_size = 10: three blocks. + @DataProvider(name = "rowCounts") + public static Object[][] rowCounts() { + return new Object[][] {{0}, {1}, {25}}; + } + + @Test(groups = {"integration"}, dataProvider = "rowCounts") + public void testHasNextIsIdempotent(int rows) throws Exception { + try (Client client = newClient().build(); + QueryResponse response = queryNative(client, rows)) { + ClickHouseBinaryFormatReader reader = client.newBinaryFormatReader(response); + List values = new ArrayList<>(); + List fromGetters = new ArrayList<>(); + while (reader.hasNext()) { + Assert.assertTrue(reader.hasNext()); + Map row = reader.next(); + // After the last row of a block, this reads the next block. + reader.hasNext(); + values.add(row.get("n")); + fromGetters.add(reader.getInteger("n")); + } + Assert.assertEquals(values, sequence(rows)); + Assert.assertEquals(fromGetters, sequence(rows)); + Assert.assertFalse(reader.hasNext()); + Assert.assertNull(reader.next()); + } + } + + @Test(groups = {"integration"}, dataProvider = "rowCounts") + public void testReadRecordReadsEveryRow(int rows) throws Exception { + try (Client client = newClient().build(); + QueryResponse response = queryNative(client, rows)) { + NativeFormatReader reader = (NativeFormatReader) client.newBinaryFormatReader(response); + List values = new ArrayList<>(); + Map record = new HashMap<>(); + while (reader.readRecord(record)) { + values.add(record.get("n")); + } + Assert.assertEquals(values, sequence(rows)); + Assert.assertFalse(reader.readRecord(record)); + } + } + + private static QueryResponse queryNative(Client client, int rows) throws Exception { + return client.query("SELECT toInt32(number) AS n FROM numbers(" + rows + ") SETTINGS max_block_size = 10", + new QuerySettings().setFormat(ClickHouseFormat.Native)).get(30, TimeUnit.SECONDS); + } + + private static List sequence(int rows) { + List values = new ArrayList<>(); + for (int i = 0; i < rows; i++) { + values.add(i); + } + return values; + } + + // Row count of each block in the stream. No blocks: an empty stream. + @DataProvider(name = "blockRowCounts") + public static Object[][] blockRowCounts() { + return new Object[][] {{new int[0]}, {new int[] {0}}, {new int[] {0, 2}}, {new int[] {2, 0, 1}}, + {new int[] {2, 0}}}; + } + + @Test(dataProvider = "blockRowCounts") + public void testSkipsBlocksWithoutRows(int[] blockRows) throws IOException { + ByteArrayOutputStream stream = new ByteArrayOutputStream(); + List expected = new ArrayList<>(); + for (int rows : blockRows) { + stream.write(nativeBlock(Arrays.asList("n", "Int32"), rows)); + expected.addAll(sequence(rows)); + } + + NativeFormatReader reader = nativeReader(stream.toByteArray()); + List fromNext = new ArrayList<>(); + Map row; + while ((row = reader.next()) != null) { + fromNext.add(row.get("n")); + } + Assert.assertEquals(fromNext, expected); + + reader = nativeReader(stream.toByteArray()); + List fromReadRecord = new ArrayList<>(); + Map record = new HashMap<>(); + while (reader.readRecord(record)) { + fromReadRecord.add(record.get("n")); + } + Assert.assertEquals(fromReadRecord, expected); + } + + @Test + public void testReadsBlocksWithManyColumns() throws IOException { + List columns = new ArrayList<>(); + for (int i = 0; i < 130; i++) { + columns.add("c" + i); + columns.add("Int32"); + } + ByteArrayOutputStream stream = new ByteArrayOutputStream(); + stream.write(nativeBlock(columns, 1)); + stream.write(nativeBlock(columns, 2)); + NativeFormatReader reader = nativeReader(stream.toByteArray()); + + Assert.assertEquals(reader.getSchema().getColumns().size(), 130); + List values = new ArrayList<>(); + Map row; + while ((row = reader.next()) != null) { + values.add(row.get("c129")); + } + Assert.assertEquals(values, Arrays.asList(0, 0, 1)); + } + + // A later block with other columns than the first block cannot come from the server: the reader is not at a + // block boundary. A null cause marks these cases. + @DataProvider(name = "brokenSecondBlocks") + public static Object[][] brokenSecondBlocks() throws IOException { + byte[] block = nativeBlock(Arrays.asList("n", "Int32"), 1); + return new Object[][] { + {"no columns", nativeBlock(Collections.emptyList(), 3), null}, + {"other column count", nativeBlock(Arrays.asList("n", "Int32", "m", "Int32"), 1), null}, + {"other name", nativeBlock(Arrays.asList("m", "Int32"), 1), null}, + {"other type", nativeBlock(Arrays.asList("n", "UInt32"), 1), null}, + {"end inside the column count", new byte[] {(byte) 0x81}, EOFException.class}, + {"end inside the values", Arrays.copyOf(block, block.length - 1), EOFException.class}, + }; + } + + @Test(dataProvider = "brokenSecondBlocks") + public void testFailsOnBrokenBlock(String label, byte[] secondBlock, Class cause) throws IOException { + ByteArrayOutputStream stream = new ByteArrayOutputStream(); + stream.write(nativeBlock(Arrays.asList("n", "Int32"), 2)); + stream.write(secondBlock); + NativeFormatReader reader = nativeReader(stream.toByteArray()); + + Assert.assertEquals(reader.next().get("n"), 0, label); + Assert.assertEquals(reader.next().get("n"), 1, label); + ClientException ex = Assert.expectThrows(ClientException.class, reader::hasNext); + Assert.assertEquals(ex.getCause() == null ? null : ex.getCause().getClass(), cause, label); + Assert.assertTrue(ex.getMessage().startsWith("Failed to read block") + && (cause != null || ex.getMessage().contains("block boundary")), label + ": " + ex.getMessage()); + Assert.assertFalse(reader.hasNext(), label); + Assert.assertNull(reader.next(), label); + } + private Client.Builder newClient() { ClickHouseNode node = getServer(ClickHouseProtocol.HTTP); return new Client.Builder() @@ -138,6 +284,25 @@ private static byte[] nativeBlockHeader(String columnName, String columnType) th return out.toByteArray(); } + /** + * Builds a Native block with {@code Int32} values 0, 1, ... in each column. + * + * @param columns column names and types, in pairs + */ + private static byte[] nativeBlock(List columns, int rows) throws IOException { + ByteArrayOutputStream out = new ByteArrayOutputStream(); + BinaryStreamUtils.writeVarInt(out, columns.size() / 2); + BinaryStreamUtils.writeVarInt(out, rows); + for (int i = 0; i < columns.size(); i += 2) { + BinaryStreamUtils.writeString(out, columns.get(i)); + BinaryStreamUtils.writeString(out, columns.get(i + 1)); + for (int row = 0; row < rows; row++) { + BinaryStreamUtils.writeInt32(out, row); + } + } + return out.toByteArray(); + } + private static byte[] fromHex(String hex) { byte[] out = new byte[hex.length() / 2]; for (int i = 0; i < out.length; i++) { diff --git a/history/latest/3365.md b/history/latest/3365.md new file mode 100644 index 000000000..bbd60e6f2 --- /dev/null +++ b/history/latest/3365.md @@ -0,0 +1,16 @@ +## Bug Fixes + +- **[client-v2]** The `Native` reader no longer returns rows that are not in the result after it loses its + position in the stream. The reader does not decode the Native layout of some nested types, for example + `Array(Array(Int8))` or `Map(String, Array(Nullable(Float64)))`, and reads a wrong number of bytes for them. It + then read the bytes after that column as the header of a next block, for example a block with no columns and some + rows, and returned the rows of that block. All blocks of a result have the same columns. The reader now compares + each block with the first block and fails with `ClientException` if the columns are different. Such a read now + fails; it does not return extra rows. Rows of the block with the wrong layout can still have wrong values. +- **[client-v2]** In the `Native` reader, `hasNext()` no longer changes the current row when it reads the next + block: the getters return the values of the row that `next()` returned. The reader now creates the schema only + from the first block. +- **[client-v2]** `NativeFormatReader.readRecord(Map)` no longer throws `NullPointerException` for an empty + result, or `IndexOutOfBoundsException` for a block without rows. It now skips blocks without rows. A stream that + ends inside the column count of a block now fails; before, it was the end of the result. + (https://github.com/ClickHouse/clickhouse-java/issues/3365) From ed55b05362f4a0d499412b8fc97ad6d59d973d13 Mon Sep 17 00:00:00 2001 From: Polyglot AI <293096396+polyglotAI-bot@users.noreply.github.com> Date: Tue, 17 Nov 2026 20:02:06 +0000 Subject: [PATCH 2/5] [client-v2] Describe the Native reader block contract in features.md The Native reader now compares each block with the first block, fails with ClientException on a different block, keeps the schema of the first block, skips blocks without rows, and has an idempotent hasNext(). Add this contract to the binary format readers entry. Co-Authored-By: Claude Opus 5.5 --- docs/features.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/features.md b/docs/features.md index fc23cc010..62fae3f82 100644 --- a/docs/features.md +++ b/docs/features.md @@ -18,7 +18,7 @@ This document lists stable, user-visible behavior in `client-v2` and `jdbc-v2` t - 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`). -- Binary format readers: Reads ClickHouse binary result formats including `Native`, `RowBinary`, `RowBinaryWithNames`, and `RowBinaryWithNamesAndTypes`. +- Binary format readers: Reads ClickHouse binary result formats including `Native`, `RowBinary`, `RowBinaryWithNames`, and `RowBinaryWithNamesAndTypes`. The `Native` reader decodes one full block at a time and takes the schema only from the first block. All blocks of a `Native` result have the same columns, so the reader compares the column count, names, and types of each later block with the first block. A different block means that the reader is not at a block boundary, usually because a column of the previous block uses a `Native` layout that the reader does not decode (for example `LowCardinality`, or some nested `Array`, `Map`, and `Tuple` types). The read then fails with a `ClientException` that recommends a `RowBinary` format such as `RowBinaryWithNamesAndTypes`, and no row of that block is returned. This check does not find a wrong layout that reads the correct number of bytes, and rows of a block that was decoded with a wrong layout can have wrong values. `hasNext()` is idempotent: it reads the next block only when all rows of the current block were taken, and it does not change the values of the current row. Blocks without rows are skipped. The result ends only when the stream ends before the first byte of a block; a stream that ends inside a block fails the read. - Binary string support: Opt-in through the `binary_string_support` property (or `Client.Builder#binaryStringSupport(boolean)`), disabled by default. The setting is resolved per operation from the merged client and query settings, so it can be overridden for a single request by setting the `binary_string_support` option on the operation's settings (e.g. `QuerySettings#setOption(ClientConfigProperties.BINARY_STRING_SUPPORT.getKey(), true)`) regardless of the client-level default. When enabled, untyped reads (e.g. `GenericRecord.getObject(...)`/`BinaryStreamReader.readValue(...)`) of top-level `String` and `FixedString` columns return a `StringValue`, which preserves the raw bytes (`toByteArray()`/`asByteBuffer()`) and lazily decodes a `String` (`asString()`), instead of eagerly decoding to a `String`. `StringValue` is a read-time holder, not a supported POJO field type: typed `queryAll(...)`/`readToPOJO` binding still maps these columns to `String` (decoded) or `byte[]` (raw bytes) according to the POJO field type. Strings nested inside containers (`Array`, `Map`, `Tuple`, `Nested`, `Variant`, `JSON`) are still read as `String`. - JSONEachRow text reader: Can stream `JSONEachRow` responses through a caller-supplied `JsonParser`, with Jackson and Gson parser factory implementations available as optional classpath dependencies, and infers a best-effort schema from the first row. - Data type conversion: Maps ClickHouse types to Java values for binary reads, POJO binding, and SQL parameter formatting, including date/time handling. From d4e4d8eec92e5432bd60283875291cfe182c3c6c Mon Sep 17 00:00:00 2001 From: Polyglot AI <293096396+polyglotAI-bot@users.noreply.github.com> Date: Tue, 17 Nov 2026 22:01:10 +0000 Subject: [PATCH 3/5] [client-v2] Native reader: use existing readers, short block-check message Address review on #3367: - Read the column count with BinaryStreamReader.readVarInt and end the result on EOFException, as before. No SequenceInputStream. - Remove the private string helpers. Read names and types with BinaryStreamReader.readString and compare them with the first block. - Make the block-check message short. It refers to the class Javadoc, which now explains the check, its causes, and the RowBinary workaround. Co-Authored-By: Claude Opus 5.5 --- .../api/data_formats/NativeFormatReader.java | 806 +++++++++--------- .../data_formats/NativeFormatReaderTest.java | 5 +- docs/features.md | 2 +- history/latest/3365.md | 3 +- 4 files changed, 399 insertions(+), 417 deletions(-) diff --git a/client-v2/src/main/java/com/clickhouse/client/api/data_formats/NativeFormatReader.java b/client-v2/src/main/java/com/clickhouse/client/api/data_formats/NativeFormatReader.java index 69b4362ce..26f7b9665 100644 --- a/client-v2/src/main/java/com/clickhouse/client/api/data_formats/NativeFormatReader.java +++ b/client-v2/src/main/java/com/clickhouse/client/api/data_formats/NativeFormatReader.java @@ -1,412 +1,394 @@ -package com.clickhouse.client.api.data_formats; - -import com.clickhouse.client.api.ClientException; -import com.clickhouse.client.api.data_formats.internal.AbstractBinaryFormatReader; -import com.clickhouse.client.api.data_formats.internal.BinaryStreamReader; -import com.clickhouse.client.api.metadata.TableSchema; -import com.clickhouse.client.api.query.QuerySettings; -import com.clickhouse.data.ClickHouseColumn; -import com.clickhouse.data.ClickHouseDataType; - -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.SequenceInputStream; -import java.nio.charset.StandardCharsets; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.Map; - -/** - * Reads a result in the {@code Native} format. - * - *

Stream layout. A Native result is a sequence of blocks. There is no header and no trailer. The server - * sends an empty result as an empty stream, but the reader also accepts blocks without rows. One block is: - *

- * VarUInt   number of columns
- * VarUInt   number of rows
- * for each column:
- *   String  column name
- *   String  column type
- *   bytes   values of all rows of the column, in the Native (column-oriented) layout of the type
- * 
- * All blocks of one result have the same columns: the same number, in the same order, with the same names and - * types. - * - *

How rows are read. - *

    - *
  • {@code readBlock()} decodes one full block into memory, column by column. The constructor reads the first - * block, so the schema is known before the first row is read. For an empty stream, {@link #getSchema()} returns - * {@code null}. The schema comes from the first block and does not change.
  • - *
  • Rows are taken from the block in memory by their index in the block. The next block is read only when all - * rows of the current block were taken. Blocks without rows are skipped.
  • - *
  • {@link #hasNext()} reads a block only when the current block has no row left. Thus, more calls before - * {@link #next()} read nothing and give the same result. Reading the next block does not change the values of - * the current row. {@link #next()} takes the row and moves to the next index. It does not read ahead. - * {@link #readRecord(Map)} takes rows in the same way.
  • - *
  • The result ends when the stream ends before the first byte of a block. If the stream ends after that byte, - * reading fails.
  • - *
  • The server does not send a block with columns that are different from the first block. If the reader gets - * such a block, it is not at a block boundary: usually a column of the previous block was decoded with a wrong - * layout, or the server wrote an error message into the stream. Reading then fails with a - * {@link ClientException}, and no row of that block is returned. Rows of the block that was decoded with a wrong - * layout can have wrong values. Some wrong layouts read the correct number of bytes, and this check does not find - * them. After a read failure, {@link #hasNext()} returns {@code false}.
  • - *
- * This reader does not use the one-row read-ahead of {@link AbstractBinaryFormatReader}. - * - *

For the backward compatibility server will not send TZ id in column type. Client should send version to a server - * to get the correct column type. - * (see: https://github.com/ClickHouse/ClickHouse/issues/38209) - */ -public class NativeFormatReader extends AbstractBinaryFormatReader { - - /** Block that rows are taken from. {@code null} at the end of the result and after a read failure. */ - private Block currentBlock; - - /** Index of the next row to take from {@link #currentBlock}. */ - private int blockRowIndex; - - /** Column names of the first block. The rows of all blocks use these names. */ - private List columnNames; - - /** - * Column names and types of the first block, as the UTF-8 bytes that the server wrote: name, type, name, type, - * and so on. All later blocks must have the same bytes. - */ - private List firstBlockHeader; - - public NativeFormatReader(InputStream inputStream, QuerySettings settings, - BinaryStreamReader.ByteBufferAllocator byteBufferAllocator, - Map> typeHintMapping) { - super(inputStream, settings, null, byteBufferAllocator, typeHintMapping); - try { - readBlock(); - } catch (IOException e) { - throw new ClientException("Failed to read block", e); - } - } - - public NativeFormatReader(InputStream inputStream, QuerySettings settings, - BinaryStreamReader.ByteBufferAllocator byteBufferAllocator) { - this(inputStream, settings, byteBufferAllocator, NO_TYPE_HINT_MAPPING); - } - - @Override - public boolean readRecord(Map record) throws IOException { - if (!hasRowInBlock()) { - return false; - } - - currentBlock.fillRecord(blockRowIndex, record); - blockRowIndex++; - return true; - } - - @Override - public boolean hasNext() { - try { - return hasRowInBlock(); - } catch (IOException e) { - throw new ClientException("Failed to read block", e); - } - } - - @Override - public Map next() { - if (!hasNext()) { - return null; - } - currentBlock.fillRecord(blockRowIndex, currentRecord); - blockRowIndex++; - return wrapRecord(currentRecord); - } - - @Override - protected boolean readRecord(Object[] record) throws IOException { - if (!hasRowInBlock()) { - return false; - } - - currentBlock.fillRecord(blockRowIndex, record); - blockRowIndex++; - return true; - } - - /** - * Makes sure that {@link #currentBlock} has a row at {@link #blockRowIndex} that was not taken yet. Reads the next - * block only when all rows of the current block were taken, and skips blocks without rows. If the current block - * has a row, this method reads nothing. Thus, it gives the same result for each call until the row is taken. - * - * @return {@code true} if there is a row to take, {@code false} at the end of the result - * @throws IOException if the next block cannot be read. The reader is then at the end of the result. - * @throws ClientException if the next block has other columns than the first block, or a column that this reader - * does not decode. The reader is then at the end of the result. - */ - private boolean hasRowInBlock() throws IOException { - try { - while (currentBlock != null && blockRowIndex >= currentBlock.getnRows()) { - readBlock(); - } - } catch (IOException | RuntimeException e) { - currentBlock = null; - endReached(); - throw e; - } - return currentBlock != null; - } - - /** - * Reads the next block into {@link #currentBlock} and sets {@link #blockRowIndex} to its first row. If the stream - * ends before the block, sets {@link #currentBlock} to {@code null}. The first block sets the schema. A later block - * must have the same columns as the first block. - * - * @throws IOException if the stream cannot be read or ends inside the block - * @throws ClientException if the block has other columns than the first block (the reader is then not at a block - * boundary), or a column that this reader does not decode - */ - private void readBlock() throws IOException { - int firstByte = input.read(); - if (firstByte < 0) { - currentBlock = null; - endReached(); - return; - } - int nColumns = firstByte; - if ((firstByte & 0x80) != 0) { - // 128 or more columns: the VarUInt continues in the next bytes. - nColumns = BinaryStreamReader.readVarInt(new SequenceInputStream( - new ByteArrayInputStream(new byte[] {(byte) firstByte}), input)); - } - int nRows = BinaryStreamReader.readVarInt(input); - - boolean firstBlock = firstBlockHeader == null; - if (!firstBlock && nColumns != columnNames.size()) { - throw blockOutOfSync("it has " + nColumns + " columns, but the first block has " + columnNames.size()); - } - List columns = firstBlock ? new ArrayList<>(nColumns) : getSchema().getColumns(); - if (firstBlock) { - columnNames = new ArrayList<>(nColumns); - firstBlockHeader = new ArrayList<>(nColumns * 2); - } - Block block = new Block(columnNames, nRows); - for (int i = 0; i < nColumns; i++) { - ClickHouseColumn column; - if (firstBlock) { - byte[] name = readStringBytes(); - byte[] type = readStringBytes(); - column = ClickHouseColumn.of(new String(name, StandardCharsets.UTF_8), - new String(type, StandardCharsets.UTF_8)); - columns.add(column); - columnNames.add(column.getColumnName()); - firstBlockHeader.add(name); - firstBlockHeader.add(type); - } else if (readsString(firstBlockHeader.get(2 * i)) && readsString(firstBlockHeader.get(2 * i + 1))) { - column = columns.get(i); - } else { - // Do not put the name and the type into the message: they were read from wrong bytes. - throw blockOutOfSync("column " + (i + 1) + " has a different name or type than in the first block"); - } - - List values; - if (isNativeDecodableQBit(column)) { - // Decode the Native bit-plane layout (docs/qbit-encoding.md). - values = binaryStreamReader.readQBitNative(column, nRows); - } else if (containsQBit(column)) { - // Any other QBit shape (non-float element, strided, Nullable/LowCardinality, or nested) - // uses a Native layout this reader does not decode; fail loudly rather than misread the - // block and desynchronize the columns that follow (docs/qbit-encoding.md). - throw new ClientException("Reading column '" + column.getColumnName() + "' (" - + column.getOriginalTypeName() + ") from the Native format is not supported: " - + "this reader decodes only a plain top-level QBit column with a Float32, Float64 " - + "or BFloat16 element type. A QBit whose element type is none of those, or that is " - + "strided, wrapped in Nullable/LowCardinality, or nested inside another type " - + "(e.g. Array/Tuple/Map), is not decoded. Use a RowBinary format " - + "(e.g. RowBinaryWithNamesAndTypes) to read such QBit values"); - } else if (isGeo(column)) { - // Native writes a geo column column-major: a Point as the two Float64 sub-columns of its - // tuple, and every other geo type as cumulative offsets followed by the flattened elements - // of the level below. The per-row decoders reached through readValue() read the RowBinary - // layout instead, which scrambles a Point block and desynchronizes the columns that follow. - values = binaryStreamReader.readGeoNative(column, nRows); - } else if (column.isArray()) { - // Native encodes an Array column as nRows cumulative offsets followed by the - // flattened elements; each row's element count is the delta between consecutive - // offsets, not the first offset. - values = new ArrayList<>(nRows); - long[] offsets = new long[nRows]; - for (int j = 0; j < nRows; j++) { - offsets[j] = binaryStreamReader.readLongLE(); - } - long prevOffset = 0; - for (int j = 0; j < nRows; j++) { - int len = Math.toIntExact(offsets[j] - prevOffset); - values.add(binaryStreamReader.readArray(column, len)); - prevOffset = offsets[j]; - } - } else if (column.isNullable() && !column.isLowCardinality()) { - // Native encodes a Nullable column as a null map of nRows bytes followed by the values of - // all rows; a row marked as null still has a placeholder value in the values section. - // RowBinary, in contrast, prefixes every value with its own marker - that marker is what - // readValue() consumes, so it must not be read here. - values = new ArrayList<>(nRows); - boolean[] nulls = new boolean[nRows]; - for (int j = 0; j < nRows; j++) { - nulls[j] = binaryStreamReader.readByte() == 1; - } - // Nothing (the type of a bare NULL) has no value bytes in RowBinary, but Native still writes - // one placeholder byte per row, so it has to be consumed here. - boolean nothing = column.getDataType() == ClickHouseDataType.Nothing; - for (int j = 0; j < nRows; j++) { - Object value; - if (nothing) { - binaryStreamReader.readByte(); - value = null; - } else { - value = binaryStreamReader.readValueWithoutNullMarker(column); - } - values.add(nulls[j] ? null : value); - } - } else { - values = new ArrayList<>(nRows); - for (int j = 0; j < nRows; j++) { - Object value = binaryStreamReader.readValue(column); - values.add(value); - } - } - block.add(values); - } - if (firstBlock) { - // Later blocks have the same columns, so the schema and the row buffers that it creates stay the same. - setSchema(new TableSchema(columns)); - } - - currentBlock = block; - blockRowIndex = 0; - } - - private byte[] readStringBytes() throws IOException { - return BinaryStreamReader.readStringBytes(input, BinaryStreamReader.readVarInt(input)); - } - - /** - * Reads a String and compares it with {@code expected}. Reads the bytes of the String only if its length is the - * same. Thus, a length read from wrong bytes cannot cause a large allocation. - */ - private boolean readsString(byte[] expected) throws IOException { - int length = BinaryStreamReader.readVarInt(input); - return length == expected.length - && Arrays.equals(BinaryStreamReader.readStringBytes(input, length), expected); - } - - private static ClientException blockOutOfSync(String reason) { - return new ClientException("Failed to read block: " + reason + ". All blocks of a Native result have the " - + "same columns, so the reader is not at a block boundary. Usually a column of the previous block " - + "uses a Native layout that this reader does not decode (for example, LowCardinality or some nested " - + "Array, Map and Tuple types), or the server wrote an error message into the stream. Use a RowBinary " - + "format (e.g. RowBinaryWithNamesAndTypes) to read such columns"); - } - - /** - * Returns {@code true} for a plain top-level {@code QBit(Float32|Float64|BFloat16, dimension)} the - * reader can decode from the Native bit-plane layout — not {@code Nullable}/{@code LowCardinality}, - * not strided, not nested. Other QBit shapes are caught by {@link #containsQBit} and rejected in - * {@link #readBlock} (see {@code docs/qbit-encoding.md}). - */ - private static boolean isNativeDecodableQBit(ClickHouseColumn column) { - if (column.getDataType() != ClickHouseDataType.QBit - || column.isNullable() || column.isLowCardinality() - || column.getNestedColumns().isEmpty()) { - return false; - } - // A strided QBit has a third parameter (stride) and a plane count this decoder does not handle. - if (column.getParameters().size() > 2) { - return false; - } - switch (column.getNestedColumns().get(0).getDataType()) { - case Float32: - case Float64: - case BFloat16: - return true; - default: - return false; - } - } - - /** - * Returns {@code true} for a geo column ({@code Point}, {@code Ring}, {@code LineString}, - * {@code MultiPoint}, {@code Polygon}, {@code MultiLineString} or {@code MultiPolygon}). Geo types - * are their own data types rather than {@code Array}/{@code Tuple}, so they do not reach the - * columnar branches of {@link #readBlock} on their own and need their own Native decoder - * ({@link BinaryStreamReader#readGeoNative(ClickHouseColumn, int)}). - */ - private static boolean isGeo(ClickHouseColumn column) { - switch (column.getDataType()) { - case Point: - case Ring: - case LineString: - case MultiPoint: - case Polygon: - case MultiLineString: - case MultiPolygon: - return true; - default: - return false; - } - } - - /** - * Returns {@code true} if {@code column} is or contains a {@code QBit} anywhere in its nested type - * tree (e.g. {@code Array}/{@code Tuple}/{@code Map(String, QBit(...))}). Used by {@link #readBlock} - * to reject the QBit shapes {@link #isNativeDecodableQBit} does not decode. {@code Nullable}/ - * {@code LowCardinality} are column flags, so a wrapped {@code QBit} still reports - * {@code dataType == QBit} here. - */ - private static boolean containsQBit(ClickHouseColumn column) { - if (column.getDataType() == ClickHouseDataType.QBit) { - return true; - } - for (ClickHouseColumn nested : column.getNestedColumns()) { - if (nested != column && containsQBit(nested)) { - return true; - } - } - return false; - } - - /** Decoded values of one block: one list of {@code nRows} values for each column. */ - private static class Block { - final List names; - - final List> values = new ArrayList<>(); - final int nRows; - - Block(List names, int nRows) { - this.names = names; - this.nRows = nRows; - } - - public void add(List values) { - this.values.add(values); - } - - public int getnRows() { - return nRows; - } - - private void fillRecord(int index, Object[] record) { - for (int i = 0; i < names.size(); i++) { - record[i] = values.get(i).get(index); - } - } - - private void fillRecord(int index, Map record) { - int colIndex = 0; - for (String name : names) { - record.put(name, values.get(colIndex).get(index)); - colIndex++; - } - } - } -} +package com.clickhouse.client.api.data_formats; + +import com.clickhouse.client.api.ClientException; +import com.clickhouse.client.api.data_formats.internal.AbstractBinaryFormatReader; +import com.clickhouse.client.api.data_formats.internal.BinaryStreamReader; +import com.clickhouse.client.api.metadata.TableSchema; +import com.clickhouse.client.api.query.QuerySettings; +import com.clickhouse.data.ClickHouseColumn; +import com.clickhouse.data.ClickHouseDataType; + +import java.io.EOFException; +import java.io.IOException; +import java.io.InputStream; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +/** + * Reads a result in the {@code Native} format. + * + *

Stream layout. A Native result is a sequence of blocks. There is no header and no trailer. The server + * sends an empty result as an empty stream, but the reader also accepts blocks without rows. One block is: + *

+ * VarUInt   number of columns
+ * VarUInt   number of rows
+ * for each column:
+ *   String  column name
+ *   String  column type
+ *   bytes   values of all rows of the column, in the Native (column-oriented) layout of the type
+ * 
+ * All blocks of one result have the same columns: the same number, in the same order, with the same names and + * types. + * + *

How rows are read. + *

    + *
  • {@code readBlock()} decodes one full block into memory, column by column. The constructor reads the first + * block, so the schema is known before the first row is read. For an empty stream, {@link #getSchema()} returns + * {@code null}. The schema comes from the first block and does not change.
  • + *
  • Rows are taken from the block in memory by their index in the block. The next block is read only when all + * rows of the current block were taken. Blocks without rows are skipped.
  • + *
  • {@link #hasNext()} reads a block only when the current block has no row left. Thus, more calls before + * {@link #next()} read nothing and give the same result. Reading the next block does not change the values of + * the current row. {@link #next()} takes the row and moves to the next index. It does not read ahead. + * {@link #readRecord(Map)} takes rows in the same way.
  • + *
  • The result ends when the stream ends before or inside the column count of the next block. If the stream + * ends after the column count, reading fails.
  • + *
  • After a read failure, {@link #hasNext()} returns {@code false}.
  • + *
+ * This reader does not use the one-row read-ahead of {@link AbstractBinaryFormatReader}. + * + *

Block check: "the reader is not at a block boundary". The server does not send a block with columns + * that are different from the first block. Thus, the reader compares the column count, the names, and the types of + * each later block with the first block. If they are different, the reader did not read the previous block to its + * end, and it reads other bytes as a block header. Usual causes: + *

    + *
  • A column of the previous block uses a Native layout that this reader does not decode, and the reader read + * a wrong number of bytes for it. Examples: {@code LowCardinality}, and some nested {@code Array}, {@code Map}, + * and {@code Tuple} types.
  • + *
  • The server wrote an error message into the stream.
  • + *
+ * Reading then fails with a {@link ClientException}, and no row of that block is returned. Rows of the block that was + * decoded with a wrong layout can have wrong values. Some wrong layouts read the correct number of bytes, and this + * check does not find them. To read such columns, use a {@code RowBinary} format, for example + * {@code RowBinaryWithNamesAndTypes}. + * + *

For the backward compatibility server will not send TZ id in column type. Client should send version to a server + * to get the correct column type. + * (see: https://github.com/ClickHouse/ClickHouse/issues/38209) + */ +public class NativeFormatReader extends AbstractBinaryFormatReader { + + /** End of the message of a failed block check. It refers to the class Javadoc, which explains the check. */ + private static final String NOT_AT_BLOCK_BOUNDARY = ". The reader is not at a block boundary, see the Javadoc of " + + NativeFormatReader.class.getName(); + + /** Block that rows are taken from. {@code null} at the end of the result and after a read failure. */ + private Block currentBlock; + + /** Index of the next row to take from {@link #currentBlock}. */ + private int blockRowIndex; + + /** Column names of the first block, {@code null} before it. The rows of all blocks use these names. */ + private List columnNames; + + /** Column types of the first block, as the server wrote them. All later blocks must have the same types. */ + private List columnTypes; + + public NativeFormatReader(InputStream inputStream, QuerySettings settings, + BinaryStreamReader.ByteBufferAllocator byteBufferAllocator, + Map> typeHintMapping) { + super(inputStream, settings, null, byteBufferAllocator, typeHintMapping); + try { + readBlock(); + } catch (IOException e) { + throw new ClientException("Failed to read block", e); + } + } + + public NativeFormatReader(InputStream inputStream, QuerySettings settings, + BinaryStreamReader.ByteBufferAllocator byteBufferAllocator) { + this(inputStream, settings, byteBufferAllocator, NO_TYPE_HINT_MAPPING); + } + + @Override + public boolean readRecord(Map record) throws IOException { + if (!hasRowInBlock()) { + return false; + } + + currentBlock.fillRecord(blockRowIndex, record); + blockRowIndex++; + return true; + } + + @Override + public boolean hasNext() { + try { + return hasRowInBlock(); + } catch (IOException e) { + throw new ClientException("Failed to read block", e); + } + } + + @Override + public Map next() { + if (!hasNext()) { + return null; + } + currentBlock.fillRecord(blockRowIndex, currentRecord); + blockRowIndex++; + return wrapRecord(currentRecord); + } + + @Override + protected boolean readRecord(Object[] record) throws IOException { + if (!hasRowInBlock()) { + return false; + } + + currentBlock.fillRecord(blockRowIndex, record); + blockRowIndex++; + return true; + } + + /** + * Makes sure that {@link #currentBlock} has a row at {@link #blockRowIndex} that was not taken yet. Reads the next + * block only when all rows of the current block were taken, and skips blocks without rows. If the current block + * has a row, this method reads nothing. Thus, it gives the same result for each call until the row is taken. + * + * @return {@code true} if there is a row to take, {@code false} at the end of the result + * @throws IOException if the next block cannot be read. The reader is then at the end of the result. + * @throws ClientException if the next block has other columns than the first block, or a column that this reader + * does not decode. The reader is then at the end of the result. + */ + private boolean hasRowInBlock() throws IOException { + try { + while (currentBlock != null && blockRowIndex >= currentBlock.getnRows()) { + readBlock(); + } + } catch (IOException | RuntimeException e) { + currentBlock = null; + endReached(); + throw e; + } + return currentBlock != null; + } + + /** + * Reads the next block into {@link #currentBlock} and sets {@link #blockRowIndex} to its first row. If the stream + * ends before the block, sets {@link #currentBlock} to {@code null}. The first block sets the schema. A later block + * must have the same columns as the first block. + * + * @throws IOException if the stream cannot be read or ends after the column count of the block + * @throws ClientException if the block has other columns than the first block (the reader is then not at a block + * boundary), or a column that this reader does not decode + */ + private void readBlock() throws IOException { + int nColumns; + try { + nColumns = BinaryStreamReader.readVarInt(input); + } catch (EOFException e) { + currentBlock = null; + endReached(); + return; + } + int nRows = BinaryStreamReader.readVarInt(input); + + boolean firstBlock = columnNames == null; + if (!firstBlock && nColumns != columnNames.size()) { + throw new ClientException("Failed to read block: it has " + nColumns + " columns, the first block has " + + columnNames.size() + NOT_AT_BLOCK_BOUNDARY); + } + List columns = firstBlock ? new ArrayList<>(nColumns) : getSchema().getColumns(); + if (firstBlock) { + columnNames = new ArrayList<>(nColumns); + columnTypes = new ArrayList<>(nColumns); + } + Block block = new Block(columnNames, nRows); + for (int i = 0; i < nColumns; i++) { + String name = BinaryStreamReader.readString(input); + String type = BinaryStreamReader.readString(input); + ClickHouseColumn column; + if (firstBlock) { + column = ClickHouseColumn.of(name, type); + columns.add(column); + columnNames.add(column.getColumnName()); + columnTypes.add(type); + } else if (name.equals(columnNames.get(i)) && type.equals(columnTypes.get(i))) { + column = columns.get(i); + } else { + // Do not put the name and the type into the message: they were read from wrong bytes. + throw new ClientException("Failed to read block: column " + (i + 1) + + " has a different name or type than in the first block" + NOT_AT_BLOCK_BOUNDARY); + } + + List values; + if (isNativeDecodableQBit(column)) { + // Decode the Native bit-plane layout (docs/qbit-encoding.md). + values = binaryStreamReader.readQBitNative(column, nRows); + } else if (containsQBit(column)) { + // Any other QBit shape (non-float element, strided, Nullable/LowCardinality, or nested) + // uses a Native layout this reader does not decode; fail loudly rather than misread the + // block and desynchronize the columns that follow (docs/qbit-encoding.md). + throw new ClientException("Reading column '" + column.getColumnName() + "' (" + + column.getOriginalTypeName() + ") from the Native format is not supported: " + + "this reader decodes only a plain top-level QBit column with a Float32, Float64 " + + "or BFloat16 element type. A QBit whose element type is none of those, or that is " + + "strided, wrapped in Nullable/LowCardinality, or nested inside another type " + + "(e.g. Array/Tuple/Map), is not decoded. Use a RowBinary format " + + "(e.g. RowBinaryWithNamesAndTypes) to read such QBit values"); + } else if (isGeo(column)) { + // Native writes a geo column column-major: a Point as the two Float64 sub-columns of its + // tuple, and every other geo type as cumulative offsets followed by the flattened elements + // of the level below. The per-row decoders reached through readValue() read the RowBinary + // layout instead, which scrambles a Point block and desynchronizes the columns that follow. + values = binaryStreamReader.readGeoNative(column, nRows); + } else if (column.isArray()) { + // Native encodes an Array column as nRows cumulative offsets followed by the + // flattened elements; each row's element count is the delta between consecutive + // offsets, not the first offset. + values = new ArrayList<>(nRows); + long[] offsets = new long[nRows]; + for (int j = 0; j < nRows; j++) { + offsets[j] = binaryStreamReader.readLongLE(); + } + long prevOffset = 0; + for (int j = 0; j < nRows; j++) { + int len = Math.toIntExact(offsets[j] - prevOffset); + values.add(binaryStreamReader.readArray(column, len)); + prevOffset = offsets[j]; + } + } else if (column.isNullable() && !column.isLowCardinality()) { + // Native encodes a Nullable column as a null map of nRows bytes followed by the values of + // all rows; a row marked as null still has a placeholder value in the values section. + // RowBinary, in contrast, prefixes every value with its own marker - that marker is what + // readValue() consumes, so it must not be read here. + values = new ArrayList<>(nRows); + boolean[] nulls = new boolean[nRows]; + for (int j = 0; j < nRows; j++) { + nulls[j] = binaryStreamReader.readByte() == 1; + } + // Nothing (the type of a bare NULL) has no value bytes in RowBinary, but Native still writes + // one placeholder byte per row, so it has to be consumed here. + boolean nothing = column.getDataType() == ClickHouseDataType.Nothing; + for (int j = 0; j < nRows; j++) { + Object value; + if (nothing) { + binaryStreamReader.readByte(); + value = null; + } else { + value = binaryStreamReader.readValueWithoutNullMarker(column); + } + values.add(nulls[j] ? null : value); + } + } else { + values = new ArrayList<>(nRows); + for (int j = 0; j < nRows; j++) { + Object value = binaryStreamReader.readValue(column); + values.add(value); + } + } + block.add(values); + } + if (firstBlock) { + // Later blocks have the same columns, so the schema and the row buffers that it creates stay the same. + setSchema(new TableSchema(columns)); + } + + currentBlock = block; + blockRowIndex = 0; + } + + /** + * Returns {@code true} for a plain top-level {@code QBit(Float32|Float64|BFloat16, dimension)} the + * reader can decode from the Native bit-plane layout — not {@code Nullable}/{@code LowCardinality}, + * not strided, not nested. Other QBit shapes are caught by {@link #containsQBit} and rejected in + * {@link #readBlock} (see {@code docs/qbit-encoding.md}). + */ + private static boolean isNativeDecodableQBit(ClickHouseColumn column) { + if (column.getDataType() != ClickHouseDataType.QBit + || column.isNullable() || column.isLowCardinality() + || column.getNestedColumns().isEmpty()) { + return false; + } + // A strided QBit has a third parameter (stride) and a plane count this decoder does not handle. + if (column.getParameters().size() > 2) { + return false; + } + switch (column.getNestedColumns().get(0).getDataType()) { + case Float32: + case Float64: + case BFloat16: + return true; + default: + return false; + } + } + + /** + * Returns {@code true} for a geo column ({@code Point}, {@code Ring}, {@code LineString}, + * {@code MultiPoint}, {@code Polygon}, {@code MultiLineString} or {@code MultiPolygon}). Geo types + * are their own data types rather than {@code Array}/{@code Tuple}, so they do not reach the + * columnar branches of {@link #readBlock} on their own and need their own Native decoder + * ({@link BinaryStreamReader#readGeoNative(ClickHouseColumn, int)}). + */ + private static boolean isGeo(ClickHouseColumn column) { + switch (column.getDataType()) { + case Point: + case Ring: + case LineString: + case MultiPoint: + case Polygon: + case MultiLineString: + case MultiPolygon: + return true; + default: + return false; + } + } + + /** + * Returns {@code true} if {@code column} is or contains a {@code QBit} anywhere in its nested type + * tree (e.g. {@code Array}/{@code Tuple}/{@code Map(String, QBit(...))}). Used by {@link #readBlock} + * to reject the QBit shapes {@link #isNativeDecodableQBit} does not decode. {@code Nullable}/ + * {@code LowCardinality} are column flags, so a wrapped {@code QBit} still reports + * {@code dataType == QBit} here. + */ + private static boolean containsQBit(ClickHouseColumn column) { + if (column.getDataType() == ClickHouseDataType.QBit) { + return true; + } + for (ClickHouseColumn nested : column.getNestedColumns()) { + if (nested != column && containsQBit(nested)) { + return true; + } + } + return false; + } + + /** Decoded values of one block: one list of {@code nRows} values for each column. */ + private static class Block { + final List names; + + final List> values = new ArrayList<>(); + final int nRows; + + Block(List names, int nRows) { + this.names = names; + this.nRows = nRows; + } + + public void add(List values) { + this.values.add(values); + } + + public int getnRows() { + return nRows; + } + + private void fillRecord(int index, Object[] record) { + for (int i = 0; i < names.size(); i++) { + record[i] = values.get(i).get(index); + } + } + + private void fillRecord(int index, Map record) { + int colIndex = 0; + for (String name : names) { + record.put(name, values.get(colIndex).get(index)); + colIndex++; + } + } + } +} diff --git a/client-v2/src/test/java/com/clickhouse/client/api/data_formats/NativeFormatReaderTest.java b/client-v2/src/test/java/com/clickhouse/client/api/data_formats/NativeFormatReaderTest.java index 83d16adbb..968cfc89d 100644 --- a/client-v2/src/test/java/com/clickhouse/client/api/data_formats/NativeFormatReaderTest.java +++ b/client-v2/src/test/java/com/clickhouse/client/api/data_formats/NativeFormatReaderTest.java @@ -185,7 +185,7 @@ public static Object[][] brokenSecondBlocks() throws IOException { {"other column count", nativeBlock(Arrays.asList("n", "Int32", "m", "Int32"), 1), null}, {"other name", nativeBlock(Arrays.asList("m", "Int32"), 1), null}, {"other type", nativeBlock(Arrays.asList("n", "UInt32"), 1), null}, - {"end inside the column count", new byte[] {(byte) 0x81}, EOFException.class}, + {"end after the column count", new byte[] {1}, EOFException.class}, {"end inside the values", Arrays.copyOf(block, block.length - 1), EOFException.class}, }; } @@ -202,7 +202,8 @@ public void testFailsOnBrokenBlock(String label, byte[] secondBlock, Class ca ClientException ex = Assert.expectThrows(ClientException.class, reader::hasNext); Assert.assertEquals(ex.getCause() == null ? null : ex.getCause().getClass(), cause, label); Assert.assertTrue(ex.getMessage().startsWith("Failed to read block") - && (cause != null || ex.getMessage().contains("block boundary")), label + ": " + ex.getMessage()); + && (cause != null || ex.getMessage().endsWith("not at a block boundary, see the Javadoc of " + + NativeFormatReader.class.getName())), label + ": " + ex.getMessage()); Assert.assertFalse(reader.hasNext(), label); Assert.assertNull(reader.next(), label); } diff --git a/docs/features.md b/docs/features.md index 62fae3f82..942a3a7b1 100644 --- a/docs/features.md +++ b/docs/features.md @@ -18,7 +18,7 @@ This document lists stable, user-visible behavior in `client-v2` and `jdbc-v2` t - 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`). -- Binary format readers: Reads ClickHouse binary result formats including `Native`, `RowBinary`, `RowBinaryWithNames`, and `RowBinaryWithNamesAndTypes`. The `Native` reader decodes one full block at a time and takes the schema only from the first block. All blocks of a `Native` result have the same columns, so the reader compares the column count, names, and types of each later block with the first block. A different block means that the reader is not at a block boundary, usually because a column of the previous block uses a `Native` layout that the reader does not decode (for example `LowCardinality`, or some nested `Array`, `Map`, and `Tuple` types). The read then fails with a `ClientException` that recommends a `RowBinary` format such as `RowBinaryWithNamesAndTypes`, and no row of that block is returned. This check does not find a wrong layout that reads the correct number of bytes, and rows of a block that was decoded with a wrong layout can have wrong values. `hasNext()` is idempotent: it reads the next block only when all rows of the current block were taken, and it does not change the values of the current row. Blocks without rows are skipped. The result ends only when the stream ends before the first byte of a block; a stream that ends inside a block fails the read. +- Binary format readers: Reads ClickHouse binary result formats including `Native`, `RowBinary`, `RowBinaryWithNames`, and `RowBinaryWithNamesAndTypes`. The `Native` reader decodes one full block at a time and takes the schema only from the first block. All blocks of a `Native` result have the same columns, so the reader compares the column count, names, and types of each later block with the first block. A different block means that the reader is not at a block boundary, usually because a column of the previous block uses a `Native` layout that the reader does not decode (for example `LowCardinality`, or some nested `Array`, `Map`, and `Tuple` types). The read then fails with a `ClientException` that refers to the `NativeFormatReader` Javadoc, and no row of that block is returned. To read such columns, use a `RowBinary` format such as `RowBinaryWithNamesAndTypes`. This check does not find a wrong layout that reads the correct number of bytes, and rows of a block that was decoded with a wrong layout can have wrong values. `hasNext()` is idempotent: it reads the next block only when all rows of the current block were taken, and it does not change the values of the current row. Blocks without rows are skipped. The result ends when the stream ends before or inside the column count of the next block; a stream that ends after the column count of a block fails the read. - Binary string support: Opt-in through the `binary_string_support` property (or `Client.Builder#binaryStringSupport(boolean)`), disabled by default. The setting is resolved per operation from the merged client and query settings, so it can be overridden for a single request by setting the `binary_string_support` option on the operation's settings (e.g. `QuerySettings#setOption(ClientConfigProperties.BINARY_STRING_SUPPORT.getKey(), true)`) regardless of the client-level default. When enabled, untyped reads (e.g. `GenericRecord.getObject(...)`/`BinaryStreamReader.readValue(...)`) of top-level `String` and `FixedString` columns return a `StringValue`, which preserves the raw bytes (`toByteArray()`/`asByteBuffer()`) and lazily decodes a `String` (`asString()`), instead of eagerly decoding to a `String`. `StringValue` is a read-time holder, not a supported POJO field type: typed `queryAll(...)`/`readToPOJO` binding still maps these columns to `String` (decoded) or `byte[]` (raw bytes) according to the POJO field type. Strings nested inside containers (`Array`, `Map`, `Tuple`, `Nested`, `Variant`, `JSON`) are still read as `String`. - JSONEachRow text reader: Can stream `JSONEachRow` responses through a caller-supplied `JsonParser`, with Jackson and Gson parser factory implementations available as optional classpath dependencies, and infers a best-effort schema from the first row. - Data type conversion: Maps ClickHouse types to Java values for binary reads, POJO binding, and SQL parameter formatting, including date/time handling. diff --git a/history/latest/3365.md b/history/latest/3365.md index bbd60e6f2..6c06a14f5 100644 --- a/history/latest/3365.md +++ b/history/latest/3365.md @@ -11,6 +11,5 @@ block: the getters return the values of the row that `next()` returned. The reader now creates the schema only from the first block. - **[client-v2]** `NativeFormatReader.readRecord(Map)` no longer throws `NullPointerException` for an empty - result, or `IndexOutOfBoundsException` for a block without rows. It now skips blocks without rows. A stream that - ends inside the column count of a block now fails; before, it was the end of the result. + result, or `IndexOutOfBoundsException` for a block without rows. It now skips blocks without rows. (https://github.com/ClickHouse/clickhouse-java/issues/3365) From af36206b1ad0834b06809ab8f0ea4d7b9c31982e Mon Sep 17 00:00:00 2001 From: Polyglot AI <293096396+polyglotAI-bot@users.noreply.github.com> Date: Tue, 17 Nov 2026 22:20:59 +0000 Subject: [PATCH 4/5] [client-v2] Native reader: compare header length before reading the bytes A later block that is read from wrong bytes can have a very large name or type length. Reading the string first allocated that length, so the reader could throw OutOfMemoryError instead of ClientException. The reader now keeps the name and type bytes of the first block and compares the length of each later string before it reads the bytes. The bytes are compared as the server wrote them, so a name that is not UTF-8 still matches. The commit also restores the CRLF line endings of NativeFormatReader.java, as on main. Co-Authored-By: Claude Opus 5.5 --- .../api/data_formats/NativeFormatReader.java | 801 +++++++++--------- .../data_formats/NativeFormatReaderTest.java | 28 + 2 files changed, 435 insertions(+), 394 deletions(-) diff --git a/client-v2/src/main/java/com/clickhouse/client/api/data_formats/NativeFormatReader.java b/client-v2/src/main/java/com/clickhouse/client/api/data_formats/NativeFormatReader.java index 26f7b9665..717631ff2 100644 --- a/client-v2/src/main/java/com/clickhouse/client/api/data_formats/NativeFormatReader.java +++ b/client-v2/src/main/java/com/clickhouse/client/api/data_formats/NativeFormatReader.java @@ -1,394 +1,407 @@ -package com.clickhouse.client.api.data_formats; - -import com.clickhouse.client.api.ClientException; -import com.clickhouse.client.api.data_formats.internal.AbstractBinaryFormatReader; -import com.clickhouse.client.api.data_formats.internal.BinaryStreamReader; -import com.clickhouse.client.api.metadata.TableSchema; -import com.clickhouse.client.api.query.QuerySettings; -import com.clickhouse.data.ClickHouseColumn; -import com.clickhouse.data.ClickHouseDataType; - -import java.io.EOFException; -import java.io.IOException; -import java.io.InputStream; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; - -/** - * Reads a result in the {@code Native} format. - * - *

Stream layout. A Native result is a sequence of blocks. There is no header and no trailer. The server - * sends an empty result as an empty stream, but the reader also accepts blocks without rows. One block is: - *

- * VarUInt   number of columns
- * VarUInt   number of rows
- * for each column:
- *   String  column name
- *   String  column type
- *   bytes   values of all rows of the column, in the Native (column-oriented) layout of the type
- * 
- * All blocks of one result have the same columns: the same number, in the same order, with the same names and - * types. - * - *

How rows are read. - *

    - *
  • {@code readBlock()} decodes one full block into memory, column by column. The constructor reads the first - * block, so the schema is known before the first row is read. For an empty stream, {@link #getSchema()} returns - * {@code null}. The schema comes from the first block and does not change.
  • - *
  • Rows are taken from the block in memory by their index in the block. The next block is read only when all - * rows of the current block were taken. Blocks without rows are skipped.
  • - *
  • {@link #hasNext()} reads a block only when the current block has no row left. Thus, more calls before - * {@link #next()} read nothing and give the same result. Reading the next block does not change the values of - * the current row. {@link #next()} takes the row and moves to the next index. It does not read ahead. - * {@link #readRecord(Map)} takes rows in the same way.
  • - *
  • The result ends when the stream ends before or inside the column count of the next block. If the stream - * ends after the column count, reading fails.
  • - *
  • After a read failure, {@link #hasNext()} returns {@code false}.
  • - *
- * This reader does not use the one-row read-ahead of {@link AbstractBinaryFormatReader}. - * - *

Block check: "the reader is not at a block boundary". The server does not send a block with columns - * that are different from the first block. Thus, the reader compares the column count, the names, and the types of - * each later block with the first block. If they are different, the reader did not read the previous block to its - * end, and it reads other bytes as a block header. Usual causes: - *

    - *
  • A column of the previous block uses a Native layout that this reader does not decode, and the reader read - * a wrong number of bytes for it. Examples: {@code LowCardinality}, and some nested {@code Array}, {@code Map}, - * and {@code Tuple} types.
  • - *
  • The server wrote an error message into the stream.
  • - *
- * Reading then fails with a {@link ClientException}, and no row of that block is returned. Rows of the block that was - * decoded with a wrong layout can have wrong values. Some wrong layouts read the correct number of bytes, and this - * check does not find them. To read such columns, use a {@code RowBinary} format, for example - * {@code RowBinaryWithNamesAndTypes}. - * - *

For the backward compatibility server will not send TZ id in column type. Client should send version to a server - * to get the correct column type. - * (see: https://github.com/ClickHouse/ClickHouse/issues/38209) - */ -public class NativeFormatReader extends AbstractBinaryFormatReader { - - /** End of the message of a failed block check. It refers to the class Javadoc, which explains the check. */ - private static final String NOT_AT_BLOCK_BOUNDARY = ". The reader is not at a block boundary, see the Javadoc of " - + NativeFormatReader.class.getName(); - - /** Block that rows are taken from. {@code null} at the end of the result and after a read failure. */ - private Block currentBlock; - - /** Index of the next row to take from {@link #currentBlock}. */ - private int blockRowIndex; - - /** Column names of the first block, {@code null} before it. The rows of all blocks use these names. */ - private List columnNames; - - /** Column types of the first block, as the server wrote them. All later blocks must have the same types. */ - private List columnTypes; - - public NativeFormatReader(InputStream inputStream, QuerySettings settings, - BinaryStreamReader.ByteBufferAllocator byteBufferAllocator, - Map> typeHintMapping) { - super(inputStream, settings, null, byteBufferAllocator, typeHintMapping); - try { - readBlock(); - } catch (IOException e) { - throw new ClientException("Failed to read block", e); - } - } - - public NativeFormatReader(InputStream inputStream, QuerySettings settings, - BinaryStreamReader.ByteBufferAllocator byteBufferAllocator) { - this(inputStream, settings, byteBufferAllocator, NO_TYPE_HINT_MAPPING); - } - - @Override - public boolean readRecord(Map record) throws IOException { - if (!hasRowInBlock()) { - return false; - } - - currentBlock.fillRecord(blockRowIndex, record); - blockRowIndex++; - return true; - } - - @Override - public boolean hasNext() { - try { - return hasRowInBlock(); - } catch (IOException e) { - throw new ClientException("Failed to read block", e); - } - } - - @Override - public Map next() { - if (!hasNext()) { - return null; - } - currentBlock.fillRecord(blockRowIndex, currentRecord); - blockRowIndex++; - return wrapRecord(currentRecord); - } - - @Override - protected boolean readRecord(Object[] record) throws IOException { - if (!hasRowInBlock()) { - return false; - } - - currentBlock.fillRecord(blockRowIndex, record); - blockRowIndex++; - return true; - } - - /** - * Makes sure that {@link #currentBlock} has a row at {@link #blockRowIndex} that was not taken yet. Reads the next - * block only when all rows of the current block were taken, and skips blocks without rows. If the current block - * has a row, this method reads nothing. Thus, it gives the same result for each call until the row is taken. - * - * @return {@code true} if there is a row to take, {@code false} at the end of the result - * @throws IOException if the next block cannot be read. The reader is then at the end of the result. - * @throws ClientException if the next block has other columns than the first block, or a column that this reader - * does not decode. The reader is then at the end of the result. - */ - private boolean hasRowInBlock() throws IOException { - try { - while (currentBlock != null && blockRowIndex >= currentBlock.getnRows()) { - readBlock(); - } - } catch (IOException | RuntimeException e) { - currentBlock = null; - endReached(); - throw e; - } - return currentBlock != null; - } - - /** - * Reads the next block into {@link #currentBlock} and sets {@link #blockRowIndex} to its first row. If the stream - * ends before the block, sets {@link #currentBlock} to {@code null}. The first block sets the schema. A later block - * must have the same columns as the first block. - * - * @throws IOException if the stream cannot be read or ends after the column count of the block - * @throws ClientException if the block has other columns than the first block (the reader is then not at a block - * boundary), or a column that this reader does not decode - */ - private void readBlock() throws IOException { - int nColumns; - try { - nColumns = BinaryStreamReader.readVarInt(input); - } catch (EOFException e) { - currentBlock = null; - endReached(); - return; - } - int nRows = BinaryStreamReader.readVarInt(input); - - boolean firstBlock = columnNames == null; - if (!firstBlock && nColumns != columnNames.size()) { - throw new ClientException("Failed to read block: it has " + nColumns + " columns, the first block has " - + columnNames.size() + NOT_AT_BLOCK_BOUNDARY); - } - List columns = firstBlock ? new ArrayList<>(nColumns) : getSchema().getColumns(); - if (firstBlock) { - columnNames = new ArrayList<>(nColumns); - columnTypes = new ArrayList<>(nColumns); - } - Block block = new Block(columnNames, nRows); - for (int i = 0; i < nColumns; i++) { - String name = BinaryStreamReader.readString(input); - String type = BinaryStreamReader.readString(input); - ClickHouseColumn column; - if (firstBlock) { - column = ClickHouseColumn.of(name, type); - columns.add(column); - columnNames.add(column.getColumnName()); - columnTypes.add(type); - } else if (name.equals(columnNames.get(i)) && type.equals(columnTypes.get(i))) { - column = columns.get(i); - } else { - // Do not put the name and the type into the message: they were read from wrong bytes. - throw new ClientException("Failed to read block: column " + (i + 1) - + " has a different name or type than in the first block" + NOT_AT_BLOCK_BOUNDARY); - } - - List values; - if (isNativeDecodableQBit(column)) { - // Decode the Native bit-plane layout (docs/qbit-encoding.md). - values = binaryStreamReader.readQBitNative(column, nRows); - } else if (containsQBit(column)) { - // Any other QBit shape (non-float element, strided, Nullable/LowCardinality, or nested) - // uses a Native layout this reader does not decode; fail loudly rather than misread the - // block and desynchronize the columns that follow (docs/qbit-encoding.md). - throw new ClientException("Reading column '" + column.getColumnName() + "' (" - + column.getOriginalTypeName() + ") from the Native format is not supported: " - + "this reader decodes only a plain top-level QBit column with a Float32, Float64 " - + "or BFloat16 element type. A QBit whose element type is none of those, or that is " - + "strided, wrapped in Nullable/LowCardinality, or nested inside another type " - + "(e.g. Array/Tuple/Map), is not decoded. Use a RowBinary format " - + "(e.g. RowBinaryWithNamesAndTypes) to read such QBit values"); - } else if (isGeo(column)) { - // Native writes a geo column column-major: a Point as the two Float64 sub-columns of its - // tuple, and every other geo type as cumulative offsets followed by the flattened elements - // of the level below. The per-row decoders reached through readValue() read the RowBinary - // layout instead, which scrambles a Point block and desynchronizes the columns that follow. - values = binaryStreamReader.readGeoNative(column, nRows); - } else if (column.isArray()) { - // Native encodes an Array column as nRows cumulative offsets followed by the - // flattened elements; each row's element count is the delta between consecutive - // offsets, not the first offset. - values = new ArrayList<>(nRows); - long[] offsets = new long[nRows]; - for (int j = 0; j < nRows; j++) { - offsets[j] = binaryStreamReader.readLongLE(); - } - long prevOffset = 0; - for (int j = 0; j < nRows; j++) { - int len = Math.toIntExact(offsets[j] - prevOffset); - values.add(binaryStreamReader.readArray(column, len)); - prevOffset = offsets[j]; - } - } else if (column.isNullable() && !column.isLowCardinality()) { - // Native encodes a Nullable column as a null map of nRows bytes followed by the values of - // all rows; a row marked as null still has a placeholder value in the values section. - // RowBinary, in contrast, prefixes every value with its own marker - that marker is what - // readValue() consumes, so it must not be read here. - values = new ArrayList<>(nRows); - boolean[] nulls = new boolean[nRows]; - for (int j = 0; j < nRows; j++) { - nulls[j] = binaryStreamReader.readByte() == 1; - } - // Nothing (the type of a bare NULL) has no value bytes in RowBinary, but Native still writes - // one placeholder byte per row, so it has to be consumed here. - boolean nothing = column.getDataType() == ClickHouseDataType.Nothing; - for (int j = 0; j < nRows; j++) { - Object value; - if (nothing) { - binaryStreamReader.readByte(); - value = null; - } else { - value = binaryStreamReader.readValueWithoutNullMarker(column); - } - values.add(nulls[j] ? null : value); - } - } else { - values = new ArrayList<>(nRows); - for (int j = 0; j < nRows; j++) { - Object value = binaryStreamReader.readValue(column); - values.add(value); - } - } - block.add(values); - } - if (firstBlock) { - // Later blocks have the same columns, so the schema and the row buffers that it creates stay the same. - setSchema(new TableSchema(columns)); - } - - currentBlock = block; - blockRowIndex = 0; - } - - /** - * Returns {@code true} for a plain top-level {@code QBit(Float32|Float64|BFloat16, dimension)} the - * reader can decode from the Native bit-plane layout — not {@code Nullable}/{@code LowCardinality}, - * not strided, not nested. Other QBit shapes are caught by {@link #containsQBit} and rejected in - * {@link #readBlock} (see {@code docs/qbit-encoding.md}). - */ - private static boolean isNativeDecodableQBit(ClickHouseColumn column) { - if (column.getDataType() != ClickHouseDataType.QBit - || column.isNullable() || column.isLowCardinality() - || column.getNestedColumns().isEmpty()) { - return false; - } - // A strided QBit has a third parameter (stride) and a plane count this decoder does not handle. - if (column.getParameters().size() > 2) { - return false; - } - switch (column.getNestedColumns().get(0).getDataType()) { - case Float32: - case Float64: - case BFloat16: - return true; - default: - return false; - } - } - - /** - * Returns {@code true} for a geo column ({@code Point}, {@code Ring}, {@code LineString}, - * {@code MultiPoint}, {@code Polygon}, {@code MultiLineString} or {@code MultiPolygon}). Geo types - * are their own data types rather than {@code Array}/{@code Tuple}, so they do not reach the - * columnar branches of {@link #readBlock} on their own and need their own Native decoder - * ({@link BinaryStreamReader#readGeoNative(ClickHouseColumn, int)}). - */ - private static boolean isGeo(ClickHouseColumn column) { - switch (column.getDataType()) { - case Point: - case Ring: - case LineString: - case MultiPoint: - case Polygon: - case MultiLineString: - case MultiPolygon: - return true; - default: - return false; - } - } - - /** - * Returns {@code true} if {@code column} is or contains a {@code QBit} anywhere in its nested type - * tree (e.g. {@code Array}/{@code Tuple}/{@code Map(String, QBit(...))}). Used by {@link #readBlock} - * to reject the QBit shapes {@link #isNativeDecodableQBit} does not decode. {@code Nullable}/ - * {@code LowCardinality} are column flags, so a wrapped {@code QBit} still reports - * {@code dataType == QBit} here. - */ - private static boolean containsQBit(ClickHouseColumn column) { - if (column.getDataType() == ClickHouseDataType.QBit) { - return true; - } - for (ClickHouseColumn nested : column.getNestedColumns()) { - if (nested != column && containsQBit(nested)) { - return true; - } - } - return false; - } - - /** Decoded values of one block: one list of {@code nRows} values for each column. */ - private static class Block { - final List names; - - final List> values = new ArrayList<>(); - final int nRows; - - Block(List names, int nRows) { - this.names = names; - this.nRows = nRows; - } - - public void add(List values) { - this.values.add(values); - } - - public int getnRows() { - return nRows; - } - - private void fillRecord(int index, Object[] record) { - for (int i = 0; i < names.size(); i++) { - record[i] = values.get(i).get(index); - } - } - - private void fillRecord(int index, Map record) { - int colIndex = 0; - for (String name : names) { - record.put(name, values.get(colIndex).get(index)); - colIndex++; - } - } - } -} +package com.clickhouse.client.api.data_formats; + +import com.clickhouse.client.api.ClientException; +import com.clickhouse.client.api.data_formats.internal.AbstractBinaryFormatReader; +import com.clickhouse.client.api.data_formats.internal.BinaryStreamReader; +import com.clickhouse.client.api.metadata.TableSchema; +import com.clickhouse.client.api.query.QuerySettings; +import com.clickhouse.data.ClickHouseColumn; +import com.clickhouse.data.ClickHouseDataType; + +import java.io.EOFException; +import java.io.IOException; +import java.io.InputStream; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Map; + +/** + * Reads a result in the {@code Native} format. + * + *

Stream layout. A Native result is a sequence of blocks. There is no header and no trailer. The server + * sends an empty result as an empty stream, but the reader also accepts blocks without rows. One block is: + *

+ * VarUInt   number of columns
+ * VarUInt   number of rows
+ * for each column:
+ *   String  column name
+ *   String  column type
+ *   bytes   values of all rows of the column, in the Native (column-oriented) layout of the type
+ * 
+ * All blocks of one result have the same columns: the same number, in the same order, with the same names and + * types. + * + *

How rows are read. + *

    + *
  • {@code readBlock()} decodes one full block into memory, column by column. The constructor reads the first + * block, so the schema is known before the first row is read. For an empty stream, {@link #getSchema()} returns + * {@code null}. The schema comes from the first block and does not change.
  • + *
  • Rows are taken from the block in memory by their index in the block. The next block is read only when all + * rows of the current block were taken. Blocks without rows are skipped.
  • + *
  • {@link #hasNext()} reads a block only when the current block has no row left. Thus, more calls before + * {@link #next()} read nothing and give the same result. Reading the next block does not change the values of + * the current row. {@link #next()} takes the row and moves to the next index. It does not read ahead. + * {@link #readRecord(Map)} takes rows in the same way.
  • + *
  • The result ends when the stream ends before or inside the column count of the next block. If the stream + * ends after the column count, reading fails.
  • + *
  • After a read failure, {@link #hasNext()} returns {@code false}.
  • + *
+ * This reader does not use the one-row read-ahead of {@link AbstractBinaryFormatReader}. + * + *

Block check: "the reader is not at a block boundary". The server does not send a block with columns + * that are different from the first block. Thus, the reader compares the column count, the names, and the types of + * each later block with the first block. If they are different, the reader did not read the previous block to its + * end, and it reads other bytes as a block header. Usual causes: + *

    + *
  • A column of the previous block uses a Native layout that this reader does not decode, and the reader read + * a wrong number of bytes for it. Examples: {@code LowCardinality}, and some nested {@code Array}, {@code Map}, + * and {@code Tuple} types.
  • + *
  • The server wrote an error message into the stream.
  • + *
+ * Reading then fails with a {@link ClientException}, and no row of that block is returned. Rows of the block that was + * decoded with a wrong layout can have wrong values. Some wrong layouts read the correct number of bytes, and this + * check does not find them. To read such columns, use a {@code RowBinary} format, for example + * {@code RowBinaryWithNamesAndTypes}. + * + *

For the backward compatibility server will not send TZ id in column type. Client should send version to a server + * to get the correct column type. + * (see: https://github.com/ClickHouse/ClickHouse/issues/38209) + */ +public class NativeFormatReader extends AbstractBinaryFormatReader { + + /** End of the message of a failed block check. It refers to the class Javadoc, which explains the check. */ + private static final String NOT_AT_BLOCK_BOUNDARY = ". The reader is not at a block boundary, see the Javadoc of " + + NativeFormatReader.class.getName(); + + /** Block that rows are taken from. {@code null} at the end of the result and after a read failure. */ + private Block currentBlock; + + /** Index of the next row to take from {@link #currentBlock}. */ + private int blockRowIndex; + + /** Column names of the first block, {@code null} before it. The rows of all blocks use these names. */ + private List columnNames; + + /** + * Column names and types of the first block, as the bytes that the server wrote: name, type, name, type, and so + * on. All later blocks must have the same bytes. + */ + private List firstBlockHeader; + + public NativeFormatReader(InputStream inputStream, QuerySettings settings, + BinaryStreamReader.ByteBufferAllocator byteBufferAllocator, + Map> typeHintMapping) { + super(inputStream, settings, null, byteBufferAllocator, typeHintMapping); + try { + readBlock(); + } catch (IOException e) { + throw new ClientException("Failed to read block", e); + } + } + + public NativeFormatReader(InputStream inputStream, QuerySettings settings, + BinaryStreamReader.ByteBufferAllocator byteBufferAllocator) { + this(inputStream, settings, byteBufferAllocator, NO_TYPE_HINT_MAPPING); + } + + @Override + public boolean readRecord(Map record) throws IOException { + if (!hasRowInBlock()) { + return false; + } + + currentBlock.fillRecord(blockRowIndex, record); + blockRowIndex++; + return true; + } + + @Override + public boolean hasNext() { + try { + return hasRowInBlock(); + } catch (IOException e) { + throw new ClientException("Failed to read block", e); + } + } + + @Override + public Map next() { + if (!hasNext()) { + return null; + } + currentBlock.fillRecord(blockRowIndex, currentRecord); + blockRowIndex++; + return wrapRecord(currentRecord); + } + + @Override + protected boolean readRecord(Object[] record) throws IOException { + if (!hasRowInBlock()) { + return false; + } + + currentBlock.fillRecord(blockRowIndex, record); + blockRowIndex++; + return true; + } + + /** + * Makes sure that {@link #currentBlock} has a row at {@link #blockRowIndex} that was not taken yet. Reads the next + * block only when all rows of the current block were taken, and skips blocks without rows. If the current block + * has a row, this method reads nothing. Thus, it gives the same result for each call until the row is taken. + * + * @return {@code true} if there is a row to take, {@code false} at the end of the result + * @throws IOException if the next block cannot be read. The reader is then at the end of the result. + * @throws ClientException if the next block has other columns than the first block, or a column that this reader + * does not decode. The reader is then at the end of the result. + */ + private boolean hasRowInBlock() throws IOException { + try { + while (currentBlock != null && blockRowIndex >= currentBlock.getnRows()) { + readBlock(); + } + } catch (IOException | RuntimeException e) { + currentBlock = null; + endReached(); + throw e; + } + return currentBlock != null; + } + + /** + * Reads the next block into {@link #currentBlock} and sets {@link #blockRowIndex} to its first row. If the stream + * ends before the block, sets {@link #currentBlock} to {@code null}. The first block sets the schema. A later block + * must have the same columns as the first block. + * + * @throws IOException if the stream cannot be read or ends after the column count of the block + * @throws ClientException if the block has other columns than the first block (the reader is then not at a block + * boundary), or a column that this reader does not decode + */ + private void readBlock() throws IOException { + int nColumns; + try { + nColumns = BinaryStreamReader.readVarInt(input); + } catch (EOFException e) { + currentBlock = null; + endReached(); + return; + } + int nRows = BinaryStreamReader.readVarInt(input); + + boolean firstBlock = columnNames == null; + if (!firstBlock && nColumns != columnNames.size()) { + throw new ClientException("Failed to read block: it has " + nColumns + " columns, the first block has " + + columnNames.size() + NOT_AT_BLOCK_BOUNDARY); + } + List columns = firstBlock ? new ArrayList<>(nColumns) : getSchema().getColumns(); + if (firstBlock) { + columnNames = new ArrayList<>(nColumns); + firstBlockHeader = new ArrayList<>(nColumns * 2); + } + Block block = new Block(columnNames, nRows); + for (int i = 0; i < nColumns; i++) { + ClickHouseColumn column; + if (firstBlock) { + byte[] name = BinaryStreamReader.readStringBytes(input, BinaryStreamReader.readVarInt(input)); + byte[] type = BinaryStreamReader.readStringBytes(input, BinaryStreamReader.readVarInt(input)); + column = ClickHouseColumn.of(new String(name, StandardCharsets.UTF_8), + new String(type, StandardCharsets.UTF_8)); + columns.add(column); + columnNames.add(column.getColumnName()); + firstBlockHeader.add(name); + firstBlockHeader.add(type); + } else { + column = columns.get(i); + for (byte[] expected : firstBlockHeader.subList(2 * i, 2 * i + 2)) { + // Compare the length first: a length read from wrong bytes can be too large to allocate. + int length = BinaryStreamReader.readVarInt(input); + if (length != expected.length + || !Arrays.equals(BinaryStreamReader.readStringBytes(input, length), expected)) { + // Do not put the name and the type into the message: they were read from wrong bytes. + throw new ClientException("Failed to read block: column " + (i + 1) + + " has a different name or type than in the first block" + NOT_AT_BLOCK_BOUNDARY); + } + } + } + + List values; + if (isNativeDecodableQBit(column)) { + // Decode the Native bit-plane layout (docs/qbit-encoding.md). + values = binaryStreamReader.readQBitNative(column, nRows); + } else if (containsQBit(column)) { + // Any other QBit shape (non-float element, strided, Nullable/LowCardinality, or nested) + // uses a Native layout this reader does not decode; fail loudly rather than misread the + // block and desynchronize the columns that follow (docs/qbit-encoding.md). + throw new ClientException("Reading column '" + column.getColumnName() + "' (" + + column.getOriginalTypeName() + ") from the Native format is not supported: " + + "this reader decodes only a plain top-level QBit column with a Float32, Float64 " + + "or BFloat16 element type. A QBit whose element type is none of those, or that is " + + "strided, wrapped in Nullable/LowCardinality, or nested inside another type " + + "(e.g. Array/Tuple/Map), is not decoded. Use a RowBinary format " + + "(e.g. RowBinaryWithNamesAndTypes) to read such QBit values"); + } else if (isGeo(column)) { + // Native writes a geo column column-major: a Point as the two Float64 sub-columns of its + // tuple, and every other geo type as cumulative offsets followed by the flattened elements + // of the level below. The per-row decoders reached through readValue() read the RowBinary + // layout instead, which scrambles a Point block and desynchronizes the columns that follow. + values = binaryStreamReader.readGeoNative(column, nRows); + } else if (column.isArray()) { + // Native encodes an Array column as nRows cumulative offsets followed by the + // flattened elements; each row's element count is the delta between consecutive + // offsets, not the first offset. + values = new ArrayList<>(nRows); + long[] offsets = new long[nRows]; + for (int j = 0; j < nRows; j++) { + offsets[j] = binaryStreamReader.readLongLE(); + } + long prevOffset = 0; + for (int j = 0; j < nRows; j++) { + int len = Math.toIntExact(offsets[j] - prevOffset); + values.add(binaryStreamReader.readArray(column, len)); + prevOffset = offsets[j]; + } + } else if (column.isNullable() && !column.isLowCardinality()) { + // Native encodes a Nullable column as a null map of nRows bytes followed by the values of + // all rows; a row marked as null still has a placeholder value in the values section. + // RowBinary, in contrast, prefixes every value with its own marker - that marker is what + // readValue() consumes, so it must not be read here. + values = new ArrayList<>(nRows); + boolean[] nulls = new boolean[nRows]; + for (int j = 0; j < nRows; j++) { + nulls[j] = binaryStreamReader.readByte() == 1; + } + // Nothing (the type of a bare NULL) has no value bytes in RowBinary, but Native still writes + // one placeholder byte per row, so it has to be consumed here. + boolean nothing = column.getDataType() == ClickHouseDataType.Nothing; + for (int j = 0; j < nRows; j++) { + Object value; + if (nothing) { + binaryStreamReader.readByte(); + value = null; + } else { + value = binaryStreamReader.readValueWithoutNullMarker(column); + } + values.add(nulls[j] ? null : value); + } + } else { + values = new ArrayList<>(nRows); + for (int j = 0; j < nRows; j++) { + Object value = binaryStreamReader.readValue(column); + values.add(value); + } + } + block.add(values); + } + if (firstBlock) { + // Later blocks have the same columns, so the schema and the row buffers that it creates stay the same. + setSchema(new TableSchema(columns)); + } + + currentBlock = block; + blockRowIndex = 0; + } + + /** + * Returns {@code true} for a plain top-level {@code QBit(Float32|Float64|BFloat16, dimension)} the + * reader can decode from the Native bit-plane layout — not {@code Nullable}/{@code LowCardinality}, + * not strided, not nested. Other QBit shapes are caught by {@link #containsQBit} and rejected in + * {@link #readBlock} (see {@code docs/qbit-encoding.md}). + */ + private static boolean isNativeDecodableQBit(ClickHouseColumn column) { + if (column.getDataType() != ClickHouseDataType.QBit + || column.isNullable() || column.isLowCardinality() + || column.getNestedColumns().isEmpty()) { + return false; + } + // A strided QBit has a third parameter (stride) and a plane count this decoder does not handle. + if (column.getParameters().size() > 2) { + return false; + } + switch (column.getNestedColumns().get(0).getDataType()) { + case Float32: + case Float64: + case BFloat16: + return true; + default: + return false; + } + } + + /** + * Returns {@code true} for a geo column ({@code Point}, {@code Ring}, {@code LineString}, + * {@code MultiPoint}, {@code Polygon}, {@code MultiLineString} or {@code MultiPolygon}). Geo types + * are their own data types rather than {@code Array}/{@code Tuple}, so they do not reach the + * columnar branches of {@link #readBlock} on their own and need their own Native decoder + * ({@link BinaryStreamReader#readGeoNative(ClickHouseColumn, int)}). + */ + private static boolean isGeo(ClickHouseColumn column) { + switch (column.getDataType()) { + case Point: + case Ring: + case LineString: + case MultiPoint: + case Polygon: + case MultiLineString: + case MultiPolygon: + return true; + default: + return false; + } + } + + /** + * Returns {@code true} if {@code column} is or contains a {@code QBit} anywhere in its nested type + * tree (e.g. {@code Array}/{@code Tuple}/{@code Map(String, QBit(...))}). Used by {@link #readBlock} + * to reject the QBit shapes {@link #isNativeDecodableQBit} does not decode. {@code Nullable}/ + * {@code LowCardinality} are column flags, so a wrapped {@code QBit} still reports + * {@code dataType == QBit} here. + */ + private static boolean containsQBit(ClickHouseColumn column) { + if (column.getDataType() == ClickHouseDataType.QBit) { + return true; + } + for (ClickHouseColumn nested : column.getNestedColumns()) { + if (nested != column && containsQBit(nested)) { + return true; + } + } + return false; + } + + /** Decoded values of one block: one list of {@code nRows} values for each column. */ + private static class Block { + final List names; + + final List> values = new ArrayList<>(); + final int nRows; + + Block(List names, int nRows) { + this.names = names; + this.nRows = nRows; + } + + public void add(List values) { + this.values.add(values); + } + + public int getnRows() { + return nRows; + } + + private void fillRecord(int index, Object[] record) { + for (int i = 0; i < names.size(); i++) { + record[i] = values.get(i).get(index); + } + } + + private void fillRecord(int index, Map record) { + int colIndex = 0; + for (String name : names) { + record.put(name, values.get(colIndex).get(index)); + colIndex++; + } + } + } +} diff --git a/client-v2/src/test/java/com/clickhouse/client/api/data_formats/NativeFormatReaderTest.java b/client-v2/src/test/java/com/clickhouse/client/api/data_formats/NativeFormatReaderTest.java index 968cfc89d..97f8226df 100644 --- a/client-v2/src/test/java/com/clickhouse/client/api/data_formats/NativeFormatReaderTest.java +++ b/client-v2/src/test/java/com/clickhouse/client/api/data_formats/NativeFormatReaderTest.java @@ -175,16 +175,44 @@ public void testReadsBlocksWithManyColumns() throws IOException { Assert.assertEquals(values, Arrays.asList(0, 0, 1)); } + @Test(groups = {"integration"}) + public void testReadsBlocksWithNameThatIsNotUtf8() throws Exception { + // The server writes the name as the bytes 61 FF 62, which are not UTF-8, in each of the two blocks. The block + // check must compare these bytes, not the bytes of the decoded name. + try (Client client = newClient().build(); + QueryResponse response = client.query("SELECT toInt32(number) AS `a\\xFFb` FROM numbers(2)" + + " SETTINGS max_block_size = 1", new QuerySettings().setFormat(ClickHouseFormat.Native)) + .get(30, TimeUnit.SECONDS)) { + ClickHouseBinaryFormatReader reader = client.newBinaryFormatReader(response); + String name = reader.getSchema().getColumns().get(0).getColumnName(); + List values = new ArrayList<>(); + while (reader.hasNext()) { + values.add(reader.next().get(name)); + } + Assert.assertEquals(values, sequence(2)); + } + } + // A later block with other columns than the first block cannot come from the server: the reader is not at a // block boundary. A null cause marks these cases. @DataProvider(name = "brokenSecondBlocks") public static Object[][] brokenSecondBlocks() throws IOException { byte[] block = nativeBlock(Arrays.asList("n", "Int32"), 1); + // VarUInt of Integer.MAX_VALUE: a length that cannot be allocated. + byte[] maxLength = {(byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, 0x07}; + ByteArrayOutputStream nameTooLong = new ByteArrayOutputStream(); + nameTooLong.write(new byte[] {1, 1}); + nameTooLong.write(maxLength); + ByteArrayOutputStream typeTooLong = new ByteArrayOutputStream(); + typeTooLong.write(new byte[] {1, 1, 1, 'n'}); + typeTooLong.write(maxLength); return new Object[][] { {"no columns", nativeBlock(Collections.emptyList(), 3), null}, {"other column count", nativeBlock(Arrays.asList("n", "Int32", "m", "Int32"), 1), null}, {"other name", nativeBlock(Arrays.asList("m", "Int32"), 1), null}, {"other type", nativeBlock(Arrays.asList("n", "UInt32"), 1), null}, + {"name length too large", nameTooLong.toByteArray(), null}, + {"type length too large", typeTooLong.toByteArray(), null}, {"end after the column count", new byte[] {1}, EOFException.class}, {"end inside the values", Arrays.copyOf(block, block.length - 1), EOFException.class}, }; From f2b8fba7b8d88a63427e8e69381af2f81f9fc31f Mon Sep 17 00:00:00 2001 From: Polyglot AI <293096396+polyglotAI-bot@users.noreply.github.com> Date: Tue, 17 Nov 2026 22:22:06 +0000 Subject: [PATCH 5/5] [client-v2] Native reader: revert the header length check, keep CRLF The maintainer decided that the column count check is enough and that the header strings are read with BinaryStreamReader.readString. This reverts the code and the tests of the previous commit. NativeFormatReader.java keeps the CRLF line endings of main. Co-Authored-By: Claude Opus 5.5 --- .../api/data_formats/NativeFormatReader.java | 37 ++++++------------- .../data_formats/NativeFormatReaderTest.java | 28 -------------- 2 files changed, 12 insertions(+), 53 deletions(-) diff --git a/client-v2/src/main/java/com/clickhouse/client/api/data_formats/NativeFormatReader.java b/client-v2/src/main/java/com/clickhouse/client/api/data_formats/NativeFormatReader.java index 717631ff2..06b4170e6 100644 --- a/client-v2/src/main/java/com/clickhouse/client/api/data_formats/NativeFormatReader.java +++ b/client-v2/src/main/java/com/clickhouse/client/api/data_formats/NativeFormatReader.java @@ -11,9 +11,7 @@ import java.io.EOFException; import java.io.IOException; import java.io.InputStream; -import java.nio.charset.StandardCharsets; import java.util.ArrayList; -import java.util.Arrays; import java.util.List; import java.util.Map; @@ -84,11 +82,8 @@ public class NativeFormatReader extends AbstractBinaryFormatReader { /** Column names of the first block, {@code null} before it. The rows of all blocks use these names. */ private List columnNames; - /** - * Column names and types of the first block, as the bytes that the server wrote: name, type, name, type, and so - * on. All later blocks must have the same bytes. - */ - private List firstBlockHeader; + /** Column types of the first block, as the server wrote them. All later blocks must have the same types. */ + private List columnTypes; public NativeFormatReader(InputStream inputStream, QuerySettings settings, BinaryStreamReader.ByteBufferAllocator byteBufferAllocator, @@ -198,32 +193,24 @@ private void readBlock() throws IOException { List columns = firstBlock ? new ArrayList<>(nColumns) : getSchema().getColumns(); if (firstBlock) { columnNames = new ArrayList<>(nColumns); - firstBlockHeader = new ArrayList<>(nColumns * 2); + columnTypes = new ArrayList<>(nColumns); } Block block = new Block(columnNames, nRows); for (int i = 0; i < nColumns; i++) { + String name = BinaryStreamReader.readString(input); + String type = BinaryStreamReader.readString(input); ClickHouseColumn column; if (firstBlock) { - byte[] name = BinaryStreamReader.readStringBytes(input, BinaryStreamReader.readVarInt(input)); - byte[] type = BinaryStreamReader.readStringBytes(input, BinaryStreamReader.readVarInt(input)); - column = ClickHouseColumn.of(new String(name, StandardCharsets.UTF_8), - new String(type, StandardCharsets.UTF_8)); + column = ClickHouseColumn.of(name, type); columns.add(column); columnNames.add(column.getColumnName()); - firstBlockHeader.add(name); - firstBlockHeader.add(type); - } else { + columnTypes.add(type); + } else if (name.equals(columnNames.get(i)) && type.equals(columnTypes.get(i))) { column = columns.get(i); - for (byte[] expected : firstBlockHeader.subList(2 * i, 2 * i + 2)) { - // Compare the length first: a length read from wrong bytes can be too large to allocate. - int length = BinaryStreamReader.readVarInt(input); - if (length != expected.length - || !Arrays.equals(BinaryStreamReader.readStringBytes(input, length), expected)) { - // Do not put the name and the type into the message: they were read from wrong bytes. - throw new ClientException("Failed to read block: column " + (i + 1) - + " has a different name or type than in the first block" + NOT_AT_BLOCK_BOUNDARY); - } - } + } else { + // Do not put the name and the type into the message: they were read from wrong bytes. + throw new ClientException("Failed to read block: column " + (i + 1) + + " has a different name or type than in the first block" + NOT_AT_BLOCK_BOUNDARY); } List values; diff --git a/client-v2/src/test/java/com/clickhouse/client/api/data_formats/NativeFormatReaderTest.java b/client-v2/src/test/java/com/clickhouse/client/api/data_formats/NativeFormatReaderTest.java index 97f8226df..968cfc89d 100644 --- a/client-v2/src/test/java/com/clickhouse/client/api/data_formats/NativeFormatReaderTest.java +++ b/client-v2/src/test/java/com/clickhouse/client/api/data_formats/NativeFormatReaderTest.java @@ -175,44 +175,16 @@ public void testReadsBlocksWithManyColumns() throws IOException { Assert.assertEquals(values, Arrays.asList(0, 0, 1)); } - @Test(groups = {"integration"}) - public void testReadsBlocksWithNameThatIsNotUtf8() throws Exception { - // The server writes the name as the bytes 61 FF 62, which are not UTF-8, in each of the two blocks. The block - // check must compare these bytes, not the bytes of the decoded name. - try (Client client = newClient().build(); - QueryResponse response = client.query("SELECT toInt32(number) AS `a\\xFFb` FROM numbers(2)" - + " SETTINGS max_block_size = 1", new QuerySettings().setFormat(ClickHouseFormat.Native)) - .get(30, TimeUnit.SECONDS)) { - ClickHouseBinaryFormatReader reader = client.newBinaryFormatReader(response); - String name = reader.getSchema().getColumns().get(0).getColumnName(); - List values = new ArrayList<>(); - while (reader.hasNext()) { - values.add(reader.next().get(name)); - } - Assert.assertEquals(values, sequence(2)); - } - } - // A later block with other columns than the first block cannot come from the server: the reader is not at a // block boundary. A null cause marks these cases. @DataProvider(name = "brokenSecondBlocks") public static Object[][] brokenSecondBlocks() throws IOException { byte[] block = nativeBlock(Arrays.asList("n", "Int32"), 1); - // VarUInt of Integer.MAX_VALUE: a length that cannot be allocated. - byte[] maxLength = {(byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, 0x07}; - ByteArrayOutputStream nameTooLong = new ByteArrayOutputStream(); - nameTooLong.write(new byte[] {1, 1}); - nameTooLong.write(maxLength); - ByteArrayOutputStream typeTooLong = new ByteArrayOutputStream(); - typeTooLong.write(new byte[] {1, 1, 1, 'n'}); - typeTooLong.write(maxLength); return new Object[][] { {"no columns", nativeBlock(Collections.emptyList(), 3), null}, {"other column count", nativeBlock(Arrays.asList("n", "Int32", "m", "Int32"), 1), null}, {"other name", nativeBlock(Arrays.asList("m", "Int32"), 1), null}, {"other type", nativeBlock(Arrays.asList("n", "UInt32"), 1), null}, - {"name length too large", nameTooLong.toByteArray(), null}, - {"type length too large", typeTooLong.toByteArray(), null}, {"end after the column count", new byte[] {1}, EOFException.class}, {"end inside the values", Arrays.copyOf(block, block.length - 1), EOFException.class}, };