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 50f9136e2..e810a8b07 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 @@ -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; @@ -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)); @@ -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); @@ -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) { @@ -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) { @@ -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); } diff --git a/client-v2/src/test/java/com/clickhouse/client/api/data_formats/internal/SerializerUtilsPrimitiveSerializationTests.java b/client-v2/src/test/java/com/clickhouse/client/api/data_formats/internal/SerializerUtilsPrimitiveSerializationTests.java index 6a334fc6a..a1e8e835e 100644 --- a/client-v2/src/test/java/com/clickhouse/client/api/data_formats/internal/SerializerUtilsPrimitiveSerializationTests.java +++ b/client-v2/src/test/java/com/clickhouse/client/api/data_formats/internal/SerializerUtilsPrimitiveSerializationTests.java @@ -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; @@ -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 @@ -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(); + } + } } diff --git a/client-v2/src/test/java/com/clickhouse/client/datatypes/RowBinaryFormatWriterTest.java b/client-v2/src/test/java/com/clickhouse/client/datatypes/RowBinaryFormatWriterTest.java index 9f46b0f0c..5ca2f7903 100644 --- a/client-v2/src/test/java/com/clickhouse/client/datatypes/RowBinaryFormatWriterTest.java +++ b/client-v2/src/test/java/com/clickhouse/client/datatypes/RowBinaryFormatWriterTest.java @@ -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; @@ -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 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('-', '_'); diff --git a/docs/features.md b/docs/features.md index ef27f4018..8a60b9b4a 100644 --- a/docs/features.md +++ b/docs/features.md @@ -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. diff --git a/docs/integration-jdbc.md b/docs/integration-jdbc.md index 868df2141..f64115f9a 100644 --- a/docs/integration-jdbc.md +++ b/docs/integration-jdbc.md @@ -733,6 +733,8 @@ public void insertEventsBatch(Connection conn, List events) throws SQLExc **RowBinary streaming insert (beta):** enable `beta.row_binary_for_simple_insert=true` so simple `INSERT INTO t VALUES (?, ?, ?)` statements serialize as RowBinary via [`WriterStatementImpl`](../jdbc-v2/src/main/java/com/clickhouse/jdbc/WriterStatementImpl.java) instead of SQL text. +With the RowBinary writer, the driver does not send SQL text, so the server does not convert the values. Bind each value with a Java type that matches the column type, for example `setLong` for `Int64`, or `setObject` with a `BigInteger` for `UInt64`, `Int128` and wider types. For an integer column, the writer converts other values to the column type: it accepts a `String` that holds an integer (for example `"18446744073709551615"`), and it drops the fractional part of a `float`, `double` or `BigDecimal`. If a value is out of the range of the column type, the insert fails with `SQLException` (from `addBatch()`, `execute()`, `executeUpdate()` or `executeBatch()`). + ```java public Connection createRowBinaryInsertConnection() throws SQLException { Properties props = new Properties(); diff --git a/history/latest/2619.md b/history/latest/2619.md new file mode 100644 index 000000000..e2c6e147e --- /dev/null +++ b/history/latest/2619.md @@ -0,0 +1,13 @@ +## Bug Fixes + +- **[client-v2]** Binary serialization of integer columns no longer changes a value that does not fit the column type. + A `Long`, `BigInteger`, `BigDecimal`, `double` or other `Number` value was narrowed without a check, so for example + `2147483648L` was written as `-2147483648` into an `Int32` column, and an `Int128` or `Int256` column accepted a value + up to the unsigned maximum and stored it as a negative number. A `BigDecimal` or `double` value outside the `long` + range was written as a wrong value (for example `-1` for the `Int128` maximum) or rejected for `UInt64` and wider + types although it was in range. Such values are now converted without loss of the integer part and checked against + the range of the column type. A value that is out of range, `NaN` or an infinity is rejected with + `IllegalArgumentException`; this includes a `double` or `float` at or above 2^63 for `Int64` (for example + `(double) Long.MAX_VALUE`), which was clamped to the maximum before. A fractional part is still dropped. With the + jdbc-v2 RowBinary writer (`beta.row_binary_for_simple_insert=true`), the insert fails with `SQLException`. + (https://github.com/ClickHouse/clickhouse-java/issues/2619) diff --git a/jdbc-v2/src/test/java/com/clickhouse/jdbc/WriterStatementImplTest.java b/jdbc-v2/src/test/java/com/clickhouse/jdbc/WriterStatementImplTest.java index d6c12f96e..533425885 100644 --- a/jdbc-v2/src/test/java/com/clickhouse/jdbc/WriterStatementImplTest.java +++ b/jdbc-v2/src/test/java/com/clickhouse/jdbc/WriterStatementImplTest.java @@ -427,6 +427,94 @@ public void testInsertUsesWriterOnlyForValuesListOfPlaceholders(String parser, S } } + @DataProvider(name = "integerTypeBounds") + Object[][] integerTypeBounds() { + return new Object[][]{ + {"Int8", "-128", "127"}, + {"UInt8", "0", "255"}, + {"Int16", "-32768", "32767"}, + {"UInt16", "0", "65535"}, + {"Int32", "-2147483648", "2147483647"}, + {"UInt32", "0", "4294967295"}, + {"Int64", "-9223372036854775808", "9223372036854775807"}, + {"UInt64", "0", "18446744073709551615"}, + {"Int128", "-170141183460469231731687303715884105728", "170141183460469231731687303715884105727"}, + {"UInt128", "0", "340282366920938463463374607431768211455"}, + {"Int256", "-57896044618658097711785492504343953926634992332820282019728792003956564819968", + "57896044618658097711785492504343953926634992332820282019728792003956564819967"}, + {"UInt256", "0", "115792089237316195423570985008687907853269984665640564039457584007913129639935"}, + }; + } + + @Test(groups = {"integration"}, dataProvider = "integerTypeBounds") + public void testSetStringIntoIntegerColumnBounds(String type, String min, String max) throws SQLException { + String table = "bt_writer_int_bounds_" + UUID.randomUUID().toString().replace('-', '_'); + Properties properties = new Properties(); + properties.setProperty(DriverProperties.BETA_ROW_BINARY_WRITER.getKey(), "true"); + properties.setProperty(ASYNC_INSERT_SETTING_KEY, ServerSettings.OFF); + try (Connection connection = getJdbcConnection(properties)) { + try (Statement stmt = connection.createStatement()) { + stmt.execute("CREATE TABLE " + table + " (id Int32, v " + type + ", tail Int32) ORDER BY id"); + } + + try { + try (PreparedStatement ps = connection.prepareStatement("INSERT INTO " + table + " VALUES (?, ?, ?)")) { + Assert.assertTrue(ps instanceof WriterStatementImpl); + String[] values = {min, max}; + for (int i = 0; i < values.length; i++) { + ps.setInt(1, i); + ps.setString(2, values[i]); + ps.setInt(3, 7); + ps.addBatch(); + } + ps.executeBatch(); + } + + try (Statement stmt = connection.createStatement(); + ResultSet rs = stmt.executeQuery("SELECT toString(v), tail FROM " + table + " ORDER BY id")) { + Assert.assertTrue(rs.next()); + Assert.assertEquals(rs.getString(1), min); + Assert.assertEquals(rs.getInt(2), 7); + Assert.assertTrue(rs.next()); + Assert.assertEquals(rs.getString(1), max); + Assert.assertEquals(rs.getInt(2), 7); + Assert.assertFalse(rs.next()); + } + } finally { + try (Statement stmt = connection.createStatement()) { + stmt.execute("DROP TABLE IF EXISTS " + table); + } + } + } + } + + @Test(groups = {"integration"}) + public void testSetLongOutOfIntegerColumnRangeFails() throws SQLException { + String table = "bt_writer_int_range_" + UUID.randomUUID().toString().replace('-', '_'); + Properties properties = new Properties(); + properties.setProperty(DriverProperties.BETA_ROW_BINARY_WRITER.getKey(), "true"); + try (Connection connection = getJdbcConnection(properties)) { + try (Statement stmt = connection.createStatement()) { + stmt.execute("CREATE TABLE " + table + " (id Int32, v Int32, tail Int32) ORDER BY id"); + } + + try (PreparedStatement ps = connection.prepareStatement("INSERT INTO " + table + " VALUES (?, ?, ?)")) { + Assert.assertTrue(ps instanceof WriterStatementImpl); + ps.setInt(1, 1); + ps.setLong(2, 2147483648L); + ps.setInt(3, 7); + SQLException thrown = Assert.expectThrows(SQLException.class, ps::addBatch); + Assert.assertTrue(thrown.getCause() instanceof IllegalArgumentException + && thrown.getCause().getMessage().contains("should be between"), + "Expected an out-of-range error, but got: " + thrown); + } finally { + try (Statement stmt = connection.createStatement()) { + stmt.execute("DROP TABLE IF EXISTS " + table); + } + } + } + } + private static boolean hasInjectedCause(Throwable t) { for (Throwable c = t; c != null; c = c.getCause()) { if (c instanceof IOException && "injected buffer close failure".equals(c.getMessage())) {