JingsongLi commented on code in PR #8185: URL: https://github.com/apache/paimon/pull/8185#discussion_r3524491070
########## paimon-core/src/main/java/org/apache/paimon/partition/PartitionTimeResolver.java: ########## @@ -0,0 +1,438 @@ +/* + * 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.paimon.partition; + +import org.apache.paimon.utils.Pair; + +import java.time.DateTimeException; +import java.time.Duration; +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.time.LocalTime; +import java.time.Period; +import java.time.format.DateTimeFormatter; +import java.time.format.DateTimeParseException; +import java.time.temporal.ChronoField; +import java.time.temporal.TemporalAmount; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Comparator; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Optional; +import java.util.stream.Collectors; + +import static org.apache.paimon.utils.Preconditions.checkArgument; + +/** + * Resolves timestamp pattern and formatter to extract time step and compute partition values for + * chain table partitions. + */ +public class PartitionTimeResolver { + private static final Map<Character, ChronoField> FIELD_MAP = new HashMap<>(); + private final List<String> partitionColumns; + private final String pattern; + private final String formatter; + private Map<PatternToken, List<FormatToken>> patternFormatMappings; + private Map<PatternToken, Pair<Integer, Integer>> patternSpanMappings; + private List<PatternToken> patternTokens; + private List<FormatToken> formatTokens; + + public PartitionTimeResolver(List<String> partitionColumns, String pattern, String formatter) { + checkArgument(pattern != null, "pattern cannot be null"); + checkArgument(formatter != null, "formatter cannot be null"); + checkArgument(partitionColumns != null, "partitionColumns cannot be null"); + this.partitionColumns = partitionColumns; + this.pattern = pattern; + this.formatter = formatter; + init(); + } + + static { + FIELD_MAP.put('y', ChronoField.YEAR); + FIELD_MAP.put('M', ChronoField.MONTH_OF_YEAR); + FIELD_MAP.put('d', ChronoField.DAY_OF_MONTH); + FIELD_MAP.put('H', ChronoField.HOUR_OF_DAY); + FIELD_MAP.put('h', ChronoField.CLOCK_HOUR_OF_AMPM); + FIELD_MAP.put('m', ChronoField.MINUTE_OF_HOUR); + FIELD_MAP.put('s', ChronoField.SECOND_OF_MINUTE); + } + + private void init() { + this.patternFormatMappings = new HashMap<>(); + this.patternTokens = parsePattern(); + this.formatTokens = parseFormatter(); + boolean matched = matchRecursive(0, 0); + checkArgument( + matched, "Failed to match pattern '%s' to formatter '%s'", pattern, formatter); + this.patternSpanMappings = calPatternSpanMappings(); + } + + /** + * Extracts the minimum time step from the given pattern and formatter. + * + * @return the smallest {@link Duration} or {@link Period} step among variable-controlled time + * units + */ + public TemporalAmount extractMinStep() { + List<TimeFieldToken> fieldTokens = + patternFormatMappings.values().stream() + .flatMap(Collection::stream) + .filter(token -> token instanceof TimeFieldToken) + .map(token -> (TimeFieldToken) token) + .collect(Collectors.toList()); + + Optional<TimeFieldToken> min = + fieldTokens.stream().min(Comparator.comparingInt(span -> span.field.ordinal())); + checkArgument(min.isPresent(), "No time unit found in variable ranges"); + ChronoField field = min.get().field; + return stepOf(field); + } + + /** + * Computes partition column values by formatting the given datetime and extracting each + * variable's segment according to the pattern-to-format mapping. + */ + public LinkedHashMap<String, String> resolvePartitionValues(LocalDateTime dateTime) { + DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(formatter, Locale.ROOT); + String formatted = dateTime.format(dateTimeFormatter); + LinkedHashMap<String, String> result = new LinkedHashMap<>(); + for (Map.Entry<PatternToken, Pair<Integer, Integer>> entry : + patternSpanMappings.entrySet()) { + String variableName = entry.getKey().token.substring(1); + int start = entry.getValue().getLeft(); + int end = entry.getValue().getRight(); + result.put(variableName, formatted.substring(start, end)); + } + return result; + } + + public LocalDateTime parsePartitionValues(List<?> partitionValues) { + Map<String, Object> valueMap = new HashMap<>(); + for (int i = 0; i < partitionColumns.size(); i++) { + valueMap.put(partitionColumns.get(i), partitionValues.get(i)); + } + + StringBuilder timestampString = new StringBuilder(); + for (PatternToken token : patternTokens) { + if (token.isVariable) { + timestampString.append(valueMap.get(token.token.substring(1))); + } else { + timestampString.append(token.token); + } + } + DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(formatter, Locale.ROOT); + try { + return LocalDateTime.parse(timestampString, dateTimeFormatter); + } catch (DateTimeParseException e) { + return LocalDateTime.of( + LocalDate.parse(timestampString, dateTimeFormatter), LocalTime.MIDNIGHT); + } + } + + private Map<PatternToken, Pair<Integer, Integer>> calPatternSpanMappings() { + int pos = 0; + Map<FormatToken, Integer> startPositions = new LinkedHashMap<>(); + for (FormatToken token : formatTokens) { + startPositions.put(token, pos); + pos += token.getLength(); Review Comment: Blocking: this offset calculation assumes every formatter token emits exactly `token.getLength()` characters, but Java `DateTimeFormatter` allows variable-width fields such as `yyyy-M-d` and `H:m:s`. On this PR head, `new PartitionTimeResolver(Arrays.asList("dt"), "$dt", "yyyy-M-d").resolvePartitionValues(LocalDateTime.of(2026, 12, 31, 0, 0))` returns `{dt=2026-12-}`, truncating the day. Please either compute spans from the actual formatted output or reject variable-width formatter patterns during table validation. ########## paimon-spark/paimon-spark-ut/src/test/java/org/apache/paimon/spark/SparkChainTableITCase.java: ########## @@ -2420,4 +2420,61 @@ public void testChainTableWithMultiChainKeys(@TempDir java.nio.file.Path tempDir spark.sql("DROP TABLE IF EXISTS `my_db1`.`chain_test`;"); spark.close(); } + + @Test + public void testChainTableWithMinuteLevelPartitions(@TempDir java.nio.file.Path tempDir) + throws IOException { + Path warehousePath = new Path("file:" + tempDir.toString()); + SparkSession.Builder builder = createSparkSessionBuilder(warehousePath); + SparkSession spark = builder.getOrCreate(); + spark.sql("CREATE DATABASE IF NOT EXISTS my_db1"); + spark.sql("USE spark_catalog.my_db1"); + + spark.sql( + "CREATE TABLE `chain_test` (\n" + + " `t1` BIGINT COMMENT 't1',\n" + + " `t2` BIGINT COMMENT 't2',\n" + + " `t3` STRING COMMENT 't3'\n" + + ") PARTITIONED BY (`dt` STRING, `hr_min` STRING)\n" + + "TBLPROPERTIES (\n" + + " 'bucket-key' = 't1',\n" + + " 'primary-key' = 'dt,hr_min,t1',\n" + + " 'partition.timestamp-pattern' = '$dt $hr_min:00',\n" + + " 'partition.timestamp-formatter' = 'yyyyMMdd HH:mm:ss',\n" + + " 'chain-table.enabled' = 'true',\n" + + " 'bucket' = '1',\n" + + " 'merge-engine' = 'deduplicate',\n" + + " 'sequence.field' = 't2',\n" + + " 'chain-table.chain-partition-keys' = 'dt,hr_min'\n" + + ");"); + + setupChainTableBranches(spark, "chain_test"); + + spark.sql( + "INSERT INTO TABLE `chain_test$branch_snapshot` PARTITION (dt = '20250810', hr_min='01:01') VALUES (3, 1, '3');"); + spark.sql( + "INSERT INTO TABLE `chain_test$branch_snapshot` PARTITION (dt = '20250810', hr_min='03:30') VALUES (4, 1, '4');"); + + spark.sql( + "INSERT INTO TABLE `chain_test$branch_delta` PARTITION (dt = '20250810', hr_min='03:35') VALUES (5, 1, '5');"); + spark.sql( + "INSERT INTO TABLE `chain_test$branch_delta` PARTITION (dt = '20250810', hr_min='03:40') VALUES (6, 1, '6');"); + spark.sql( + "INSERT INTO TABLE `chain_test$branch_delta` PARTITION (dt = '20250810', hr_min='03:45') VALUES (7, 1, '7');"); + + assertThat( + spark + .sql( + "select * from `chain_test` where dt='20250810' and hr_min='03:40'") + .collectAsList().stream() + .map(Row::toString) + .collect(Collectors.toList())) + .containsExactlyInAnyOrder( Review Comment: Blocking: this new test is currently failing on the PR head. Running `mvn -pl paimon-spark/paimon-spark-ut -am -Pfast-build -DfailIfNoTests=false -Dtest=SparkChainTableITCase#testChainTableWithMinuteLevelPartitions test` still returns an extra `[7,1,7,20250810,03:40]` row from the `03:45` delta partition for the `03:40` query. That means chain planning can still read future delta partitions after the requested chain partition, so please tighten the selected delta partitions to the actual `(anchor, requested]` range before merging. -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected]
