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


##########
maintenance/optimizer/src/main/java/org/apache/gravitino/maintenance/optimizer/recommender/job/PartitionUtils.java:
##########
@@ -156,18 +236,64 @@ private static String formatLiteral(Transform transform, 
Column column, String r
       case DECIMAL:
         return rawValue;
       case DATE:
-        return "DATE '" + rawValue + "'";
       case TIMESTAMP:
-        return "TIMESTAMP '" + rawValue + "'";
       case TIME:
-        return "TIME '" + rawValue + "'";
+        // Same CALL embedding constraint as days(); escape " / \ like string 
literals.
+        return type.name() + " \"" + escapeStringLiteral(rawValue) + "\"";
       default:
         return "\"" + escapeStringLiteral(rawValue) + "\"";
     }
   }
 
+  /**
+   * Converts a day-partition stored value to {@code yyyy-MM-dd}.
+   *
+   * <p>Supported inputs match Iceberg {@code DateTimeUtil} (no iceberg-api 
dependency):
+   *
+   * <ul>
+   *   <li>ISO {@code yyyy-MM-dd} — same as {@code 
DateTimeUtil.isoDateToDays(String)}
+   *   <li>epoch-day integer string — same as {@code 
DateTimeUtil.daysToIsoDate(int)}
+   * </ul>
+   *
+   * <p>Both appear because callers store partition values as strings: 
update-stats uses {@code
+   * String.valueOf(Spark date)} (ISO), while Iceberg metadata may expose the 
raw epoch-day int.
+   * Compact forms like {@code 20260101} are not ISO dates; if all digits they 
are parsed as
+   * epoch-day (same as {@code daysToIsoDate(20260101)}), not as a calendar 
compact date.
+   */
+  private static String toIsoDateFromDayPartitionValue(String rawValue) {
+    try {
+      // DateTimeUtil.isoDateToDays(String): ISO_LOCAL_DATE only.
+      return LocalDate.parse(rawValue, DateTimeFormatter.ISO_LOCAL_DATE)
+          .format(DateTimeFormatter.ISO_LOCAL_DATE);
+    } catch (DateTimeParseException ignored) {
+      // fall through to epoch-day
+    }
+    try {
+      // DateTimeUtil.daysToIsoDate(int).
+      return LocalDate.ofEpochDay(Integer.parseInt(rawValue))
+          .format(DateTimeFormatter.ISO_LOCAL_DATE);
+    } catch (NumberFormatException e) {
+      throw new IllegalArgumentException(
+          "Day partition value must be an ISO date (yyyy-MM-dd) or epoch-day 
integer "
+              + "(Iceberg DateTimeUtil), but got: "
+              + rawValue,
+          e);
+    }
+  }
+
+  /**
+   * Escapes a value for a double-quoted Iceberg Spark literal that is later 
embedded in {@code CALL
+   * ... where => '...'} via {@code IcebergJobUtils.escapeSqlString} 
(single-quote doubling only).
+   *
+   * <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 {@code
+   * where} argument. Build the inner double-quoted escapes ({@code \} → 
{@code \\}, {@code "} →
+   * {@code \"}), then double every backslash so one outer parse leaves those 
inner escapes intact
+   * (e.g. raw {@code a"b\c} → {@code a\\"b\\\\c} in the where text).
+   */
   private static String escapeStringLiteral(String value) {
-    return value.replace("\\", "\\\\").replace("\"", "\\\"");
+    // Inner: \ → \\, " → \"; then double all backslashes for outer CALL where 
=> '...'.
+    return value.replace("\\", "\\\\\\\\").replace("\"", "\\\\\"");

Review Comment:
   Good catch — fixed in e247fb52e4.
   
   `PartitionUtils` was baking CALL `where => '...'` outer escaping into a 
general where builder, so any other consumer would get over-escaped literals.
   
   **Change:**
   - `PartitionUtils.escapeStringLiteral` now only does one-level escaping for 
double-quoted Iceberg Spark literals (`\` → `\\`, `"` → `\"`).
   - Added `IcebergJobUtils.escapeSparkCallStringArg`, which doubles 
backslashes first (so one Spark outer parse leaves inner escapes intact), then 
doubles single quotes.
   - `IcebergRewriteDataFilesJob.buildProcedureCall` uses that helper only for 
the `where` argument.
   
   **Tests:** unit coverage for the new helper, and Spark CALL E2E for 
partition values containing `"`, `\`, and `'` (ansi.doubleQuotedIdentifiers 
on/off).



##########
maintenance/optimizer/src/main/java/org/apache/gravitino/maintenance/optimizer/recommender/job/PartitionUtils.java:
##########
@@ -156,18 +236,64 @@ private static String formatLiteral(Transform transform, 
Column column, String r
       case DECIMAL:
         return rawValue;
       case DATE:
-        return "DATE '" + rawValue + "'";
       case TIMESTAMP:
-        return "TIMESTAMP '" + rawValue + "'";
       case TIME:
-        return "TIME '" + rawValue + "'";
+        // Same CALL embedding constraint as days(); escape " / \ like string 
literals.
+        return type.name() + " \"" + escapeStringLiteral(rawValue) + "\"";
       default:
         return "\"" + escapeStringLiteral(rawValue) + "\"";
     }
   }
 
