diff --git a/docs/features.md b/docs/features.md index a8f7e12b3..66519fe05 100644 --- a/docs/features.md +++ b/docs/features.md @@ -123,7 +123,7 @@ Compatibility-sensitive traits: - Stream and reader setters (`setAsciiStream`, `setUnicodeStream`, `setBinaryStream`, `setCharacterStream`, `setNCharacterStream`) are treated as text input encoded with the same string-escaping rules, including length-based truncation when a length is supplied. - `getString()` formatting for temporal values is stable output: `Date` uses `yyyy-MM-dd`, `DateTime` uses `yyyy-MM-dd HH:mm:ss`, and `DateTime64` preserves fractional precision, all interpreted in server timezone context where applicable. - Date and timestamp setters with `Calendar` are timezone-sensitive by design. Preserving the current day-shift and instant-preserving behavior is important for compatibility. -- `setObject()` temporal behavior is specific and should not drift: `LocalDateTime` and `Instant` are rendered through `fromUnixTimestamp64Nano(...)`, while `Timestamp` and `Date` use quoted textual forms. +- Text `setObject()` quotes `Timestamp`/`Date` and uses `fromUnixTimestamp64Nano(...)` for `LocalDateTime`/`Instant`. RowBinary `Date`/`Date32` take `java.sql.Date` in known table order. - JDBC `ssl_mode` handling is compatibility-sensitive: values are case-insensitive, `none` is aliased to `trust` (the no-verification mode), and an unrecognized value throws `SQLException` during connection configuration. The normalized canonical mode name is forwarded to the underlying `client-v2` transport. - Connection `Properties` values must be strings, with one scoped exception: the `ssl_context` key may carry a live `javax.net.ssl.SSLContext` object. Any other non-string property value still throws `IllegalArgumentException` during connection configuration. A string `ssl_context` (supplied via `setProperty` or a URL query parameter) is rejected with `SQLException`, since a string cannot represent a live context. - INSERT result semantics depend on server-side `async_insert` and `wait_for_async_insert`. The driver does not override these settings, so it follows whatever the server profile or user configuration sets. When `async_insert=1` and `wait_for_async_insert=0`, `Statement.executeUpdate(...)` and `PreparedStatement.executeUpdate(...)` may return `0` (or an under-counted value), and parsing/data errors in the INSERT body may not be reported synchronously as a `SQLException`. Set `async_insert=0` (or `wait_for_async_insert=1`) per connection or statement to restore synchronous row counts and error reporting. diff --git a/history/latest/3386.md b/history/latest/3386.md new file mode 100644 index 000000000..0972e957f --- /dev/null +++ b/history/latest/3386.md @@ -0,0 +1,3 @@ +- **[jdbc-v2]** Fixed RowBinary prepared inserts with `setObject(..., java.sql.Date)` when parameters are known to follow + the table's writable column order. `Date` and `Date32` parameters use the same calendar conversion as `setDate(...)`. + (https://github.com/ClickHouse/clickhouse-java/issues/3386) 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 a01944f5d..0c62a0706 100644 --- a/jdbc-v2/src/main/java/com/clickhouse/jdbc/WriterStatementImpl.java +++ b/jdbc-v2/src/main/java/com/clickhouse/jdbc/WriterStatementImpl.java @@ -7,6 +7,7 @@ import com.clickhouse.client.api.insert.InsertSettings; import com.clickhouse.client.api.metadata.TableSchema; import com.clickhouse.data.ClickHouseColumn; +import com.clickhouse.data.ClickHouseDataType; import com.clickhouse.data.ClickHouseFormat; import com.clickhouse.jdbc.internal.ExceptionUtils; import com.clickhouse.jdbc.internal.ParsedPreparedStatement; @@ -52,6 +53,7 @@ public class WriterStatementImpl extends PreparedStatementImpl implements Prepar private ByteArrayOutputStream out; private ClickHouseBinaryFormatWriter writer; private final TableSchema tableSchema; + private final boolean usesTableColumnOrder; public WriterStatementImpl(ConnectionImpl connection, String originalSql, TableSchema tableSchema, ParsedPreparedStatement parsedStatement) @@ -68,6 +70,13 @@ public WriterStatementImpl(ConnectionImpl connection, String originalSql, TableS } else { this.tableSchema = tableSchema; } + // The wire insert has no column list, and the writer skips generated columns. + List columns = this.tableSchema.getColumns(); + this.usesTableColumnOrder = !parsedStatement.hasUnresolvedInsertColumns() + && columns.equals(tableSchema.getColumns()) + && (!this.tableSchema.hasDefaults() || columns.stream().limit(parsedStatement.getArgCount()) + .noneMatch(column -> column.hasDefault() + && column.getDefaultValue() != ClickHouseColumn.DefaultValue.DEFAULT)); try { resetWriter(); } catch (IOException e) { @@ -435,6 +444,13 @@ public void setObject(int parameterIndex, Object x, int targetSqlType) throws SQ @Override public void setObject(int parameterIndex, Object x) throws SQLException { ensureOpen(); + if (usesTableColumnOrder && x instanceof Date) { + ClickHouseDataType type = tableSchema.getColumnByIndex(parameterIndex).getDataType(); + if (type == ClickHouseDataType.Date || type == ClickHouseDataType.Date32) { + setDate(parameterIndex, (Date) x); + return; + } + } writer.setValue(parameterIndex, x); } diff --git a/jdbc-v2/src/main/java/com/clickhouse/jdbc/internal/ParsedPreparedStatement.java b/jdbc-v2/src/main/java/com/clickhouse/jdbc/internal/ParsedPreparedStatement.java index 173d92f5c..ab3b25227 100644 --- a/jdbc-v2/src/main/java/com/clickhouse/jdbc/internal/ParsedPreparedStatement.java +++ b/jdbc-v2/src/main/java/com/clickhouse/jdbc/internal/ParsedPreparedStatement.java @@ -16,6 +16,8 @@ public final class ParsedPreparedStatement { private String[] insertColumns; + private boolean unresolvedInsertColumns; + private boolean useFunction; private boolean hasErrors; @@ -74,6 +76,14 @@ public void setInsertColumns(String[] insertColumns) { this.insertColumns = insertColumns; } + public boolean hasUnresolvedInsertColumns() { + return unresolvedInsertColumns; + } + + public void setUnresolvedInsertColumns(boolean unresolvedInsertColumns) { + this.unresolvedInsertColumns = unresolvedInsertColumns; + } + public String getTable() { return table; } 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 c452f0db6..df616b704 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,10 +99,11 @@ public ParsedPreparedStatement parsePreparedStatement(String sql) { stmt.setInsertWithSelect(parsedStmt.containsKeyword("SELECT") && (parsedStmt.getStatementType() == StatementType.INSERT)); stmt.setAssignValuesGroups(parsedStmt.getValueGroups()); - Integer startIndex = parsedStmt.getPositions().get(ClickHouseSqlStatement.KEYWORD_VALUES_START); - Integer endIndexValue = parsedStmt.getPositions().get(ClickHouseSqlStatement.KEYWORD_VALUES_END); - if (startIndex != null && endIndexValue != null) { - int endIndex = endIndexValue; + Map positions = parsedStmt.getPositions(); + stmt.setUnresolvedInsertColumns(positions.containsKey(ClickHouseSqlStatement.KEYWORD_TABLE_COLUMNS_START)); + Integer startIndex = positions.get(ClickHouseSqlStatement.KEYWORD_VALUES_START); + Integer endIndex = positions.get(ClickHouseSqlStatement.KEYWORD_VALUES_END); + if (startIndex != null && endIndex != null) { stmt.setAssignValuesListStartPosition(startIndex); stmt.setAssignValuesListStopPosition(endIndex); String query = parsedStmt.getSQL(); @@ -129,11 +130,8 @@ public ParsedPreparedStatement parsePreparedStatement(String sql) { } /** - * The token manager records keyword positions as offsets into the SQL it rebuilds from the token stream, which - * is not always identical to the SQL it was given: semicolons are dropped and JDBC escape sequences are - * rewritten. Consumers of the values list positions slice the original SQL, so when the two have drifted apart - * the positions address the wrong characters or point past the end of the string. Discard them in that case to - * let the generic parameter substitution path handle the statement. + * Offsets refer to JavaCC's rebuilt SQL, which may omit semicolons or rewrite JDBC escapes. + * Discard offsets that do not match the original SQL so generic parameter substitution can handle the insert. */ private void discardValuesListPositionsNotMatchingOriginalSql(String sql, ParsedPreparedStatement stmt) { int startPosition = stmt.getAssignValuesListStartPosition(); diff --git a/jdbc-v2/src/test/java/com/clickhouse/jdbc/JDBCDateTimeTests.java b/jdbc-v2/src/test/java/com/clickhouse/jdbc/JDBCDateTimeTests.java index 10094ad63..ffcc1ce6b 100644 --- a/jdbc-v2/src/test/java/com/clickhouse/jdbc/JDBCDateTimeTests.java +++ b/jdbc-v2/src/test/java/com/clickhouse/jdbc/JDBCDateTimeTests.java @@ -6,6 +6,7 @@ import com.clickhouse.client.api.DataTypeUtils; import com.clickhouse.client.api.internal.ServerSettings; import org.testng.Assert; +import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import java.sql.Array; @@ -88,6 +89,110 @@ void testDaysBeforeBirthdayParty() throws SQLException { } } + @DataProvider + public static Object[][] rowBinaryDateInsertOrder() { + return new Object[][] {{"JAVACC", false}, {"ANTLR4", true}}; + } + + @Test(groups = {"integration"}, dataProvider = "rowBinaryDateInsertOrder") + void testRowBinarySetObjectWithSqlDate(String parser, boolean explicitColumns) throws SQLException { + Properties properties = new Properties(); + properties.setProperty(DriverProperties.BETA_ROW_BINARY_WRITER.getKey(), "true"); + properties.setProperty(DriverProperties.SQL_PARSER.getKey(), parser); + String table = "test_row_binary_sql_date_" + parser; + String columns = explicitColumns ? " (id, d, d32, nullable_date, tail)" : ""; + try (Connection connection = getJdbcConnection(properties); + Statement statement = connection.createStatement()) { + statement.executeUpdate("CREATE TABLE " + table + + " (id Int32, d Date, d32 Date32, nullable_date Nullable(Date32), tail Int32) ORDER BY id"); + + try (PreparedStatement insert = connection.prepareStatement( + "INSERT INTO " + table + columns + " VALUES (?, ?, ?, ?, ?)")) { + Assert.assertTrue(insert instanceof WriterStatementImpl); + insert.setInt(1, 1); + insert.setObject(2, Date.valueOf("2013-07-15")); + insert.setObject(3, Date.valueOf("1965-12-31")); + insert.setObject(4, Date.valueOf("1999-12-31")); + insert.setInt(5, 42); + insert.addBatch(); + + insert.setInt(1, 2); + insert.setDate(2, Date.valueOf("2013-07-15")); + insert.setDate(3, Date.valueOf("1965-12-31")); + insert.setObject(4, null); + insert.setInt(5, 43); + insert.addBatch(); + insert.executeBatch(); + } + + try (ResultSet rows = statement.executeQuery( + "SELECT id, toString(d), toString(d32), toString(nullable_date), tail " + + "FROM " + table + " ORDER BY id")) { + Assert.assertTrue(rows.next()); + Assert.assertEquals(rows.getInt(1), 1); + Assert.assertEquals(rows.getString(2), "2013-07-15"); + Assert.assertEquals(rows.getString(3), "1965-12-31"); + Assert.assertEquals(rows.getString(4), "1999-12-31"); + Assert.assertEquals(rows.getInt(5), 42); + Assert.assertTrue(rows.next()); + Assert.assertEquals(rows.getInt(1), 2); + Assert.assertEquals(rows.getString(2), "2013-07-15"); + Assert.assertEquals(rows.getString(3), "1965-12-31"); + Assert.assertNull(rows.getString(4)); + Assert.assertEquals(rows.getInt(5), 43); + Assert.assertFalse(rows.next()); + } + } + } + + @DataProvider + public static Object[][] rowBinaryParsers() { + return new Object[][] {{"JAVACC"}, {"ANTLR4"}, {"ANTLR4_PARAMS_PARSER"}}; + } + + @Test(groups = {"integration"}, dataProvider = "rowBinaryParsers") + void testRowBinarySetObjectRejectsSqlDateWithReorderedColumns(String parser) throws SQLException { + Properties properties = new Properties(); + properties.setProperty(DriverProperties.BETA_ROW_BINARY_WRITER.getKey(), "true"); + properties.setProperty(DriverProperties.SQL_PARSER.getKey(), parser); + String table = "test_row_binary_reordered_date_" + parser; + try (Connection connection = getJdbcConnection(properties); + Statement statement = connection.createStatement()) { + statement.executeUpdate("CREATE TABLE " + table + + " (id Int32, first_date Date32, second_date Date32, tail Int32) ORDER BY id"); + try (PreparedStatement insert = connection.prepareStatement("INSERT INTO " + + table + " (id, second_date, first_date, tail) VALUES (?, ?, ?, ?)")) { + Assert.assertTrue(insert instanceof WriterStatementImpl); + insert.setInt(1, 1); + insert.setObject(2, Date.valueOf("1965-12-31")); + insert.setObject(3, Date.valueOf("2013-07-15")); + insert.setInt(4, 42); + Assert.expectThrows(SQLException.class, insert::addBatch); + } + try (ResultSet rows = statement.executeQuery("SELECT count() FROM " + table)) { + Assert.assertTrue(rows.next()); + Assert.assertEquals(rows.getInt(1), 0); + } + } + } + + @Test(groups = {"integration"}) + void testRowBinarySetObjectRejectsSqlDateBeforeGeneratedColumn() throws SQLException { + Properties properties = new Properties(); + properties.setProperty(DriverProperties.BETA_ROW_BINARY_WRITER.getKey(), "true"); + String table = "test_row_binary_generated_date"; + runQuery("CREATE TABLE " + table + " (d Date32, generated Int32 MATERIALIZED 99, " + + "first_number Int32, second_number Int32 DEFAULT -1) ORDER BY d"); + try (Connection connection = getJdbcConnection(properties); + PreparedStatement insert = connection.prepareStatement("INSERT INTO " + table + " VALUES (?, ?, ?)")) { + Assert.assertTrue(insert instanceof WriterStatementImpl); + insert.setObject(1, Date.valueOf("1965-12-31")); + insert.setInt(2, 41); + insert.setInt(3, 42); + Assert.expectThrows(SQLException.class, insert::addBatch); + } + } + @Test(groups = {"integration"}) void testDateWithTimezone() throws Exception {