Skip to content

Passing an Instant as a query parameter in client-v2 fails during parsing #2456

Description

@jnd77

Description

The API for query parameters with an Instant generates a query which can not be parsed by the server.

Steps to reproduce

See example below.

Error Log or Exception StackTrace

com.clickhouse.client.api.ServerException: Code: 457. DB::Exception: Value 2025-06-16T11:54:26.413588562Z cannot be parsed as DateTime64 for query parameter 'year_start' because it isn't parsed completely: only 29 of 30 bytes was parsed: 2025-06-16T11:54:26.413588562. (BAD_QUERY_PARAMETER) (version 25.3.3.42 (official build))

Expected Behaviour

It should work smoothly.

Code Example

  @Test
  void testParamsWithInstant() throws Exception {
    final Client client = new Client.Builder()
        .addEndpoint(Protocol.HTTP, "localhost", 8123, false)
        .setUsername("default")
        .setPassword("")
        .build();
    final Map<String, Object> params = Map.of("year_start", Instant.now());
    // This query should not throw an exception
    client.query("SELECT * FROM system.tables WHERE metadata_modification_time < {year_start:DateTime64}", params).get();
  }

Test is passing when serializing the parameter to a String, e.g. "2025-06-16 11:54:26.413588562".

A related query with an array also fails with the following parsing error:

com.clickhouse.client.api.ServerException: Code: 130. DB::Exception: Cannot read array from text, expected comma or end of array, found '-': value [2025-06-16T12:03:29.844112439Z] cannot be parsed as Array(DateTime64) for query parameter 'year_start'. (CANNOT_READ_ARRAY_FROM_TEXT) (version 25.3.3.42 (official build)) 

The error above was done with:

    final Map<String, Object> params = Map.of("year_start", List.of(Instant.now()));
    // This query should not throw an exception
    client.query("SELECT * FROM system.tables WHERE metadata_modification_time in {year_start:Array(DateTime64)}", params).get();

Configuration

Client Configuration

See above.

Environment

  • Cloud
  • Client version:
  • Language version:
  • OS:

ClickHouse Server

  • ClickHouse Server version: 25.3.3.42
  • ClickHouse Server non-default settings, if any:
  • CREATE TABLE statements for tables involved:
  • Sample data for all these tables, use clickhouse-obfuscator if necessary

Activity

  1. added
    jdbc
    data-types
    on Jun 30, 2025
  2. enqueue commented on Jul 10, 2025

    @enqueue
    Contributor

    Great bug report 👏

    The reason for this can be found in HttpAPIClientHelper.java#L557 ff.:

    if (requestConfig.containsKey("statement_params")) {
        Map<String, Object> params = (Map<String, Object>) requestConfig.get("statement_params");
        for (Map.Entry<String, Object> entry : params.entrySet()) {
            req.addParameter("param_" + entry.getKey(), String.valueOf(entry.getValue()));
        }
    }

    This implementation simply invokes toString() on any parameter value supplied, which leads to incompatible behavior.

    I would try to solve this issue, e.g. by using SerializerUtils methods. It would be great if we knew the ClickHouse data type, but that would require parsing the parameterized query -> no. Would that be OK for you @chernser ? Any further hints?

    Bonus: Check that Unicode parameters work.

    final Map<String, Object> params = Map.of("happy", "🙂");
    client.query("SELECT * FROM foo WHERE bar = {happy:String}", params).get();
  3. chernser commented on Jul 10, 2025

    @chernser
    Contributor

    @enqueue thank you for helping with this issue!

    Yes, we should do NO query parsing on client side.
    We used just toString because it should not be too complex: in most cases application should care about converting java objects to a string.
    Lets start with adding utility methods to com.clickhouse.client.api.DataTypeUtils.
    I do want to keep main logic thin because it affects performance.
    You may use a SerializerUtils but this class might be refactored soon.

  4. enqueue commented on Jul 10, 2025

    @enqueue
    Contributor

    @chernser OK, I will try and use / enhance com.clickhouse.client.api.DataTypeUtils. This would allow us to test using simple JUnit tests.

    Perhaps we can re-use some code from JDBC PreparedStatementImpl.encodeObject() or from SerializerUtils. I will first have to understand how DateTime64 works with different precision etc.

  5. added
    client
    and removed
    jdbc
    on Jul 12, 2025
  6. enqueue commented on Jul 12, 2025

    @enqueue
    Contributor

    It's not as easy as it looks. Without parsing statement we do not know if target of parameter is DateTime64 or not.

    I tried different parameter values via curl, and I did not find a satisfactory solution.

    If we assumed DateTime64, we could pass decimal parameter value. But this would not work for Date, DateTime, or DateTime32 column types.

    Formatting Instant as some date / time string is not nice, either. Even if setting date_time_input_format setting to "best_effort", I was not able to find a String representation that would satisfy all requirements.

  7. chernser commented on Jul 12, 2025

    @chernser
    Contributor

    @enqueue
    If I'm understood the problem correctly it is: application doesn't know haw to format Instance/Date/Time into Date/Date64/DateTime64.

    So we need to provide set of conversion methods for most common cases + give access to formatters we use in this methods.
    As the result we would get something

    instantAsDateStr(Instant)
    instantAsDateTime64(Instant)
    

    Conversion and type guessing is mostly always application specific and client may not handle everything. But client should provide tools. like this methods.
    In the future we may create a request builder what will be separate from the main code to not add extra logic. Another option is to use something like JOOQ that helps to build requests from application data.

  8. enqueue commented on Jul 21, 2025

    @enqueue
    Contributor

    Tried to simply use decimal everywhere, because we do not know targeted precision. However, I probably ran into some overflow / parsing issue on ClickHouse side. Will investigate further.

    SELECT
        fromUnixTimestamp64Nano(1753013142232323232) AS fromTimestamp,
        toTypeName(fromTimestamp) AS timestampType,
        toDecimal64(fromTimestamp, 9) AS decimalValue,
        toDateTime64(1753013142.2323232, 9) AS dateTimeViaDecimal,
        toDecimal64(1753013142.2323232, 9) AS manualValue
    
    Query id: c8840a09-55a0-4bad-af99-921bc52aa3da
    
       ┌─────────────────fromTimestamp─┬─timestampType─┬─────────decimalValue─┬────────────dateTimeViaDecimal─┬──────────manualValue─┐
    1. │ 2025-07-20 14:05:42.232323232 │ DateTime64(9) │ 1753013142.232323232 │ 2025-07-20 14:05:42.232323072 │ 1753013142.232323072 │
       └───────────────────────────────┴───────────────┴──────────────────────┴───────────────────────────────┴──────────────────────┘
    
    1 row in set. Elapsed: 0.003 sec. 
    
  9. added this to the 0.9.1 milestone on Jul 23, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    clientdata-typesenhancement

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions