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..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 @@ -16,16 +16,75 @@ 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}. + * + *

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: + *

+ * 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) { @@ -44,10 +103,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 +112,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 +133,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 +142,76 @@ protected boolean readRecord(Object[] record) throws IOException { return true; } - private boolean readBlock() throws IOException { + /** + * 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 false; + return; } 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 = 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++) { - - ClickHouseColumn column = ClickHouseColumn.of(BinaryStreamReader.readString(input), - BinaryStreamReader.readString(input)); - columns.add(column); - - names.add(column.getColumnName()); - types.add(column.getDataType().name()); + 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)) { @@ -190,14 +279,15 @@ 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; } /** @@ -267,16 +357,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..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 @@ -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,149 @@ 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 after the column count", new byte[] {1}, 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().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); + } + private Client.Builder newClient() { ClickHouseNode node = getServer(ClickHouseProtocol.HTTP); return new Client.Builder() @@ -138,6 +285,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/docs/features.md b/docs/features.md index fc23cc010..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`. +- 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 new file mode 100644 index 000000000..6c06a14f5 --- /dev/null +++ b/history/latest/3365.md @@ -0,0 +1,15 @@ +## 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. + (https://github.com/ClickHouse/clickhouse-java/issues/3365)