From 5677c1a643cfac3617b95095c605951443f2bd45 Mon Sep 17 00:00:00 2001 From: Polyglot AI <293096396+polyglotAI-bot@users.noreply.github.com> Date: Tue, 24 Nov 2026 01:29:25 +0000 Subject: [PATCH] [jdbc-v2] RowBinary writer: store the values of setBytes, the stream setters and setURL With beta.row_binary_for_simple_insert=true, WriterStatementImpl had empty bodies for setBytes, all overloads of setAsciiStream, setUnicodeStream, setBinaryStream, setCharacterStream and setNCharacterStream, and setURL. The value never reached RowBinaryFormatWriter, so the column got NULL, its default, or the insert failed with "An attempt to write null into not nullable column". The setters now give the value to the writer. setBytes passes the array. The InputStream setters read the bytes, and the Reader setters read the characters, up to the length when one is given. setURL passes the URL text. A negative length, a stream that ends before the length, or a read failure throws SQLException. Fixes: https://github.com/ClickHouse/clickhouse-java/issues/3406 Fixes: https://github.com/ClickHouse/clickhouse-java/issues/3334 Co-Authored-By: Claude Opus 5.5 --- docs/features.md | 1 + history/latest/3406.md | 8 + .../clickhouse/jdbc/WriterStatementImpl.java | 109 ++++++++-- .../jdbc/WriterStatementImplTest.java | 187 ++++++++++++++++++ 4 files changed, 292 insertions(+), 13 deletions(-) create mode 100644 history/latest/3406.md diff --git a/docs/features.md b/docs/features.md index ef27f40186..d4a6286e4b 100644 --- a/docs/features.md +++ b/docs/features.md @@ -110,6 +110,7 @@ Compatibility-sensitive traits: Compatibility-sensitive traits: - Prepared statements are client-side SQL rendering, not server-side prepared statements. Changes to literal encoding or placeholder parsing are externally visible behavior. +- With `beta.row_binary_for_simple_insert=true`, the RowBinary writer stores the values of `setBytes`, `setAsciiStream`, `setUnicodeStream` and `setBinaryStream` byte for byte, and the values of `setCharacterStream`, `setNCharacterStream` and `setURL` as text. The length of an `InputStream` counts bytes, and the length of a `Reader` counts characters. The setter reads the stream before it returns. It fails with `SQLException` when the length is negative or the stream ends before the length. - `DatabaseMetaData#getSchemas`, `#getTables` and `#getColumns` return the same result-set columns and values with and without `jdbc_metadata_use_show_statements`, with two exceptions for the `SHOW` statements: `getTables()` returns `null` in `REMARKS` and `TYPE_SCHEM`, because `SHOW TABLES` returns no table comment and no database engine. `getColumns()` with the `SHOW` statements sends one `DESCRIBE TABLE` query for each table that matches, and skips a database or table that fails with `UNKNOWN_TABLE`, `UNKNOWN_DATABASE`, `ACCESS_DENIED` or `DATALAKE_DATABASE_ERROR` (for example, a table with column-level grants only, which `system.columns` shows with the granted columns). - JDBC `cluster_name` is compatibility-sensitive for cancellation behavior: when configured, `Statement.cancel()` issues `KILL QUERY ON CLUSTER ''`, and when omitted it falls back to a local `KILL QUERY`. - `Statement.cancel()` does nothing when the statement has no running query (the query is finished or not started yet). The `NOTHING_TO_KILL` error, which servers with `kill_throw_if_noop` enabled (the default since ClickHouse 26.11) return for such a `KILL QUERY`, is not thrown to the caller. Other `KILL QUERY` errors are thrown as `SQLException`. diff --git a/history/latest/3406.md b/history/latest/3406.md new file mode 100644 index 0000000000..084ba7e757 --- /dev/null +++ b/history/latest/3406.md @@ -0,0 +1,8 @@ +- **[jdbc-v2]** Fixed the RowBinary writer for simple `INSERT ... VALUES (?, ...)` statements + (`beta.row_binary_for_simple_insert=true`). It dropped the value of `setBytes`, `setURL` and of all overloads of + `setAsciiStream`, `setUnicodeStream`, `setBinaryStream`, `setCharacterStream` and `setNCharacterStream`. The column + then got `NULL` or its default, or the insert failed with "An attempt to write null into not nullable column". Now + the writer stores the value: `byte[]` and `InputStream` values byte for byte, `Reader` and `URL` values as text. The + setter reads the stream before it returns. It fails with `SQLException` when the length is negative or the stream + ends before the length. (https://github.com/ClickHouse/clickhouse-java/issues/3406, + https://github.com/ClickHouse/clickhouse-java/issues/3334) diff --git a/jdbc-v2/src/main/java/com/clickhouse/jdbc/WriterStatementImpl.java b/jdbc-v2/src/main/java/com/clickhouse/jdbc/WriterStatementImpl.java index a01944f5db..13880124b9 100644 --- a/jdbc-v2/src/main/java/com/clickhouse/jdbc/WriterStatementImpl.java +++ b/jdbc-v2/src/main/java/com/clickhouse/jdbc/WriterStatementImpl.java @@ -49,6 +49,8 @@ public class WriterStatementImpl extends PreparedStatementImpl implements Prepar private static final Logger LOG = LoggerFactory.getLogger(WriterStatementImpl.class); + private static final int STREAM_BUFFER_SIZE = 8192; + private ByteArrayOutputStream out; private ClickHouseBinaryFormatWriter writer; private final TableSchema tableSchema; @@ -204,7 +206,7 @@ public void setString(int parameterIndex, String x) throws SQLException { @Override public void setBytes(int parameterIndex, byte[] x) throws SQLException { ensureOpen(); - + writer.setValue(parameterIndex, x); } @Override @@ -224,69 +226,150 @@ public void setTimestamp(int parameterIndex, Timestamp x) throws SQLException { @Override public void setAsciiStream(int parameterIndex, InputStream x, int length) throws SQLException { - ensureOpen(); + setAsciiStream(parameterIndex, x, (long) length); } @Override public void setAsciiStream(int parameterIndex, InputStream x) throws SQLException { ensureOpen(); - + writer.setValue(parameterIndex, readBytes(parameterIndex, x, null)); } @Override public void setAsciiStream(int parameterIndex, InputStream x, long length) throws SQLException { ensureOpen(); - + writer.setValue(parameterIndex, readBytes(parameterIndex, x, length)); } @Override public void setUnicodeStream(int parameterIndex, InputStream x, int length) throws SQLException { ensureOpen(); + writer.setValue(parameterIndex, readBytes(parameterIndex, x, (long) length)); } @Override public void setBinaryStream(int parameterIndex, InputStream x, int length) throws SQLException { - ensureOpen(); + setBinaryStream(parameterIndex, x, (long) length); } - @Override public void setBinaryStream(int parameterIndex, InputStream x) throws SQLException { ensureOpen(); - + writer.setValue(parameterIndex, readBytes(parameterIndex, x, null)); } @Override public void setBinaryStream(int parameterIndex, InputStream x, long length) throws SQLException { ensureOpen(); - + writer.setValue(parameterIndex, readBytes(parameterIndex, x, length)); } @Override public void setCharacterStream(int parameterIndex, Reader x, int length) throws SQLException { - ensureOpen(); + setCharacterStream(parameterIndex, x, (long) length); } @Override public void setCharacterStream(int parameterIndex, Reader x, long length) throws SQLException { ensureOpen(); + writer.setString(parameterIndex, readChars(parameterIndex, x, length)); } @Override public void setCharacterStream(int parameterIndex, Reader x) throws SQLException { ensureOpen(); + writer.setString(parameterIndex, readChars(parameterIndex, x, null)); } @Override public void setNCharacterStream(int parameterIndex, Reader x) throws SQLException { - ensureOpen(); - + setCharacterStream(parameterIndex, x); } @Override public void setNCharacterStream(int parameterIndex, Reader x, long length) throws SQLException { - ensureOpen(); + setCharacterStream(parameterIndex, x, length); + } + + /** + * Reads the bytes of a stream parameter. The writer keeps only the value, so the stream is read when + * the parameter is set. + * + * @param parameterIndex index of the parameter, for the error message + * @param x stream, or {@code null} + * @param length number of bytes to read, or {@code null} to read to the end of the stream + * @return the bytes, or {@code null} when {@code x} is {@code null} + * @throws SQLException when the length is negative, the stream ends before {@code length} bytes, + * or the stream cannot be read + */ + private static byte[] readBytes(int parameterIndex, InputStream x, Long length) throws SQLException { + if (x == null) { + return null; + } + checkStreamLength(parameterIndex, length); + ByteArrayOutputStream bytes = new ByteArrayOutputStream(); + byte[] buffer = new byte[STREAM_BUFFER_SIZE]; + long remaining = length == null ? Long.MAX_VALUE : length; + try { + int read; + while (remaining > 0 && (read = x.read(buffer, 0, (int) Math.min(buffer.length, remaining))) != -1) { + bytes.write(buffer, 0, read); + remaining -= read; + } + } catch (IOException e) { + throw new SQLException("Failed to read the stream of parameter " + parameterIndex, + ExceptionUtils.SQL_STATE_SQL_ERROR, e); + } + checkStreamEnd(parameterIndex, length, remaining, "bytes"); + return bytes.toByteArray(); + } + + /** + * Reads the characters of a character stream parameter. The writer keeps only the value, so the + * stream is read when the parameter is set. + * + * @param parameterIndex index of the parameter, for the error message + * @param x reader, or {@code null} + * @param length number of characters to read, or {@code null} to read to the end of the stream + * @return the characters, or {@code null} when {@code x} is {@code null} + * @throws SQLException when the length is negative, the stream ends before {@code length} characters, + * or the stream cannot be read + */ + private static String readChars(int parameterIndex, Reader x, Long length) throws SQLException { + if (x == null) { + return null; + } + checkStreamLength(parameterIndex, length); + StringBuilder chars = new StringBuilder(); + char[] buffer = new char[STREAM_BUFFER_SIZE]; + long remaining = length == null ? Long.MAX_VALUE : length; + try { + int read; + while (remaining > 0 && (read = x.read(buffer, 0, (int) Math.min(buffer.length, remaining))) != -1) { + chars.append(buffer, 0, read); + remaining -= read; + } + } catch (IOException e) { + throw new SQLException("Failed to read the stream of parameter " + parameterIndex, + ExceptionUtils.SQL_STATE_SQL_ERROR, e); + } + checkStreamEnd(parameterIndex, length, remaining, "characters"); + return chars.toString(); + } + private static void checkStreamLength(int parameterIndex, Long length) throws SQLException { + if (length != null && length < 0) { + throw new SQLException("Stream length cannot be negative: " + length + " (parameter " + parameterIndex + + ")", ExceptionUtils.SQL_STATE_CLIENT_ERROR); + } + } + + private static void checkStreamEnd(int parameterIndex, Long length, long remaining, String unit) + throws SQLException { + if (length != null && remaining > 0) { + throw new SQLException("The stream of parameter " + parameterIndex + " ended after " + + (length - remaining) + " of " + length + " " + unit, ExceptionUtils.SQL_STATE_SQL_ERROR); + } } @Override @@ -405,7 +488,7 @@ public void setNull(int parameterIndex, int sqlType, String typeName) throws SQL @Override public void setURL(int parameterIndex, URL x) throws SQLException { ensureOpen(); - + writer.setString(parameterIndex, x == null ? null : x.toString()); } @Override 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 d6c12f96e9..d6bf63a8d4 100644 --- a/jdbc-v2/src/test/java/com/clickhouse/jdbc/WriterStatementImplTest.java +++ b/jdbc-v2/src/test/java/com/clickhouse/jdbc/WriterStatementImplTest.java @@ -6,9 +6,15 @@ import org.testng.annotations.DataProvider; import org.testng.annotations.Test; +import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; +import java.io.InputStream; +import java.io.Reader; +import java.io.StringReader; import java.lang.reflect.Field; +import java.net.URL; +import java.nio.charset.StandardCharsets; import java.sql.Connection; import java.sql.JDBCType; import java.sql.PreparedStatement; @@ -134,6 +140,187 @@ public void testWriterNullIntoDefaultedArrayUsesDefault() throws Exception { } } + @FunctionalInterface + private interface ParameterSetter { + void set(PreparedStatement stmt, int index, String value) throws Exception; + } + + private static InputStream utf8Stream(String value) { + return value == null ? null : new ByteArrayInputStream(value.getBytes(StandardCharsets.UTF_8)); + } + + private static int utf8Length(String value) { + return value == null ? 0 : value.getBytes(StandardCharsets.UTF_8).length; + } + + private static Reader reader(String value) { + return value == null ? null : new StringReader(value); + } + + private static int charLength(String value) { + return value == null ? 0 : value.length(); + } + + @SuppressWarnings("deprecation") + @DataProvider(name = "bytesStreamAndUrlSetters") + public static Object[][] bytesStreamAndUrlSetters() { + String[] text = {"abc", "żółw", "", null}; + String[] ascii = {"abc", "def", "", null}; + return new Object[][] { + {"setBytes", (ParameterSetter) (s, i, v) -> s.setBytes(i, v == null ? null : v.getBytes(StandardCharsets.UTF_8)), text}, + {"setAsciiStream", (ParameterSetter) (s, i, v) -> s.setAsciiStream(i, utf8Stream(v)), ascii}, + {"setAsciiStream(int)", (ParameterSetter) (s, i, v) -> s.setAsciiStream(i, utf8Stream(v), utf8Length(v)), ascii}, + {"setAsciiStream(long)", (ParameterSetter) (s, i, v) -> s.setAsciiStream(i, utf8Stream(v), (long) utf8Length(v)), ascii}, + {"setUnicodeStream", (ParameterSetter) (s, i, v) -> s.setUnicodeStream(i, utf8Stream(v), utf8Length(v)), text}, + {"setBinaryStream", (ParameterSetter) (s, i, v) -> s.setBinaryStream(i, utf8Stream(v)), text}, + {"setBinaryStream(int)", (ParameterSetter) (s, i, v) -> s.setBinaryStream(i, utf8Stream(v), utf8Length(v)), text}, + {"setBinaryStream(long)", (ParameterSetter) (s, i, v) -> s.setBinaryStream(i, utf8Stream(v), (long) utf8Length(v)), text}, + {"setCharacterStream", (ParameterSetter) (s, i, v) -> s.setCharacterStream(i, reader(v)), text}, + {"setCharacterStream(int)", (ParameterSetter) (s, i, v) -> s.setCharacterStream(i, reader(v), charLength(v)), text}, + {"setCharacterStream(long)", (ParameterSetter) (s, i, v) -> s.setCharacterStream(i, reader(v), (long) charLength(v)), text}, + {"setNCharacterStream", (ParameterSetter) (s, i, v) -> s.setNCharacterStream(i, reader(v)), text}, + {"setNCharacterStream(long)", (ParameterSetter) (s, i, v) -> s.setNCharacterStream(i, reader(v), (long) charLength(v)), text}, + {"setURL", (ParameterSetter) (s, i, v) -> s.setURL(i, v == null ? null : new URL(v)), + new String[] {"http://example.com/a", "http://example.com/b", null}}, + }; + } + + @Test(groups = {"integration"}, dataProvider = "bytesStreamAndUrlSetters") + public void testWriterStoresValueOfBytesStreamAndUrlSetters(String setter, ParameterSetter bind, String[] values) + throws Exception { + String table = "writer_stmt_setter_" + 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, n Nullable(String), d String DEFAULT 'x', s String, " + + "tail Int32) ORDER BY id"); + } + + try { + List> expected = new ArrayList<>(); + try (PreparedStatement ps = connection.prepareStatement("INSERT INTO " + table + " VALUES (?, ?, ?, ?, ?)")) { + Assert.assertTrue(ps instanceof WriterStatementImpl); + for (int r = 0; r < values.length; r++) { + String v = values[r]; + String plain = v == null ? values[0] : v; + ps.setInt(1, r + 1); + bind.set(ps, 2, v); + bind.set(ps, 3, v); + bind.set(ps, 4, plain); + ps.setInt(5, 7); + ps.addBatch(); + expected.add(Arrays.asList(r + 1, v, v == null ? "x" : v, plain, 7)); + } + ps.executeBatch(); + } + + List> actual = new ArrayList<>(); + try (Statement stmt = connection.createStatement(); + ResultSet rs = stmt.executeQuery("SELECT id, n, d, s, tail FROM " + table + " ORDER BY id")) { + while (rs.next()) { + actual.add(Arrays.asList(rs.getInt(1), rs.getString(2), rs.getString(3), rs.getString(4), rs.getInt(5))); + } + } + Assert.assertEquals(actual, expected, setter); + } finally { + try (Statement stmt = connection.createStatement()) { + stmt.execute("DROP TABLE IF EXISTS " + table); + } + } + } + } + + @Test(groups = {"integration"}) + public void testWriterStoresRawBytesAndReadsOnlyStreamLength() throws Exception { + String table = "writer_stmt_stream_length_" + 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, f FixedString(3), b String, a String, c String, " + + "tail Int32) ORDER BY id"); + } + + try { + byte[] raw = {0x00, (byte) 0xFF, (byte) 0x80, 0x41}; + InputStream binary = new ByteArrayInputStream(raw); + InputStream ascii = utf8Stream("abcdef"); + Reader chars = reader("żółwik"); + try (PreparedStatement ps = connection.prepareStatement("INSERT INTO " + table + " VALUES (?, ?, ?, ?, ?, ?)")) { + Assert.assertTrue(ps instanceof WriterStatementImpl); + ps.setInt(1, 1); + ps.setBytes(2, Arrays.copyOf(raw, 3)); + ps.setBinaryStream(3, binary, 3L); + ps.setAsciiStream(4, ascii, 3); + ps.setCharacterStream(5, chars, 4L); + ps.setInt(6, 7); + Assert.assertEquals(ps.executeUpdate(), 1); + } + Assert.assertEquals(binary.read(), 0x41); + Assert.assertEquals(ascii.read(), 'd'); + Assert.assertEquals(chars.read(), 'i'); + + try (Statement stmt = connection.createStatement(); + ResultSet rs = stmt.executeQuery("SELECT id, hex(f), hex(b), a, c, tail FROM " + table)) { + Assert.assertTrue(rs.next()); + Assert.assertEquals(Arrays.asList(rs.getInt(1), rs.getString(2), rs.getString(3), rs.getString(4), + rs.getString(5), rs.getInt(6)), + Arrays.asList(1, "00FF80", "00FF80", "abc", "żółw", 7)); + Assert.assertFalse(rs.next()); + } + } finally { + try (Statement stmt = connection.createStatement()) { + stmt.execute("DROP TABLE IF EXISTS " + table); + } + } + } + } + + @DataProvider(name = "unreadableStreams") + public static Object[][] unreadableStreams() { + InputStream failingStream = new InputStream() { + @Override + public int read() throws IOException { + throw new IOException("injected read failure"); + } + }; + Reader failingReader = new Reader() { + @Override + public int read(char[] buffer, int offset, int length) throws IOException { + throw new IOException("injected read failure"); + } + + @Override + public void close() { + } + }; + return new Object[][] { + {"setBinaryStream shorter than length", (ParameterSetter) (s, i, v) -> s.setBinaryStream(i, utf8Stream("ab"), 3L), "07000"}, + {"setCharacterStream shorter than length", (ParameterSetter) (s, i, v) -> s.setCharacterStream(i, reader("ab"), 3L), "07000"}, + {"setBinaryStream negative length", (ParameterSetter) (s, i, v) -> s.setBinaryStream(i, utf8Stream("ab"), -1), "HY000"}, + {"setCharacterStream negative length", (ParameterSetter) (s, i, v) -> s.setCharacterStream(i, reader("ab"), -1), "HY000"}, + {"setBinaryStream read failure", (ParameterSetter) (s, i, v) -> s.setBinaryStream(i, failingStream), "07000"}, + {"setCharacterStream read failure", (ParameterSetter) (s, i, v) -> s.setCharacterStream(i, failingReader), "07000"}, + }; + } + + @Test(groups = {"integration"}, dataProvider = "unreadableStreams") + public void testWriterStreamSetterFailsForUnreadableStream(String setter, ParameterSetter bind, String sqlState) + throws Exception { + Properties properties = new Properties(); + properties.setProperty(DriverProperties.BETA_ROW_BINARY_WRITER.getKey(), "true"); + try (Connection connection = getJdbcConnection(properties); + PreparedStatement ps = connection.prepareStatement("INSERT INTO system.numbers VALUES (?)")) { + Assert.assertTrue(ps instanceof WriterStatementImpl); + SQLException thrown = Assert.expectThrows(SQLException.class, () -> bind.set(ps, 1, null)); + Assert.assertEquals(thrown.getSQLState(), sqlState, setter); + Assert.assertTrue(thrown.getMessage().contains("parameter 1"), thrown.getMessage()); + } + } + private static boolean hasNonNullableColumnMessage(Throwable thrown) { for (Throwable t = thrown; t != null; t = t.getCause()) { if (t.getMessage() != null && t.getMessage().contains("An attempt to write null into not nullable column")) {