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
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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");
}
Expand All @@ -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;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

we are trying to fix UTC and setting UTC in this place. This kind of wrong. It should all be aligned.

}

@Override
Expand Down Expand Up @@ -89,14 +102,19 @@ public void setValue(int colIndex, Object value) {
public void commitRow() throws IOException {
if (rowStarted) {
List<ClickHouseColumn> 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++;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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<ZoneId> WRITER_DEFAULT_TIME_ZONE =

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is very ugly way to make SerializerUtils (static by nature) as stateful class.
the biggest issue that this code doesn't enforce you to set correct timezone.

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()) {
Expand Down Expand Up @@ -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;
}
Expand Down
6 changes: 6 additions & 0 deletions history/latest/3394.md
Original file line number Diff line number Diff line change
@@ -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)
28 changes: 28 additions & 0 deletions jdbc-v2/src/main/java/com/clickhouse/jdbc/ConnectionImpl.java
Original file line number Diff line number Diff line change
@@ -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;
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -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;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

UTC timezone always reloads from server

Medium Severity

getEffectiveServerTimeZone treats any UTC value as “not yet loaded” and calls loadServerInfo, which overwrites the client’s server_time_zone with the live server zone. Explicit UTC cannot be pinned, use_time_zone is never consulted, and the documented workaround does not preserve the previous behaviour. Mutating shared client config also changes how later reads on the same connection decode DateTime.

Additional Locations (1)
Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit 42ba5fe. Configure here.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Failed timezone lookup caches UTC forever

Medium Severity

When loadServerInfo fails, getEffectiveServerTimeZone swallows the exception and stores UTC in effectiveServerTimeZone for the connection lifetime. A transient error on the first writer statement then writes tz-less DateTime / DateTime64 values as UTC on a non-UTC server, recreating the mismatch this change is meant to fix.

Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit 42ba5fe. Configure here.

return tz;
}

private void ensureOpenForClientInfo() throws SQLClientInfoException {
if (isClosed()) {
throw new SQLClientInfoException("Connection is closed",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -75,14 +76,20 @@ 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();
}

out = new ByteArrayOutputStream();
writer = new RowBinaryFormatWriter(out, tableSchema, tableSchema.hasDefaults() ?
ClickHouseFormat.RowBinaryWithDefaults : ClickHouseFormat.RowBinary);
ClickHouseFormat.RowBinaryWithDefaults : ClickHouseFormat.RowBinary, resolveServerTimeZone());
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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();
}
}
}
Loading