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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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));
Expand All @@ -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));
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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 ? "<null value>" : 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 {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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;
Expand Down Expand Up @@ -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<GenericRecord> 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);
Expand Down
2 changes: 1 addition & 1 deletion docs/features.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`.
Expand Down
3 changes: 3 additions & 0 deletions history/latest/3400.md
Original file line number Diff line number Diff line change
@@ -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)
Loading