From 6a4ec6707877f88f969c2603b1a334a4abba8791 Mon Sep 17 00:00:00 2001 From: Saad Fikri Date: Sat, 28 Nov 2026 10:45:25 +0000 Subject: [PATCH] [jdbc-v2] RowBinary writer: respect the INSERT column list The JavaCC parser never extracted the column list from INSERT statements, so the RowBinary writer always fell back to the full table schema. When columns were reordered or a subset was used, values ended up in the wrong columns or the server rejected the payload. - JavaCCParser.extractInsertColumns() now reads the ColumnsStart/ColumnsEnd positions recorded by the grammar and tokenizes the column list, handling quoted identifiers, dollar signs, nested names, and inline comments. - WriterStatementImpl passes the extracted column names to Client.insert(), quoting them with SQLUtils.enquoteIdentifier() so reserved words and special characters are safe. - Added unit tests for edge cases (dollar signs, comments in column lists) and integration tests for column reordering, subsets, batch inserts, and quoted columns across all three parser backends. Closes #3422 --- history/latest/3422.md | 6 + .../clickhouse/jdbc/WriterStatementImpl.java | 11 +- .../jdbc/internal/SqlParserFacade.java | 128 +++++++++++++ .../jdbc/WriterStatementImplTest.java | 172 ++++++++++++++++++ .../internal/BaseSqlParserFacadeTest.java | 18 +- 5 files changed, 326 insertions(+), 9 deletions(-) create mode 100644 history/latest/3422.md diff --git a/history/latest/3422.md b/history/latest/3422.md new file mode 100644 index 0000000000..15a91de6c4 --- /dev/null +++ b/history/latest/3422.md @@ -0,0 +1,6 @@ +- **[jdbc-v2]** Fixed the RowBinary writer ignoring the INSERT column list. With + `beta.row_binary_for_simple_insert=true`, `INSERT INTO t (b, a) VALUES (?, ?)` was writing + values in table order instead of statement order, and column subsets like `INSERT INTO t (k, b)` + on a wider table wrote into the wrong columns. The JavaCC parser now extracts the column list + (the ANTLR4 backends already did), and `executeLargeUpdate()` passes the columns to the server. + (https://github.com/ClickHouse/clickhouse-java/issues/3422) 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..41866885d3 100644 --- a/jdbc-v2/src/main/java/com/clickhouse/jdbc/WriterStatementImpl.java +++ b/jdbc-v2/src/main/java/com/clickhouse/jdbc/WriterStatementImpl.java @@ -6,6 +6,7 @@ import com.clickhouse.client.api.insert.InsertResponse; import com.clickhouse.client.api.insert.InsertSettings; import com.clickhouse.client.api.metadata.TableSchema; +import com.clickhouse.client.api.sql.SQLUtils; import com.clickhouse.data.ClickHouseColumn; import com.clickhouse.data.ClickHouseFormat; import com.clickhouse.jdbc.internal.ExceptionUtils; @@ -34,6 +35,7 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; +import java.util.Collections; import java.util.List; import java.util.concurrent.TimeUnit; @@ -52,6 +54,7 @@ public class WriterStatementImpl extends PreparedStatementImpl implements Prepar private ByteArrayOutputStream out; private ClickHouseBinaryFormatWriter writer; private final TableSchema tableSchema; + private final List insertColumnNames; public WriterStatementImpl(ConnectionImpl connection, String originalSql, TableSchema tableSchema, ParsedPreparedStatement parsedStatement) @@ -60,13 +63,17 @@ public WriterStatementImpl(ConnectionImpl connection, String originalSql, TableS if (parsedStatement.getInsertColumns() != null) { List insertColumns = new ArrayList<>(); + List colNames = new ArrayList<>(); for (String column : parsedStatement.getInsertColumns()) { insertColumns.add(tableSchema.getColumnByName(column)); + colNames.add(SQLUtils.enquoteIdentifier(column, false)); } this.tableSchema = new TableSchema(tableSchema.getTableName(), tableSchema.getQuery(), tableSchema.getDatabaseName(), insertColumns); + this.insertColumnNames = colNames; } else { this.tableSchema = tableSchema; + this.insertColumnNames = Collections.emptyList(); } try { resetWriter(); @@ -124,8 +131,8 @@ public long executeLargeUpdate() throws SQLException { settings.setQueryId(setLastQueryID(settings.getQueryId())); try (InsertResponse response = queryTimeout == 0 ? - connection.getClient().insert(tableSchema.getTableName(),in, writer.getFormat(), settings).get() - : connection.getClient().insert(tableSchema.getTableName(),in, writer.getFormat(), settings).get(queryTimeout, TimeUnit.SECONDS)) { + connection.getClient().insert(tableSchema.getTableName(), insertColumnNames, in, writer.getFormat(), settings).get() + : connection.getClient().insert(tableSchema.getTableName(), insertColumnNames, in, writer.getFormat(), settings).get(queryTimeout, TimeUnit.SECONDS)) { updateCount = Math.max(0, (int) response.getWrittenRows()); // when statement alters schema no result rows returned. lastQueryId = response.getQueryId(); } catch (Exception e) { diff --git a/jdbc-v2/src/main/java/com/clickhouse/jdbc/internal/SqlParserFacade.java b/jdbc-v2/src/main/java/com/clickhouse/jdbc/internal/SqlParserFacade.java index c452f0db62..36728f48ab 100644 --- a/jdbc-v2/src/main/java/com/clickhouse/jdbc/internal/SqlParserFacade.java +++ b/jdbc-v2/src/main/java/com/clickhouse/jdbc/internal/SqlParserFacade.java @@ -99,6 +99,17 @@ public ParsedPreparedStatement parsePreparedStatement(String sql) { stmt.setInsertWithSelect(parsedStmt.containsKeyword("SELECT") && (parsedStmt.getStatementType() == StatementType.INSERT)); stmt.setAssignValuesGroups(parsedStmt.getValueGroups()); + // Extract the INSERT column list from the ColumnsStart/ColumnsEnd positions recorded by the + // grammar, so the RowBinary writer knows which columns the statement addresses and in what + // order. Without this, the writer falls back to the full table schema and values end up in + // the wrong columns when the INSERT lists columns in a different order or omits some. + if (parsedStmt.getStatementType() == StatementType.INSERT) { + String[] insertColumns = extractInsertColumns(parsedStmt); + if (insertColumns != null) { + stmt.setInsertColumns(insertColumns); + } + } + Integer startIndex = parsedStmt.getPositions().get(ClickHouseSqlStatement.KEYWORD_VALUES_START); Integer endIndexValue = parsedStmt.getPositions().get(ClickHouseSqlStatement.KEYWORD_VALUES_END); if (startIndex != null && endIndexValue != null) { @@ -229,6 +240,123 @@ private List processRoles(Map settings) { } + /** + * Extracts the column names from the INSERT column list recorded by the grammar between + * {@code ColumnsStart} and {@code ColumnsEnd}. Each identifier is unescaped so that + * backtick-quoted or double-quoted names match the plain names in the table schema. + * Nested identifiers ({@code `directory`.`id`}) are rejoined with {@code '.'}, mirroring + * the ANTLR4 parser behavior. + * + * @return the column names in statement order, or {@code null} when there is no column list + */ + private static String[] extractInsertColumns(ClickHouseSqlStatement parsedStmt) { + Integer colStart = parsedStmt.getPositions().get(ClickHouseSqlStatement.KEYWORD_TABLE_COLUMNS_START); + Integer colEnd = parsedStmt.getPositions().get(ClickHouseSqlStatement.KEYWORD_TABLE_COLUMNS_END); + if (colStart == null || colEnd == null) { + return null; + } + + // The content between the parentheses, e.g. "a, `b c`, `dir`.`id`" + String content = parsedStmt.getContentBetweenKeywords( + ClickHouseSqlStatement.KEYWORD_TABLE_COLUMNS_START, + ClickHouseSqlStatement.KEYWORD_TABLE_COLUMNS_END, 1); + if (content.isEmpty()) { + return null; + } + + // Tokenize by commas, respecting quoted identifiers. The rebuilt SQL may contain + // comments (-- ... or /* ... */) because the JavaCC token manager appends them to the + // builder, so the loop must skip them. Dollar signs are part of identifiers in + // ClickHouse (the server accepts e.g. col$1), matching skipIdentifier() in this class. + List columns = new ArrayList<>(); + int len = content.length(); + int i = 0; + while (i < len) { + char ch = content.charAt(i); + + // Skip whitespace and commas between identifiers + if (ch == ',' || Character.isWhitespace(ch)) { + i++; + continue; + } + + // Skip single-line comments: --, //, # + if (ch == '#' || (i + 1 < len && content.charAt(i + 1) == ch && (ch == '-' || ch == '/'))) { + i = skipLineComment(content, ch == '#' ? i : i + 1, len); + continue; + } + + // Skip block comments: /* ... */ + if (ch == '/' && i + 1 < len && content.charAt(i + 1) == '*') { + i = ClickHouseUtils.skipMultiLineComment(content, i + 2, len); + continue; + } + + // Collect one possibly-nested identifier (components separated by '.') + StringBuilder column = new StringBuilder(); + boolean first = true; + while (i < len) { + if (!first) { + column.append('.'); + } + first = false; + + ch = content.charAt(i); + if (ClickHouseSqlUtils.isQuote(ch)) { + // Quoted identifier: find matching closing quote (with escape handling) + int start = i; + i++; + while (i < len) { + char c = content.charAt(i); + if (c == '\\') { + i += 2; // skip escaped character + } else if (c == ch) { + if (i + 1 < len && content.charAt(i + 1) == ch) { + i += 2; // doubled quote escape + } else { + i++; // closing quote + break; + } + } else { + i++; + } + } + column.append(ClickHouseSqlUtils.unescape(content.substring(start, i))); + } else if (isIdentifierChar(ch)) { + // Unquoted identifier: word characters and dollar signs + int start = i; + while (i < len && isIdentifierChar(content.charAt(i))) { + i++; + } + column.append(content.substring(start, i)); + } else { + // Unexpected character — skip it to guarantee forward progress + i++; + first = true; // undo the dot we didn't actually add + continue; + } + + // Check if followed by '.' (nested identifier continues) + if (i < len && content.charAt(i) == '.') { + i++; // skip the dot, loop continues to read next component + } else { + break; // end of this identifier + } + } + + if (column.length() > 0) { + columns.add(column.toString()); + } + } + + return columns.isEmpty() ? null : columns.toArray(new String[0]); + } + + private static boolean isIdentifierChar(char ch) { + return ch == '_' || ch == '$' || (ch >= '0' && ch <= '9') + || (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z'); + } + public ClickHouseSqlStatement parse(String sql) { JdbcParseHandler handler = JdbcParseHandler.getInstance(); ClickHouseSqlStatement[] stmts = ClickHouseSqlParser.parse(sql, handler); 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..57dac0b056 100644 --- a/jdbc-v2/src/test/java/com/clickhouse/jdbc/WriterStatementImplTest.java +++ b/jdbc-v2/src/test/java/com/clickhouse/jdbc/WriterStatementImplTest.java @@ -435,4 +435,176 @@ private static boolean hasInjectedCause(Throwable t) { } return false; } + + // --- Tests for issue #3422: RowBinary writer must respect the INSERT column list --- + + @DataProvider(name = "allParsers") + Object[][] allParsers() { + return new Object[][]{ + {"JAVACC"}, + {"ANTLR4"}, + {"ANTLR4_PARAMS_PARSER"}, + }; + } + + /** + * INSERT INTO t (b, a) VALUES (?, ?) must store parameter 1 into column b and parameter 2 into + * column a, not the other way around. Before the fix, the writer ignored the column list and + * wrote values in the table's column order. + */ + @Test(groups = {"integration"}, dataProvider = "allParsers") + public void testInsertColumnReordering(String parser) throws SQLException { + String table = "bt_writer_col_reorder_" + parser.toLowerCase(); + Properties properties = new Properties(); + properties.setProperty(DriverProperties.BETA_ROW_BINARY_WRITER.getKey(), "true"); + properties.setProperty(DriverProperties.SQL_PARSER.getKey(), parser); + properties.setProperty(ASYNC_INSERT_SETTING_KEY, ServerSettings.OFF); + try (Connection connection = getJdbcConnection(properties)) { + try (Statement stmt = connection.createStatement()) { + stmt.execute("DROP TABLE IF EXISTS " + table); + stmt.execute("CREATE TABLE " + table + " (a Int32, b Int32) ORDER BY ()"); + } + + try (PreparedStatement ps = connection.prepareStatement( + "INSERT INTO " + table + " (b, a) VALUES (?, ?)")) { + Assert.assertTrue(ps instanceof WriterStatementImpl, + "Expected WriterStatementImpl for parser " + parser); + ps.setInt(1, 10); // b = 10 + ps.setInt(2, 20); // a = 20 + Assert.assertEquals(ps.executeUpdate(), 1); + } + + try (Statement stmt = connection.createStatement(); + ResultSet rs = stmt.executeQuery("SELECT a, b FROM " + table)) { + Assert.assertTrue(rs.next()); + Assert.assertEquals(rs.getInt("a"), 20); + Assert.assertEquals(rs.getInt("b"), 10); + Assert.assertFalse(rs.next()); + } + } finally { + runQuery("DROP TABLE IF EXISTS " + table); + } + } + + /** + * INSERT INTO t (k, b) VALUES (?, ?) on a table (k Int32, a Nullable(Int32), b Nullable(Int32)) + * must leave column a as NULL. + */ + @Test(groups = {"integration"}, dataProvider = "allParsers") + public void testInsertColumnSubset(String parser) throws SQLException { + String table = "bt_writer_col_subset_" + parser.toLowerCase(); + Properties properties = new Properties(); + properties.setProperty(DriverProperties.BETA_ROW_BINARY_WRITER.getKey(), "true"); + properties.setProperty(DriverProperties.SQL_PARSER.getKey(), parser); + properties.setProperty(ASYNC_INSERT_SETTING_KEY, ServerSettings.OFF); + try (Connection connection = getJdbcConnection(properties)) { + try (Statement stmt = connection.createStatement()) { + stmt.execute("DROP TABLE IF EXISTS " + table); + stmt.execute("CREATE TABLE " + table + + " (k Int32, a Nullable(Int32), b Nullable(Int32)) ORDER BY ()"); + } + + try (PreparedStatement ps = connection.prepareStatement( + "INSERT INTO " + table + " (k, b) VALUES (?, ?)")) { + Assert.assertTrue(ps instanceof WriterStatementImpl, + "Expected WriterStatementImpl for parser " + parser); + ps.setInt(1, 1); // k = 1 + ps.setInt(2, 42); // b = 42 + Assert.assertEquals(ps.executeUpdate(), 1); + } + + try (Statement stmt = connection.createStatement(); + ResultSet rs = stmt.executeQuery("SELECT k, a, b FROM " + table)) { + Assert.assertTrue(rs.next()); + Assert.assertEquals(rs.getInt("k"), 1); + Assert.assertNull(rs.getObject("a"), "Column a should be NULL"); + Assert.assertEquals(rs.getInt("b"), 42); + Assert.assertFalse(rs.next()); + } + } finally { + runQuery("DROP TABLE IF EXISTS " + table); + } + } + + /** + * executeBatch with a reordered column list must place values in the correct columns. + */ + @Test(groups = {"integration"}, dataProvider = "allParsers") + public void testBatchInsertColumnReordering(String parser) throws SQLException { + String table = "bt_writer_batch_reorder_" + parser.toLowerCase(); + Properties properties = new Properties(); + properties.setProperty(DriverProperties.BETA_ROW_BINARY_WRITER.getKey(), "true"); + properties.setProperty(DriverProperties.SQL_PARSER.getKey(), parser); + properties.setProperty(ASYNC_INSERT_SETTING_KEY, ServerSettings.OFF); + try (Connection connection = getJdbcConnection(properties)) { + try (Statement stmt = connection.createStatement()) { + stmt.execute("DROP TABLE IF EXISTS " + table); + stmt.execute("CREATE TABLE " + table + " (a Int32, b String) ORDER BY ()"); + } + + try (PreparedStatement ps = connection.prepareStatement( + "INSERT INTO " + table + " (b, a) VALUES (?, ?)")) { + Assert.assertTrue(ps instanceof WriterStatementImpl, + "Expected WriterStatementImpl for parser " + parser); + ps.setString(1, "row1"); // b + ps.setInt(2, 1); // a + ps.addBatch(); + ps.setString(1, "row2"); // b + ps.setInt(2, 2); // a + ps.addBatch(); + int[] results = ps.executeBatch(); + Assert.assertEquals(results.length, 2); + } + + try (Statement stmt = connection.createStatement(); + ResultSet rs = stmt.executeQuery("SELECT a, b FROM " + table + " ORDER BY a")) { + Assert.assertTrue(rs.next()); + Assert.assertEquals(rs.getInt("a"), 1); + Assert.assertEquals(rs.getString("b"), "row1"); + Assert.assertTrue(rs.next()); + Assert.assertEquals(rs.getInt("a"), 2); + Assert.assertEquals(rs.getString("b"), "row2"); + Assert.assertFalse(rs.next()); + } + } finally { + runQuery("DROP TABLE IF EXISTS " + table); + } + } + + /** + * Backtick-quoted column names must be matched to the table schema correctly. + */ + @Test(groups = {"integration"}, dataProvider = "allParsers") + public void testInsertQuotedColumnReordering(String parser) throws SQLException { + String table = "bt_writer_quoted_reorder_" + parser.toLowerCase(); + Properties properties = new Properties(); + properties.setProperty(DriverProperties.BETA_ROW_BINARY_WRITER.getKey(), "true"); + properties.setProperty(DriverProperties.SQL_PARSER.getKey(), parser); + properties.setProperty(ASYNC_INSERT_SETTING_KEY, ServerSettings.OFF); + try (Connection connection = getJdbcConnection(properties)) { + try (Statement stmt = connection.createStatement()) { + stmt.execute("DROP TABLE IF EXISTS " + table); + stmt.execute("CREATE TABLE " + table + " (a Int32, b Int32) ORDER BY ()"); + } + + try (PreparedStatement ps = connection.prepareStatement( + "INSERT INTO " + table + " (`b`, `a`) VALUES (?, ?)")) { + Assert.assertTrue(ps instanceof WriterStatementImpl, + "Expected WriterStatementImpl for parser " + parser); + ps.setInt(1, 10); // b = 10 + ps.setInt(2, 20); // a = 20 + Assert.assertEquals(ps.executeUpdate(), 1); + } + + try (Statement stmt = connection.createStatement(); + ResultSet rs = stmt.executeQuery("SELECT a, b FROM " + table)) { + Assert.assertTrue(rs.next()); + Assert.assertEquals(rs.getInt("a"), 20); + Assert.assertEquals(rs.getInt("b"), 10); + Assert.assertFalse(rs.next()); + } + } finally { + runQuery("DROP TABLE IF EXISTS " + table); + } + } } diff --git a/jdbc-v2/src/test/java/com/clickhouse/jdbc/internal/BaseSqlParserFacadeTest.java b/jdbc-v2/src/test/java/com/clickhouse/jdbc/internal/BaseSqlParserFacadeTest.java index 316448a938..a0ddc57649 100644 --- a/jdbc-v2/src/test/java/com/clickhouse/jdbc/internal/BaseSqlParserFacadeTest.java +++ b/jdbc-v2/src/test/java/com/clickhouse/jdbc/internal/BaseSqlParserFacadeTest.java @@ -712,6 +712,16 @@ public void testInsertColumnNamesAreUnescaped() { // for both the doubled (``) and backslash-escaped (\`) forms assertInsertColumns("INSERT INTO t (`od``d`) VALUES (?)", "od`d"); assertInsertColumns("INSERT INTO t (`od\\`d`) VALUES (?)", "od`d"); + + // Dollar sign in unquoted identifier (ClickHouse allows col$1) + assertInsertColumns("INSERT INTO t (col$1, col$2) VALUES (?, ?)", "col$1", "col$2"); + assertInsertColumns("INSERT INTO t ($col) VALUES (?)", "$col"); + + // Column list with inline block comment + assertInsertColumns("INSERT INTO t (a /* first */, b) VALUES (?, ?)", "a", "b"); + + // Column list with trailing single-line comment + assertInsertColumns("INSERT INTO t (a, b -- columns\n) VALUES (?, ?)", "a", "b"); } private void assertInsertColumns(String sql, String... expectedColumns) { @@ -719,13 +729,7 @@ private void assertInsertColumns(String sql, String... expectedColumns) { Assert.assertFalse(stmt.isHasErrors(), "Query should parse without errors: " + sql); Assert.assertTrue(stmt.isInsert(), "Should be an INSERT: " + sql); String[] actualColumns = stmt.getInsertColumns(); - // The JavaCC backend does not extract INSERT column names, so null is allowed there. The - // ANTLR4 backends must extract them, so a null is a regression and must fail the test - // loudly instead of being silently skipped. - if (javaCcBackend) { - return; - } - Assert.assertNotNull(actualColumns, "ANTLR4 backend should extract INSERT column names for: " + sql); + Assert.assertNotNull(actualColumns, "All backends should extract INSERT column names for: " + sql); Assert.assertEquals(actualColumns, expectedColumns, "Insert column names mismatch for: " + sql); }