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
4 changes: 2 additions & 2 deletions docs/clickhouse-docs/jdbc.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -358,7 +358,7 @@ There are few ways to change the mapping:
| FixedString | VARCHAR | java.lang.String |

- `String` can be read only as `java.lang.String` or `byte[]`.
- `FixedString` is read as is and will be padded with zeros to the length of the column. (For example `FixedString(10)` for `'John'` will be read as `'John\0\0\0\0\0\0\0\0\0'`.)
- `FixedString(N)` values are padded with zero bytes (`\0`) to `N` bytes. `getString(...)`, and `getObject(...)` when it returns a `String`, cut the value after its last valid UTF-8 character: they remove the trailing `\0` characters and an incomplete multi-byte character at the end (decoded as `U+FFFD`). For example `FixedString(10)` for `'John'` is read as `'John'`. `getBytes(...)`, `getBinaryStream(...)` and `getObject(..., byte[].class)` return all `N` bytes.

**Enum Types**

Expand Down Expand Up @@ -1002,7 +1002,7 @@ try (Connection conn = DriverManager.getConnection(url, properties)) {
| String | ✅ | VARCHAR | java.lang.String | VARCHAR | java.lang.String |
| FixedString | ✅ | VARCHAR | java.lang.String | VARCHAR | java.lang.String |

- `FixedString` is read as is in both versions. For example `FixedString(10)` for `'John'` will be read as `'John\0\0\0\0\0\0\0\0\0'`.
- `FixedString` text is different: V1 reads it as is, and V2 `getString(...)` and `getObject(...)` (when it returns a `String`) remove the trailing `\0` padding and an incomplete multi-byte character at the end. For example `FixedString(10)` for `'John'` is read as `'John\0\0\0\0\0\0'` in V1 and as `'John'` in V2. In V2, `getBytes(...)` returns all `N` bytes.
- When `PreparedStatement#setBytes` is used it will be converted to `unhex('<hex_string>')` and then read as `String`.
- Strings are stored in UTF-8 encoding.

Expand Down
2 changes: 2 additions & 0 deletions docs/features.md
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,7 @@ Compatibility-sensitive traits:
- JDBC escape processing: Translates supported JDBC escape syntax for dates, timestamps, and functions before execution. Escape sequences are only recognized outside of quoted text, so string literals and quoted identifiers — including inlined parameter values that contain `{fn `, `{d '...'}`, or `{ts '...'}` — are passed through unchanged.
- Result set streaming: Streams result sets from ClickHouse binary formats and `FORMAT JSONEachRow`, enforces max-row limits, and manages result-set lifecycle correctly.
- Binary string reads: `ResultSet#getBytes(int|String)` and `ResultSet#getBinaryStream(int|String)` return the raw bytes of a `String`/`FixedString` column. Combined with the `binary_string_support` connection property, non-UTF-8/binary content stored in `String` columns round-trips byte-for-byte; `NULL` values report `null` with `wasNull()` set. `ResultSet#getObject(...)` never exposes the internal `StringValue` holder for these columns: `getObject(column, byte[].class)` returns the raw bytes, while `getObject(column, Object.class)` and the no-type `getObject(column)` overloads return a decoded `String`.
- `FixedString` text reads: `ResultSet#getString(int|String)`, and `ResultSet#getObject(...)` when it returns a `String`, cut a `FixedString(N)` value after its last valid UTF-8 character. The server pads a value that is shorter than `N` bytes with zero bytes (`\0`), and a value that is cut to `N` bytes (for example with `left`) can end in an incomplete multi-byte character. `toFixedString('Dario', 10)` is read as `"Dario"`, not as `"Dario\0\0\0\0\0"`, and `toFixedString(left('José', 4), 4)` as `"Jos"`. This applies to `FixedString`, `Nullable(FixedString)`, `LowCardinality(FixedString)` and `SimpleAggregateFunction(f, FixedString)` columns of the binary formats, also with `binary_string_support`, and has no setting. The binary accessors (`getBytes(...)`, `getBinaryStream(...)`, `getObject(..., byte[].class)`) are not changed. A `FORMAT JSONEachRow` result set has no `FixedString` column type, so its values are not changed; the server setting `output_format_trim_fixed_string` removes the zero bytes there.
- Result-set metadata: Exposes JDBC `ResultSetMetaData` backed by ClickHouse column schema.
- Database metadata: Implements JDBC `DatabaseMetaData` for ClickHouse catalogs, schemas, tables, columns, and related capability reporting.
- Metadata with `SHOW` statements: By default `DatabaseMetaData#getSchemas`, `#getTables` and `#getColumns` use `SHOW DATABASES`, `SHOW FULL TABLES` and `DESCRIBE TABLE`, so they also return tables that the server does not show in the system tables by default (for example, tables of `DataLakeCatalog` databases). The driver property `jdbc_metadata_use_show_statements=false` selects the `system.databases`, `system.tables` and `system.columns` queries.
Expand All @@ -117,6 +118,7 @@ Compatibility-sensitive traits:
- `?` placeholder detection is SQL-aware and should not treat question marks inside quoted strings, quoted identifiers, comments, casts, or similar syntax as bind parameters.
- String-like ClickHouse values have stable JDBC expectations: `String`, `FixedString`, and `Enum` values are returned as strings, while `UUID` is available both as `getString()` and `getObject(..., UUID.class)`.
- Binary access to `String`/`FixedString` columns is compatibility-sensitive: `getBytes(...)` and `getBinaryStream(...)` expose the raw column bytes (not a re-encoded text literal), and a `NULL` column returns `null` with `wasNull()` reporting `true`. The `binary_string_support` connection property is passed through to the underlying `client-v2` transport.
- Trimming of `FixedString` text is compatibility-sensitive and limited to `getString(...)` and `getObject(...)` results of type `String` for a `FixedString` column. jdbc-v2 sees the text after the UTF-8 decoding, so it removes the trailing `\0` characters (zero bytes) and the trailing replacement characters `U+FFFD` (bytes that are not valid UTF-8). A real `U+FFFD` at the end of the value is also removed. These characters inside the value, and trailing spaces, are kept. This trimming does not apply to `String` columns, to `FixedString` values inside `Array`, `Tuple`, `Map`, `Variant` or `Dynamic`, or to `getNString`, `getNCharacterStream` and `getUnicodeStream`.
- `Geometry` has a stable JDBC mapping: metadata reports SQL type `ARRAY` with type name `Geometry`, read paths return nested Java arrays rather than custom wrappers, and write paths depend on the caller preserving the intended point/array nesting shape.
- JDBC `Geometry` writes share the same ambiguity as the client serializer: variant selection is inferred from nesting depth, so `Ring` versus `LineString` versus `MultiPoint`, and `Polygon` versus `MultiLineString`, are not currently distinguishable when writing through the generic `Geometry` path.
- JDBC `FORMAT JSONEachRow` support is opt-in through the `jdbc_json_parser_factory` driver property, whose value must be a fully-qualified `JsonParserFactory` class name with a public no-argument constructor; JSONEachRow numeric and structured value behavior follows the selected parser and configured server output settings. Inferred JSON arrays are returned from `ResultSet.getObject(...)` as parser-native `List` values rather than JDBC `Array` values because JSONEachRow does not include element metadata. JDBC temporal typed accessors such as `getTimestamp(...)` are not guaranteed for JSONEachRow result sets; callers that need stable JDBC temporal conversions should use the binary default format or perform application-level conversion from string/object values. The recommended way to read JSON in JDBC is configuring `format=JSONEachRow` in connection properties (along with `jdbc_json_parser_factory`). Setting `format=` (empty or `null`) is an option: while it permits SQL query `FORMAT` clauses to take effect, any statement without an explicit `FORMAT` clause will fail because ClickHouse server falls back to `default_format` (`TabSeparated` or what set in `clickhouse_setting_default_format` on the connection). `DatabaseMetaData` methods are exempt — they pin `RowBinaryWithNamesAndTypes` in the settings of the statements they run internally, so metadata works for any value of `format`.
Expand Down
10 changes: 10 additions & 0 deletions history/latest/3288.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
## Breaking changes

- **[jdbc-v2]** `ResultSet#getString(...)`, and `ResultSet#getObject(...)` when it returns a `String`, now cut a
`FixedString(N)` value after its last valid UTF-8 character: the trailing zero bytes (`\0`) that the server adds to a
value shorter than `N` bytes, and an incomplete multi-byte character at the end, are removed.
`toFixedString('Dario', 10)` is read as `"Dario"`, not as `"Dario\0\0\0\0\0"`. Applications such as Tableau 2026.3
show these zero bytes. Only top-level `FixedString` columns change. An application that removes the zero bytes itself
(for example with `indexOf('\0')`), or that expects a text of `N` characters, must change. To read all `N` bytes, use
`getBytes(...)`, `getBinaryStream(...)` or `getObject(..., byte[].class)`, which are not changed.
(https://github.com/ClickHouse/clickhouse-java/issues/3288)
27 changes: 25 additions & 2 deletions jdbc-v2/src/main/java/com/clickhouse/jdbc/ResultSetImpl.java
Original file line number Diff line number Diff line change
Expand Up @@ -317,7 +317,8 @@ public String getString(String columnLabel) throws SQLException {
try {
if (reader.hasValue(columnLabel)) {
wasNull = false;
return reader.getString(columnLabel);
String value = reader.getString(columnLabel);
return value == null ? null : trimFixedString(columnLabel, value);
} else {
wasNull = true;
return null;
Expand All @@ -327,6 +328,27 @@ public String getString(String columnLabel) throws SQLException {
}
}

/**
* Cuts the text of a {@code FixedString} column after its last valid UTF-8 character. The server pads a
* {@code FixedString(N)} value that is shorter than {@code N} bytes with zero bytes, and a value that is cut to
* {@code N} bytes can end in an incomplete multi-byte character. The UTF-8 decoding gives {@code '\0'} for a zero
* byte and the replacement character U+FFFD for bytes that are not valid UTF-8: the first 1, 2 or 3 bytes of a
* 2-, 3- or 4-byte character decode to one U+FFFD. These characters are removed from the end, so the text ends
* with the last complete character. The same characters inside the value are kept. The text of other column
* types is returned unchanged.
*/
private String trimFixedString(String columnLabel, String value) {

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.

but this also will cut 2, 3 ,4 byte characters incorrectly so they will look agly. We can detect it and cut before.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

I checked this. The cut character is already removed. client-v2 decodes the FixedString bytes as UTF-8, and the first 1, 2 or 3 bytes of a 2-, 3- or 4-byte character decode to one U+FFFD (the same on JDK 8 and JDK 17). The loop removes the trailing U+FFFD together with the \0 padding, so the text ends with the last complete character:

Value Bytes getString
toFixedString(left('aé', 2), 4) 61 C3 00 00 "a"
toFixedString(left('a€', 2), 2) 61 E2 "a"
toFixedString(left('a€', 3), 6) 61 E2 82 00 00 00 "a"
toFixedString(left('a😀', 2), 2) 61 F0 "a"
toFixedString(left('a😀', 3), 5) 61 F0 9F 00 00 "a"
toFixedString(left('a😀', 4), 4) 61 F0 9F 98 "a"
toFixedString(left('é€😀', 8), 10) C3 A9 E2 82 AC F0 9F 98 00 00 "é€"

In 61931bf I added these rows to testFixedStringTextRead (with binary_string_support off and on), and the Javadoc now says this. With a trim of \0 only, these 16 cases fail and the text ends in U+FFFD.

One limit: jdbc-v2 gets the decoded text, not the bytes (client-v2 decodes FixedString when binary_string_support is off). So a real U+FFFD (EF BF BD) at the end is also removed. To keep it, the check must run on the bytes before the decoding, and that needs a change in client-v2. Do you want that, or is the current result correct for you?

int end = value.length();
while (end > 0 && (value.charAt(end - 1) == '\0' || value.charAt(end - 1) == '\uFFFD')) {
end--;
}
if (end == value.length()
|| getSchema().getColumnByName(columnLabel).getValueDataType() != ClickHouseDataType.FixedString) {
return value;
}
return value.substring(0, end);
}

@Override
public boolean getBoolean(String columnLabel) throws SQLException {
checkClosed();
Expand Down Expand Up @@ -1556,7 +1578,8 @@ public <T> T getObjectImpl(String columnLabel, Class<?> type, Map<String, Class<
"Use getObject(...) to read this column.");
}

return (T) JdbcUtils.convert(value, type, column, multiDimensionalArrayElementType);
Object result = JdbcUtils.convert(value, type, column, multiDimensionalArrayElementType);
return (T) (result instanceof String ? trimFixedString(columnLabel, (String) result) : result);
} else {
wasNull = true;
return null;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2071,6 +2071,79 @@ public void testStringsUsedAsBytes() throws Exception {
}
}

@Test(groups = { "integration" }, dataProvider = "testFixedStringTextReadDP")
public void testFixedStringTextRead(String expression, String expected, boolean binaryStringSupport)
throws Exception {
Properties props = new Properties();
props.put(ClientConfigProperties.BINARY_STRING_SUPPORT.getKey(), String.valueOf(binaryStringSupport));
try (Connection conn = getJdbcConnection(props);
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT " + expression + " AS v")) {
assertTrue(rs.next());
assertEquals(rs.getString(1), expected);
assertEquals(rs.getString("v"), expected);
assertEquals(rs.getObject(1), expected);
assertEquals(rs.getObject("v", String.class), expected);
assertEquals(rs.getObject(1, Object.class), expected);
assertEquals(rs.getObject("v", Map.of("FixedString", String.class)), expected);
assertFalse(rs.wasNull());
assertFalse(rs.next());
}
}

@DataProvider(name = "testFixedStringTextReadDP")
public Object[][] testFixedStringTextReadDP() {
Object[][] values = {
{ "toFixedString('Dario', 10)", "Dario" },
{ "toFixedString('Dario ', 10)", "Dario " },
{ "toFixedString('abcd', 4)", "abcd" },
{ "toFixedString('', 4)", "" },
{ "toFixedString('a\u00e9\u20ac\ud83d\ude00', 14)", "a\u00e9\u20ac\ud83d\ude00" },
{ "toFixedString(left('Jos\u00e9', 4), 4)", "Jos" },
{ "toFixedString(left('a\u00e9', 2), 4)", "a" },
{ "toFixedString(left('a\u20ac', 2), 2)", "a" },
{ "toFixedString(left('a\u20ac', 3), 6)", "a" },
{ "toFixedString(left('a\ud83d\ude00', 2), 2)", "a" },
{ "toFixedString(left('a\ud83d\ude00', 3), 5)", "a" },
{ "toFixedString(left('a\ud83d\ude00', 4), 4)", "a" },
{ "toFixedString(left('\u00e9\u20ac\ud83d\ude00', 8), 10)", "\u00e9\u20ac" },
{ "CAST(unhex('6100620000') AS FixedString(5))", "a\0b" },
{ "CAST(unhex('61FF62') AS FixedString(4))", "a\uFFFDb" },
{ "CAST('ab' AS Nullable(FixedString(4)))", "ab" },
{ "CAST('ab' AS LowCardinality(FixedString(4)))", "ab" },
{ "CAST('ab' AS LowCardinality(Nullable(FixedString(4))))", "ab" },
{ "CAST('ab' AS SimpleAggregateFunction(any, FixedString(4)))", "ab" },
};
List<Object[]> rows = new ArrayList<>();
for (Object[] value : values) {
rows.add(new Object[] { value[0], value[1], false });
rows.add(new Object[] { value[0], value[1], true });
}
return rows.toArray(new Object[0][]);
}

@Test(groups = { "integration" })
public void testFixedStringTextReadKeepsOtherValues() throws Exception {
try (Connection conn = getJdbcConnection();
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT toFixedString('ab', 4) AS fixed, 'ab\\0\\0' AS str, "
+ "[toFixedString('ab', 4)] AS arr, CAST(NULL AS Nullable(FixedString(4))) AS nul")) {
assertTrue(rs.next());
byte[] padded = { 'a', 'b', 0, 0 };
assertEquals(rs.getBytes("fixed"), padded);
assertEquals(rs.getBinaryStream("fixed").readAllBytes(), padded);
assertEquals(rs.getObject("fixed", byte[].class), padded);
assertEquals(rs.getString("str"), "ab\0\0");
assertEquals(rs.getObject("str"), "ab\0\0");
assertEquals(java.lang.reflect.Array.get(rs.getArray("arr").getArray(), 0), "ab\0\0");
assertNull(rs.getString("nul"));
assertTrue(rs.wasNull());
assertNull(rs.getObject("nul"));
assertTrue(rs.wasNull());
assertFalse(rs.next());
}
}

private static byte[] readClickHouseLogo() {
try (InputStream is = JdbcDataTypeTests.class.getResourceAsStream("/ch_logo.png")) {
Assert.assertNotNull(is, "ch_logo.png not found in test resources");
Expand Down
Loading