juntaozhang commented on code in PR #8185: URL: https://github.com/apache/paimon/pull/8185#discussion_r3520629608
########## paimon-core/src/main/java/org/apache/paimon/partition/PartitionTimeResolver.java: ########## @@ -0,0 +1,421 @@ +/* + * 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.Objects; +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); + 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) { + StringBuilder timestampString = new StringBuilder(); + int valueIdx = 0; + for (PatternToken token : patternTokens) { + if (token.isVariable) { + timestampString.append(partitionValues.get(valueIdx).toString()); + valueIdx++; + } else { + timestampString.append(token.token); + } + } + DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(formatter, Locale.ROOT); + try { + return LocalDateTime.parse(timestampString, Objects.requireNonNull(dateTimeFormatter)); + } catch (DateTimeParseException e) { + return LocalDateTime.of( + LocalDate.parse(timestampString, Objects.requireNonNull(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)); + } + } + checkArgument(!tokens.isEmpty(), "No time unit found in formatter: %s", formatter); + return tokens; + } + + private static boolean isTimeChar(char c) { + return FIELD_MAP.containsKey(c); + } + + /** Parses pattern string into pattern tokens (variables and literals). */ + private List<PatternToken> parsePattern() { + List<PatternToken> tokens = new ArrayList<>(); + int len = pattern.length(); + int cursor = 0; + int partCursor = 0; + StringBuilder literalBuf = new StringBuilder(); + while (cursor < len) { + char curr = pattern.charAt(cursor); + if (curr == '$') { + if (literalBuf.length() > 0) { + tokens.add(new PatternToken(literalBuf.toString(), false)); + literalBuf.setLength(0); + } + checkArgument( + partCursor < partitionColumns.size(), + "Extra variable in pattern, exceed partitionColumns count"); + String part = curr + partitionColumns.get(partCursor); + checkArgument(pattern.substring(cursor).startsWith(part)); Review Comment: Thanks for the guidance. 1. This is already supported. The new `parsePattern()` matches variables by name rather than by position, and `parsePartitionValues()` resolves values from a column-name map, so a pattern like `$hour $dt` works regardless of the order in partitionColumns. 2. I still use `partitionColumns` here because regex cannot resolve the ambiguity in cases like `$dt01`, where it is impossible to tell whether `dt01` is a single column name or `dt` followed by literal `01`. 3. Other cases from `PartitionTimeExtractor`, such as default pattern/formatter handling, will be fully migrated in the next PR. -- 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]
