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
6 changes: 6 additions & 0 deletions history/latest/3422.md
Original file line number Diff line number Diff line change
@@ -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)
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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;

Expand All @@ -52,6 +54,7 @@ public class WriterStatementImpl extends PreparedStatementImpl implements Prepar
private ByteArrayOutputStream out;
private ClickHouseBinaryFormatWriter writer;
private final TableSchema tableSchema;
private final List<String> insertColumnNames;

public WriterStatementImpl(ConnectionImpl connection, String originalSql, TableSchema tableSchema,
ParsedPreparedStatement parsedStatement)
Expand All @@ -60,13 +63,17 @@ public WriterStatementImpl(ConnectionImpl connection, String originalSql, TableS

if (parsedStatement.getInsertColumns() != null) {
List<ClickHouseColumn> insertColumns = new ArrayList<>();
List<String> 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;
Comment thread
cursor[bot] marked this conversation as resolved.
Resolved
} else {
this.tableSchema = tableSchema;
this.insertColumnNames = Collections.emptyList();
}
try {
resetWriter();
Expand Down Expand Up @@ -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) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down Expand Up @@ -229,6 +240,123 @@ private List<String> processRoles(Map<String, String> 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<String> 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');
}
Comment thread
cursor[bot] marked this conversation as resolved.
Resolved

public ClickHouseSqlStatement parse(String sql) {
JdbcParseHandler handler = JdbcParseHandler.getInstance();
ClickHouseSqlStatement[] stmts = ClickHouseSqlParser.parse(sql, handler);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
}
}
Loading