client-v2: a scalar date/time query parameter with sub-second precision is rejected by a DateTime placeholder

Aberta
#3,435 1 comentário 0 reações 0 responsáveis Ver no GitHub

Mantenedores costumam responder em até 1 dia

Ninguém assumiu esta issue ainda.

Avaliação

Dificuldade
4/5
Tempo estimado
3-5 dias
Facilidade para iniciantes
48/100
Tipo de issue
Bug
Clareza
Razoavelmente clara
Status de atividade
Ativa
Stack de tecnologia
java
Domínio
backend, databases

Direção de pesquisa

Start with client-v2/src/main/java/com/clickhouse/client/api/internal/DataTypeConverter.java and its convertParameterToString and dateTimeToString methods; compare scalar formatting with the container path that uses ClickHouseValues.convertToSqlExpression. Reproduce with the provided DateTime and DateTime64 examples, then check Nullable(DateTime) as described. Done when scalar date/time parameters use a server accepted form for the declared type, with coverage for the listed Java time classes.

Escrita pelo modelo de indexação a partir do texto da issue.

Descrição

bug client data-types

Description

Client.query(sql, Map<String, Object> params, settings) formats a scalar query parameter with DataTypeConverter.convertParameterToString(Object), which has no knowledge of the declared {name:Type} in the SQL text. Every scalar that is not a CharSequence and not a container falls through to String.valueOf(value) (client-v2/src/main/java/com/clickhouse/client/api/internal/DataTypeConverter.java:269-288).

For a date/time value that carries sub-second precision, toString() emits a fractional part. The server parses a {p:DateTime} parameter as whole seconds, so it rejects the value with BAD_QUERY_PARAMETER (code 457, "isn't parsed completely"). The same value works with {p:DateTime64(3)}.

The same type-unawareness also means that Instant, ZonedDateTime, java.util.Date and java.sql.Timestamp are sent in their Java toString() form (trailing Z, [UTC] zone suffix, or the legacy EEE MMM dd ... form), which the server cannot parse as a DateTime at all. The same values inside a List/Map parameter are formatted correctly, because the container path uses ClickHouseValues.convertToSqlExpression.

This is the Java counterpart of ClickHouse/clickhouse-js#1204, where a JS Date with non-zero milliseconds produces a fractional timestamp that a DateTime parameter rejects.

Related but not the same: #3387 / PR #3388 cover a LocalDateTime/LocalTime with zero seconds. PR #3388 switches LocalDateTime to DATETIME_WITH_NANOS_FORMATTER, which still emits 2026-11-19 12:34:00.5 for a value with milliseconds, so a DateTime placeholder keeps failing after that fix. PR #3388 also leaves Instant, ZonedDateTime, java.util.Date and java.sql.Timestamp on the String.valueOf path.

ClickHouse server version

26.11.2.4 (official build), reached over HTTP at localhost:8123.

Reproduction

Test class placed in client-v2/src/test/java/com/clickhouse/client/, run with mvn -pl client-v2 test -Dtest=ScratchDateTimeParamTest -Dgroups=scratch:

package com.clickhouse.client;

import com.clickhouse.client.api.Client;
import com.clickhouse.client.api.data_formats.ClickHouseBinaryFormatReader;
import com.clickhouse.client.api.internal.DataTypeConverter;
import com.clickhouse.client.api.query.QueryResponse;
import org.testng.annotations.Test;

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import java.util.Collections;
import java.util.Date;
import java.util.Map;

public class ScratchDateTimeParamTest {

    private static void show(String label, Object value) {
        System.out.println("FORMATTED " + label + " -> ["
                + DataTypeConverter.INSTANCE.convertParameterToString(value) + "]");
    }

    private static void run(Client client, String label, String type, Object value) {
        String sql = "SELECT {d:" + type + "} AS dt";
        Map<String, Object> params = Collections.singletonMap("d", value);
        try (QueryResponse resp = client.query(sql, params, null).get()) {
            ClickHouseBinaryFormatReader reader = client.newBinaryFormatReader(resp);
            reader.next();
            System.out.println("RESULT " + label + " type=" + type + " -> OK " + reader.getString("dt"));
        } catch (Exception e) {
            System.out.println("RESULT " + label + " type=" + type + " -> ERROR " + e.getMessage());
        }
    }

