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


##########
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 + ")";

Review Comment:
   Fixed on latest HEAD (`668d1d606f`).
   
   - Template `buildTemplateSparkConfigs` sets 
`spark.sql.defaultCatalog={{catalog_name}}`.
   - `IcebergRewriteDataFilesJob` / `IcebergMaintenanceJob` call 
`ensureIcebergCatalogConfigs(sparkConf, catalogName)` so bare 
`years()`/`days()` resolve on the target Iceberg catalog (not `spark_catalog`).
   - `spark_conf` must not set `spark.sql.defaultCatalog`; the job owns it from 
`catalog_name`.
   - Builtin rewrite IT exercises strategy-generated predicates using the 
template/ensure path (does not hand-set `defaultCatalog` independently).
   
   Resolving.



##########
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:
   Fixed on latest HEAD (`668d1d606f`).
   
   Outer CALL args use Spark string-literal rules via 
`escapeSparkCallStringArg` (`'` → `\'` after doubling backslashes). Added 
regression that inserts distinct `O'Brien` / `OBrien` through the DataFrame 
API, makes both rewrite-eligible, rewrites only `O'Brien`, and asserts only 
that partition's data files change.
   
   Resolving.



##########
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:
   Fixed on latest HEAD (`668d1d606f`).
   
   `PartitionUtils` emits single-quoted literals (`DATE '...'`, `region = 
'...'`) so predicates survive `spark.sql.ansi.doubleQuotedIdentifiers`. Added 
CALL E2E coverage for all four combinations of `spark.sql.ansi.enabled` × 
`doubleQuotedIdentifiers` for both string and DATE predicates.
   
   Resolving.



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