jerryshao commented on code in PR #14883:
URL: https://github.com/apache/gravitino/pull/14883#discussion_r4548257407


##########
maintenance/optimizer/src/main/java/org/apache/gravitino/maintenance/optimizer/recommender/job/PartitionUtils.java:
##########
@@ -110,40 +140,92 @@ private static String getColumnName(Transform transform) {
     throw new IllegalArgumentException("Unsupported transform: " + 
transform.getClass().getName());
   }
 
+  /** Resolves the leaf type for {@code event.ts}-style paths under a 
top-level struct column. */
+  private static Type resolveLeafDataType(Column column, String columnName) {
+    // Exact match (including odd top-level names that contain '.') — no 
nested walk.
+    if (column.name().equalsIgnoreCase(columnName) || columnName.indexOf('.') 
< 0) {
+      return column.dataType();
+    }
+    Type type = column.dataType();
+    String[] parts = columnName.split("\\.");
+    for (int i = 1; i < parts.length; i++) {
+      if (!(type instanceof Types.StructType)) {
+        throw new IllegalArgumentException(
+            "Cannot resolve nested field '" + columnName + "': not a struct 
path");
+      }
+      Types.StructType.Field matched = null;
+      for (Types.StructType.Field field : ((Types.StructType) type).fields()) {
+        if (field.name().equalsIgnoreCase(parts[i])) {
+          matched = field;
+          break;
+        }
+      }
+      if (matched == null) {
+        throw new IllegalArgumentException(
+            "Nested field '" + columnName + "' not found in table schema");
+      }
+      type = matched.type();
+    }
+    return type;
+  }
+
+  /**
+   * Builds the left-hand side of a partition predicate using Iceberg Spark 
system functions.
+   *
+   * <p>Temporal transforms use plural names ({@code years}/{@code 
months}/{@code days}/{@code
+   * hours}) matching {@code 
org.apache.iceberg.spark.functions.SparkFunctions}. {@code bucket} and
+   * {@code truncate} put the width argument first, matching Iceberg's Spark 
UDF signatures.
+   */
   private static String buildExpression(Transform transform, String 
columnName) {
     if (transform instanceof Transforms.IdentityTransform) {
       return columnName;
-    } else if (transform instanceof Transforms.YearTransform
-        || transform instanceof Transforms.MonthTransform
-        || transform instanceof Transforms.DayTransform
-        || transform instanceof Transforms.HourTransform) {
-      return transform.name() + "(" + columnName + ")";
+    } else if (transform instanceof Transforms.YearTransform) {
+      return "years(" + columnName + ")";
+    } else if (transform instanceof Transforms.MonthTransform) {
+      return "months(" + columnName + ")";
+    } else if (transform instanceof Transforms.DayTransform) {
+      return "days(" + columnName + ")";
+    } else if (transform instanceof Transforms.HourTransform) {
+      return "hours(" + columnName + ")";
     } else if (transform instanceof Transforms.BucketTransform) {
       return "bucket("
-          + columnName
-          + ", "
           + ((Transforms.BucketTransform) transform).numBuckets()
+          + ", "
+          + columnName
           + ")";
     } else if (transform instanceof Transforms.TruncateTransform) {
       return "truncate("
-          + columnName
-          + ", "
           + ((Transforms.TruncateTransform) transform).width()
+          + ", "
+          + columnName
           + ")";
     }
     throw new IllegalArgumentException("Unsupported transform: " + 
transform.getClass().getName());
   }
 
-  private static String formatLiteral(Transform transform, Column column, 
String rawValue) {
+  private static String formatLiteral(Transform transform, Type type, String 
rawValue) {
+    // years/months/hours/bucket: raw Iceberg ints from producers (e.g. 
update-stats
+    // String.valueOf(Spark partition field)). years = years since 1970 
(calendar 2024 → 54),
+    // not a calendar year/month; months/hours likewise. Validate before 
emitting.
     if (transform instanceof Transforms.YearTransform
         || transform instanceof Transforms.MonthTransform
-        || transform instanceof Transforms.DayTransform
         || transform instanceof Transforms.HourTransform
         || transform instanceof Transforms.BucketTransform) {
-      return rawValue;
+      try {
+        return Long.toString(Long.parseLong(rawValue));
+      } catch (NumberFormatException e) {
+        throw new IllegalArgumentException(
+            "Partition value for years/months/hours/bucket must be an integer, 
but got: "
+                + rawValue,
+            e);
+      }
+    }
+
+    // days() → DateType; double-quoted DATE survives CALL where => '...' 
embedding.
+    if (transform instanceof Transforms.DayTransform) {
+      return "DATE \"" + 
escapeStringLiteral(toIsoDateFromDayPartitionValue(rawValue)) + "\"";

Review Comment:
   Day values must now be ISO yyyy-MM-dd and anything else throws, whereas 
before the raw value was passed through. Partitions already stored as epoch 
days or another format will now fail the whole recommendation; please confirm 
all producers write ISO, or accept epoch-day ints too.



##########
maintenance/optimizer/src/main/java/org/apache/gravitino/maintenance/optimizer/recommender/job/PartitionUtils.java:
##########
@@ -82,14 +107,19 @@ public static String getWhereClauseForPartition(
       Transform transform = partitioning[i];
 
       String columnName = getColumnName(transform);
-      Column column =
-          Preconditions.checkNotNull(
-              columnMap.get(columnName.toLowerCase(Locale.ROOT)),
-              "Column '%s' not found in table schema",
-              columnName);
+      // Nested paths like event.ts are absent from schema; fall back to 
top-level event.
+      Column column = columnMap.get(columnName.toLowerCase(Locale.ROOT));
+      if (column == null && columnName.indexOf('.') >= 0) {

Review Comment:
   Falling back to the top-level column for a dotted name like a.b also 
swallows a genuinely missing column whose name has a dot. Is the later struct 
walk guaranteed to fail clearly in that case?



##########
maintenance/jobs/src/main/java/org/apache/gravitino/maintenance/jobs/iceberg/IcebergJobUtils.java:
##########
@@ -188,6 +188,25 @@ public static String escapeSqlString(String value) {
     return value.replace("'", "''");
   }
 
+  /**
+   * Escapes a value for a Spark {@code CALL} named-arg single-quoted string 
(e.g. {@code where =>
+   * '...'}).
+   *
+   * <p>Even with {@code spark.sql.parser.escapedStringLiterals=false}, Spark 
still treats {@code
+   * \\} (and {@code \"} when a single backslash remains) inside the outer 
single-quoted argument.
+   * Double every backslash first so one outer parse leaves inner escapes 
(from a double-quoted
+   * predicate literal) intact, then double single quotes.
+   *
+   * @param value the string value to escape
+   * @return escaped string safe for use in a Spark CALL string argument, or 
null if input is null
+   */
+  public static String escapeSparkCallStringArg(String value) {
+    if (value == null) {
+      return null;
+    }
+    return escapeSqlString(value.replace("\\", "\\\\"));

Review Comment:
   Escaping a single quote by doubling it (escapeSqlString) is not reliably 
handled by Spark's parser, which can treat '' as two adjacent strings and drop 
the quote, changing the predicate value. Escape it as backslash-quote after 
doubling backslashes, and add a test with an apostrophe in a string partition 
value.



-- 
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]

Reply via email to