    @Test(groups = {"scratch"})
    public void testDateTimeParamWithMillis() {
        LocalDateTime ldtMs = LocalDateTime.of(2025, 3, 19, 10, 30, 0, 500_000_000);
        LocalDateTime ldtNoMs = LocalDateTime.of(2025, 3, 19, 10, 30, 0);
        Instant instMs = ldtMs.toInstant(ZoneOffset.UTC);
        ZonedDateTime zdtMs = ldtMs.atZone(ZoneId.of("UTC"));
        Date utilDate = Date.from(instMs);
        java.sql.Timestamp ts = java.sql.Timestamp.valueOf(ldtMs);

        show("LocalDateTime(ms=500)", ldtMs);
        show("Instant(ms=500)", instMs);
        show("ZonedDateTime(ms=500)", zdtMs);
        show("java.util.Date(ms=500)", utilDate);
        show("java.sql.Timestamp(ms=500)", ts);

        try (Client client = new Client.Builder()
                .addEndpoint("http://localhost:8123")
                .setUsername("default")
                .setPassword("")
                .compressServerResponse(false)
                .build()) {
            run(client, "LocalDateTime(ms=500)", "DateTime('UTC')", ldtMs);
            run(client, "LocalDateTime(ms=0)", "DateTime('UTC')", ldtNoMs);
            run(client, "LocalDateTime(ms=500)", "DateTime64(3,'UTC')", ldtMs);
            run(client, "Instant(ms=500)", "DateTime('UTC')", instMs);
            run(client, "ZonedDateTime(ms=500)", "DateTime('UTC')", zdtMs);
            run(client, "java.util.Date(ms=500)", "DateTime('UTC')", utilDate);
            run(client, "java.sql.Timestamp(ms=500)", "DateTime('UTC')", ts);
        }
    }
}
Actual output (current main, server 26.11.2.4)
FORMATTED LocalDateTime(ms=500)      -> [2025-03-19T10:30:00.500]
FORMATTED Instant(ms=500)            -> [2025-03-19T10:30:00.500Z]
FORMATTED ZonedDateTime(ms=500)      -> [2025-03-19T10:30:00.500Z[UTC]]
FORMATTED java.util.Date(ms=500)     -> [Wed Mar 19 10:30:00 UTC 2025]
FORMATTED java.sql.Timestamp(ms=500) -> [2025-03-19 10:30:00.5]

RESULT LocalDateTime(ms=500)  type=DateTime('UTC')     -> ERROR Code: 457. DB::Exception: Value 2025-03-19T10:30:00.500 cannot be parsed as DateTime('UTC') for query parameter 'd' because it isn't parsed completely: only 19 of 23 bytes was parsed: 2025-03-19T10:30:00. (BAD_QUERY_PARAMETER)
RESULT LocalDateTime(ms=0)    type=DateTime('UTC')     -> ERROR Code: 41. DB::Exception: Cannot parse time component of DateTime 10:30: value 2025-03-19T10:30 cannot be parsed as DateTime('UTC') for query parameter 'd'. (CANNOT_PARSE_DATETIME)
RESULT LocalDateTime(ms=500)  type=DateTime64(3,'UTC') -> OK 2025-03-19 10:30:00.5
RESULT Instant(ms=500)        type=DateTime('UTC')     -> ERROR Code: 457. DB::Exception: Value 2025-03-19T10:30:00.500Z cannot be parsed as DateTime('UTC') ... only 19 of 24 bytes was parsed
RESULT ZonedDateTime(ms=500)  type=DateTime('UTC')     -> ERROR Code: 457. DB::Exception: Value 2025-03-19T10:30:00.500Z[UTC] cannot be parsed as DateTime('UTC') ... only 19 of 29 bytes was parsed
RESULT java.util.Date(ms=500) type=DateTime('UTC')     -> ERROR Code: 41. DB::Exception: Cannot parse datetime: value Wed Mar 19 10:30:00 UTC 2025 cannot be parsed as DateTime('UTC') for query parameter 'd'. (CANNOT_PARSE_DATETIME)
RESULT java.sql.Timestamp(ms=500) type=DateTime('UTC') -> ERROR Code: 457. DB::Exception: Value 2025-03-19 10:30:00.5 cannot be parsed as DateTime('UTC') ... only 19 of 21 bytes was parsed

The LocalDateTime(ms=0) line is the already-reported #3387; it is included only to separate the two failures.

Expected

A date/time value binds to a DateTime placeholder, the way the same value inside Array(DateTime) already does. The server accepts 2025-03-19 10:30:00 for a DateTime parameter and 2025-03-19 10:30:00.500 for a DateTime64(3) parameter.

Suggested fix

DataTypeConverter.convertParameterToString (client-v2/src/main/java/com/clickhouse/client/api/internal/DataTypeConverter.java:269) needs the declared parameter type to pick between the whole-second and the fractional text form; the converter already has type-aware dateTimeToString(Object, ClickHouseColumn) helpers for the write path. Options a maintainer may want to weigh:

  • read the {name:Type} placeholder out of the SQL text and route the value through the existing type-aware formatters (this is the direction discussed in ClickHouse/clickhouse-js#1204), or
  • expose a typed parameter API so the caller declares the target type, or
  • at minimum, give Instant, ZonedDateTime, OffsetDateTime, java.util.Date and java.sql.Timestamp a ClickHouse text form instead of String.valueOf, and document that a value with sub-second precision needs a DateTime64(n) placeholder.

Whatever is chosen should also cover Nullable(DateTime), which fails the same way.

Link

Relayed from ClickHouse/clickhouse-js#1204 · tracking issue ClickHouse/integrations-ai-playground#794

Linguagem predominante
Java
Estrelas
1.6k
Forks
657
Merge médio
2d 6h
PRs com merge (30d)
36

Preparar o ambiente

Primeiros passos

  1. Leia a issue inteira e depois o guia de contribuição do projeto.
  2. Comente na issue dizendo que vai assumir — evita que duas pessoas façam o mesmo trabalho.
  3. Faça um fork do repositório e trabalhe em uma branch.
  4. Abra um pull request que referencie o número da issue.

Mais de ClickHouse/clickhouse-java

Todas as issues de ClickHouse/clickhouse-java

Issues semelhantes

Mais issues de Java

Receba novas issues na sua caixa de entrada

Um resumo curto de issues do GitHub para quem está começando.