JingsongLi commented on code in PR #8185: URL: https://github.com/apache/paimon/pull/8185#discussion_r3523314244
########## paimon-core/src/main/java/org/apache/paimon/partition/PartitionTimeResolver.java: ########## @@ -0,0 +1,433 @@ +/* + * 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(); + } + + Map<PatternToken, Pair<Integer, Integer>> patternSpanMapping = new LinkedHashMap<>(); + for (PatternToken patternToken : patternTokens) { + if (!patternToken.isVariable) { + continue; + } + List<FormatToken> tokens = patternFormatMappings.get(patternToken); + int start = startPositions.get(tokens.get(0)); + int end = start; + for (FormatToken token : tokens) { + end += token.getLength(); + } + patternSpanMapping.put(patternToken, Pair.of(start, end)); + } + return patternSpanMapping; + } + + /** Parses formatter into format tokens (time fields and literals). */ + private List<FormatToken> parseFormatter() { + List<FormatToken> tokens = new ArrayList<>(); + for (int pos = 0; pos < formatter.length(); pos++) { + char c = formatter.charAt(pos); + if (isTimeChar(c)) { + int start = pos; + while (pos < formatter.length() && formatter.charAt(pos) == c) { + pos++; + } + ChronoField field = FIELD_MAP.get(c); + tokens.add(new TimeFieldToken(field, start, pos)); + pos--; + } else if (c == '\'') { + // parse literals + int start = pos++; + for (; pos < formatter.length(); pos++) { + if (formatter.charAt(pos) == '\'') { + if (pos + 1 < formatter.length() && formatter.charAt(pos + 1) == '\'') { + pos++; + } else { + break; // end of literal + } + } + } + checkArgument( + pos < formatter.length(), + "Pattern ends with an incomplete string literal: " + formatter); + String str = formatter.substring(start + 1, pos); + if (str.isEmpty()) { + tokens.add(new LiteralToken("'", start, pos + 1)); + } else { + tokens.add(new LiteralToken(str.replace("''", "'"), start, pos + 1)); + } + } else { + tokens.add(new LiteralToken(String.valueOf(c), pos, pos + 1)); Review Comment: This still silently accepts unsupported `DateTimeFormatter` pattern letters as literals. For example, after removing `S` from `FIELD_MAP`, a formatter such as `yyyyMMddHHmmssSSS` is tokenized with three literal `S` tokens here, but `DateTimeFormatter` will format them as fractional-second digits. If `$dt` consumes the whole formatter, `extractMinStep()` only sees seconds and chain delta planning advances by one second while generating values like `...000`, so millisecond partitions are skipped instead of being rejected. Please reject unquoted formatter pattern letters that are not in `FIELD_MAP` (or implement their step semantics), rather than treating them as literal text. -- 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]
