From 0158c034907eb37b7f16e365ce848f52ff4afc42 Mon Sep 17 00:00:00 2001 From: Sunyi Xu <94rbmyftn9@privaterelay.appleid.com> Date: Tue, 24 Nov 2026 02:38:54 +0800 Subject: [PATCH] fix(client-v2): write RowBinary Variant NULLs Write the Variant NULL discriminator in plain and defaults-aware RowBinary values, including nested variants. Preserve explicit column defaults and non-null alternative encoding. Refs #3400 --- .../RowBinaryFormatSerializer.java | 12 ++-- .../internal/SerializerUtils.java | 15 ++-- .../writers/PojoWriterDataSetTest.java | 68 +++++++++++++++++++ docs/features.md | 2 +- history/latest/3400.md | 3 + 5 files changed, 85 insertions(+), 15 deletions(-) create mode 100644 history/latest/3400.md diff --git a/client-v2/src/main/java/com/clickhouse/client/api/data_formats/RowBinaryFormatSerializer.java b/client-v2/src/main/java/com/clickhouse/client/api/data_formats/RowBinaryFormatSerializer.java index 1f7e9d85a1..96c739a363 100644 --- a/client-v2/src/main/java/com/clickhouse/client/api/data_formats/RowBinaryFormatSerializer.java +++ b/client-v2/src/main/java/com/clickhouse/client/api/data_formats/RowBinaryFormatSerializer.java @@ -197,6 +197,7 @@ public static boolean writeValuePreamble(OutputStream out, boolean defaultsSuppo } public static boolean writeValuePreamble(OutputStream out, boolean defaultsSupport, Object value, boolean isNullable, ClickHouseDataType dataType, boolean hasDefault, String column) throws IOException { + boolean encodesNull = dataType == ClickHouseDataType.Dynamic || dataType == ClickHouseDataType.Variant; if (defaultsSupport) { if (value != null) {//Because we now support defaults, we have to send nonNull SerializerUtils.writeNonNull(out);//Write 0 for no default @@ -212,8 +213,7 @@ public static boolean writeValuePreamble(OutputStream out, boolean defaultsSuppo SerializerUtils.writeNonNull(out); SerializerUtils.writeNull(out);//Then we send null, write 1 return false;//And we're done - } else if (dataType == ClickHouseDataType.Dynamic) { - // A Dynamic column can hold a null: it is serialized below as the implicit `Nothing` type. + } else if (encodesNull) { SerializerUtils.writeNonNull(out);//Write 0 for no default } else { throw new IllegalArgumentException(String.format("An attempt to write null into not nullable column '%s'", column)); @@ -226,12 +226,8 @@ public static boolean writeValuePreamble(OutputStream out, boolean defaultsSuppo return false; } SerializerUtils.writeNonNull(out); - } else if (value == null) { - if (dataType == ClickHouseDataType.Dynamic) { - // A Dynamic column can hold a null: it is serialized below as the implicit `Nothing` type. - } else { - throw new IllegalArgumentException(String.format("An attempt to write null into not nullable column '%s'", column)); - } + } else if (value == null && !encodesNull) { + throw new IllegalArgumentException(String.format("An attempt to write null into not nullable column '%s'", column)); } } diff --git a/client-v2/src/main/java/com/clickhouse/client/api/data_formats/internal/SerializerUtils.java b/client-v2/src/main/java/com/clickhouse/client/api/data_formats/internal/SerializerUtils.java index 50f9136e20..3217f99b3b 100644 --- a/client-v2/src/main/java/com/clickhouse/client/api/data_formats/internal/SerializerUtils.java +++ b/client-v2/src/main/java/com/clickhouse/client/api/data_formats/internal/SerializerUtils.java @@ -889,14 +889,17 @@ public static void serializeJSON(OutputStream stream, Object value) throws IOExc } public static void serializerVariant(OutputStream out, ClickHouseColumn column, Object value) throws IOException { - int typeOrdNum = column.getVariantOrdNum(value); - if (typeOrdNum != -1) { - BinaryStreamUtils.writeUnsignedInt8(out, typeOrdNum); - serializeData(out, value, column.getNestedColumns().get(typeOrdNum)); - } else { - throw new IllegalArgumentException("Cannot write value of class " + (value == null ? "" : value.getClass()) + if (value == null) { + out.write(0xFF); + return; + } + int tag = column.getVariantOrdNum(value); + if (tag == -1) { + throw new IllegalArgumentException("Cannot write value of class " + value.getClass() + " into column with variant type " + column.getOriginalTypeName()); } + BinaryStreamUtils.writeUnsignedInt8(out, tag); + serializeData(out, value, column.getNestedColumns().get(tag)); } public static void serializerGeometry(OutputStream out, ClickHouseColumn column, Object value) throws IOException { diff --git a/client-v2/src/test/java/com/clickhouse/client/datatypes/writers/PojoWriterDataSetTest.java b/client-v2/src/test/java/com/clickhouse/client/datatypes/writers/PojoWriterDataSetTest.java index 3cb6461e6c..9c4d1a191a 100644 --- a/client-v2/src/test/java/com/clickhouse/client/datatypes/writers/PojoWriterDataSetTest.java +++ b/client-v2/src/test/java/com/clickhouse/client/datatypes/writers/PojoWriterDataSetTest.java @@ -11,6 +11,7 @@ import com.clickhouse.client.api.insert.InsertResponse; import com.clickhouse.client.api.internal.ServerSettings; import com.clickhouse.client.api.metadata.TableSchema; +import com.clickhouse.client.api.query.GenericRecord; import com.clickhouse.client.api.query.QueryResponse; import com.clickhouse.client.api.query.QuerySettings; import com.clickhouse.client.datatypes.DataSetPojoGenerator; @@ -24,6 +25,7 @@ import com.clickhouse.data.ClickHouseDataType; import com.clickhouse.data.ClickHouseFormat; import com.clickhouse.data.ClickHouseVersion; +import lombok.Value; import org.testng.Assert; import org.testng.SkipException; import org.testng.annotations.BeforeClass; @@ -93,6 +95,72 @@ public Object[][] primitiveDataSetEntries() { return cases.toArray(new Object[0][]); } + @DataProvider + public Object[][] variantDefaults() { + return new Object[][] {{false}, {true}}; + } + + @Test(groups = {"integration"}, dataProvider = "variantDefaults") + public void testWriteNullVariantWithPojo(boolean defaults) throws Exception { + if (serverVersion.check("(,24.8]")) { + throw new SkipException("Variant requires ClickHouse newer than 24.8 in this suite"); + } + String table = "pojo_writer_variant_null_" + defaults; + String fallback = defaults ? ", fallback Variant(Int32, String) DEFAULT CAST('fallback', 'Variant(Int32, String)')" : ""; + try (Client client = newClientBuilder().serverSetting(ServerSettings.ASYNC_INSERT, "0") + .serverSetting(ServerSettings.WAIT_END_OF_QUERY, "1") + .serverSetting("allow_experimental_variant_type", "1").build()) { + client.execute("CREATE TABLE " + table + " (id Int32, v Variant(Int32, String, Array(Int32)), " + + "nested Array(Variant(Int32, String)), tail Int32" + fallback + ") ORDER BY id") + .get(TIMEOUT_SECONDS, TimeUnit.SECONDS).close(); + try { + Object nullVariant = client.queryAll("SELECT CAST(NULL, 'Variant(Int32, String)') AS v") + .get(0).getObject("v"); + Assert.assertNull(nullVariant); + client.register(VariantPojo.class, client.getTableSchema(table)); + client.insert(table, Arrays.asList( + new VariantPojo(1, "hello", new Object[] {"one", 7}, 41, null), + new VariantPojo(2, nullVariant, new Object[] {null, 5, null}, 42, null), + new VariantPojo(3, new Integer[] {3, 4}, new Object[] {"last"}, 43, null))) + .get(TIMEOUT_SECONDS, TimeUnit.SECONDS).close(); + + List rows = client.queryAll("SELECT id, toString(variantType(v)) AS kind, " + + "isNull(v) AS is_null, toString(v) AS value, toJSONString(nested) AS nested_value, tail" + + (defaults ? ", toString(fallback) AS fallback_value" : "") + + " FROM " + table + " ORDER BY id"); + String[][] expected = { + {"String", "hello", "[\"one\",7]"}, + {"None", "", "[null,5,null]"}, + {"Array(Int32)", "[3,4]", "[\"last\"]"}, + }; + Assert.assertEquals(rows.size(), expected.length); + for (int i = 0; i < expected.length; i++) { + GenericRecord row = rows.get(i); + Assert.assertEquals(row.getInteger("id"), i + 1); + Assert.assertEquals(row.getString("kind"), expected[i][0]); + Assert.assertEquals(row.getBoolean("is_null"), i == 1); + Assert.assertEquals(row.getString("value"), expected[i][1]); + Assert.assertEquals(row.getString("nested_value"), expected[i][2]); + Assert.assertEquals(row.getInteger("tail"), i + 41); + if (defaults) { + Assert.assertEquals(row.getString("fallback_value"), "fallback"); + } + } + } finally { + dropTable(client, table); + } + } + } + + @Value + public static class VariantPojo { + int id; + Object v; + Object[] nested; + int tail; + Object fallback; + } + @Test(groups = {"integration"}, dataProvider = "dataSetEntries") public void testWriteDataSetWithPojo(DataSetEntry entry) throws Exception { runPojoWriteTest(entry, DataSetPojoGenerator.forDataSet(entry), true); diff --git a/docs/features.md b/docs/features.md index a8f7e12b30..af0bc9d523 100644 --- a/docs/features.md +++ b/docs/features.md @@ -27,7 +27,7 @@ This document lists stable, user-visible behavior in `client-v2` and `jdbc-v2` t - Geometry type support: For ClickHouse `25.11+`, where `Geometry` changed from a string alias to `Variant(Point, Ring, LineString, MultiLineString, Polygon, MultiPolygon)`, the client reads and writes `Geometry` values through generic records, binary readers, POJO binding, and SQL parameter formatting, using Java array dimensionality to represent the geometry shape. ClickHouse `26.8+` adds `MultiPoint` to that variant, appended after the existing six so their discriminators are unchanged; a `MultiPoint` value read from a `Geometry` column is returned as `double[][]`, the same shape as `Ring` and `LineString`. - MultiPoint type support: For ClickHouse `26.8+`, reads and writes the `MultiPoint` geo type, which is transmitted exactly like `Ring` and `LineString` (`Array(Point)`) and is represented as `double[][]` through generic records, binary readers, POJO binding, and SQL parameter formatting. A `MultiPoint` held in a `Dynamic` column is decoded on read; it cannot be written into a `Dynamic` column, because the client infers the type from the Java value and `double[][]` resolves to `Ring`. - Nested type support: Un-flattened `Nested(f1 T1, ..., fN TN)` columns (tables created with `flatten_nested = 0`) can be written through the insert path (`Client#insert`) using `RowBinaryFormatWriter#setValue`, and are read back through the binary readers and generic records. The column is serialized the same way it is read — identically to `Array(Tuple(T1, ..., TN))`, a var-uint row count followed by one tuple per nested row — so the value supplied for the column is a `List` (or array) of tuples, one tuple per nested row, each carrying the N field values in declaration order. -- Insert APIs: Supports inserting registered POJOs, raw streams, and callback-driven writers, with optional column lists and format selection. +- Inserts accept registered POJOs, raw streams, or callbacks, with optional columns and formats. RowBinary writes `Variant` NULLs. - Insert controls: Supports insert-specific settings such as deduplication token, query id, compression behavior, and request headers. - Command execution: Executes DDL or other non-result commands and exposes response summaries and operation metrics. - Session handling: Supports client-wide and per-operation HTTP sessions, operation-level session overrides, runtime updates of client `session_id`, and server-side session validation through `session_check`. diff --git a/history/latest/3400.md b/history/latest/3400.md new file mode 100644 index 0000000000..6b440380e8 --- /dev/null +++ b/history/latest/3400.md @@ -0,0 +1,3 @@ +- **[client-v2]** RowBinary inserts now encode `Variant` NULL values with the `0xFF` discriminator, including + nested elements. In RowBinaryWithDefaults, a null binding to a column with an explicit default still uses + that default. (https://github.com/ClickHouse/clickhouse-java/issues/3400)