+  /**
+   * Converts a day-partition stored value to {@code yyyy-MM-dd}.
+   *
+   * <p>Supported inputs match Iceberg {@code DateTimeUtil} (no iceberg-api 
dependency):
+   *
+   * <ul>
+   *   <li>ISO {@code yyyy-MM-dd} — same as {@code 
DateTimeUtil.isoDateToDays(String)}
+   *   <li>epoch-day integer string — same as {@code 
DateTimeUtil.daysToIsoDate(int)}
+   * </ul>
+   *
+   * <p>Both appear because callers store partition values as strings: 
update-stats uses {@code
+   * String.valueOf(Spark date)} (ISO), while Iceberg metadata may expose the 
raw epoch-day int.
+   * Compact forms like {@code 20260101} are not ISO dates; if all digits they 
are parsed as
+   * epoch-day (same as {@code daysToIsoDate(20260101)}), not as a calendar 
compact date.
+   */
+  private static String toIsoDateFromDayPartitionValue(String rawValue) {
+    try {
+      // DateTimeUtil.isoDateToDays(String): ISO_LOCAL_DATE only.
+      return LocalDate.parse(rawValue, DateTimeFormatter.ISO_LOCAL_DATE)
+          .format(DateTimeFormatter.ISO_LOCAL_DATE);
+    } catch (DateTimeParseException ignored) {
+      // fall through to epoch-day
+    }
+    try {
+      // DateTimeUtil.daysToIsoDate(int).
+      return LocalDate.ofEpochDay(Integer.parseInt(rawValue))

Review Comment:
   Agreed — fixed in e247fb52e4.
   
   Keeping an epoch-day fallback for any all-digit string was unsafe: a compact 
date like `20260101` is not ISO, but would parse as an epoch-day and become a 
date around year 57000, so the filter matches nothing and compaction is skipped 
silently.
   
   **Change:** day partition values now accept **ISO `yyyy-MM-dd` only**, 
matching Iceberg `DateTimeUtil.isoDateToDays(String)`. Non-ISO inputs 
(epoch-day ints such as `19723`, compact `20260101`, etc.) throw a clear 
`IllegalArgumentException`.
   
   This matches the TMS update-stats path: Spark `DateType` partition fields 
become ISO via `String.valueOf`. Unit tests cover accept-ISO / reject-epoch-day 
/ reject-compact-date.



##########
maintenance/optimizer/src/main/java/org/apache/gravitino/maintenance/optimizer/recommender/job/PartitionUtils.java:
##########
@@ -110,40 +140,90 @@ 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 partition values are Iceberg ints; 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));

Review Comment:
   Checked — the producer path is fine; no code change needed beyond docs/tests 
(e247fb52e4).
   
   `years` / `months` / `hours` compare against Iceberg ints (e.g. calendar 
year 2024 → `54` = 2024 − 1970), not calendar year/month values.
   
   **Producer:** `IcebergUpdateStatsAndMetricsJob.toPartitionPath` stores 
`String.valueOf` of the Spark/Iceberg `partition` struct fields. Those fields 
already use transform-native Iceberg ints for years/months/hours (and ISO dates 
for days). We do not reinterpret them.
   
   **Evidence:** Spark IT `assertTemporalIntRewrite` reads the partition value 
from `.partitions` via `String.valueOf` and runs `CALL rewrite_data_files` with 
`years|months|hours(ts) = <that value>`.
   
   Also fixed a misleading unit test that used calendar `"2024"` with 
`Transforms.year` (now `"54"`), and documented the Iceberg-int semantics on 
`formatLiteral` / `toPartitionPath`.



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