diff --git a/client-v2/src/main/java/com/clickhouse/client/api/ClientConfigProperties.java b/client-v2/src/main/java/com/clickhouse/client/api/ClientConfigProperties.java index 61a23cbe3..98e6aabb0 100644 --- a/client-v2/src/main/java/com/clickhouse/client/api/ClientConfigProperties.java +++ b/client-v2/src/main/java/com/clickhouse/client/api/ClientConfigProperties.java @@ -5,6 +5,7 @@ import com.clickhouse.client.api.enums.SSLMode; import com.clickhouse.client.api.internal.CompressedBlockOutputStream; import com.clickhouse.client.api.internal.ConfigDescription; +import com.clickhouse.client.api.internal.ValidationUtils; import com.clickhouse.client.api.internal.WorkloadIdentitySupport; import com.clickhouse.data.ClickHouseDataType; import com.clickhouse.data.ClickHouseFormat; @@ -491,7 +492,7 @@ public Object parseValue(String value) { } if (valueType.equals(TimeZone.class)) { - return TimeZone.getTimeZone(value); + return ValidationUtils.toTimeZone(value, key); } if (valueType.equals(Map.class)) { diff --git a/client-v2/src/main/java/com/clickhouse/client/api/internal/ValidationUtils.java b/client-v2/src/main/java/com/clickhouse/client/api/internal/ValidationUtils.java index bfd4cfd08..08bc14b6e 100644 --- a/client-v2/src/main/java/com/clickhouse/client/api/internal/ValidationUtils.java +++ b/client-v2/src/main/java/com/clickhouse/client/api/internal/ValidationUtils.java @@ -1,9 +1,14 @@ package com.clickhouse.client.api.internal; +import java.time.DateTimeException; +import java.time.Instant; +import java.time.ZoneId; +import java.time.zone.ZoneRules; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.Set; +import java.util.TimeZone; public class ValidationUtils { @@ -45,6 +50,43 @@ public static void checkValueFromSet(Object value, String name, Set validValu } } + /** + * Converts a time zone ID to a {@link TimeZone}. Unlike {@link TimeZone#getTimeZone(String)}, which returns + * GMT for an ID that it does not recognise, this method throws an exception for an unknown or malformed ID. + * IDs are validated by {@link ZoneId#of(String)}. + * + * @param timeZoneId - time zone ID, for example {@code Europe/Berlin}, {@code UTC} or {@code +05:30} + * @param name - name of the setting, used in the error message + * @return time zone for the ID + * @throws SettingsValidationException if the ID is not a valid time zone ID, or if it is a fixed offset + * with seconds, for example {@code +05:30:45} (on Java 17 and earlier, + * {@link TimeZone#getTimeZone(ZoneId)} returns GMT for it) + */ + public static TimeZone toTimeZone(String timeZoneId, String name) { + ZoneId zoneId; + try { + zoneId = ZoneId.of(timeZoneId); + } catch (DateTimeException e) { + SettingsValidationException error = new SettingsValidationException(name, + "\"" + name + "\" must be a valid time zone ID, but was '" + timeZoneId + "'"); + error.initCause(e); + throw error; + } + String id = zoneId.getId(); + if (id.startsWith("UTC+") || id.startsWith("UTC-") || id.startsWith("UT+") || id.startsWith("UT-")) { + // TimeZone does not recognise these offset IDs and returns GMT for them. Use the offset itself. + zoneId = zoneId.normalized(); + } + ZoneRules rules = zoneId.getRules(); + if (rules.isFixedOffset() && rules.getOffset(Instant.EPOCH).getTotalSeconds() % 60 != 0) { + // On Java 17 and earlier, TimeZone.getTimeZone returns GMT for an offset with seconds. Reject such + // offsets on every Java version, so that the result does not depend on the runtime. + throw new SettingsValidationException(name, "\"" + name + + "\" must be a time zone ID with an offset in whole minutes, but was '" + timeZoneId + "'"); + } + return TimeZone.getTimeZone(zoneId); + } + /** * Creates a unmodifiable set from the given values. * @param values diff --git a/client-v2/src/main/java/com/clickhouse/client/api/query/QuerySettings.java b/client-v2/src/main/java/com/clickhouse/client/api/query/QuerySettings.java index 9df39f407..84ce21171 100644 --- a/client-v2/src/main/java/com/clickhouse/client/api/query/QuerySettings.java +++ b/client-v2/src/main/java/com/clickhouse/client/api/query/QuerySettings.java @@ -224,7 +224,8 @@ public QuerySettings setUseTimeZone(String timeZone) { throw new ValidationUtils.SettingsValidationException(ClientConfigProperties.USE_TIMEZONE.getKey(), "Cannot set both use_time_zone and use_server_time_zone"); } - settings.setOption(ClientConfigProperties.USE_TIMEZONE.getKey(), TimeZone.getTimeZone(timeZone)); + settings.setOption(ClientConfigProperties.USE_TIMEZONE.getKey(), + ValidationUtils.toTimeZone(timeZone, ClientConfigProperties.USE_TIMEZONE.getKey())); return this; } diff --git a/client-v2/src/test/java/com/clickhouse/client/SettingsTests.java b/client-v2/src/test/java/com/clickhouse/client/SettingsTests.java index 66271d925..3b22ecc6a 100644 --- a/client-v2/src/test/java/com/clickhouse/client/SettingsTests.java +++ b/client-v2/src/test/java/com/clickhouse/client/SettingsTests.java @@ -9,6 +9,7 @@ import com.clickhouse.client.api.internal.SslContextProvider; import com.clickhouse.client.api.query.QuerySettings; import org.testng.Assert; +import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import javax.net.ssl.SSLContext; @@ -20,6 +21,7 @@ import java.util.Arrays; import java.util.Collections; import java.util.List; +import java.util.TimeZone; import java.util.concurrent.TimeUnit; @Test(groups = {"unit"}) @@ -238,6 +240,50 @@ void testQuerySettingsSpecific() throws Exception { } } + @DataProvider(name = "validTimeZoneIds") + public static Object[][] validTimeZoneIds() { + return new Object[][]{ + // time zone ID -> expected TimeZone ID + {"America/Los_Angeles", "America/Los_Angeles"}, + {"UTC", "UTC"}, + {"GMT", "GMT"}, + {"Etc/GMT+5", "Etc/GMT+5"}, + {"Africa/Monrovia", "Africa/Monrovia"}, + {"GMT+05:30", "GMT+05:30"}, + {"+05:30", "GMT+05:30"}, + {"+05:30:00", "GMT+05:30"}, + {"-09:30", "GMT-09:30"}, + {"UTC+05:30", "GMT+05:30"}, + {"UT-03:00", "GMT-03:00"}, + }; + } + + @Test(dataProvider = "validTimeZoneIds") + void testQuerySettingsUseTimeZone(String timeZoneId, String expectedId) { + QuerySettings settings = new QuerySettings().setUseTimeZone(timeZoneId); + TimeZone timeZone = (TimeZone) settings.getAllSettings().get(ClientConfigProperties.USE_TIMEZONE.getKey()); + Assert.assertEquals(timeZone.getID(), expectedId); + Assert.assertEquals(timeZone, TimeZone.getTimeZone(expectedId)); + } + + @DataProvider(name = "invalidTimeZoneIds") + public static Object[][] invalidTimeZoneIds() { + return new Object[][]{ + {"Mars/Olympus_Mons"}, {"America/Los_Angels"}, {""}, {" UTC"}, {"+25:00"}, {"UTC+5:3"}, + {"+05:30:45"}, {"-05:30:45"}, {"UTC+05:30:45"}, {"GMT+05:30:45"}, + }; + } + + @Test(dataProvider = "invalidTimeZoneIds") + void testQuerySettingsUseTimeZoneRejectsInvalidId(String timeZoneId) { + QuerySettings settings = new QuerySettings(); + IllegalArgumentException e = Assert.expectThrows(IllegalArgumentException.class, + () -> settings.setUseTimeZone(timeZoneId)); + Assert.assertTrue(e.getMessage().contains(ClientConfigProperties.USE_TIMEZONE.getKey()), e.getMessage()); + Assert.assertTrue(e.getMessage().contains("'" + timeZoneId + "'"), e.getMessage()); + Assert.assertFalse(settings.getAllSettings().containsKey(ClientConfigProperties.USE_TIMEZONE.getKey())); + } + @Test public void testInsertSettingsSpecific() throws Exception { { diff --git a/client-v2/src/test/java/com/clickhouse/client/api/ClientConfigPropertiesTest.java b/client-v2/src/test/java/com/clickhouse/client/api/ClientConfigPropertiesTest.java index d2dd71f8a..c3d785b48 100644 --- a/client-v2/src/test/java/com/clickhouse/client/api/ClientConfigPropertiesTest.java +++ b/client-v2/src/test/java/com/clickhouse/client/api/ClientConfigPropertiesTest.java @@ -12,6 +12,7 @@ import java.util.LinkedHashMap; import java.util.List; import java.util.Map; +import java.util.TimeZone; public class ClientConfigPropertiesTest { @@ -133,6 +134,23 @@ public void testFromKeyValuePairsRoundTrip() { Assert.assertEquals(new ArrayList<>(parsed.entrySet()), new ArrayList<>(pairs.entrySet())); } + @DataProvider(name = "timeZoneProperties") + public static Object[][] timeZoneProperties() { + return new Object[][]{ + {ClientConfigProperties.USE_TIMEZONE}, {ClientConfigProperties.SERVER_TIMEZONE}, + }; + } + + @Test(groups = {"unit"}, dataProvider = "timeZoneProperties") + public void testTimeZoneParsing(ClientConfigProperties property) { + Assert.assertEquals(property.parseValue("America/Los_Angeles"), TimeZone.getTimeZone("America/Los_Angeles")); + Assert.assertEquals(property.parseValue("UTC+05:30"), TimeZone.getTimeZone("GMT+05:30")); + IllegalArgumentException e = Assert.expectThrows(IllegalArgumentException.class, + () -> property.parseValue("Mars/Olympus_Mons")); + Assert.assertTrue(e.getMessage().contains(property.getKey()), e.getMessage()); + Assert.assertTrue(e.getMessage().contains("'Mars/Olympus_Mons'"), e.getMessage()); + } + @Test(groups = {"unit"}) public void testDescriptions() { Map descriptions = ClientConfigPropertiesDescriptions.getDescriptions(); diff --git a/client-v2/src/test/java/com/clickhouse/client/query/QueryTests.java b/client-v2/src/test/java/com/clickhouse/client/query/QueryTests.java index a1e5da534..3d48ceeb5 100644 --- a/client-v2/src/test/java/com/clickhouse/client/query/QueryTests.java +++ b/client-v2/src/test/java/com/clickhouse/client/query/QueryTests.java @@ -62,6 +62,7 @@ import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; import java.time.LocalDate; +import java.time.Instant; import java.time.LocalDateTime; import java.time.ZoneId; import java.time.ZonedDateTime; @@ -2047,6 +2048,37 @@ public void testClientUseOwnTimeZone() { } } + @DataProvider(name = "useTimeZones") + public static Object[][] useTimeZones() { + return new Object[][]{ + // time zone ID -> epoch 0 as local date-time in that time zone + {"Europe/Berlin", LocalDateTime.of(1970, 1, 1, 1, 0)}, + {"UTC+05:30", LocalDateTime.of(1970, 1, 1, 5, 30)}, + {"+05:30", LocalDateTime.of(1970, 1, 1, 5, 30)}, + }; + } + + @Test(groups = {"integration"}, dataProvider = "useTimeZones") + public void testUseTimeZone(String timeZoneId, LocalDateTime expected) throws Exception { + try (Client client = newClient().useTimeZone(timeZoneId).build()) { + assertEpochReadAs(client, new QuerySettings(), expected); + } + try (Client client = newClient().useTimeZone("UTC").build()) { + assertEpochReadAs(client, new QuerySettings().setUseTimeZone(timeZoneId), expected); + } + } + + private static void assertEpochReadAs(Client client, QuerySettings settings, LocalDateTime expected) + throws Exception { + try (QueryResponse response = client.query("SELECT toDateTime(0) AS t", settings).get(10, TimeUnit.SECONDS)) { + ClickHouseBinaryFormatReader reader = client.newBinaryFormatReader(response); + Assert.assertNotNull(reader.next()); + ZonedDateTime t = reader.getZonedDateTime("t"); + Assert.assertEquals(t.toInstant(), Instant.EPOCH); + Assert.assertEquals(t.toLocalDateTime(), expected); + } + } + @Test public void testAsyncQuery() { try (Client client = newClient().useAsyncRequests(true).build()){ diff --git a/docs/features.md b/docs/features.md index 978ca67af..35add2bdc 100644 --- a/docs/features.md +++ b/docs/features.md @@ -40,6 +40,7 @@ This document lists stable, user-visible behavior in `client-v2` and `jdbc-v2` t - Span recording (tracing SPI): `Client.Builder.setSpanRecorder(SpanRecorder)` registers a backend-agnostic recorder (package `com.clickhouse.client.api.observability`) that observes client operations. Every operation - a query, a command or an insert, including the `ping` and `getTableSchema` calls, which run a query - starts one operation span, and every transport request made for it, including each retry, starts a child request span. `SpanRecorder` and `Span` are plain interfaces; an implementation extends the `DefaultSpanRecorder` base class and overrides only what it wants to record, so a recorder keeps working when the client starts a kind of span it does not know about. The registered recorder is the first thing the client calls, and it is called with everything the client knows about the operation - its settings object, the statement, the target table, the batch size, the endpoint, the metrics of the completed operation and the failure - so an implementation is free to record whatever it needs and in whatever form. Deriving the standard span names and attribute values from those structures is done by `SpanSupport`, which a recorder implementation calls if it wants them; using it is opt-in, and its methods may be overridden to report other values. A recorder opts in through `DefaultSpanRecorder#getSpanSupport()` (or `SpanSupport.DEFAULT`). Span names and attribute keys follow the OpenTelemetry semantic conventions for database and HTTP client spans, the keys are defined by the `SpanAttribute` enum, and the values are derived by `SpanSupport`, so every recorder that uses it reports the same information. An operation span is named `query `, or `insert .` for an insert, and carries `db.system.name`, `db.namespace`, `clickhouse.query_id`, `db.query.text` (query/command), `db.query.parameter.` (parameterized query), `db.operation.name` (insert), `db.collection.name` (insert), `db.operation.batch.size` (POJO insert), `server.address`/`server.port` of the first configured endpoint (each attempt reports its own on the request span), the metrics of the completed operation on success, and `error.type` plus `db.response.status_code` on failure. Success is reported per operation kind, because the metrics that describe a read are not the ones that describe a write: `SpanRecorder#recordQuerySuccess` is called for a read operation and `SpanRecorder#recordInsertSuccess` for an insert, and each records only the metrics of its own kind - a query reports `db.response.returned_rows`, `clickhouse.response.read_rows` and `clickhouse.response.read_bytes`, an insert reports `clickhouse.response.written_rows` and `clickhouse.response.written_bytes`, and both report `clickhouse.query_id`. These values come from the server's progress summary, which is not always available (for example a query reports them with `QuerySettings#waitEndOfQuery(true)`); a metric the server did not report is left out. The same distinction is on the metrics themselves: `OperationMetrics#getOperationType()` returns `OperationType.QUERY` or `OperationType.INSERT`. It reports the kind of the call the application made, not the kind of work the server did, so a command that writes - `INSERT INTO ... SELECT` run through `execute` - is reported as a query. A request span is named `POST` and carries `http.request.method`, the `server.address`/`server.port` of that attempt, `http.response.status_code` once a response is received, and `error.type`/`db.response.status_code` when the attempt fails. An operation span is started on the calling thread, so it joins the caller's ambient trace even when `async_operations` runs the operation on the client's executor, and it is ended when the operation returns its response to the caller - so it covers sending the request and receiving the response head, not streaming the response body afterwards. Each span of an operation that started is ended exactly once, also when the operation failed; an operation that could not be started at all - a closed client, for example - does not report a span. When no recorder is registered nothing is recorded and no span-related work is done. - Metrics recording (metrics SPI): `Client.Builder.setMetricsRecorder(MetricsRecorder)` registers a backend-agnostic recorder (package `com.clickhouse.client.api.observability`) that receives the metrics of client operations, so an application can export them to any metrics backend. It follows the same pattern as the span SPI: `MetricsRecorder` is a plain interface, an implementation extends the `DefaultMetricsRecorder` base class and overrides only what it wants to record, so a recorder keeps working when the client starts reporting an event it does not know about, and the reusable `MetricsSupport` class derives the standard values from the same structures (opt-in through `DefaultMetricsRecorder#getMetricsSupport()`, and overridable). Every completed operation reports exactly one event - `recordQuerySuccess`/`recordInsertSuccess` or `recordQueryFailure`/`recordInsertFailure` - so counting those events gives the number of operations by outcome, and every retried attempt reports `recordQueryRetry`/`recordInsertRetry`, so an operation that succeeds on its third attempt reports two retries. The durations of a successful operation are read from its `OperationMetrics`; a failed operation has no metrics, so the client measures its duration itself and passes it in. Metric names, units and attribute keys follow the OpenTelemetry semantic conventions for database clients where a convention exists and are placed under `clickhouse.` where it does not: the `MetricName` enum defines `db.client.operation.duration` (unit `s`), `clickhouse.client.operation.serialization.duration` (unit `s`), `clickhouse.client.operation.count` and `clickhouse.client.operation.retries`, each with the unit and description an exporter registers its instrument with. Durations are reported in **seconds**, while `ClientMetrics` values are milliseconds - `MetricsSupport` converts them and returns `MetricsSupport.DURATION_UNKNOWN` for a duration the client did not measure (the serialization duration is measured for a POJO insert only), so a recorder never reports a made-up value. The attribute keys are the `MetricAttribute` enum - `db.system.name`, `db.namespace`, `db.operation.name` (`query` or `insert`), `db.collection.name` (insert), and `error.type` plus `db.response.status_code` on a failure. That is deliberately a smaller set than `SpanAttribute`, because an attribute of a metric becomes a time series: the statement text, the query id and the statement parameters stay on spans. A successful operation has no `error.type` attribute, so the successful time series is the one without it. When no recorder is registered nothing is recorded and no metrics-related work is done. The recorder is registered per client instance and must be thread-safe. - Configuration surface: Supports arbitrary client options, cookies, custom headers, server-setting prefixes, client naming, query id suppliers, and buffer sizing. +- Time zone settings: `use_time_zone` and `server_time_zone` (client options and JDBC properties) and `QuerySettings#setUseTimeZone` accept the IDs that `java.time.ZoneId#of` accepts: region IDs (`Europe/Berlin`), `UTC`, `GMT`, and fixed offsets in whole minutes (`+05:30`, `UTC+05:30`, `GMT+05:30`). An unknown or malformed ID, or an offset with seconds, is rejected with an `IllegalArgumentException`. It is never replaced with `GMT`. - Configuration property descriptions: Each `ClientConfigProperties` constant has a short description in its `@com.clickhouse.client.api.internal.ConfigDescription` annotation. At build time, an annotation processor generates `ClientConfigPropertiesDescriptions`; its `getDescriptions()` returns an unmodifiable map from each constant to its description, in the order of the constants. A constant without a description, or with a blank description, fails the build. - `User-Agent` header and client metadata: Every request sends a `User-Agent` header in the standard ClickHouse client format, ` clickhouse-java-v2/ (:; ...; lv:java/; os:; arch:; hc:ahc_)`, where `` is a custom `User-Agent` header value if one is set and the client name otherwise, with leading and trailing whitespace removed (omitted when both are blank). A blank client name or `User-Agent` value set for one operation counts as not set: the request uses the value of the client configuration. The client name is the documented way to identify the application; a custom `User-Agent` header replaces it. The `arch` entry is the CPU architecture that the JVM reports (`os.arch`, for example `amd64` or `aarch64`). The `hc` entry is the HTTP client: `ahc_` (Apache HttpClient) and the version of the library that the client is built with (also in the shaded jar). `Client.Builder.setClientName(String, Map)` (or the `client_id_metadata` property, written as `key1=value1,key2=value2`, where a `,` or `\` in a value is escaped with `\`) adds key/value pairs to the comment group in the given order, then `lv`, `os`, `arch` and `hc` if the metadata does not set these keys, ignoring case (so an application can replace them); keys and values are trimmed and entries with a `null` or empty key or value are ignored. Keys and values must be printable ASCII, a key must not contain spaces or any of `:;(),=`, and a value must not contain any of `;()`: an invalid entry is rejected with `ClientMisconfigurationException` when the client is built. Client metadata is a client-level setting: it is not read from operation settings, and it is kept when the client name changes (`Client.Builder.setClientName(String)`, `Client#updateClientName`). The client logs a warning when the `User-Agent` value of the client configuration is longer than 200 characters. - SQL helpers: Includes SQL quoting and temporal formatting helpers used by callers building SQL text safely. diff --git a/history/latest/3286.md b/history/latest/3286.md new file mode 100644 index 000000000..f0b74cc2d --- /dev/null +++ b/history/latest/3286.md @@ -0,0 +1,16 @@ +## Breaking changes + +- **[client-v2, jdbc-v2]** `QuerySettings#setUseTimeZone` and the `use_time_zone` / `server_time_zone` client options + (`Client.Builder#useTimeZone`, `Client.Builder#setServerTimeZone`, JDBC connection properties) now reject an unknown + or malformed time zone ID with an `IllegalArgumentException`. Before, `TimeZone#getTimeZone(String)` silently replaced + such an ID with `GMT`, so date-time values were interpreted in the wrong time zone. IDs are validated with + `ZoneId#of`, the check that `Client.Builder#build` already did for `use_time_zone` (and for `server_time_zone` when + `use_server_time_zone` is on). Because of this, `QuerySettings#setUseTimeZone`, and `server_time_zone` set together + with `use_time_zone`, now also reject legacy `java.util.TimeZone` IDs that `ZoneId` does not accept: three-letter + aliases such as `PST`, `IST` or `EST`, and custom IDs such as `GMT+5:30`, `GMT+530` or `GMT+20`. + Use a region ID (`America/Los_Angeles`) or an offset (`GMT+05:30`, `+05:30`) instead. Offsets with seconds + (`+05:30:45`, `GMT+05:30:45`) are rejected on every Java version: on Java 17 and earlier `TimeZone` replaces them + with `GMT`, and on later versions they are rejected too, so that a setting does not depend on the Java version + (on Java 21, `GMT+05:30:45` was accepted before). Offset IDs with a `UTC` or `UT` prefix (`UTC+05:30`) and plain + offsets (`+05:30`) now give their offset instead of `GMT`. + (https://github.com/ClickHouse/clickhouse-java/issues/3286) diff --git a/jdbc-v2/src/test/java/com/clickhouse/jdbc/ConnectionTest.java b/jdbc-v2/src/test/java/com/clickhouse/jdbc/ConnectionTest.java index d36e0691f..b52a0b01e 100644 --- a/jdbc-v2/src/test/java/com/clickhouse/jdbc/ConnectionTest.java +++ b/jdbc-v2/src/test/java/com/clickhouse/jdbc/ConnectionTest.java @@ -1410,6 +1410,24 @@ public void testUseUserTimeZone() throws Exception { } + @DataProvider(name = "invalidTimeZoneProperties") + public static Object[][] invalidTimeZoneProperties() { + return new Object[][]{ + {ClientConfigProperties.USE_TIMEZONE.getKey()}, + {ClientConfigProperties.SERVER_TIMEZONE.getKey()}, + }; + } + + @Test(groups = {"integration"}, dataProvider = "invalidTimeZoneProperties") + public void testInvalidTimeZoneIdRejected(String property) { + Properties props = new Properties(); + props.put(ClientConfigProperties.USE_TIMEZONE.getKey(), "America/New_York"); + props.put(property, "America/New_Yrok"); + SQLException e = expectThrows(SQLException.class, () -> getJdbcConnection(props)); + assertTrue(e.getCause() instanceof IllegalArgumentException, String.valueOf(e.getCause())); + assertTrue(e.getCause().getMessage().contains("America/New_Yrok"), e.getCause().getMessage()); + } + @Test(groups = {"integration"}) public void testEndpointUrlPathIsPreserved() throws Exception { if (isCloud()) {