From 42ba5fe7370a0f03d98abdbf18b1cd51a504fa61 Mon Sep 17 00:00:00 2001 From: Luke Gannon Date: Wed, 25 Nov 2026 17:08:20 +0000 Subject: [PATCH] jdbc-v2: store DateTime in the server time zone in the RowBinary writer With beta.row_binary_for_simple_insert=true, the RowBinary writer stored DateTime/DateTime64 values for columns without an explicit time zone as if their wall clock were UTC, while the text path and the reader use the server time zone. On a non-UTC server the same value was stored hours apart depending on the path. The writer now resolves the server time zone (ConnectionImpl caches it via loadServerInfo) and applies it to tz-less DateTime/DateTime64 columns, including nested in Array/Map/Tuple/Nullable. Backward-compatible: the existing writer constructor and every other serializer caller default to UTC. Fixes #3394 Co-Authored-By: Claude Opus 4.8 --- .../data_formats/RowBinaryFormatWriter.java | 32 +++++++++++---- .../internal/SerializerUtils.java | 18 +++++++- history/latest/3394.md | 6 +++ .../com/clickhouse/jdbc/ConnectionImpl.java | 28 +++++++++++++ .../clickhouse/jdbc/WriterStatementImpl.java | 9 +++- .../clickhouse/jdbc/JDBCDateTimeTests.java | 41 +++++++++++++++++++ 6 files changed, 124 insertions(+), 10 deletions(-) create mode 100644 history/latest/3394.md diff --git a/client-v2/src/main/java/com/clickhouse/client/api/data_formats/RowBinaryFormatWriter.java b/client-v2/src/main/java/com/clickhouse/client/api/data_formats/RowBinaryFormatWriter.java index 2a2ecedd34..4cb42cdf68 100644 --- a/client-v2/src/main/java/com/clickhouse/client/api/data_formats/RowBinaryFormatWriter.java +++ b/client-v2/src/main/java/com/clickhouse/client/api/data_formats/RowBinaryFormatWriter.java @@ -13,6 +13,7 @@ import java.math.BigInteger; import java.time.LocalDate; import java.time.LocalDateTime; +import java.time.ZoneId; import java.time.ZonedDateTime; import java.util.Arrays; import java.util.List; @@ -36,11 +37,22 @@ public class RowBinaryFormatWriter implements ClickHouseBinaryFormatWriter { private final boolean defaultSupport; + private final ZoneId defaultTimeZone; + private int rowCount = 0; private boolean rowStarted = false; // indicates if at least one value was written to a row public RowBinaryFormatWriter(OutputStream out, TableSchema tableSchema, ClickHouseFormat format) { + this(out, tableSchema, format, ZoneId.of("UTC")); + } + + /** + * @param defaultTimeZone time zone used for DateTime/DateTime64 columns that declare no zone of + * their own. Pass the server time zone so stored values match the text + * path and the reader (clickhouse-java#3394). + */ + public RowBinaryFormatWriter(OutputStream out, TableSchema tableSchema, ClickHouseFormat format, ZoneId defaultTimeZone) { if (format != ClickHouseFormat.RowBinary && format != ClickHouseFormat.RowBinaryWithDefaults) { throw new IllegalArgumentException("Only RowBinary and RowBinaryWithDefaults are supported"); } @@ -49,6 +61,7 @@ public RowBinaryFormatWriter(OutputStream out, TableSchema tableSchema, ClickHou this.tableSchema = tableSchema; this.row = new Object[tableSchema.getColumns().size()]; this.defaultSupport = format == ClickHouseFormat.RowBinaryWithDefaults; + this.defaultTimeZone = defaultTimeZone == null ? ZoneId.of("UTC") : defaultTimeZone; } @Override @@ -89,14 +102,19 @@ public void setValue(int colIndex, Object value) { public void commitRow() throws IOException { if (rowStarted) { List columnList = tableSchema.getColumns(); - for (int i = 0; i < row.length; i++) { - ClickHouseColumn column = columnList.get(i); - // here we skip if we have a default value that is MATERIALIZED or ALIAS or ... - if (column.hasDefault() && column.getDefaultValue() != ClickHouseColumn.DefaultValue.DEFAULT) - continue; - if (RowBinaryFormatSerializer.writeValuePreamble(out, defaultSupport, column, row[i])) { - SerializerUtils.serializeData(out, row[i], column); + SerializerUtils.setWriterDefaultTimeZone(defaultTimeZone); + try { + for (int i = 0; i < row.length; i++) { + ClickHouseColumn column = columnList.get(i); + // here we skip if we have a default value that is MATERIALIZED or ALIAS or ... + if (column.hasDefault() && column.getDefaultValue() != ClickHouseColumn.DefaultValue.DEFAULT) + continue; + if (RowBinaryFormatSerializer.writeValuePreamble(out, defaultSupport, column, row[i])) { + SerializerUtils.serializeData(out, row[i], column); + } } + } finally { + SerializerUtils.resetWriterDefaultTimeZone(); } clearRow(); rowCount++; 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 50f9136e20..26ce88c2bf 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 @@ -62,6 +62,20 @@ @SuppressWarnings("deprecation") public class SerializerUtils { + // Default time zone for DateTime/DateTime64 columns that declare no zone of their own. + // The RowBinary writer sets it to the server time zone so stored values match the text path + // and the reader; it stays UTC for every other caller. See clickhouse-java#3394. + private static final ThreadLocal WRITER_DEFAULT_TIME_ZONE = + ThreadLocal.withInitial(() -> ZoneId.of("UTC")); + + public static void setWriterDefaultTimeZone(ZoneId zoneId) { + WRITER_DEFAULT_TIME_ZONE.set(zoneId == null ? ZoneId.of("UTC") : zoneId); + } + + public static void resetWriterDefaultTimeZone() { + WRITER_DEFAULT_TIME_ZONE.remove(); + } + public static void serializeData(OutputStream stream, Object value, ClickHouseColumn column) throws IOException { //Serialize the value to the stream based on the data type switch (column.getDataType()) { @@ -733,12 +747,12 @@ private static void serializePrimitiveData(OutputStream stream, Object value, Cl writeDate32(stream, value, ZoneId.of("UTC")); // TODO: check break; case DateTime: { - ZoneId zoneId = column.getTimeZone() == null ? ZoneId.of("UTC") : column.getTimeZone().toZoneId(); + ZoneId zoneId = column.getTimeZone() == null ? WRITER_DEFAULT_TIME_ZONE.get() : column.getTimeZone().toZoneId(); writeDateTime(stream, value, zoneId); break; } case DateTime64: { - ZoneId zoneId = column.getTimeZone() == null ? ZoneId.of("UTC") : column.getTimeZone().toZoneId(); + ZoneId zoneId = column.getTimeZone() == null ? WRITER_DEFAULT_TIME_ZONE.get() : column.getTimeZone().toZoneId(); writeDateTime64(stream, value, column.getScale(), zoneId); break; } diff --git a/history/latest/3394.md b/history/latest/3394.md new file mode 100644 index 0000000000..5d90974367 --- /dev/null +++ b/history/latest/3394.md @@ -0,0 +1,6 @@ +- **[jdbc-v2]** The RowBinary writer (`beta.row_binary_for_simple_insert`) now stores + `DateTime`/`DateTime64` values for columns without an explicit time zone in the **server** + time zone, matching the text path and the reader, instead of UTC. Behaviour change on + non-UTC servers for the beta writer path; pin the zone with `use_time_zone` / + `use_server_time_zone` to keep the old behaviour. + (https://github.com/ClickHouse/clickhouse-java/issues/3394) diff --git a/jdbc-v2/src/main/java/com/clickhouse/jdbc/ConnectionImpl.java b/jdbc-v2/src/main/java/com/clickhouse/jdbc/ConnectionImpl.java index 35542a0ece..93cb83012a 100644 --- a/jdbc-v2/src/main/java/com/clickhouse/jdbc/ConnectionImpl.java +++ b/jdbc-v2/src/main/java/com/clickhouse/jdbc/ConnectionImpl.java @@ -1,6 +1,7 @@ package com.clickhouse.jdbc; import com.clickhouse.client.api.Client; +import java.time.ZoneId; import com.clickhouse.client.api.ClientConfigProperties; import com.clickhouse.client.api.data_formats.JsonParserFactory; import com.clickhouse.client.api.metadata.TableSchema; @@ -52,6 +53,7 @@ public class ConnectionImpl implements Connection, JdbcV2Wrapper { protected final String url; private final Client client; // this member is private to force using getClient() + private volatile ZoneId effectiveServerTimeZone; protected final JdbcConfiguration config; private boolean closed = false; @@ -750,6 +752,32 @@ public Client getClient() throws SQLException { return client; } + /** + * Resolves the server time zone once per connection and caches it. The RowBinary writer uses it + * so DateTime/DateTime64 columns without their own zone are stored in the server zone, matching + * the text path and the reader (clickhouse-java#3394). Falls back to UTC. + */ + public ZoneId getEffectiveServerTimeZone() { + ZoneId tz = effectiveServerTimeZone; + if (tz != null) { + return tz; + } + String zoneId = null; + try { + zoneId = client.getServerTimeZone(); + if (zoneId == null || "UTC".equalsIgnoreCase(zoneId)) { + // The configured default is UTC and the real zone is only detected lazily; load it once. + client.loadServerInfo(); + zoneId = client.getServerTimeZone(); + } + } catch (Exception e) { + // fall back to UTC below + } + tz = ZoneId.of(zoneId == null ? "UTC" : zoneId); + effectiveServerTimeZone = tz; + return tz; + } + private void ensureOpenForClientInfo() throws SQLClientInfoException { if (isClosed()) { throw new SQLClientInfoException("Connection is closed", 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..c689e6d249 100644 --- a/jdbc-v2/src/main/java/com/clickhouse/jdbc/WriterStatementImpl.java +++ b/jdbc-v2/src/main/java/com/clickhouse/jdbc/WriterStatementImpl.java @@ -18,6 +18,7 @@ import java.io.Reader; import java.math.BigDecimal; import java.net.URL; +import java.time.ZoneId; import java.sql.Array; import java.sql.Blob; import java.sql.Clob; @@ -75,6 +76,12 @@ public WriterStatementImpl(ConnectionImpl connection, String originalSql, TableS } } + // DateTime/DateTime64 columns without their own zone are stored in the server time zone, + // matching the text path and the reader (clickhouse-java#3394). Falls back to UTC. + private ZoneId resolveServerTimeZone() { + return connection.getEffectiveServerTimeZone(); + } + private void resetWriter() throws IOException { if (out != null) { out.close(); @@ -82,7 +89,7 @@ private void resetWriter() throws IOException { out = new ByteArrayOutputStream(); writer = new RowBinaryFormatWriter(out, tableSchema, tableSchema.hasDefaults() ? - ClickHouseFormat.RowBinaryWithDefaults : ClickHouseFormat.RowBinary); + ClickHouseFormat.RowBinaryWithDefaults : ClickHouseFormat.RowBinary, resolveServerTimeZone()); } @Override 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 10094ad63b..952c9895ba 100644 --- a/jdbc-v2/src/test/java/com/clickhouse/jdbc/JDBCDateTimeTests.java +++ b/jdbc-v2/src/test/java/com/clickhouse/jdbc/JDBCDateTimeTests.java @@ -15,6 +15,7 @@ import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; +import java.sql.Timestamp; import java.time.Duration; import java.time.Instant; import java.time.LocalDate; @@ -313,4 +314,44 @@ void testTimestampInRange() throws Exception { } } } + + // Regression for #3394: the RowBinary writer must store DateTime in the server time zone + // (like the text path), not UTC, for columns without their own zone. + @Test(groups = {"integration"}) + void testRowBinaryWriterDateTimeServerTimeZone() throws Exception { + Properties writerProps = new Properties(); + writerProps.put("beta.row_binary_for_simple_insert", "true"); + Timestamp ts = Timestamp.valueOf("2024-01-15 12:00:00"); + try (Connection text = getJdbcConnection(); + Connection writer = getJdbcConnection(writerProps); + Statement stmt = text.createStatement()) { + stmt.executeUpdate("DROP TABLE IF EXISTS test_writer_dt_tz"); + stmt.executeUpdate("CREATE TABLE test_writer_dt_tz (path String, t DateTime, " + + "t64 DateTime64(3), tb DateTime('Asia/Tokyo')) ENGINE = MergeTree ORDER BY path"); + insertWriterDateTimeRow(text, "text", ts); + insertWriterDateTimeRow(writer, "writer", ts); + try (ResultSet rs = stmt.executeQuery("SELECT " + + "anyIf(toString(t,'UTC'), path='writer') AS wt, anyIf(toString(t,'UTC'), path='text') AS tt, " + + "anyIf(toString(t64,'UTC'), path='writer') AS wt64, anyIf(toString(t64,'UTC'), path='text') AS tt64, " + + "anyIf(toString(tb,'UTC'), path='writer') AS wtb, anyIf(toString(tb,'UTC'), path='text') AS ttb " + + "FROM test_writer_dt_tz")) { + Assert.assertTrue(rs.next()); + Assert.assertEquals(rs.getString("wt"), rs.getString("tt")); + Assert.assertEquals(rs.getString("wt64"), rs.getString("tt64")); + Assert.assertEquals(rs.getString("wtb"), rs.getString("ttb")); + } + stmt.executeUpdate("DROP TABLE IF EXISTS test_writer_dt_tz"); + } + } + + private void insertWriterDateTimeRow(Connection conn, String path, Timestamp ts) throws SQLException { + try (PreparedStatement ps = conn.prepareStatement("INSERT INTO test_writer_dt_tz VALUES (?, ?, ?, ?)")) { + ps.setString(1, path); + ps.setObject(2, ts); + ps.setObject(3, ts); + ps.setObject(4, ts); + ps.addBatch(); + ps.executeBatch(); + } + } }