You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@fluss.apache.org by ja...@apache.org on 2026/07/16 16:35:59 UTC
(fluss) branch main updated: [server] Auto partition time format supporting yyyy-MM-dd (#3558)
This is an automated email from the ASF dual-hosted git repository.
wuchong pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/fluss.git
The following commit(s) were added to refs/heads/main by this push:
new e1a70de09 [server] Auto partition time format supporting yyyy-MM-dd (#3558)
e1a70de09 is described below
commit e1a70de0993d5dc046f92a2e9574b5c5fba9440b
Author: Yang Guo <10...@users.noreply.github.com>
AuthorDate: Fri Jul 17 00:35:54 2026 +0800
[server] Auto partition time format supporting yyyy-MM-dd (#3558)
---
.../fluss/client/admin/FlussAdminITCase.java | 199 +++++++++++++++
.../client/table/AutoPartitionedTableITCase.java | 100 ++++++++
.../org/apache/fluss/config/ConfigOptions.java | 22 +-
.../apache/fluss/utils/AutoPartitionStrategy.java | 20 +-
.../org/apache/fluss/utils/PartitionUtils.java | 274 +++++++++++++++++++--
.../org/apache/fluss/utils/PartitionUtilsTest.java | 225 ++++++++++++++++-
.../server/coordinator/AutoPartitionManager.java | 66 +++--
.../fluss/server/coordinator/MetadataManager.java | 1 +
.../server/utils/TableDescriptorValidation.java | 50 ++++
.../coordinator/AutoPartitionManagerTest.java | 108 +++++++-
website/docs/engine-flink/options.md | 1 +
.../table-design/data-distribution/partitioning.md | 14 +-
12 files changed, 1023 insertions(+), 57 deletions(-)
diff --git a/fluss-client/src/test/java/org/apache/fluss/client/admin/FlussAdminITCase.java b/fluss-client/src/test/java/org/apache/fluss/client/admin/FlussAdminITCase.java
index 7615bb164..150b84e56 100644
--- a/fluss-client/src/test/java/org/apache/fluss/client/admin/FlussAdminITCase.java
+++ b/fluss-client/src/test/java/org/apache/fluss/client/admin/FlussAdminITCase.java
@@ -38,6 +38,7 @@ import org.apache.fluss.exception.DatabaseAlreadyExistException;
import org.apache.fluss.exception.DatabaseNotEmptyException;
import org.apache.fluss.exception.DatabaseNotExistException;
import org.apache.fluss.exception.FlussRuntimeException;
+import org.apache.fluss.exception.InvalidAlterTableException;
import org.apache.fluss.exception.InvalidConfigException;
import org.apache.fluss.exception.InvalidDatabaseException;
import org.apache.fluss.exception.InvalidPartitionException;
@@ -1494,6 +1495,204 @@ class FlussAdminITCase extends ClientToServerITCaseBase {
String.valueOf(currentYear)));
}
+ @Test
+ void testTimeFormatOptionForAutoPartitionedTable() throws Exception {
+ String dbName = DEFAULT_TABLE_PATH.getDatabaseName();
+
+ TableDescriptor nonDayTable =
+ TableDescriptor.builder()
+ .schema(
+ Schema.newBuilder()
+ .column("id", DataTypes.STRING())
+ .column("pt", DataTypes.STRING())
+ .build())
+ .distributedBy(3, "id")
+ .partitionedBy("pt")
+ .property(ConfigOptions.TABLE_AUTO_PARTITION_ENABLED, true)
+ .property(
+ ConfigOptions.TABLE_AUTO_PARTITION_TIME_UNIT,
+ AutoPartitionTimeUnit.MONTH)
+ .property(ConfigOptions.TABLE_AUTO_PARTITION_TIME_FORMAT, "MM-yyyy")
+ .build();
+ assertThatThrownBy(
+ () ->
+ admin.createTable(
+ TablePath.of(
+ dbName,
+ "test_invalid_auto_partition_day_format_non_day"),
+ nonDayTable,
+ false)
+ .get())
+ .cause()
+ .isInstanceOf(InvalidTableException.class)
+ .hasMessageContaining(ConfigOptions.TABLE_AUTO_PARTITION_TIME_FORMAT.key())
+ .hasMessageContaining("must contain fields [year, month] in this order")
+ .hasMessageContaining("MONTH");
+
+ TableDescriptor disabledAutoPartitionTable =
+ TableDescriptor.builder()
+ .schema(
+ Schema.newBuilder()
+ .column("id", DataTypes.STRING())
+ .column("pt", DataTypes.STRING())
+ .build())
+ .distributedBy(3, "id")
+ .partitionedBy("pt")
+ .property(ConfigOptions.TABLE_AUTO_PARTITION_TIME_FORMAT, "yyyy-MM-dd")
+ .build();
+ admin.createTable(
+ TablePath.of(dbName, "test_auto_partition_time_format_disabled"),
+ disabledAutoPartitionTable,
+ false)
+ .get();
+
+ TableDescriptor datePartitionKeyWithCompactDayFormat =
+ TableDescriptor.builder()
+ .schema(
+ Schema.newBuilder()
+ .column("id", DataTypes.STRING())
+ .column("pt", DataTypes.DATE())
+ .build())
+ .distributedBy(3, "id")
+ .partitionedBy("pt")
+ .property(ConfigOptions.TABLE_AUTO_PARTITION_ENABLED, true)
+ .property(
+ ConfigOptions.TABLE_AUTO_PARTITION_TIME_UNIT,
+ AutoPartitionTimeUnit.DAY)
+ .build();
+ assertThatThrownBy(
+ () ->
+ admin.createTable(
+ TablePath.of(
+ dbName,
+ "test_invalid_auto_partition_day_format_date_key"),
+ datePartitionKeyWithCompactDayFormat,
+ false)
+ .get())
+ .cause()
+ .isInstanceOf(InvalidTableException.class)
+ .hasMessageContaining(ConfigOptions.TABLE_AUTO_PARTITION_TIME_FORMAT.key())
+ .hasMessageContaining("yyyy-MM-dd")
+ .hasMessageContaining("DATE");
+
+ TableDescriptor datePartitionKeyWithMonthUnit =
+ TableDescriptor.builder()
+ .schema(
+ Schema.newBuilder()
+ .column("id", DataTypes.STRING())
+ .column("pt", DataTypes.DATE())
+ .build())
+ .distributedBy(3, "id")
+ .partitionedBy("pt")
+ .property(ConfigOptions.TABLE_AUTO_PARTITION_ENABLED, true)
+ .property(
+ ConfigOptions.TABLE_AUTO_PARTITION_TIME_UNIT,
+ AutoPartitionTimeUnit.MONTH)
+ .build();
+ assertThatThrownBy(
+ () ->
+ admin.createTable(
+ TablePath.of(
+ dbName,
+ "test_invalid_auto_partition_month_unit_date_key"),
+ datePartitionKeyWithMonthUnit,
+ false)
+ .get())
+ .cause()
+ .isInstanceOf(InvalidTableException.class)
+ .hasMessageContaining(ConfigOptions.TABLE_AUTO_PARTITION_TIME_UNIT.key())
+ .hasMessageContaining(AutoPartitionTimeUnit.DAY.name())
+ .hasMessageContaining("DATE");
+
+ TableDescriptor validDashedDayFormatTable =
+ TableDescriptor.builder()
+ .schema(
+ Schema.newBuilder()
+ .column("id", DataTypes.STRING())
+ .column("pt", DataTypes.STRING())
+ .build())
+ .distributedBy(3, "id")
+ .partitionedBy("pt")
+ .property(ConfigOptions.TABLE_AUTO_PARTITION_ENABLED, true)
+ .property(
+ ConfigOptions.TABLE_AUTO_PARTITION_TIME_UNIT,
+ AutoPartitionTimeUnit.DAY)
+ .property(ConfigOptions.TABLE_AUTO_PARTITION_TIME_FORMAT, "yyyy-MM-dd")
+ .build();
+ TablePath tablePath = TablePath.of(dbName, "test_invalid_auto_partition_day_format_alter");
+ admin.createTable(tablePath, validDashedDayFormatTable, false).get();
+
+ assertThatThrownBy(
+ () ->
+ admin.alterTable(
+ tablePath,
+ Collections.singletonList(
+ TableChange.set(
+ ConfigOptions
+ .TABLE_AUTO_PARTITION_TIME_FORMAT
+ .key(),
+ "yyyyMMdd")),
+ false)
+ .get())
+ .cause()
+ .isInstanceOf(InvalidAlterTableException.class)
+ .hasMessageContaining(ConfigOptions.TABLE_AUTO_PARTITION_TIME_FORMAT.key());
+
+ admin.alterTable(
+ tablePath,
+ Collections.singletonList(
+ TableChange.set(
+ ConfigOptions.TABLE_AUTO_PARTITION_ENABLED.key(), "false")),
+ false)
+ .get();
+ assertThatThrownBy(
+ () ->
+ admin.createPartition(
+ tablePath,
+ newPartitionSpec("pt", "20000101"),
+ false)
+ .get())
+ .cause()
+ .isInstanceOf(InvalidPartitionException.class)
+ .hasMessageContaining("yyyy-MM-dd");
+ admin.createPartition(tablePath, newPartitionSpec("pt", "2000-01-01"), false).get();
+
+ TableDescriptor disabledDateDayTable =
+ TableDescriptor.builder()
+ .schema(
+ Schema.newBuilder()
+ .column("id", DataTypes.STRING())
+ .column("pt", DataTypes.DATE())
+ .build())
+ .distributedBy(3, "id")
+ .partitionedBy("pt")
+ .property(
+ ConfigOptions.TABLE_AUTO_PARTITION_TIME_UNIT,
+ AutoPartitionTimeUnit.DAY)
+ .build();
+ TablePath disabledDateDayTablePath =
+ TablePath.of(dbName, "test_invalid_auto_partition_day_format_enable");
+ admin.createTable(disabledDateDayTablePath, disabledDateDayTable, false).get();
+
+ assertThatThrownBy(
+ () ->
+ admin.alterTable(
+ disabledDateDayTablePath,
+ Collections.singletonList(
+ TableChange.set(
+ ConfigOptions
+ .TABLE_AUTO_PARTITION_ENABLED
+ .key(),
+ "true")),
+ false)
+ .get())
+ .cause()
+ .isInstanceOf(InvalidTableException.class)
+ .hasMessageContaining(ConfigOptions.TABLE_AUTO_PARTITION_TIME_FORMAT.key())
+ .hasMessageContaining("yyyy-MM-dd")
+ .hasMessageContaining("DATE");
+ }
+
@Test
void testCreateInvalidPartitionForAutoPartitionedTable() throws Exception {
String dbName = DEFAULT_TABLE_PATH.getDatabaseName();
diff --git a/fluss-client/src/test/java/org/apache/fluss/client/table/AutoPartitionedTableITCase.java b/fluss-client/src/test/java/org/apache/fluss/client/table/AutoPartitionedTableITCase.java
index 8cf4014c3..a33b40456 100644
--- a/fluss-client/src/test/java/org/apache/fluss/client/table/AutoPartitionedTableITCase.java
+++ b/fluss-client/src/test/java/org/apache/fluss/client/table/AutoPartitionedTableITCase.java
@@ -382,6 +382,72 @@ class AutoPartitionedTableITCase extends ClientToServerITCaseBase {
verifyPartitionLogs(table, schema.getRowType(), expectPartitionAppendRows);
}
+ @Test
+ void testWriteToDashedDayPartitionShouldCreateAndValidateStringKey() throws Exception {
+ clientConf.set(ConfigOptions.CLIENT_WRITER_DYNAMIC_CREATE_PARTITION_ENABLED, true);
+ TablePath tablePath = TablePath.of("test_db_1", "test_write_dashed_day_partition_string");
+ createDayPartitionedTable(tablePath, DataTypes.STRING(), true);
+ Map<String, Long> partitionIdByNames =
+ FLUSS_CLUSTER_EXTENSION.waitUntilPartitionAllReady(tablePath);
+ assertThat(partitionIdByNames.keySet())
+ .allMatch(partition -> partition.matches("\\d{4}-\\d{2}-\\d{2}"));
+
+ Table table = conn.getTable(tablePath);
+ UpsertWriter upsertWriter = table.newUpsert().createWriter();
+ String todayPartition = LocalDate.now().toString();
+ upsertWriter.upsert(row(1, "a", todayPartition));
+ upsertWriter.flush();
+
+ List<PartitionInfo> partitionInfos = admin.listPartitionInfos(tablePath).get();
+ assertThat(
+ partitionInfos.stream()
+ .map(PartitionInfo::getPartitionName)
+ .collect(Collectors.toList()))
+ .contains(todayPartition)
+ .allMatch(partition -> partition.matches("\\d{4}-\\d{2}-\\d{2}"));
+
+ assertThatThrownBy(
+ () ->
+ upsertWriter.upsert(
+ row(
+ 2,
+ "b",
+ LocalDate.now()
+ .format(
+ DateTimeFormatter.ofPattern(
+ "yyyyMMdd")))))
+ .rootCause()
+ .isInstanceOf(InvalidPartitionException.class)
+ .hasMessageContaining("yyyy-MM-dd")
+ .hasMessageContaining("DAY");
+ }
+
+ @Test
+ void testWriteToDashedDayPartitionShouldCreateAndValidateDateKey() throws Exception {
+ clientConf.set(ConfigOptions.CLIENT_WRITER_DYNAMIC_CREATE_PARTITION_ENABLED, true);
+ TablePath tablePath = TablePath.of("test_db_1", "test_write_dashed_day_partition_date");
+ createDayPartitionedTable(tablePath, DataTypes.DATE(), false);
+ Map<String, Long> partitionIdByNames =
+ FLUSS_CLUSTER_EXTENSION.waitUntilPartitionAllReady(tablePath);
+ assertThat(partitionIdByNames.keySet())
+ .allMatch(partition -> partition.matches("\\d{4}-\\d{2}-\\d{2}"));
+
+ Table table = conn.getTable(tablePath);
+ AppendWriter appendWriter = table.newAppend().createWriter();
+ LocalDate today = LocalDate.now();
+ int todayEpochDay = (int) today.toEpochDay();
+ appendWriter.append(row(1, "a", todayEpochDay));
+ appendWriter.flush();
+
+ List<PartitionInfo> partitionInfos = admin.listPartitionInfos(tablePath).get();
+ assertThat(
+ partitionInfos.stream()
+ .map(PartitionInfo::getPartitionName)
+ .collect(Collectors.toList()))
+ .contains(today.toString())
+ .allMatch(partition -> partition.matches("\\d{4}-\\d{2}-\\d{2}"));
+ }
+
@Test
void testWriteToInvalidPartitionShouldThrowException() throws Exception {
// Enable dynamic partition creation so the writer attempts to create the partition.
@@ -443,4 +509,38 @@ class AutoPartitionedTableITCase extends ClientToServerITCaseBase {
createTable(tablePath, partitionTableDescriptor, false);
return schema;
}
+
+ private Schema createDayPartitionedTable(
+ TablePath tablePath,
+ org.apache.fluss.types.DataType partitionType,
+ boolean isPrimaryTable)
+ throws Exception {
+ Schema.Builder schemaBuilder =
+ Schema.newBuilder()
+ .column("a", DataTypes.INT())
+ .withComment("a is first column")
+ .column("b", DataTypes.STRING())
+ .withComment("b is second column")
+ .column("c", partitionType)
+ .withComment("c is third column");
+
+ if (isPrimaryTable) {
+ schemaBuilder.primaryKey("a", "c");
+ }
+
+ Schema schema = schemaBuilder.build();
+
+ TableDescriptor partitionTableDescriptor =
+ TableDescriptor.builder()
+ .schema(schema)
+ .partitionedBy("c")
+ .property(ConfigOptions.TABLE_AUTO_PARTITION_ENABLED, true)
+ .property(
+ ConfigOptions.TABLE_AUTO_PARTITION_TIME_UNIT,
+ AutoPartitionTimeUnit.DAY)
+ .property(ConfigOptions.TABLE_AUTO_PARTITION_TIME_FORMAT, "yyyy-MM-dd")
+ .build();
+ createTable(tablePath, partitionTableDescriptor, false);
+ return schema;
+ }
}
diff --git a/fluss-common/src/main/java/org/apache/fluss/config/ConfigOptions.java b/fluss-common/src/main/java/org/apache/fluss/config/ConfigOptions.java
index 1914df7e1..cc7ce32ad 100644
--- a/fluss-common/src/main/java/org/apache/fluss/config/ConfigOptions.java
+++ b/fluss-common/src/main/java/org/apache/fluss/config/ConfigOptions.java
@@ -1647,13 +1647,31 @@ public class ConfigOptions {
+ "If the value is `HOUR`, the partition format for "
+ "auto created is yyyyMMddHH. "
+ "If the value is `DAY`, the partition format for "
- + "auto created is yyyyMMdd. "
+ + "auto created is yyyyMMdd by default. "
+ "If the value is `MONTH`, the partition format for "
+ "auto created is yyyyMM. "
+ "If the value is `QUARTER`, the partition format for "
+ "auto created is yyyyQ. "
+ "If the value is `YEAR`, the partition format for "
- + "auto created is yyyy.");
+ + "auto created is yyyy. The default format can be overridden "
+ + "by `table.auto-partition.time-format`.");
+
+ public static final ConfigOption<String> TABLE_AUTO_PARTITION_TIME_FORMAT =
+ key("table.auto-partition.time-format")
+ .stringType()
+ .noDefaultValue()
+ .withDescription(
+ "The DateTimeFormatter pattern for auto-created partitions. "
+ + "By default, the format is determined by `table.auto-partition.time-unit`: "
+ + "`yyyy` for YEAR, `yyyyQ` for QUARTER, `yyyyMM` for MONTH, "
+ + "`yyyyMMdd` for DAY, and `yyyyMMddHH` for HOUR. "
+ + "A custom format must list time fields from the largest to the smallest unit, "
+ + "include every field required by the configured time unit, and use fixed-width numeric fields. "
+ + "For example, `yyyy-MM-dd` is valid for DAY, while `MM-yyyy`, `yyyy-MM`, and `yyyy-M-dd` are invalid. "
+ + "The generated partition value must also satisfy Fluss partition-name restrictions: "
+ + "at most 200 ASCII alphanumeric, underscore, or hyphen characters, without the reserved `__` prefix. "
+ + "Optional pattern sections using `[` and `]` are not supported. "
+ + "The format is retained when auto partitioning is disabled and continues to validate manually created partitions.");
public static final ConfigOption<String> TABLE_AUTO_PARTITION_TIMEZONE =
key("table.auto-partition.time-zone")
diff --git a/fluss-common/src/main/java/org/apache/fluss/utils/AutoPartitionStrategy.java b/fluss-common/src/main/java/org/apache/fluss/utils/AutoPartitionStrategy.java
index a3a725adc..3c393415e 100644
--- a/fluss-common/src/main/java/org/apache/fluss/utils/AutoPartitionStrategy.java
+++ b/fluss-common/src/main/java/org/apache/fluss/utils/AutoPartitionStrategy.java
@@ -31,6 +31,7 @@ public class AutoPartitionStrategy {
private final boolean autoPartitionEnabled;
private final String key;
private final AutoPartitionTimeUnit timeUnit;
+ private final String timeFormat;
private final int numPreCreate;
private final int numToRetain;
private final TimeZone timeZone;
@@ -39,12 +40,14 @@ public class AutoPartitionStrategy {
boolean autoPartitionEnabled,
String key,
AutoPartitionTimeUnit autoPartitionTimeUnit,
+ String timeFormat,
int numPreCreate,
int numToRetain,
TimeZone timeZone) {
this.autoPartitionEnabled = autoPartitionEnabled;
this.key = key;
this.timeUnit = autoPartitionTimeUnit;
+ this.timeFormat = timeFormat;
this.numPreCreate = numPreCreate;
this.numToRetain = numToRetain;
this.timeZone = timeZone;
@@ -59,6 +62,7 @@ public class AutoPartitionStrategy {
conf.getBoolean(ConfigOptions.TABLE_AUTO_PARTITION_ENABLED),
conf.getString(ConfigOptions.TABLE_AUTO_PARTITION_KEY),
conf.get(ConfigOptions.TABLE_AUTO_PARTITION_TIME_UNIT),
+ conf.getOptional(ConfigOptions.TABLE_AUTO_PARTITION_TIME_FORMAT).orElse(null),
conf.getInt(ConfigOptions.TABLE_AUTO_PARTITION_NUM_PRECREATE),
conf.getInt(ConfigOptions.TABLE_AUTO_PARTITION_NUM_RETENTION),
TimeZone.getTimeZone(conf.getString(ConfigOptions.TABLE_AUTO_PARTITION_TIMEZONE)));
@@ -76,6 +80,10 @@ public class AutoPartitionStrategy {
return timeUnit;
}
+ public String timeFormat() {
+ return timeFormat;
+ }
+
public int numPreCreate() {
return numPreCreate;
}
@@ -98,6 +106,9 @@ public class AutoPartitionStrategy {
+ '\''
+ ", timeUnit="
+ timeUnit
+ + ", timeFormat='"
+ + timeFormat
+ + '\''
+ ", numPreCreate="
+ numPreCreate
+ ", numToRetain="
@@ -121,12 +132,19 @@ public class AutoPartitionStrategy {
&& numToRetain == that.numToRetain
&& Objects.equals(key, that.key)
&& timeUnit == that.timeUnit
+ && Objects.equals(timeFormat, that.timeFormat)
&& Objects.equals(timeZone, that.timeZone);
}
@Override
public int hashCode() {
return Objects.hash(
- autoPartitionEnabled, key, timeUnit, numPreCreate, numToRetain, timeZone);
+ autoPartitionEnabled,
+ key,
+ timeUnit,
+ timeFormat,
+ numPreCreate,
+ numToRetain,
+ timeZone);
}
}
diff --git a/fluss-common/src/main/java/org/apache/fluss/utils/PartitionUtils.java b/fluss-common/src/main/java/org/apache/fluss/utils/PartitionUtils.java
index c8f67955a..55c7762f2 100644
--- a/fluss-common/src/main/java/org/apache/fluss/utils/PartitionUtils.java
+++ b/fluss-common/src/main/java/org/apache/fluss/utils/PartitionUtils.java
@@ -19,6 +19,7 @@ package org.apache.fluss.utils;
import org.apache.fluss.annotation.VisibleForTesting;
import org.apache.fluss.config.AutoPartitionTimeUnit;
+import org.apache.fluss.config.Configuration;
import org.apache.fluss.exception.InvalidPartitionException;
import org.apache.fluss.metadata.PartitionSpec;
import org.apache.fluss.metadata.ResolvedPartitionSpec;
@@ -101,29 +102,33 @@ public class PartitionUtils {
@VisibleForTesting
static void validatePartitionValues(List<String> partitionValues, boolean isCreate) {
for (String value : partitionValues) {
- String invalidNameError = detectInvalidName(value);
- if (invalidNameError != null || (isCreate && validatePrefix(value) != null)) {
+ String invalidReason = getInvalidPartitionValueReason(value, isCreate);
+ if (invalidReason != null) {
throw new InvalidPartitionException(
- "The partition value "
- + value
- + " is invalid: "
- + (invalidNameError != null
- ? invalidNameError
- : validatePrefix(value)));
+ "The partition value " + value + " is invalid: " + invalidReason);
}
}
}
+ private static String getInvalidPartitionValueReason(String value, boolean isCreate) {
+ String invalidNameError = detectInvalidName(value);
+ return invalidNameError != null
+ ? invalidNameError
+ : isCreate ? validatePrefix(value) : null;
+ }
+
/**
- * Validates that the partition time value in the given {@link PartitionSpec} is valid and not
- * out-of-date when auto-partition is enabled. Throws {@link InvalidPartitionException} if the
- * format doesn't match or the partition is older than the earliest retained one.
+ * Validates that the partition time value in the given {@link PartitionSpec} matches the
+ * configured time format. When auto-partition is enabled, this also validates that the
+ * partition is not out-of-date. Throws {@link InvalidPartitionException} if either validation
+ * fails.
*/
public static void validateAutoPartitionTime(
PartitionSpec partitionSpec,
List<String> partitionKeys,
AutoPartitionStrategy autoPartitionStrategy) {
- if (!autoPartitionStrategy.isAutoPartitionEnabled()) {
+ if (!autoPartitionStrategy.isAutoPartitionEnabled()
+ && autoPartitionStrategy.timeFormat() == null) {
return;
}
String autoPartitionKey =
@@ -132,19 +137,28 @@ public class PartitionUtils {
: partitionKeys.get(0);
String partitionTime = partitionSpec.getSpecMap().get(autoPartitionKey);
AutoPartitionTimeUnit timeUnit = autoPartitionStrategy.timeUnit();
- if (partitionTime == null || !isValidPartitionTime(partitionTime, timeUnit)) {
+ if (partitionTime == null
+ || !isValidPartitionTime(partitionTime, timeUnit, autoPartitionStrategy)) {
throw new InvalidPartitionException(
String.format(
"Partition value '%s' does not match the expected format '%s' "
+ "for auto-partition time unit '%s'.",
- partitionTime, getPartitionTimeFormat(timeUnit), timeUnit));
+ partitionTime,
+ getPartitionTimeFormat(timeUnit, autoPartitionStrategy),
+ timeUnit));
+ }
+ if (!autoPartitionStrategy.isAutoPartitionEnabled()) {
+ return;
}
ZonedDateTime currentZonedDateTime =
ZonedDateTime.ofInstant(Instant.now(), autoPartitionStrategy.timeZone().toZoneId());
// Get the earliest partition time that needs to be retained.
String lastRetainPartitionTime =
generateAutoPartitionTime(
- currentZonedDateTime, -autoPartitionStrategy.numToRetain(), timeUnit);
+ currentZonedDateTime,
+ -autoPartitionStrategy.numToRetain(),
+ timeUnit,
+ autoPartitionStrategy);
if (lastRetainPartitionTime.compareTo(partitionTime) > 0) {
throw new InvalidPartitionException(
String.format(
@@ -171,30 +185,68 @@ public class PartitionUtils {
ZonedDateTime current,
int offset,
AutoPartitionTimeUnit timeUnit) {
- String autoPartitionFieldSpec = generateAutoPartitionTime(current, offset, timeUnit);
+ return generateAutoPartition(
+ partitionKeys,
+ current,
+ offset,
+ timeUnit,
+ AutoPartitionStrategy.from(new Configuration()));
+ }
+
+ public static ResolvedPartitionSpec generateAutoPartition(
+ List<String> partitionKeys,
+ ZonedDateTime current,
+ int offset,
+ AutoPartitionTimeUnit timeUnit,
+ AutoPartitionStrategy autoPartitionStrategy) {
+ String autoPartitionFieldSpec =
+ generateAutoPartitionTime(current, offset, timeUnit, autoPartitionStrategy);
return ResolvedPartitionSpec.fromPartitionName(partitionKeys, autoPartitionFieldSpec);
}
public static String generateAutoPartitionTime(
ZonedDateTime current, int offset, AutoPartitionTimeUnit timeUnit) {
+ return generateAutoPartitionTime(
+ current, offset, timeUnit, AutoPartitionStrategy.from(new Configuration()));
+ }
+
+ public static String generateAutoPartitionTime(
+ ZonedDateTime current,
+ int offset,
+ AutoPartitionTimeUnit timeUnit,
+ AutoPartitionStrategy autoPartitionStrategy) {
String autoPartitionFieldSpec;
switch (timeUnit) {
case YEAR:
- autoPartitionFieldSpec = getFormattedTime(current.plusYears(offset), YEAR_FORMAT);
+ autoPartitionFieldSpec =
+ getFormattedTime(
+ current.plusYears(offset),
+ getPartitionTimeFormat(timeUnit, autoPartitionStrategy));
break;
case QUARTER:
autoPartitionFieldSpec =
- getFormattedTime(current.plusMonths(offset * 3L), QUARTER_FORMAT);
+ getFormattedTime(
+ current.plusMonths(offset * 3L),
+ getPartitionTimeFormat(timeUnit, autoPartitionStrategy));
break;
case MONTH:
- autoPartitionFieldSpec = getFormattedTime(current.plusMonths(offset), MONTH_FORMAT);
+ autoPartitionFieldSpec =
+ getFormattedTime(
+ current.plusMonths(offset),
+ getPartitionTimeFormat(timeUnit, autoPartitionStrategy));
break;
case DAY:
- autoPartitionFieldSpec = getFormattedTime(current.plusDays(offset), DAY_FORMAT);
+ autoPartitionFieldSpec =
+ getFormattedTime(
+ current.plusDays(offset),
+ getPartitionTimeFormat(timeUnit, autoPartitionStrategy));
break;
case HOUR:
- autoPartitionFieldSpec = getFormattedTime(current.plusHours(offset), HOUR_FORMAT);
+ autoPartitionFieldSpec =
+ getFormattedTime(
+ current.plusHours(offset),
+ getPartitionTimeFormat(timeUnit, autoPartitionStrategy));
break;
default:
throw new IllegalArgumentException("Unsupported time unit: " + timeUnit);
@@ -202,8 +254,178 @@ public class PartitionUtils {
return autoPartitionFieldSpec;
}
+ /**
+ * Validates that a custom time format preserves time order under string comparison.
+ *
+ * @param timeUnit the auto-partition time unit
+ * @param autoPartitionStrategy the auto-partition strategy containing the custom format
+ * @throws IllegalArgumentException if the pattern is invalid or does not preserve time order
+ */
+ public static void validateTimeFormat(
+ AutoPartitionTimeUnit timeUnit, AutoPartitionStrategy autoPartitionStrategy) {
+ String timeFormat = autoPartitionStrategy.timeFormat();
+ if (timeFormat == null) {
+ return;
+ }
+ try {
+ DateTimeFormatter.ofPattern(timeFormat);
+ } catch (IllegalArgumentException e) {
+ throw new IllegalArgumentException(
+ String.format("Invalid date-time format pattern '%s'.", timeFormat), e);
+ }
+ validateTimeFields(timeFormat, timeUnit);
+ validateTimeFormatPartitionValue(timeFormat, autoPartitionStrategy);
+ }
+
+ private static void validateTimeFormatPartitionValue(
+ String timeFormat, AutoPartitionStrategy autoPartitionStrategy) {
+ ZonedDateTime representativeTime =
+ ZonedDateTime.of(
+ 2024, 11, 11, 11, 0, 0, 0, autoPartitionStrategy.timeZone().toZoneId());
+ String partitionValue = getFormattedTime(representativeTime, timeFormat);
+ String invalidReason = getInvalidPartitionValueReason(partitionValue, true);
+ if (invalidReason != null) {
+ throw new IllegalArgumentException(
+ String.format(
+ "Time format '%s' generates invalid partition value '%s': %s.",
+ timeFormat, partitionValue, invalidReason));
+ }
+ }
+
+ private static void validateTimeFields(String timeFormat, AutoPartitionTimeUnit timeUnit) {
+ List<TimeFormatField> expectedFields = getExpectedTimeFormatFields(timeUnit);
+ List<TimeFormatField> actualFields = new ArrayList<>();
+ boolean inLiteral = false;
+ for (int index = 0; index < timeFormat.length(); ) {
+ char patternChar = timeFormat.charAt(index);
+ if (patternChar == '\'') {
+ if (index + 1 < timeFormat.length() && timeFormat.charAt(index + 1) == '\'') {
+ index += 2;
+ } else {
+ inLiteral = !inLiteral;
+ index++;
+ }
+ continue;
+ }
+ if (!inLiteral && (patternChar == '[' || patternChar == ']')) {
+ throw new IllegalArgumentException(
+ String.format(
+ "Time format '%s' must not contain optional sections ('[' or ']').",
+ timeFormat));
+ }
+ if (inLiteral || !isAsciiLetter(patternChar)) {
+ index++;
+ continue;
+ }
+
+ int end = index + 1;
+ while (end < timeFormat.length() && timeFormat.charAt(end) == patternChar) {
+ end++;
+ }
+ TimeFormatField field = TimeFormatField.fromPattern(patternChar);
+ if (field == null) {
+ throw new IllegalArgumentException(
+ String.format(
+ "Time format '%s' contains unsupported time field '%s'.",
+ timeFormat, patternChar));
+ }
+ field.validateWidth(timeFormat, end - index);
+ actualFields.add(field);
+ index = end;
+ }
+
+ if (!actualFields.equals(expectedFields)) {
+ throw new IllegalArgumentException(
+ String.format(
+ "Time format '%s' must contain fields %s in this order for time unit '%s', but found %s.",
+ timeFormat, expectedFields, timeUnit, actualFields));
+ }
+ }
+
+ private static boolean isAsciiLetter(char character) {
+ return (character >= 'A' && character <= 'Z') || (character >= 'a' && character <= 'z');
+ }
+
+ private static List<TimeFormatField> getExpectedTimeFormatFields(
+ AutoPartitionTimeUnit timeUnit) {
+ switch (timeUnit) {
+ case YEAR:
+ return Arrays.asList(TimeFormatField.YEAR);
+ case QUARTER:
+ return Arrays.asList(TimeFormatField.YEAR, TimeFormatField.QUARTER);
+ case MONTH:
+ return Arrays.asList(TimeFormatField.YEAR, TimeFormatField.MONTH);
+ case DAY:
+ return Arrays.asList(
+ TimeFormatField.YEAR, TimeFormatField.MONTH, TimeFormatField.DAY);
+ case HOUR:
+ return Arrays.asList(
+ TimeFormatField.YEAR,
+ TimeFormatField.MONTH,
+ TimeFormatField.DAY,
+ TimeFormatField.HOUR);
+ default:
+ throw new IllegalArgumentException("Unsupported time unit: " + timeUnit);
+ }
+ }
+
+ private enum TimeFormatField {
+ YEAR("year", 4),
+ QUARTER("quarter", 1),
+ MONTH("month", 2),
+ DAY("day", 2),
+ HOUR("hour", 2);
+
+ private final String name;
+ private final int width;
+
+ TimeFormatField(String name, int width) {
+ this.name = name;
+ this.width = width;
+ }
+
+ private static TimeFormatField fromPattern(char patternChar) {
+ switch (patternChar) {
+ case 'y':
+ case 'u':
+ return YEAR;
+ case 'Q':
+ case 'q':
+ return QUARTER;
+ case 'M':
+ case 'L':
+ return MONTH;
+ case 'd':
+ return DAY;
+ case 'H':
+ return HOUR;
+ default:
+ return null;
+ }
+ }
+
+ private void validateWidth(String timeFormat, int actualWidth) {
+ if (actualWidth != width) {
+ throw new IllegalArgumentException(
+ String.format(
+ "Time field '%s' in format '%s' must have fixed width %d, but found %d.",
+ name, timeFormat, width, actualWidth));
+ }
+ }
+
+ @Override
+ public String toString() {
+ return name;
+ }
+ }
+
/** Returns the time string format pattern for the given time unit. */
- private static String getPartitionTimeFormat(AutoPartitionTimeUnit timeUnit) {
+ private static String getPartitionTimeFormat(
+ AutoPartitionTimeUnit timeUnit, AutoPartitionStrategy autoPartitionStrategy) {
+ String timeFormat = autoPartitionStrategy.timeFormat();
+ if (timeFormat != null) {
+ return timeFormat;
+ }
switch (timeUnit) {
case YEAR:
return YEAR_FORMAT;
@@ -223,9 +445,13 @@ public class PartitionUtils {
/**
* Returns true if the given time string matches the format expected for the given time unit.
*/
- private static boolean isValidPartitionTime(String time, AutoPartitionTimeUnit timeUnit) {
+ private static boolean isValidPartitionTime(
+ String time,
+ AutoPartitionTimeUnit timeUnit,
+ AutoPartitionStrategy autoPartitionStrategy) {
try {
- DateTimeFormatter.ofPattern(getPartitionTimeFormat(timeUnit)).parse(time);
+ DateTimeFormatter.ofPattern(getPartitionTimeFormat(timeUnit, autoPartitionStrategy))
+ .parse(time);
return true;
} catch (DateTimeParseException e) {
return false;
diff --git a/fluss-common/src/test/java/org/apache/fluss/utils/PartitionUtilsTest.java b/fluss-common/src/test/java/org/apache/fluss/utils/PartitionUtilsTest.java
index aeb2c1d7c..4717910b5 100644
--- a/fluss-common/src/test/java/org/apache/fluss/utils/PartitionUtilsTest.java
+++ b/fluss-common/src/test/java/org/apache/fluss/utils/PartitionUtilsTest.java
@@ -19,6 +19,7 @@ package org.apache.fluss.utils;
import org.apache.fluss.config.AutoPartitionTimeUnit;
import org.apache.fluss.config.ConfigOptions;
+import org.apache.fluss.config.Configuration;
import org.apache.fluss.exception.InvalidPartitionException;
import org.apache.fluss.metadata.PartitionSpec;
import org.apache.fluss.metadata.ResolvedPartitionSpec;
@@ -31,6 +32,8 @@ import org.apache.fluss.types.DataTypeRoot;
import org.junit.jupiter.api.Test;
+import java.time.Instant;
+import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
@@ -44,6 +47,7 @@ import static org.apache.fluss.record.TestData.DEFAULT_REMOTE_DATA_DIR;
import static org.apache.fluss.utils.PartitionUtils.convertValueOfType;
import static org.apache.fluss.utils.PartitionUtils.generateAutoPartition;
import static org.apache.fluss.utils.PartitionUtils.parseValueOfType;
+import static org.apache.fluss.utils.PartitionUtils.validateAutoPartitionTime;
import static org.apache.fluss.utils.PartitionUtils.validatePartitionSpec;
import static org.apache.fluss.utils.PartitionUtils.validatePartitionValues;
import static org.assertj.core.api.Assertions.assertThat;
@@ -101,6 +105,96 @@ class PartitionUtilsTest {
+ "partitioned table test_db_1.test_non_pk_table_1.");
}
+ @Test
+ void testAutoPartitionStrategyUsesConfiguredTimeFormat() {
+ Configuration conf = new Configuration();
+ assertThat(AutoPartitionStrategy.from(conf).timeFormat()).isNull();
+
+ conf.setString(ConfigOptions.TABLE_AUTO_PARTITION_TIME_FORMAT, "yyyy-MM-dd");
+ assertThat(AutoPartitionStrategy.from(conf).timeFormat()).isEqualTo("yyyy-MM-dd");
+ }
+
+ @Test
+ void testValidateCustomTimeFormat() {
+ Configuration conf = new Configuration();
+ AutoPartitionTimeUnit[] timeUnits = AutoPartitionTimeUnit.values();
+ String[] validFormats = {"yyyy", "yyyy-'Q'Q", "yyyy-MM", "yyyy-MM-dd", "yyyy-MM-dd-HH"};
+ for (int index = 0; index < timeUnits.length; index++) {
+ conf.setString(ConfigOptions.TABLE_AUTO_PARTITION_TIME_FORMAT, validFormats[index]);
+ AutoPartitionStrategy validStrategy = AutoPartitionStrategy.from(conf);
+ AutoPartitionTimeUnit timeUnit = timeUnits[index];
+ assertThatNoException()
+ .isThrownBy(() -> PartitionUtils.validateTimeFormat(timeUnit, validStrategy));
+ }
+
+ conf.setString(ConfigOptions.TABLE_AUTO_PARTITION_TIME_FORMAT, "MM-yyyy");
+ AutoPartitionStrategy invalidOrderStrategy = AutoPartitionStrategy.from(conf);
+ assertThatThrownBy(
+ () ->
+ PartitionUtils.validateTimeFormat(
+ AutoPartitionTimeUnit.MONTH, invalidOrderStrategy))
+ .isInstanceOf(IllegalArgumentException.class)
+ .hasMessageContaining("must contain fields [year, month] in this order");
+
+ conf.setString(ConfigOptions.TABLE_AUTO_PARTITION_TIME_FORMAT, "yyyy-MM-dd");
+ AutoPartitionStrategy insufficientPrecisionStrategy = AutoPartitionStrategy.from(conf);
+ assertThatThrownBy(
+ () ->
+ PartitionUtils.validateTimeFormat(
+ AutoPartitionTimeUnit.HOUR, insufficientPrecisionStrategy))
+ .isInstanceOf(IllegalArgumentException.class)
+ .hasMessageContaining("[year, month, day, hour]");
+
+ conf.setString(ConfigOptions.TABLE_AUTO_PARTITION_TIME_FORMAT, "yyyy-M-dd");
+ AutoPartitionStrategy variableWidthStrategy = AutoPartitionStrategy.from(conf);
+ assertThatThrownBy(
+ () ->
+ PartitionUtils.validateTimeFormat(
+ AutoPartitionTimeUnit.DAY, variableWidthStrategy))
+ .isInstanceOf(IllegalArgumentException.class)
+ .hasMessageContaining("must have fixed width 2");
+
+ conf.setString(ConfigOptions.TABLE_AUTO_PARTITION_TIME_FORMAT, "yyyy[-MM[-dd]]");
+ AutoPartitionStrategy optionalSectionsStrategy = AutoPartitionStrategy.from(conf);
+ assertThatThrownBy(
+ () ->
+ PartitionUtils.validateTimeFormat(
+ AutoPartitionTimeUnit.DAY, optionalSectionsStrategy))
+ .isInstanceOf(IllegalArgumentException.class)
+ .hasMessageContaining("must not contain optional sections");
+
+ conf.setString(ConfigOptions.TABLE_AUTO_PARTITION_TIME_FORMAT, "yyyy/MM/dd");
+ AutoPartitionStrategy invalidCharacterStrategy = AutoPartitionStrategy.from(conf);
+ assertThatThrownBy(
+ () ->
+ PartitionUtils.validateTimeFormat(
+ AutoPartitionTimeUnit.DAY, invalidCharacterStrategy))
+ .isInstanceOf(IllegalArgumentException.class)
+ .hasMessageContaining("generates invalid partition value '2024/11/11'")
+ .hasMessageContaining("ASCII alphanumerics, '_' and '-'");
+
+ conf.setString(ConfigOptions.TABLE_AUTO_PARTITION_TIME_FORMAT, "__yyyy");
+ AutoPartitionStrategy reservedPrefixStrategy = AutoPartitionStrategy.from(conf);
+ assertThatThrownBy(
+ () ->
+ PartitionUtils.validateTimeFormat(
+ AutoPartitionTimeUnit.YEAR, reservedPrefixStrategy))
+ .isInstanceOf(IllegalArgumentException.class)
+ .hasMessageContaining("generates invalid partition value '__2024'")
+ .hasMessageContaining("reserved");
+
+ conf.setString(
+ ConfigOptions.TABLE_AUTO_PARTITION_TIME_FORMAT,
+ "yyyy" + org.apache.commons.lang3.StringUtils.repeat("_", 197));
+ AutoPartitionStrategy overlongValueStrategy = AutoPartitionStrategy.from(conf);
+ assertThatThrownBy(
+ () ->
+ PartitionUtils.validateTimeFormat(
+ AutoPartitionTimeUnit.YEAR, overlongValueStrategy))
+ .isInstanceOf(IllegalArgumentException.class)
+ .hasMessageContaining("longer than the max allowed length 200");
+ }
+
@Test
void testGenerateAutoPartitionName() {
LocalDateTime localDateTime = LocalDateTime.of(2024, 11, 11, 11, 11);
@@ -131,12 +225,29 @@ class PartitionUtilsTest {
// for day
testGenerateAutoPartitionName(
zonedDateTime,
+ AutoPartitionStrategy.from(new Configuration()),
AutoPartitionTimeUnit.DAY,
new int[] {-1, 0, 1, 2, 3, 20},
new String[] {
"20241110", "20241111", "20241112", "20241113", "20241114", "20241201"
});
+ Configuration dashedDayConf = new Configuration();
+ dashedDayConf.setString(ConfigOptions.TABLE_AUTO_PARTITION_TIME_FORMAT, "yyyy-MM-dd");
+ testGenerateAutoPartitionName(
+ zonedDateTime,
+ AutoPartitionStrategy.from(dashedDayConf),
+ AutoPartitionTimeUnit.DAY,
+ new int[] {-1, 0, 1, 2, 3, 20},
+ new String[] {
+ "2024-11-10",
+ "2024-11-11",
+ "2024-11-12",
+ "2024-11-13",
+ "2024-11-14",
+ "2024-12-01"
+ });
+
// for hour
testGenerateAutoPartitionName(
zonedDateTime,
@@ -158,17 +269,129 @@ class PartitionUtilsTest {
AutoPartitionTimeUnit autoPartitionTimeUnit,
int[] offsets,
String[] expected) {
+ testGenerateAutoPartitionName(
+ zonedDateTime,
+ AutoPartitionStrategy.from(new Configuration()),
+ autoPartitionTimeUnit,
+ offsets,
+ expected);
+ }
+
+ void testGenerateAutoPartitionName(
+ ZonedDateTime zonedDateTime,
+ AutoPartitionStrategy autoPartitionStrategy,
+ AutoPartitionTimeUnit autoPartitionTimeUnit,
+ int[] offsets,
+ String[] expected) {
for (int i = 0; i < offsets.length; i++) {
ResolvedPartitionSpec resolvedPartitionSpec =
generateAutoPartition(
Collections.singletonList("dt"),
zonedDateTime,
offsets[i],
- autoPartitionTimeUnit);
+ autoPartitionTimeUnit,
+ autoPartitionStrategy);
assertThat(resolvedPartitionSpec.getPartitionName()).isEqualTo(expected[i]);
}
}
+ @Test
+ void testValidateAutoPartitionTimeWithConfiguredDayFormat() {
+ Configuration dashedDayConf = new Configuration();
+ dashedDayConf.setBoolean(ConfigOptions.TABLE_AUTO_PARTITION_ENABLED, true);
+ dashedDayConf.set(ConfigOptions.TABLE_AUTO_PARTITION_TIME_UNIT, AutoPartitionTimeUnit.DAY);
+ dashedDayConf.setString(ConfigOptions.TABLE_AUTO_PARTITION_TIME_FORMAT, "yyyy-MM-dd");
+ AutoPartitionStrategy dashedDayStrategy = AutoPartitionStrategy.from(dashedDayConf);
+
+ LocalDate today =
+ Instant.now().atZone(dashedDayStrategy.timeZone().toZoneId()).toLocalDate();
+
+ assertThatNoException()
+ .isThrownBy(
+ () ->
+ validateAutoPartitionTime(
+ new PartitionSpec(
+ Collections.singletonMap("dt", today.toString())),
+ Collections.singletonList("dt"),
+ dashedDayStrategy));
+
+ assertThatThrownBy(
+ () ->
+ validateAutoPartitionTime(
+ new PartitionSpec(
+ Collections.singletonMap(
+ "dt",
+ today.format(
+ java.time.format.DateTimeFormatter
+ .ofPattern("yyyyMMdd")))),
+ Collections.singletonList("dt"),
+ dashedDayStrategy))
+ .isInstanceOf(InvalidPartitionException.class)
+ .hasMessageContaining("yyyy-MM-dd")
+ .hasMessageContaining("DAY");
+ }
+
+ @Test
+ void testValidateConfiguredTimeFormatWhenAutoPartitionIsDisabled() {
+ Configuration conf = new Configuration();
+ conf.setString(ConfigOptions.TABLE_AUTO_PARTITION_TIME_FORMAT, "yyyy-MM-dd");
+ AutoPartitionStrategy strategy = AutoPartitionStrategy.from(conf);
+
+ assertThatNoException()
+ .isThrownBy(
+ () ->
+ validateAutoPartitionTime(
+ new PartitionSpec(
+ Collections.singletonMap("dt", "2000-01-01")),
+ Collections.singletonList("dt"),
+ strategy));
+ assertThatThrownBy(
+ () ->
+ validateAutoPartitionTime(
+ new PartitionSpec(
+ Collections.singletonMap("dt", "20000101")),
+ Collections.singletonList("dt"),
+ strategy))
+ .isInstanceOf(InvalidPartitionException.class)
+ .hasMessageContaining("yyyy-MM-dd");
+ }
+
+ @Test
+ void testValidateAutoPartitionTimeRetentionBoundaryWithConfiguredDayFormat() {
+ Configuration dashedDayConf = new Configuration();
+ dashedDayConf.setBoolean(ConfigOptions.TABLE_AUTO_PARTITION_ENABLED, true);
+ dashedDayConf.set(ConfigOptions.TABLE_AUTO_PARTITION_TIME_UNIT, AutoPartitionTimeUnit.DAY);
+ dashedDayConf.setString(ConfigOptions.TABLE_AUTO_PARTITION_TIME_FORMAT, "yyyy-MM-dd");
+ AutoPartitionStrategy dashedDayStrategy = AutoPartitionStrategy.from(dashedDayConf);
+
+ LocalDate today =
+ Instant.now().atZone(dashedDayStrategy.timeZone().toZoneId()).toLocalDate();
+ LocalDate earliestRetained = today.minusDays(7);
+ LocalDate outOfDate = today.minusDays(8);
+
+ assertThatNoException()
+ .isThrownBy(
+ () ->
+ validateAutoPartitionTime(
+ new PartitionSpec(
+ Collections.singletonMap(
+ "dt", earliestRetained.toString())),
+ Collections.singletonList("dt"),
+ dashedDayStrategy));
+
+ assertThatThrownBy(
+ () ->
+ validateAutoPartitionTime(
+ new PartitionSpec(
+ Collections.singletonMap(
+ "dt", outOfDate.toString())),
+ Collections.singletonList("dt"),
+ dashedDayStrategy))
+ .isInstanceOf(InvalidPartitionException.class)
+ .hasMessageContaining(outOfDate.toString())
+ .hasMessageContaining(earliestRetained.toString());
+ }
+
@Test
void testString() {
Object value = BinaryString.fromString("Fluss");
diff --git a/fluss-server/src/main/java/org/apache/fluss/server/coordinator/AutoPartitionManager.java b/fluss-server/src/main/java/org/apache/fluss/server/coordinator/AutoPartitionManager.java
index 0a817c0e1..d47cf7967 100644
--- a/fluss-server/src/main/java/org/apache/fluss/server/coordinator/AutoPartitionManager.java
+++ b/fluss-server/src/main/java/org/apache/fluss/server/coordinator/AutoPartitionManager.java
@@ -471,7 +471,11 @@ public class AutoPartitionManager implements AutoCloseable {
for (int idx = 0; idx < partitionToPreCreate; idx++) {
ResolvedPartitionSpec partition =
generateAutoPartition(
- partitionKeys, currentZonedDateTime, idx, autoPartitionTimeUnit);
+ partitionKeys,
+ currentZonedDateTime,
+ idx,
+ autoPartitionTimeUnit,
+ autoPartitionStrategy);
// if the partition already exists, we don't need to create it, otherwise, create it
if (!currentPartitions.containsKey(partition.getPartitionName())) {
partitionsToCreate.add(partition);
@@ -499,7 +503,10 @@ public class AutoPartitionManager implements AutoCloseable {
// Get the earliest one partition time that need to retain.
String lastRetainPartitionTime =
generateAutoPartitionTime(
- currentZonedDateTime, -numToRetain, autoPartitionStrategy.timeUnit());
+ currentZonedDateTime,
+ -numToRetain,
+ autoPartitionStrategy.timeUnit(),
+ autoPartitionStrategy);
// For partition table with a single partition key, for example dt(yyyyMMdd)
// assuming now is 20250508, and table.auto-partition.num-retention=2 then partition
@@ -517,38 +524,43 @@ public class AutoPartitionManager implements AutoCloseable {
currentPartitions.headMap(lastRetainPartitionTime).entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<String, Set<String>> entry = iterator.next();
+ dropPartitions(tablePath, partitionKeys, iterator, entry);
+ }
+ }
- Iterator<String> dropIterator;
- if (entry.getValue() == null) {
- dropIterator = new HashSet<>(Collections.singleton(entry.getKey())).iterator();
- } else {
- dropIterator = entry.getValue().iterator();
- }
-
- while (dropIterator.hasNext()) {
- String partitionName = dropIterator.next();
- // drop the partition
- try {
- metadataManager.dropPartition(
- tablePath,
- ResolvedPartitionSpec.fromPartitionName(partitionKeys, partitionName),
- false);
- } catch (PartitionNotExistException e) {
- LOG.info(
- "Auto partitioning skip to delete partition {} for table [{}] as the partition is not exist.",
- partitionName,
- tablePath);
- }
+ private void dropPartitions(
+ TablePath tablePath,
+ List<String> partitionKeys,
+ Iterator<Map.Entry<String, Set<String>>> iterator,
+ Map.Entry<String, Set<String>> entry) {
+ Iterator<String> dropIterator;
+ if (entry.getValue() == null) {
+ dropIterator = new HashSet<>(Collections.singleton(entry.getKey())).iterator();
+ } else {
+ dropIterator = entry.getValue().iterator();
+ }
- // only remove when zk success, this reflects to the partitionsByTable
- dropIterator.remove();
+ while (dropIterator.hasNext()) {
+ String partitionName = dropIterator.next();
+ try {
+ metadataManager.dropPartition(
+ tablePath,
+ ResolvedPartitionSpec.fromPartitionName(partitionKeys, partitionName),
+ false);
+ } catch (PartitionNotExistException e) {
LOG.info(
- "Auto partitioning deleted partition {} for table [{}].",
+ "Auto partitioning skip to delete partition {} for table [{}] as the partition is not exist.",
partitionName,
tablePath);
}
- iterator.remove();
+
+ dropIterator.remove();
+ LOG.info(
+ "Auto partitioning deleted partition {} for table [{}].",
+ partitionName,
+ tablePath);
}
+ iterator.remove();
}
@VisibleForTesting
diff --git a/fluss-server/src/main/java/org/apache/fluss/server/coordinator/MetadataManager.java b/fluss-server/src/main/java/org/apache/fluss/server/coordinator/MetadataManager.java
index d87b85d5e..318424882 100644
--- a/fluss-server/src/main/java/org/apache/fluss/server/coordinator/MetadataManager.java
+++ b/fluss-server/src/main/java/org/apache/fluss/server/coordinator/MetadataManager.java
@@ -548,6 +548,7 @@ public class MetadataManager {
// reuse the same validate logic with the createTable() method
validateTableDescriptor(newDescriptor);
+
// pre alter table properties, e.g. create lake table in lake storage if it's to
// enable datalake for the table
preAlterTableProperties(
diff --git a/fluss-server/src/main/java/org/apache/fluss/server/utils/TableDescriptorValidation.java b/fluss-server/src/main/java/org/apache/fluss/server/utils/TableDescriptorValidation.java
index 4be0a0534..8a6e9fa2c 100644
--- a/fluss-server/src/main/java/org/apache/fluss/server/utils/TableDescriptorValidation.java
+++ b/fluss-server/src/main/java/org/apache/fluss/server/utils/TableDescriptorValidation.java
@@ -18,6 +18,7 @@
package org.apache.fluss.server.utils;
import org.apache.fluss.annotation.Internal;
+import org.apache.fluss.config.AutoPartitionTimeUnit;
import org.apache.fluss.config.ConfigOption;
import org.apache.fluss.config.ConfigOptions;
import org.apache.fluss.config.Configuration;
@@ -65,6 +66,7 @@ import static org.apache.fluss.metadata.TableDescriptor.LOG_OFFSET_COLUMN;
import static org.apache.fluss.metadata.TableDescriptor.OFFSET_COLUMN_NAME;
import static org.apache.fluss.metadata.TableDescriptor.TIMESTAMP_COLUMN_NAME;
import static org.apache.fluss.utils.PartitionUtils.PARTITION_KEY_SUPPORTED_TYPES;
+import static org.apache.fluss.utils.PartitionUtils.validateTimeFormat;
/** Validator of {@link TableDescriptor}. */
public class TableDescriptorValidation {
@@ -461,6 +463,8 @@ public class TableDescriptorValidation {
Configuration tableConf, List<String> partitionKeys, RowType rowType) {
boolean isPartitioned = !partitionKeys.isEmpty();
AutoPartitionStrategy autoPartition = AutoPartitionStrategy.from(tableConf);
+ boolean hasExplicitTimeFormat =
+ tableConf.contains(ConfigOptions.TABLE_AUTO_PARTITION_TIME_FORMAT);
if (!isPartitioned && autoPartition.isAutoPartitionEnabled()) {
throw new InvalidConfigException(
@@ -484,6 +488,18 @@ public class TableDescriptorValidation {
}
}
+ if (hasExplicitTimeFormat) {
+ try {
+ validateTimeFormat(autoPartition.timeUnit(), autoPartition);
+ } catch (IllegalArgumentException e) {
+ throw new InvalidTableException(
+ String.format(
+ "Invalid table property '%s': %s",
+ ConfigOptions.TABLE_AUTO_PARTITION_TIME_FORMAT.key(),
+ e.getMessage()));
+ }
+ }
+
if (autoPartition.isAutoPartitionEnabled()) {
if (partitionKeys.size() > 1) {
// must specify auto partition key for auto partition table when optional keys
@@ -518,10 +534,44 @@ public class TableDescriptorValidation {
+ "partition is enabled, please set table property '%s'.",
ConfigOptions.TABLE_AUTO_PARTITION_TIME_UNIT.key()));
}
+
+ String autoPartitionKey =
+ StringUtils.isNullOrWhitespaceOnly(autoPartition.key())
+ ? partitionKeys.get(0)
+ : autoPartition.key();
+ DataType autoPartitionDataType =
+ rowType.getTypeAt(rowType.getFieldIndex(autoPartitionKey));
+ checkDateAutoPartitionCompatibility(
+ autoPartition, autoPartitionKey, autoPartitionDataType);
}
}
}
+ private static void checkDateAutoPartitionCompatibility(
+ AutoPartitionStrategy autoPartition,
+ String autoPartitionKey,
+ DataType autoPartitionDataType) {
+ if (autoPartitionDataType.getTypeRoot() != DataTypeRoot.DATE) {
+ return;
+ }
+ if (autoPartition.timeUnit() != AutoPartitionTimeUnit.DAY) {
+ throw new InvalidTableException(
+ String.format(
+ "Table property '%s' must be '%s' when auto partition key '%s' has DATE type.",
+ ConfigOptions.TABLE_AUTO_PARTITION_TIME_UNIT.key(),
+ AutoPartitionTimeUnit.DAY,
+ autoPartitionKey));
+ }
+ if (!"yyyy-MM-dd".equals(autoPartition.timeFormat())) {
+ throw new InvalidTableException(
+ String.format(
+ "Table property '%s' must be '%s' when auto partition key '%s' has DATE type.",
+ ConfigOptions.TABLE_AUTO_PARTITION_TIME_FORMAT.key(),
+ "yyyy-MM-dd",
+ autoPartitionKey));
+ }
+ }
+
private static void checkDeleteBehavior(Configuration tableConf, boolean hasPrimaryKey) {
Optional<DeleteBehavior> deleteBehaviorOptional =
tableConf.getOptional(ConfigOptions.TABLE_DELETE_BEHAVIOR);
diff --git a/fluss-server/src/test/java/org/apache/fluss/server/coordinator/AutoPartitionManagerTest.java b/fluss-server/src/test/java/org/apache/fluss/server/coordinator/AutoPartitionManagerTest.java
index a24ab80db..9b4c8a20f 100644
--- a/fluss-server/src/test/java/org/apache/fluss/server/coordinator/AutoPartitionManagerTest.java
+++ b/fluss-server/src/test/java/org/apache/fluss/server/coordinator/AutoPartitionManagerTest.java
@@ -53,6 +53,7 @@ import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.Arrays;
import java.util.Collection;
+import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
@@ -393,6 +394,89 @@ class AutoPartitionManagerTest {
assertThat(partitions.keySet()).containsExactlyInAnyOrder(params.expectedPartitionsFinal);
}
+ @Test
+ void testDayFormatWithDashes() throws Exception {
+ ZonedDateTime startTime =
+ LocalDateTime.parse("2024-09-10T00:00:00").atZone(ZoneId.systemDefault());
+ ManualClock clock = new ManualClock(startTime.toInstant().toEpochMilli());
+ ManuallyTriggeredScheduledExecutorService periodicExecutor =
+ new ManuallyTriggeredScheduledExecutorService();
+
+ AutoPartitionManager autoPartitionManager =
+ new AutoPartitionManager(
+ new TestingServerMetadataCache(3),
+ new MetadataManager(
+ zookeeperClient,
+ new Configuration(),
+ new LakeCatalogDynamicLoader(new Configuration(), null, true)),
+ remoteDirDynamicLoader,
+ new Configuration(),
+ clock,
+ periodicExecutor);
+ autoPartitionManager.start();
+
+ TableInfo table =
+ createPartitionedTable(2, 4, AutoPartitionTimeUnit.DAY, false, "yyyy-MM-dd");
+ TablePath tablePath = table.getTablePath();
+ autoPartitionManager.addAutoPartitionTable(table, true);
+ periodicExecutor.triggerNonPeriodicScheduledTask();
+
+ Map<String, PartitionRegistration> partitions =
+ zookeeperClient.getPartitionRegistrations(tablePath);
+ assertThat(partitions.keySet())
+ .containsExactlyInAnyOrder("2024-09-10", "2024-09-11", "2024-09-12", "2024-09-13");
+
+ int replicaFactor = table.getTableConfig().getReplicationFactor();
+ Map<Integer, BucketAssignment> bucketAssignments =
+ generateAssignment(
+ table.getNumBuckets(),
+ replicaFactor,
+ new TabletServerInfo[] {
+ new TabletServerInfo(0, "rack0"),
+ new TabletServerInfo(1, "rack1"),
+ new TabletServerInfo(2, "rack2")
+ })
+ .getBucketAssignments();
+ PartitionAssignment partitionAssignment =
+ new PartitionAssignment(table.getTableId(), bucketAssignments);
+ metadataManager.createPartition(
+ tablePath,
+ table.getTableId(),
+ remoteDataDir,
+ partitionAssignment,
+ fromPartitionName(table.getPartitionKeys(), "2024-09-15"),
+ false);
+ autoPartitionManager.addPartition(table.getTableId(), "2024-09-15");
+
+ metadataManager.dropPartition(
+ tablePath, fromPartitionName(table.getPartitionKeys(), "2024-09-10"), false);
+ autoPartitionManager.removePartition(table.getTableId(), "2024-09-10");
+
+ clock.advanceTime(Duration.ofDays(3).plus(Duration.ofHours(23)));
+ periodicExecutor.triggerPeriodicScheduledTasks();
+ partitions = zookeeperClient.getPartitionRegistrations(tablePath);
+ assertThat(partitions.keySet())
+ .containsExactlyInAnyOrder(
+ "2024-09-11",
+ "2024-09-12",
+ "2024-09-13",
+ "2024-09-14",
+ "2024-09-15",
+ "2024-09-16");
+
+ clock.advanceTime(Duration.ofDays(2));
+ periodicExecutor.triggerPeriodicScheduledTasks();
+ partitions = zookeeperClient.getPartitionRegistrations(tablePath);
+ assertThat(partitions.keySet())
+ .containsExactlyInAnyOrder(
+ "2024-09-13",
+ "2024-09-14",
+ "2024-09-15",
+ "2024-09-16",
+ "2024-09-17",
+ "2024-09-18");
+ }
+
@Test
void testMaxPartitions() throws Exception {
int expectPartitionNumber = 10;
@@ -973,7 +1057,7 @@ class AutoPartitionManagerTest {
int partitionRetentionNum, int partitionPreCreateNum, AutoPartitionTimeUnit timeUnit)
throws Exception {
return createPartitionedTable(
- partitionRetentionNum, partitionPreCreateNum, timeUnit, false);
+ partitionRetentionNum, partitionPreCreateNum, timeUnit, false, null);
}
private TableInfo createPartitionedTable(
@@ -982,6 +1066,21 @@ class AutoPartitionManagerTest {
AutoPartitionTimeUnit timeUnit,
boolean multiplePartitionKeys)
throws Exception {
+ return createPartitionedTable(
+ partitionRetentionNum,
+ partitionPreCreateNum,
+ timeUnit,
+ multiplePartitionKeys,
+ null);
+ }
+
+ private TableInfo createPartitionedTable(
+ int partitionRetentionNum,
+ int partitionPreCreateNum,
+ AutoPartitionTimeUnit timeUnit,
+ boolean multiplePartitionKeys,
+ String timeFormat)
+ throws Exception {
long tableId = 1;
TablePath tablePath =
multiplePartitionKeys
@@ -1017,6 +1116,13 @@ class AutoPartitionManagerTest {
.property(
ConfigOptions.TABLE_AUTO_PARTITION_NUM_RETENTION,
partitionRetentionNum)
+ .properties(
+ timeFormat == null
+ ? Collections.emptyMap()
+ : Collections.singletonMap(
+ ConfigOptions.TABLE_AUTO_PARTITION_TIME_FORMAT
+ .key(),
+ timeFormat))
.property(
ConfigOptions.TABLE_AUTO_PARTITION_NUM_PRECREATE,
multiplePartitionKeys ? 0 : partitionPreCreateNum)
diff --git a/website/docs/engine-flink/options.md b/website/docs/engine-flink/options.md
index 329ea94f1..c612a968f 100644
--- a/website/docs/engine-flink/options.md
+++ b/website/docs/engine-flink/options.md
@@ -70,6 +70,7 @@ See more details about [ALTER TABLE ... SET](engine-flink/ddl.md#set-properties)
| table.auto-partition.enabled | Boolean | false | Whether enable auto partition for the table. Disable by default. When auto partition is enabled, the partitions of the table will be created automatically. [...]
| table.auto-partition.key | String | (None) | This configuration defines the time-based partition key to be used for auto-partitioning when a table is partitioned with multiple keys. Auto-partitioning utilizes a time-based partition key to handle partitions automatically, including creating new ones and removing outdated ones, by comparing the time value of the partition with the current system time. In the case of a table using multiple par [...]
| table.auto-partition.time-unit | ENUM | DAY | The time granularity for auto created partitions. The default value is `DAY`. Valid values are `HOUR`, `DAY`, `MONTH`, `QUARTER`, `YEAR`. If the value is `HOUR`, the partition format for auto created is yyyyMMddHH. If the value is `DAY`, the partition format for auto created is yyyyMMdd. If the value is `MONTH`, the partition format for auto created is yyyyMM. If the value is `QUARTER`, the parti [...]
+| table.auto-partition.time-format | String | based on time unit | The `DateTimeFormatter` pattern for auto-created partitions. The defaults are `yyyy` for YEAR, `yyyyQ` for QUARTER, `yyyyMM` for MONTH, `yyyyMMdd` for DAY, and `yyyyMMddHH` for HOUR. A custom format must order fields from largest to smallest, include every field required by the configured time unit, use fixed-width numeric fields, and must not contain optional sections (`[` or `]`). Its output mu [...]
| table.auto-partition.num-precreate | Integer | 2 | The number of partitions to pre-create for auto created partitions in each check for auto partition. For example, if the current check time is 2024-11-11 and the value is configured as 3, then partitions 20241111, 20241112, 20241113 will be pre-created. If any one partition exists, it'll skip creating the partition. The default value is 2, which means 2 partitions will be pre-created. If the `tab [...]
| table.auto-partition.num-retention | Integer | 7 | The number of history partitions to retain for auto created partitions in each check for auto partition. For example, if the current check time is 2024-11-11, time-unit is DAY, and the value is configured as 3, then the history partitions 20241108, 20241109, 20241110 will be retained. The partitions earlier than 20241108 will be deleted. The default value is 7, which means that 7 partitions will [...]
| table.auto-partition.time-zone | String | the system time zone | The time zone for auto partitions, which is by default the same as the system time zone. [...]
diff --git a/website/docs/table-design/data-distribution/partitioning.md b/website/docs/table-design/data-distribution/partitioning.md
index 69255bd0f..e2b8643b2 100644
--- a/website/docs/table-design/data-distribution/partitioning.md
+++ b/website/docs/table-design/data-distribution/partitioning.md
@@ -60,6 +60,7 @@ In this case, when automatic partitioning occurs (Fluss will periodically operat
| table.auto-partition.enabled | Boolean | no | false | Whether enable auto partition for the table. Disable by default. When auto partition is enabled, the partitions of the table will be created automatically. [...]
| table.auto-partition.key | String | no | (none) | This configuration defines the time-based partition key to be used for auto-partitioning when a table is partitioned with multiple keys. Auto-partitioning utilizes a time-based partition key to handle partitions automatically, including creating new ones and removing outdated ones, by comparing the time value of the partition with the current system time. In the case of a table using multiple partition key [...]
| table.auto-partition.time-unit | ENUM | no | DAY | The time granularity for auto created partitions. The default value is 'DAY'. Valid values are 'HOUR', 'DAY', 'MONTH', 'QUARTER', 'YEAR'. If the value is 'HOUR', the partition format for auto created is yyyyMMddHH. If the value is 'DAY', the partition format for auto created is yyyyMMdd. If the value is 'MONTH', the partition format for auto created is yyyyMM. If the value is 'QUARTER', the partition forma [...]
+| table.auto-partition.time-format | String | no | based on time unit | The `DateTimeFormatter` pattern for auto-created partitions. A custom format must list fields from the largest to the smallest time unit, include every field required by `table.auto-partition.time-unit`, and use fixed-width numeric fields. For example, `yyyy-MM-dd` is valid for DAY. [...]
| table.auto-partition.num-precreate | Integer | no | 2 | The number of partitions to pre-create for auto created partitions in each check for auto partition. For example, if the current check time is 2024-11-11 and the value is configured as 3, then partitions 20241111, 20241112, 20241113 will be pre-created. If any one partition exists, it'll skip creating the partition. The default value is 2, which means 2 partitions will be pre-created. If the 'table.auto-pa [...]
| table.auto-partition.num-retention | Integer | no | 7 | The number of history partitions to retain for auto created partitions in each check for auto partition. For example, if the current check time is 2024-11-11, time-unit is DAY, and the value is configured as 3, then the history partitions 20241108, 20241109, 20241110 will be retained. The partitions earlier than 20241108 will be deleted. The default value is 7. This option can be modified after table creat [...]
| table.auto-partition.time-zone | String | no | the system time zone | The time zone for auto partitions, which is by default the same as the system time zone. [...]
@@ -74,7 +75,18 @@ The time unit for the automatic partition table `auto-partition.time-unit` can t
| MONTH | yyyyMM | 202409 |
| QUARTER | yyyyQ | 20241 |
| YEAR | yyyy | 2024 |
-
+
+The default format can be overridden with `table.auto-partition.time-format`. Custom formats must satisfy all of the following rules:
+
+- Time fields are ordered from the largest to the smallest unit.
+- Every field that affects the configured partition granularity is present.
+- Numeric fields use a fixed width: four digits for year, two for month, day, and hour, and one for quarter.
+- Optional pattern sections using `[` and `]` are not supported because every partition value must contain all required fields.
+
+For example, `yyyy-MM-dd` is a valid DAY format. `MM-yyyy` has the wrong field order, `yyyy-MM` omits the day, and `yyyy-M-dd` uses a variable-width month, so they are rejected. The generated value must also be a valid Fluss partition value: no more than 200 ASCII alphanumeric, underscore, or hyphen characters, and without the reserved `__` prefix. Consequently, `yyyy/MM/dd` is invalid because `/` is not allowed. Literal text can be quoted, as in `yyyy-'Q'Q` for QUARTER. When the auto-pa [...]
+
+The configured time format is retained when auto partitioning is disabled. It continues to validate partition names created manually, while retention checks are skipped.
+
### Fluss Cluster Configuration
Below are the configuration items related to Fluss cluster and automatic partitioning.