Skip to content

World's most powerful open data catalog for building a high-performance, geo-distributed and federated metadata lake.

[#11841] fix(clickhouse): fix partition expression round-trip for day transform and nested functions (#11842)

weijiajunc0293f6cbac3
diff --git a/catalogs-contrib/catalog-jdbc-clickhouse/src/main/java/org/apache/gravitino/catalog/clickhouse/operations/ClickHouseTableOperations.java b/catalogs-contrib/catalog-jdbc-clickhouse/src/main/java/org/apache/gravitino/catalog/clickhouse/operations/ClickHouseTableOperations.java
index dc057389c3..3e870fd8b1 100644
--- a/catalogs-contrib/catalog-jdbc-clickhouse/src/main/java/org/apache/gravitino/catalog/clickhouse/operations/ClickHouseTableOperations.java
+++ b/catalogs-contrib/catalog-jdbc-clickhouse/src/main/java/org/apache/gravitino/catalog/clickhouse/operations/ClickHouseTableOperations.java
@@ -913,6 +913,7 @@ public class ClickHouseTableOperations extends JdbcTableOperations {
// NOTE: Cannot use getColumnBuilder() here because we need to override the default
// value for MATERIALIZED/ALIAS columns between getBasicJdbcColumnInfo() and build().
List<JdbcColumn> jdbcColumns = new ArrayList<>();
+ Map<String, String> nativeColumnTypes = new HashMap<>();
ResultSet columns = getColumns(connection, databaseName, tableName);
while (columns.next()) {
if (!Objects.equals(columns.getString("TABLE_NAME"), tableName)) {
@@ -922,6 +923,7 @@ public class ClickHouseTableOperations extends JdbcTableOperations {
// Correct default value for MATERIALIZED/ALIAS columns: the JDBC driver
// hardcodes IS_GENERATEDCOLUMN to 'NO', so re-derive with isExpression=true.
String columnName = columns.getString("COLUMN_NAME");
+ nativeColumnTypes.put(columnName, columns.getString("TYPE_NAME"));
String defaultKind = defaultKinds.getOrDefault(columnName, "");
if ("MATERIALIZED".equals(defaultKind) || "ALIAS".equals(defaultKind)) {
String columnDef = columns.getString("COLUMN_DEF");
@@ -949,7 +951,8 @@ public class ClickHouseTableOperations extends JdbcTableOperations {
SystemTableMetadata systemTableMetadata =
getSystemTableMetadata(connection, databaseName, tableName);
String partitionKey = getPartitionKey(connection, databaseName, tableName);
- jdbcTableBuilder.withPartitioning(parsePartitioning(partitionKey));
+ jdbcTableBuilder.withPartitioning(
+ ClickHouseTableSqlUtils.parsePartitioning(partitionKey, nativeColumnTypes));
jdbcTableBuilder.withSortOrders(systemTableMetadata.sortOrders());
Distribution distribution = getDistributionInfo(connection, databaseName, tableName);
diff --git a/catalogs-contrib/catalog-jdbc-clickhouse/src/main/java/org/apache/gravitino/catalog/clickhouse/operations/ClickHouseTableSqlUtils.java b/catalogs-contrib/catalog-jdbc-clickhouse/src/main/java/org/apache/gravitino/catalog/clickhouse/operations/ClickHouseTableSqlUtils.java
index 1294ed6085..85b1dd52e8 100644
--- a/catalogs-contrib/catalog-jdbc-clickhouse/src/main/java/org/apache/gravitino/catalog/clickhouse/operations/ClickHouseTableSqlUtils.java
+++ b/catalogs-contrib/catalog-jdbc-clickhouse/src/main/java/org/apache/gravitino/catalog/clickhouse/operations/ClickHouseTableSqlUtils.java
@@ -54,6 +54,8 @@ final class ClickHouseTableSqlUtils {
Pattern.compile("toYear\\((.+)\\)", Pattern.CASE_INSENSITIVE);
private static final Pattern TO_MONTH_PATTERN =
Pattern.compile("toYYYYMM\\((.+)\\)", Pattern.CASE_INSENSITIVE);
+ private static final Pattern TO_DAY_PATTERN =
+ Pattern.compile("toYYYYMMDD\\((.+)\\)", Pattern.CASE_INSENSITIVE);
private static final Pattern TO_START_OF_WEEK_PATTERN =
Pattern.compile("toStartOfWeek[(](.+)[)]", Pattern.CASE_INSENSITIVE);
private static final Pattern TO_START_OF_MONTH_PATTERN =
@@ -353,6 +355,11 @@ final class ClickHouseTableSqlUtils {
}
static Transform[] parsePartitioning(@Nullable String partitionKey) {
+ return parsePartitioning(partitionKey, Collections.emptyMap());
+ }
+
+ static Transform[] parsePartitioning(
+ @Nullable String partitionKey, Map<String, String> nativeColumnTypes) {
if (StringUtils.isBlank(partitionKey)) {
return Transforms.EMPTY_TRANSFORM;
}
@@ -369,7 +376,7 @@ final class ClickHouseTableSqlUtils {
if (StringUtils.isBlank(expression)) {
continue;
}
- Transform transform = parsePartitionExpression(expression);
+ Transform transform = parsePartitionExpression(expression, nativeColumnTypes);
if (transform == null) {
// A single unsupported native expression means the whole partition key cannot be
// represented as structured transforms.
@@ -390,7 +397,9 @@ final class ClickHouseTableSqlUtils {
.formatted(quoteIdentifier(partitionFieldName(transform)));
case Transforms.NAME_OF_MONTH -> "toYYYYMM(%s)"
.formatted(quoteIdentifier(partitionFieldName(transform)));
- case Transforms.NAME_OF_DAY -> "toDate(%s)"
+ // Day transforms use the integer form; legacy toDate keys remain readable but are
+ // canonicalized to toYYYYMMDD when creating another table from the loaded transform.
+ case Transforms.NAME_OF_DAY -> "toYYYYMMDD(%s)"
.formatted(quoteIdentifier(partitionFieldName(transform)));
case "tostartofweek" -> "toStartOfWeek(%s)"
.formatted(quoteIdentifier(partitionFieldName(transform)));
@@ -480,6 +489,28 @@ final class ClickHouseTableSqlUtils {
&& !StringUtils.containsAny(identifier, "(", ")", " ", "%", "+", "-", "*", "/");
}
+ /**
+ * Extracts a single column through unary toDate conversions, with bounded nesting. Other wrappers
+ * can change the partition value and are not removed. Explicit time zones and other
+ * multi-argument conversions remain unsupported.
+ */
+ @Nullable
+ static String extractInnermostField(@Nullable String expression) {
+ String current = StringUtils.trim(expression);
+ for (int depth = 0; depth < 10 && StringUtils.isNotBlank(current); depth++) {
+ String identifier = extractPartitionIdentifier(current);
+ if (identifier != null) {
+ return identifier;
+ }
+ Matcher matcher = FUNCTION_WRAPPER_PATTERN.matcher(current);
+ if (!matcher.matches() || !StringUtils.equalsIgnoreCase(matcher.group(1), "toDate")) {
+ return null;
+ }
+ current = StringUtils.trim(matcher.group(2));
+ }
+ return null;
+ }
+
private static boolean isStrictIdentifier(String identifier) {
return StringUtils.isNotBlank(identifier) && identifier.matches("^[a-zA-Z_][a-zA-Z0-9_]*$");
}
@@ -501,24 +532,38 @@ final class ClickHouseTableSqlUtils {
}
@Nullable
- private static Transform parsePartitionExpression(String expression) {
+ private static Transform parsePartitionExpression(
+ String expression, Map<String, String> nativeColumnTypes) {
String trimmedExpression = StringUtils.trim(expression);
Matcher toYearMatcher = TO_YEAR_PATTERN.matcher(trimmedExpression);
if (toYearMatcher.matches()) {
- String identifier = extractPartitionIdentifier(toYearMatcher.group(1));
+ String identifier = extractDatePartitionIdentifier(toYearMatcher.group(1), nativeColumnTypes);
return identifier == null ? null : Transforms.year(identifier);
}
Matcher toYYYYMMMatcher = TO_MONTH_PATTERN.matcher(trimmedExpression);
if (toYYYYMMMatcher.matches()) {
- String identifier = extractPartitionIdentifier(toYYYYMMMatcher.group(1));
+ String identifier =
+ extractDatePartitionIdentifier(toYYYYMMMatcher.group(1), nativeColumnTypes);
return identifier == null ? null : Transforms.month(identifier);
}
Matcher toDateMatcher = TO_DATE_PATTERN.matcher(trimmedExpression);
if (toDateMatcher.matches()) {
- String identifier = extractPartitionIdentifier(toDateMatcher.group(1));
+ String identifier = extractDatePartitionIdentifier(toDateMatcher.group(1), nativeColumnTypes);
+ // toDate accepts strings/numbers and narrows wider temporal ranges. Replacing those casts
+ // with toYYYYMMDD(column) would change values or fail, so retain their native expression.
+ String nativeType = identifier == null ? null : nativeColumnTypes.get(identifier);
+ if (nativeType != null && !"Date".equals(nativeType)) {
+ return null;
+ }
+ return identifier == null ? null : Transforms.day(identifier);
+ }
+
+ Matcher toDayMatcher = TO_DAY_PATTERN.matcher(trimmedExpression);
+ if (toDayMatcher.matches()) {
+ String identifier = extractDatePartitionIdentifier(toDayMatcher.group(1), nativeColumnTypes);
return identifier == null ? null : Transforms.day(identifier);
}
@@ -559,6 +604,22 @@ final class ClickHouseTableSqlUtils {
return identifier == null ? null : Transforms.identity(identifier);
}
+ @Nullable
+ private static String extractDatePartitionIdentifier(
+ String expression, Map<String, String> nativeColumnTypes) {
+ String identifier = extractPartitionIdentifier(expression);
+ if (identifier != null) {
+ return identifier;
+ }
+ identifier = extractInnermostField(expression);
+ // toDate is an identity only for native Date. Other input types can overflow or require
+ // casts. Even DateTime can cross the epoch boundary in a non-UTC timezone when converted
+ // to Date. Without this identity guarantee, retain the native key instead of dropping casts.
+ return identifier != null && "Date".equals(nativeColumnTypes.get(identifier))
+ ? identifier
+ : null;
+ }
+
/**
* Extracts a partition column name from an expression. A backtick-quoted identifier (which may
* contain special characters such as {@code -}) is always treated as a column name. Otherwise the
diff --git a/catalogs-contrib/catalog-jdbc-clickhouse/src/test/java/org/apache/gravitino/catalog/clickhouse/operations/TestClickHouseTableOperations.java b/catalogs-contrib/catalog-jdbc-clickhouse/src/test/java/org/apache/gravitino/catalog/clickhouse/operations/TestClickHouseTableOperations.java
index e8eed507b5..55761d2753 100644
--- a/catalogs-contrib/catalog-jdbc-clickhouse/src/test/java/org/apache/gravitino/catalog/clickhouse/operations/TestClickHouseTableOperations.java
+++ b/catalogs-contrib/catalog-jdbc-clickhouse/src/test/java/org/apache/gravitino/catalog/clickhouse/operations/TestClickHouseTableOperations.java
@@ -1196,7 +1196,7 @@ public class TestClickHouseTableOperations extends TestClickHouse {
Distributions.NONE,
indexes,
ClickHouseUtils.getSortOrders("c1"));
- Assertions.assertTrue(dayPartitionSql.contains("PARTITION BY toDate(`c1`)"));
+ Assertions.assertTrue(dayPartitionSql.contains("PARTITION BY toYYYYMMDD(`c1`)"));
String multiPartitionSql =
ops.buildCreateSql(
@@ -1209,7 +1209,7 @@ public class TestClickHouseTableOperations extends TestClickHouse {
indexes,
ClickHouseUtils.getSortOrders("c1"));
Assertions.assertTrue(
- multiPartitionSql.contains("PARTITION BY tuple(toYear(`c1`), toDate(`c1`))"));
+ multiPartitionSql.contains("PARTITION BY tuple(toYear(`c1`), toYYYYMMDD(`c1`))"));
IllegalArgumentException exception =
Assertions.assertThrows(
@@ -1530,6 +1530,112 @@ public class TestClickHouseTableOperations extends TestClickHouse {
Assertions.assertTrue(exception.getMessage().contains("auto increment"));
}
+ @Test
+ void testDayAndNestedPartitionRoundTrip() throws Exception {
+ String jdbcUrl = containerSuite.getClickHouseContainer().getJdbcUrl(TEST_DB_NAME);
+ try (Connection connection =
+ DriverManager.getConnection(
+ jdbcUrl,
+ containerSuite.getClickHouseContainer().getUsername(),
+ containerSuite.getClickHouseContainer().getPassword());
+ Statement statement = connection.createStatement()) {
+ for (String[] expression :
+ new String[][] {
+ {"toYYYYMMDD(event_time)", "toYYYYMMDD(event_time)", "day", "DateTime"},
+ {"toDate(event_time)", "toYYYYMMDD(event_time)", "day", "Date"},
+ {"toYYYYMM(toDate(event_time))", "toYYYYMM(event_time)", "month", "Date"},
+ {"toYear(toDate(event_time))", "toYear(event_time)", "year", "Date"}
+ }) {
+ String source = RandomStringUtils.randomAlphabetic(16);
+ String target = source + "_copy";
+ try {
+ statement.execute(
+ String.format(
+ "CREATE TABLE %s.%s (event_time %s) ENGINE = MergeTree PARTITION BY %s ORDER BY event_time",
+ TEST_DB_NAME, source, expression[3], expression[0]));
+ JdbcTable loaded = TABLE_OPERATIONS.load(TEST_DB_NAME.toString(), source);
+ Assertions.assertArrayEquals(
+ new Transform[] {
+ switch (expression[2]) {
+ case "day" -> Transforms.day("event_time");
+ case "month" -> Transforms.month("event_time");
+ default -> Transforms.year("event_time");
+ }
+ },
+ loaded.partitioning());
+ TABLE_OPERATIONS.create(
+ TEST_DB_NAME.toString(),
+ target,
+ Arrays.stream(loaded.columns())
+ .map(JdbcColumn.class::cast)
+ .toArray(JdbcColumn[]::new),
+ null,
+ Collections.emptyMap(),
+ loaded.partitioning(),
+ Distributions.NONE,
+ Indexes.EMPTY_INDEXES,
+ getSortOrders("event_time"));
+ JdbcTable recreated = TABLE_OPERATIONS.load(TEST_DB_NAME.toString(), target);
+ Assertions.assertArrayEquals(loaded.partitioning(), recreated.partitioning());
+ Assertions.assertEquals(
+ expression[1], recreated.properties().get(TableConstants.PARTITION_KEY));
+ } finally {
+ statement.execute(String.format("DROP TABLE IF EXISTS %s.%s", TEST_DB_NAME, target));
+ statement.execute(String.format("DROP TABLE IF EXISTS %s.%s", TEST_DB_NAME, source));
+ }
+ }
+ }
+ }
+
+ @Test
+ void testUnsafePartitionCastsRetainNativeExpression() throws Exception {
+ String jdbcUrl = containerSuite.getClickHouseContainer().getJdbcUrl(TEST_DB_NAME);
+ try (Connection connection =
+ DriverManager.getConnection(
+ jdbcUrl,
+ containerSuite.getClickHouseContainer().getUsername(),
+ containerSuite.getClickHouseContainer().getPassword());
+ Statement statement = connection.createStatement()) {
+ // DateTime -> Date can clamp the epoch boundary even though the source type is temporal.
+ try (ResultSet result =
+ statement.executeQuery(
+ "SELECT toYear(toDateTime(0, 'America/New_York')), "
+ + "toYear(toDate(toDateTime(0, 'America/New_York')))")) {
+ Assertions.assertTrue(result.next());
+ Assertions.assertEquals(1969, result.getInt(1));
+ Assertions.assertEquals(1970, result.getInt(2));
+ }
+ for (String[] definition :
+ new String[][] {
+ {"String", "toYYYYMM(toDate(event_time))"},
+ {"UInt32", "toYear(toDate(event_time))"},
+ {"Date32", "toYear(toDate(event_time))"},
+ {"DateTime64(0)", "toYear(toDate(event_time))"},
+ {"DateTime64(3)", "toYear(toDate(event_time))"},
+ {"DateTime('Asia/Shanghai')", "toYear(toDate(event_time))"},
+ {"Date", "toYear(toDateTime(event_time))"},
+ {"DateTime", "toYear(toDate(event_time))"},
+ {"DateTime", "toDate(event_time)"},
+ {"String", "toDate(event_time)"},
+ {"UInt32", "toDate(event_time)"}
+ }) {
+ String table = RandomStringUtils.randomAlphabetic(16);
+ try {
+ statement.execute(
+ String.format(
+ "CREATE TABLE %s.%s (event_time %s) ENGINE = MergeTree PARTITION BY %s ORDER BY event_time",
+ TEST_DB_NAME, table, definition[0], definition[1]));
+ JdbcTable loaded = TABLE_OPERATIONS.load(TEST_DB_NAME.toString(), table);
+ Assertions.assertEquals(0, loaded.partitioning().length, definition[0]);
+ Assertions.assertEquals(
+ definition[1], loaded.properties().get(TableConstants.PARTITION_KEY));
+ } finally {
+ statement.execute(String.format("DROP TABLE IF EXISTS %s.%s", TEST_DB_NAME, table));
+ }
+ }
+ }
+ }
+
@Test
void testParsePartitioningAndIndexExpressions() {
TestableClickHouseTableOperations ops = new TestableClickHouseTableOperations();
diff --git a/catalogs-contrib/catalog-jdbc-clickhouse/src/test/java/org/apache/gravitino/catalog/clickhouse/operations/TestClickHouseTableSqlUtils.java b/catalogs-contrib/catalog-jdbc-clickhouse/src/test/java/org/apache/gravitino/catalog/clickhouse/operations/TestClickHouseTableSqlUtils.java
new file mode 100644
index 0000000000..402a34c6aa
--- /dev/null
+++ b/catalogs-contrib/catalog-jdbc-clickhouse/src/test/java/org/apache/gravitino/catalog/clickhouse/operations/TestClickHouseTableSqlUtils.java
@@ -0,0 +1,228 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.catalog.clickhouse.operations;
+
+import static org.apache.gravitino.catalog.clickhouse.operations.ClickHouseClusterUtils.escapeSingleQuotes;
+
+import java.util.Map;
+import org.apache.gravitino.rel.expressions.NamedReference;
+import org.apache.gravitino.rel.expressions.transforms.Transform;
+import org.apache.gravitino.rel.expressions.transforms.Transforms;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
+
+public class TestClickHouseTableSqlUtils {
+
+ @Test
+ void testEscapeSingleQuotesNormal() {
+ Assertions.assertEquals("my_db", escapeSingleQuotes("my_db"));
+ }
+
+ @Test
+ void testEscapeSingleQuotesWithQuote() {
+ Assertions.assertEquals("test''db", escapeSingleQuotes("test'db"));
+ }
+
+ @Test
+ void testEscapeSingleQuotesMultiple() {
+ Assertions.assertEquals("a''b''c", escapeSingleQuotes("a'b'c"));
+ }
+
+ @Test
+ void testEscapeSingleQuotesEmpty() {
+ Assertions.assertEquals("", escapeSingleQuotes(""));
+ }
+
+ // ---------------------------------------------------------------------------
+ // toPartitionExpression round-trip with day/month/year transforms
+ // ---------------------------------------------------------------------------
+
+ @Test
+ void testToPartitionExpressionDay() {
+ Transform day = Transforms.day("dt");
+ Assertions.assertEquals("toYYYYMMDD(`dt`)", ClickHouseTableSqlUtils.toPartitionExpression(day));
+ }
+
+ @Test
+ void testToPartitionExpressionMonth() {
+ Transform month = Transforms.month("dt");
+ Assertions.assertEquals("toYYYYMM(`dt`)", ClickHouseTableSqlUtils.toPartitionExpression(month));
+ }
+
+ @Test
+ void testToPartitionExpressionYear() {
+ Transform year = Transforms.year("dt");
+ Assertions.assertEquals("toYear(`dt`)", ClickHouseTableSqlUtils.toPartitionExpression(year));
+ }
+
+ @Test
+ void testToPartitionExpressionIdentity() {
+ Transform identity = Transforms.identity(new String[] {"col"});
+ Assertions.assertEquals("`col`", ClickHouseTableSqlUtils.toPartitionExpression(identity));
+ }
+
+ // ---------------------------------------------------------------------------
+ // extractInnermostField — nested function unwrapping
+ // ---------------------------------------------------------------------------
+
+ @Test
+ void testExtractInnermostFieldSimple() {
+ Assertions.assertEquals("dt", ClickHouseTableSqlUtils.extractInnermostField("dt"));
+ }
+
+ @Test
+ void testExtractInnermostFieldBacktickQuoted() {
+ Assertions.assertEquals("dt", ClickHouseTableSqlUtils.extractInnermostField("`dt`"));
+ }
+
+ @Test
+ void testExtractInnermostFieldSingleWrapper() {
+ Assertions.assertEquals("dt", ClickHouseTableSqlUtils.extractInnermostField("toDate(dt)"));
+ }
+
+ @Test
+ void testExtractInnermostFieldNested() {
+ Assertions.assertEquals(
+ "dt", ClickHouseTableSqlUtils.extractInnermostField("toDate(toDate(dt))"));
+ }
+
+ @Test
+ void testExtractInnermostFieldNestedYear() {
+ Assertions.assertEquals(
+ "dt", ClickHouseTableSqlUtils.extractInnermostField("toDate(toDate(toDate(dt)))"));
+ }
+
+ @Test
+ void testExtractInnermostFieldNullOnComplex() {
+ Assertions.assertNull(ClickHouseTableSqlUtils.extractInnermostField("intDiv(col, 100)"));
+ }
+
+ // ---------------------------------------------------------------------------
+ // parsePartitioning — round-trip verification
+ // ---------------------------------------------------------------------------
+
+ @Test
+ void testParsePartitioningRoundTripDay() {
+ Transform[] parsed = ClickHouseTableSqlUtils.parsePartitioning("toYYYYMMDD(dt)");
+ Assertions.assertEquals(1, parsed.length);
+ Assertions.assertEquals("day", parsed[0].name());
+ Assertions.assertEquals("dt", ((NamedReference) parsed[0].arguments()[0]).fieldName()[0]);
+ Assertions.assertEquals(
+ "toYYYYMMDD(`dt`)", ClickHouseTableSqlUtils.toPartitionExpression(parsed[0]));
+ }
+
+ @Test
+ void testParsePartitioningRoundTripMonth() {
+ Transform[] parsed = ClickHouseTableSqlUtils.parsePartitioning("toYYYYMM(dt)");
+ Assertions.assertEquals(1, parsed.length);
+ Assertions.assertEquals("month", parsed[0].name());
+ Assertions.assertEquals(
+ "toYYYYMM(`dt`)", ClickHouseTableSqlUtils.toPartitionExpression(parsed[0]));
+ }
+
+ @Test
+ void testParsePartitioningRoundTripYear() {
+ Transform[] parsed = ClickHouseTableSqlUtils.parsePartitioning("toYear(dt)");
+ Assertions.assertEquals(1, parsed.length);
+ Assertions.assertEquals("year", parsed[0].name());
+ Assertions.assertEquals(
+ "toYear(`dt`)", ClickHouseTableSqlUtils.toPartitionExpression(parsed[0]));
+ }
+
+ @Test
+ void testParsePartitioningNestedToYYYYMM() {
+ Transform[] parsed =
+ ClickHouseTableSqlUtils.parsePartitioning(
+ "toYYYYMM(toDate(dt))", Map.of("dt", "Date", "event-time", "Date"));
+ Assertions.assertEquals(1, parsed.length);
+ Assertions.assertEquals("month", parsed[0].name());
+ Assertions.assertEquals("dt", ((NamedReference) parsed[0].arguments()[0]).fieldName()[0]);
+ }
+
+ @Test
+ void testParsePartitioningNestedToYear() {
+ Transform[] parsed =
+ ClickHouseTableSqlUtils.parsePartitioning(
+ "toYear(toDate(dt))", Map.of("dt", "Date", "event-time", "Date"));
+ Assertions.assertEquals(1, parsed.length);
+ Assertions.assertEquals("year", parsed[0].name());
+ Assertions.assertEquals("dt", ((NamedReference) parsed[0].arguments()[0]).fieldName()[0]);
+ }
+
+ @Test
+ void testUnsupportedNestedExpressionsRemainUnsupported() {
+ for (String expression :
+ new String[] {
+ "toYear(toString(dt))",
+ "toYYYYMM(abs(dt))",
+ "toYYYYMMDD(toYear(dt))",
+ "toDate(toDateTime(dt, 'UTC'))",
+ "toYear(dt + 1)",
+ "tuple(toYYYYMMDD(dt), toYear(abs(dt)))"
+ }) {
+ Assertions.assertEquals(
+ 0, ClickHouseTableSqlUtils.parsePartitioning(expression).length, expression);
+ }
+ Assertions.assertNull(ClickHouseTableSqlUtils.extractInnermostField(null));
+ Assertions.assertNull(ClickHouseTableSqlUtils.extractInnermostField("toDateTime(dt)"));
+ Assertions.assertNull(
+ ClickHouseTableSqlUtils.extractInnermostField(
+ "toDate(".repeat(10) + "dt" + ")".repeat(10)));
+ }
+
+ @Test
+ void testNestedDayAndQuotedColumn() {
+ Transform[] parsed =
+ ClickHouseTableSqlUtils.parsePartitioning(
+ "toYYYYMMDD(toDate(`event-time`))", Map.of("dt", "Date", "event-time", "Date"));
+ Assertions.assertEquals(1, parsed.length);
+ Assertions.assertEquals(
+ "toYYYYMMDD(`event-time`)", ClickHouseTableSqlUtils.toPartitionExpression(parsed[0]));
+ Assertions.assertEquals(
+ "day", ClickHouseTableSqlUtils.parsePartitioning("toDate(dt)")[0].name());
+ }
+
+ @Test
+ void testNestedConversionsRequireSafeNativeColumnType() {
+ for (String type :
+ new String[] {
+ "String",
+ "UInt32",
+ "DateTime",
+ "Date32",
+ "DateTime64(0)",
+ "DateTime64(3)",
+ "DateTime('Asia/Shanghai')"
+ }) {
+ Assertions.assertEquals(
+ 0,
+ ClickHouseTableSqlUtils.parsePartitioning("toYYYYMM(toDate(dt))", Map.of("dt", type))
+ .length,
+ type);
+ }
+ Assertions.assertEquals(
+ 0, ClickHouseTableSqlUtils.parsePartitioning("toYYYYMM(toDate(dt))").length);
+ for (String type : new String[] {"String", "UInt32", "DateTime", "Date32", "DateTime64(3)"}) {
+ Assertions.assertEquals(
+ 0,
+ ClickHouseTableSqlUtils.parsePartitioning("toDate(dt)", Map.of("dt", type)).length,
+ type);
+ }
+ }
+}
diff --git a/docs/jdbc-clickhouse-catalog.md b/docs/jdbc-clickhouse-catalog.md
index ac505482c7..a66144850a 100644
--- a/docs/jdbc-clickhouse-catalog.md
+++ b/docs/jdbc-clickhouse-catalog.md
@@ -340,10 +340,12 @@ The `engine_parameters` property applies to `ReplacingMergeTree`, `SummingMergeT
- `PARTITION BY`: single-column identity and some functions are supported only, and only for MergeTree-family engines. For example `PARTITION BY created_at`, `PARTITION BY toYYYYMM(created_at)`, `PARTITION BY toStartOfWeek(created_at)`, `PARTITION BY toStartOfMonth(created_at)`, `PARTITION BY toStartOfQuarter(created_at)`, and `PARTITION BY toStartOfYear(created_at)` are supported, but `PARTITION BY (created_at + 1)` is not supported.
In all, the following partitioning expressions are supported:
- Identity: `PARTITION BY column_name`
- - Functions: `PARTITION BY toDate(column_name)`, `PARTITION BY toYear(column_name)`, `PARTITION BY toYYYYMM(column_name)`, `PARTITION BY toStartOfWeek(column_name)`, `PARTITION BY toStartOfMonth(column_name)`, `PARTITION BY toStartOfQuarter(column_name)`, and `PARTITION BY toStartOfYear(column_name)`. Other function expressions are not supported as structured transforms.
+ - Functions: `PARTITION BY toYYYYMMDD(column_name)`, `PARTITION BY toYear(column_name)`, `PARTITION BY toYYYYMM(column_name)`, `PARTITION BY toStartOfWeek(column_name)`, `PARTITION BY toStartOfMonth(column_name)`, `PARTITION BY toStartOfQuarter(column_name)`, and `PARTITION BY toStartOfYear(column_name)`. Other function expressions are not supported as structured transforms.
- `toStartOfWeek(column_name)` uses ClickHouse's default mode `0` (Sunday start) and the server timezone. Calls with an explicit mode or timezone are not structured.
- Not support: `PARTITION BY (column_name + 1)`, `PARTITION BY (toYear(column_name) + 1)`, etc. (Note: ClickHouse itself does support arbitrary partitioning expressions, but Gravitino supports only the above patterns for partitioning).
+ Day transforms generate `toYYYYMMDD(column_name)` (integer day keys). Legacy `toDate` keys on `Date` columns remain readable as day transforms, but recreating a table from them canonicalizes the key to `toYYYYMMDD`; this changes the native key type and partition IDs. It does not alter existing tables. Unary `toDate` wrappers inside year/month/day expressions are unwrapped on load only for columns whose native type is `Date`. Other input types (including `DateTime`, whose conversion can cross the epoch boundary in non-UTC timezones), `toDateTime`, explicit timezones, multi-argument conversions and arbitrary wrappers retain only the native expression, since removing a conversion can change values or make recreated SQL invalid.
+
The patterns above apply when creating a table. When loading a table, Gravitino preserves ClickHouse's canonical native partition expression (as returned by `system.tables.partition_key`) in the read-only `partition-key` property. An arbitrary native expression is therefore retained on load even when it cannot be mapped to one of the supported `Transform`s; in that case `Table.partitioning()` is empty and the full expression is exposed through `partition-key`.
- Distribution: fixed to `Distributions.NONE`. For a `Distributed` engine table, you can specify the sharding key and remote database/table through table properties to fulfill the same use cases. We will later consider adding more flexible distribution strategies if there is demand.