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 @@ -4,9 +4,11 @@
import com.clickhouse.client.api.ClientException;
import com.clickhouse.client.api.serde.POJOFieldDeserializer;
import com.clickhouse.data.ClickHouseAggregateFunction;
import com.clickhouse.data.ClickHouseChecker;
import com.clickhouse.data.ClickHouseColumn;
import com.clickhouse.data.ClickHouseDataType;
import com.clickhouse.data.ClickHouseEnum;
import com.clickhouse.data.ClickHouseValues;
import com.clickhouse.data.format.BinaryStreamUtils;
import com.clickhouse.data.value.ClickHouseBitmap;
import com.clickhouse.data.value.ClickHouseGeoMultiPolygonValue;
Expand Down Expand Up @@ -666,10 +668,12 @@ private static void serializePrimitiveData(OutputStream stream, Object value, Cl
BinaryStreamUtils.writeInt64(stream, convertToLong(value));
break;
case Int128:
BinaryStreamUtils.writeInt128(stream, NumberConverter.toBigInteger(value));
BinaryStreamUtils.writeInt128(stream, ClickHouseChecker.between(convertToBigInteger(value),
ClickHouseValues.TYPE_BIG_INTEGER, INT128_MIN, INT128_MAX));
break;
case Int256:
BinaryStreamUtils.writeInt256(stream, NumberConverter.toBigInteger(value));
BinaryStreamUtils.writeInt256(stream, ClickHouseChecker.between(convertToBigInteger(value),
ClickHouseValues.TYPE_BIG_INTEGER, INT256_MIN, INT256_MAX));
break;
case UInt8:
BinaryStreamUtils.writeUnsignedInt8(stream, convertToInteger(value));
Expand All @@ -681,13 +685,13 @@ private static void serializePrimitiveData(OutputStream stream, Object value, Cl
BinaryStreamUtils.writeUnsignedInt32(stream, convertToLong(value));
break;
case UInt64:
BinaryStreamUtils.writeUnsignedInt64(stream, NumberConverter.toBigInteger(value));
BinaryStreamUtils.writeUnsignedInt64(stream, convertToBigInteger(value));
break;
case UInt128:
BinaryStreamUtils.writeUnsignedInt128(stream, NumberConverter.toBigInteger(value));
BinaryStreamUtils.writeUnsignedInt128(stream, convertToBigInteger(value));
break;
case UInt256:
BinaryStreamUtils.writeUnsignedInt256(stream, NumberConverter.toBigInteger(value));
BinaryStreamUtils.writeUnsignedInt256(stream, convertToBigInteger(value));
break;
case BFloat16:
BinaryStreamUtils.writeBFloat16(stream, (float) value);
Expand Down Expand Up @@ -1053,11 +1057,21 @@ public static void serializeAggregateFunction(OutputStream stream, Object value,
}
}

private static final BigInteger LONG_MIN = BigInteger.valueOf(Long.MIN_VALUE);
private static final BigInteger LONG_MAX = BigInteger.valueOf(Long.MAX_VALUE);
private static final BigInteger INT128_MIN = BigInteger.ONE.shiftLeft(127).negate();
private static final BigInteger INT128_MAX = BigInteger.ONE.shiftLeft(127).subtract(BigInteger.ONE);
private static final BigInteger INT256_MIN = BigInteger.ONE.shiftLeft(255).negate();
private static final BigInteger INT256_MAX = BigInteger.ONE.shiftLeft(255).subtract(BigInteger.ONE);

public static Integer convertToInteger(Object value) {
if (value instanceof Integer) {
return (Integer) value;
} else if (value instanceof Number) {
} else if (value instanceof Short || value instanceof Byte) {
return ((Number) value).intValue();
} else if (value instanceof Number) {
return (int) ClickHouseChecker.between(convertToLong(value), ClickHouseValues.TYPE_LONG,
Integer.MIN_VALUE, Integer.MAX_VALUE);
} else if (value instanceof String) {
return Integer.parseInt((String) value);
} else if (value instanceof Boolean) {
Expand All @@ -1070,8 +1084,14 @@ public static Integer convertToInteger(Object value) {
public static Long convertToLong(Object value) {
if (value instanceof Long) {
return (Long) value;
} else if (value instanceof Number) {
} else if (value instanceof Integer || value instanceof Short || value instanceof Byte) {
return ((Number) value).longValue();
} else if ((value instanceof Double || value instanceof Float)
&& ((Number) value).doubleValue() >= -0x1p63 && ((Number) value).doubleValue() < 0x1p63) {
return (long) ((Number) value).doubleValue();
} else if (value instanceof Number) {
return ClickHouseChecker.between(convertToBigInteger(value), ClickHouseValues.TYPE_BIG_INTEGER,
LONG_MIN, LONG_MAX).longValue();
} else if (value instanceof String) {
return Long.parseLong((String) value);
} else if (value instanceof Boolean) {
Expand All @@ -1081,6 +1101,50 @@ public static Long convertToLong(Object value) {
}
}

/**
* Converts a value for an integer column to {@link BigInteger}. A fractional part is dropped, but the
* integer part is kept exactly, so a range check of the column type sees the real value.
*/
private static BigInteger convertToBigInteger(Object value) {
if (value instanceof BigInteger) {
return (BigInteger) value;
} else if (value instanceof Long || value instanceof Integer || value instanceof Short || value instanceof Byte) {
return BigInteger.valueOf(((Number) value).longValue());
} else if (value instanceof Double || value instanceof Float) {
double d = ((Number) value).doubleValue();
if (Double.isNaN(d) || Double.isInfinite(d)) {
throw new IllegalArgumentException("Cannot convert " + value + " to BigInteger");
}
return new BigDecimal(d).toBigInteger();
} else if (value instanceof BigDecimal) {
return toIntegerPart((BigDecimal) value);
} else if (value instanceof Number) {
return toIntegerPart(new BigDecimal(value.toString()));
} else {
return NumberConverter.toBigInteger(value);
}
}

/** 2^256 has 78 decimal digits, so a value with more integer digits fits no integer column. */
private static final int MAX_INTEGER_DIGITS = 78;

/**
* Returns the integer part of the value. The number of integer digits is checked first, because
* {@link BigDecimal#toBigInteger()} on a short value such as {@code 1E+500000000} or {@code 1E-500000000}
* computes a power of ten with hundreds of millions of digits.
*/
private static BigInteger toIntegerPart(BigDecimal value) {
long integerDigits = (long) value.precision() - value.scale();
if (value.signum() == 0 || integerDigits <= 0) {
return BigInteger.ZERO;
}
if (integerDigits > MAX_INTEGER_DIGITS) {
throw new IllegalArgumentException("Cannot convert " + value + " to BigInteger: " + integerDigits
+ " integer digits do not fit any integer type");
}
return value.toBigInteger();
}

public static String convertToString(Object value) {
return java.lang.String.valueOf(value);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import com.clickhouse.client.api.query.QuerySettings;
import com.clickhouse.data.ClickHouseColumn;
import com.clickhouse.data.format.BinaryStreamUtils;
import com.clickhouse.data.value.UnsignedLong;
import org.testng.Assert;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
Expand Down Expand Up @@ -126,6 +127,82 @@ private Object[][] invalidStringValues() {
};
}

@Test(dataProvider = "outOfRangeIntegerValues")
public void testSerializeIntegerColumnRejectsOutOfRangeValue(String type, Object value, String message) {
IllegalArgumentException e = Assert.expectThrows(IllegalArgumentException.class,
() -> serializeSingleValue(type, value));
Assert.assertTrue(e.getMessage().contains(message),
"Unexpected message for " + value + " in " + type + ": " + e.getMessage());
}

@DataProvider(name = "outOfRangeIntegerValues")
private Object[][] outOfRangeIntegerValues() {
String outOfRange = "should be between";
return new Object[][] {
{"Int8", 4294967296L, outOfRange},
{"Int32", 2147483648L, outOfRange},
{"Int32", "2147483648", "For input string"},
{"UInt32", BigInteger.ONE.shiftLeft(64), outOfRange},
{"Int64", new BigInteger("9223372036854775808"), outOfRange},
{"Int64", 1.0E19d, outOfRange},
{"Int64", UnsignedLong.MAX_VALUE, outOfRange},
{"Int64", new CustomNumber("1e20"), outOfRange},
{"UInt64", Double.NaN, "Cannot convert NaN"},
{"Int128", BigInteger.ONE.shiftLeft(127).toString(), outOfRange},
{"Int256", new BigDecimal(BigInteger.ONE.shiftLeft(255).negate().subtract(BigInteger.ONE)), outOfRange},
{"UInt256", new BigDecimal("9.99E+77"), outOfRange},
};
}

@Test(dataProvider = "integerValuesWithLargeExponent", timeOut = 10000)
public void testSerializeIntegerColumnRejectsValueWithLargeExponent(String type, Number value) {
IllegalArgumentException e = Assert.expectThrows(IllegalArgumentException.class,
() -> serializeSingleValue(type, value));
Assert.assertTrue(e.getMessage().contains("integer digits do not fit any integer type"),
"Unexpected message for " + value + " in " + type + ": " + e.getMessage());
}

@DataProvider(name = "integerValuesWithLargeExponent")
private Object[][] integerValuesWithLargeExponent() {
return new Object[][] {
{"Int32", new BigDecimal("1E+500000000")},
{"Int64", new BigDecimal("-1E+500000000")},
{"UInt64", new BigDecimal("1E+500000000")},
{"Int256", new BigDecimal("-1E+500000000")},
{"UInt256", new BigDecimal("1E+500000000")},
{"UInt256", new BigDecimal("1E+78")},
{"Int32", new ScientificNumber("1E+500000000")},
{"UInt256", new ScientificNumber("1E+500000000")},
};
}

@Test(dataProvider = "integerPartValues", timeOut = 10000)
public void testSerializeIntegerColumnWritesIntegerPart(String type, Number value, BigInteger expected)
throws IOException {
RowBinaryWithNamesAndTypesFormatReader reader = serializeSingleValue(type, value);

reader.next();

Assert.assertEquals(reader.getBigInteger("value"), expected);
}

@DataProvider(name = "integerPartValues")
private Object[][] integerPartValues() {
BigInteger uint256Max = BigInteger.ONE.shiftLeft(256).subtract(BigInteger.ONE);
BigInteger int256Min = BigInteger.ONE.shiftLeft(255).negate();
return new Object[][] {
{"Int32", new BigDecimal("1E-500000000"), BigInteger.ZERO},
{"Int64", new BigDecimal("-1E-500000000"), BigInteger.ZERO},
{"UInt256", new BigDecimal("1E-500000000"), BigInteger.ZERO},
{"Int32", new ScientificNumber("1E-500000000"), BigInteger.ZERO},
{"Int32", new BigDecimal("0E+500000000"), BigInteger.ZERO},
{"Int32", new BigDecimal("-12.9"), BigInteger.valueOf(-12)},
{"UInt256", new BigDecimal("1E+77"), BigInteger.TEN.pow(77)},
{"UInt256", new BigDecimal(uint256Max).add(new BigDecimal("0.5")), uint256Max},
{"Int256", new BigDecimal(int256Min).subtract(new BigDecimal("0.5")), int256Min},
};
}

@Test
public void testSerializeBFloat16RoundTripAllValues() throws IOException {
// Exhaustively round-trip every one of the 2^16 BFloat16 bit patterns. For pattern b the
Expand Down Expand Up @@ -212,4 +289,38 @@ public String toString() {
return value.toPlainString();
}
}

/** A generic {@link Number} whose text is in scientific notation, such as {@code 1E+500000000}. */
private static final class ScientificNumber extends Number {
private final BigDecimal value;

private ScientificNumber(String value) {
this.value = new BigDecimal(value);
}

@Override
public int intValue() {
return value.intValue();
}

@Override
public long longValue() {
return value.longValue();
}

@Override
public float floatValue() {
return value.floatValue();
}

@Override
public double doubleValue() {
return value.doubleValue();
}

@Override
public String toString() {
return value.toString();
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@
import com.clickhouse.data.ClickHouseColumn;
import com.clickhouse.data.ClickHouseFormat;
import com.clickhouse.data.ClickHouseVersion;
import com.clickhouse.data.format.BinaryStreamUtils;
import com.clickhouse.data.value.UnsignedLong;
import org.apache.commons.lang3.RandomStringUtils;
import org.testng.Assert;
import org.testng.annotations.BeforeMethod;
Expand Down Expand Up @@ -654,6 +656,55 @@ public void writeStringIntoUInt64AndUUIDTest(String columnType, Object value, St
Assert.assertEquals(row.getDouble("tail"), 0.5d);
}

@DataProvider(name = "integerColumnValues")
private Object[][] integerColumnValues() {
BigInteger int128Max = BigInteger.ONE.shiftLeft(127).subtract(BigInteger.ONE);
BigInteger int256Min = BigInteger.ONE.shiftLeft(255).negate();
return new Object[][] {
{"Int8", (short) -128, "-128"},
{"Int16", -3.99f, "-3"},
{"Int32", 2147483647L, "2147483647"},
{"Int32", 2.75d, "2"},
{"Int64", BigInteger.valueOf(Long.MIN_VALUE), "-9223372036854775808"},
{"Int64", new BigDecimal("-7.9"), "-7"},
{"UInt64", new BigDecimal("18446744073709551615"), "18446744073709551615"},
{"UInt64", UnsignedLong.MAX_VALUE, "18446744073709551615"},
{"UInt64", 1.0E19d, "10000000000000000000"},
{"Int128", int128Max.toString(), int128Max.toString()},
{"Int128", new BigDecimal(int128Max), int128Max.toString()},
{"UInt128", new BigDecimal(BinaryStreamUtils.U_INT128_MAX), BinaryStreamUtils.U_INT128_MAX.toString()},
{"Int256", new BigDecimal(int256Min), int256Min.toString()},
{"UInt256", new BigDecimal(BinaryStreamUtils.U_INT256_MAX), BinaryStreamUtils.U_INT256_MAX.toString()},
};
}

@Test (groups = { "integration" }, dataProvider = "integerColumnValues")
public void writeIntegerColumnValueTest(String columnType, Object value, String expected) throws Exception {
String tableName = "rowBinaryFormatWriterTest_integer_" + UUID.randomUUID().toString().replace('-', '_');
initTable(tableName,
"CREATE TABLE \"" + tableName + "\" (id Int32, c " + columnType + ", tail Float64) ORDER BY id",
new CommandSettings());
TableSchema schema = client.getTableSchema(tableName);
ClickHouseFormat format = ClickHouseFormat.RowBinaryWithDefaults;

try (InsertResponse response = client.insert(tableName, out -> {
RowBinaryFormatWriter w = new RowBinaryFormatWriter(out, schema, format);
w.setValue(schema.nameToColumnIndex("id"), 1);
w.setValue(schema.nameToColumnIndex("c"), value);
w.setValue(schema.nameToColumnIndex("tail"), 0.5d);
w.commitRow();
}, format, settings).get(EXECUTE_CMD_TIMEOUT, TimeUnit.SECONDS)) {
}

List<GenericRecord> records = client.queryAll(
"SELECT id, toString(c) AS c, tail FROM \"" + tableName + "\" ORDER BY id");
Assert.assertEquals(records.size(), 1);
GenericRecord row = records.get(0);
Assert.assertEquals(row.getInteger("id"), 1);
Assert.assertEquals(row.getString("c"), expected);
Assert.assertEquals(row.getDouble("tail"), 0.5d);
}

@Test (groups = { "integration" })
public void writeBinaryStringsTest() throws Exception {
String tableName = "rowBinaryFormatWriterTest_writeBinaryStringsTests_" + UUID.randomUUID().toString().replace('-', '_');
Expand Down
1 change: 1 addition & 0 deletions docs/features.md
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@ Compatibility-sensitive traits:
- `QBit` is wire-compatible with `Array(element_type)` and should not drift: the client transmits the logical vector as a length-prefixed array of its element type (`float[]` for `BFloat16`/`Float32`, `double[]` for `Float64`) rather than the server's bit-transposed on-disk layout, so a `QBit(E, N)` value read from or written to the server round-trips as an array of `E`. A written `QBit(E, N)` value must be a Java array or `List` holding exactly `N` elements: a wrong-sized (including empty) vector, or a non-null value that is neither an array nor a `List`, is rejected during binary serialization with an `IllegalArgumentException` rather than deferred to a server error or silently writing a misaligned stream, matching the fixed dimension the server enforces. Symmetrically, a `QBit(E, N)` read whose on-wire element count does not equal the declared dimension `N` is rejected with a `ClientException` rather than returning a wrong-length vector.
- Timezone conversion helpers preserve nanoseconds and can intentionally shift local date or time when interpreted in a different timezone; this behavior is covered by tests and should not be normalized away.
- Array-shaped columns reject a value they cannot represent: a non-`null` value written to an `Array` column, or to one of the array-backed geo types (`Ring`, `LineString`, `MultiPoint`, `Polygon`, `MultiLineString`, `MultiPolygon`), must be a Java array or a `List`. Anything else is rejected during binary serialization with a `ClientException` naming the value class and the column type, rather than writing no bytes for the column - which previously left the following columns misframed in the `RowBinary` stream, surfacing as a server-side `CANNOT_READ_ALL_DATA` or, with `RowBinaryWithDefaults`, as a silently successful insert of corrupted rows. A `null` still writes the var-int length `0`, and arrays and `List`s serialize exactly as before.
- Integer columns reject a value they cannot represent: in binary serialization (`RowBinaryFormatWriter`, POJO insert, and the jdbc-v2 RowBinary writer), a value for an `Int8` to `Int256` or `UInt8` to `UInt256` column is converted to the column type without loss of its integer part. A `String` must hold an integer, and the fractional part of a `float`, `double` or `BigDecimal` is dropped. A value that is out of the range of the column type, `NaN` or an infinity is rejected with an `IllegalArgumentException` instead of being wrapped into the range.
- `Geometry` handling is shape-sensitive: supported values are 1D through 4D Java arrays representing the nested geometry variants, and unsupported shapes or non-array values are rejected during serialization.
- `Geometry` write inference is dimension-based rather than fully type-specific: point, ring/line string, polygon/multi-line string, and multi-polygon are selected from array depth, so writing `Geometry` cannot currently distinguish `Ring` from `LineString` or `Polygon` from `MultiLineString`. `MultiPoint` shares the same 2D shape and is deliberately not selectable through the generic `Geometry` write path — a 2D value keeps resolving to `Ring`, so writing `MultiPoint` requires a concrete `MultiPoint` column.
- Session precedence is part of the contract: client session defaults apply to each request, operation settings may override them, and only the client `session_id` is mutable at runtime while other client session properties remain fixed for the lifetime of the client.
Expand Down
Loading
Loading