jerryshao commented on code in PR #14883:
URL: https://github.com/apache/gravitino/pull/14883#discussion_r4583302348
##########
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:
[P1] When both ANSI settings are enabled, `days(ts) = DATE "2024-01-01"`
fails while Spark parses the inner predicate, before Iceberg translates it.
Please use literal syntax that survives both parser stages and enable both
settings together in the CALL test. Include a string predicate as well, since
`"usa"` becomes an identifier in that mode.
##########
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:
[P1] With the stock rewrite template, the target Iceberg catalog is
registered but `spark_catalog` remains current. Qualifying
`catalog.system.rewrite_data_files` selects the procedure, while its `where`
expression still resolves bare `years(ts)` in the session catalog. The new test
sets `spark.sql.defaultCatalog` itself and hides this difference. Please
resolve the functions against the target catalog in production and exercise a
strategy-generated predicate with the template’s actual configuration.
##########
maintenance/optimizer/src/main/java/org/apache/gravitino/maintenance/optimizer/recommender/job/PartitionUtils.java:
##########
@@ -156,16 +238,40 @@ 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) + "\"";
}
}
+ /**
+ * Validates and normalizes a day-partition stored value to {@code
yyyy-MM-dd}.
+ *
+ * <p>Only ISO {@code yyyy-MM-dd} is accepted, matching Iceberg {@code
+ * DateTimeUtil.isoDateToDays(String)}. TMS update-stats stores Spark {@code
DateType} partition
+ * values via {@code String.valueOf}, which is already ISO. Epoch-day ints
and compact forms like
+ * {@code 20260101} are rejected rather than guessed.
+ */
+ private static String toIsoDateFromDayPartitionValue(String rawValue) {
+ try {
+ return LocalDate.parse(rawValue, DateTimeFormatter.ISO_LOCAL_DATE)
Review Comment:
[P2] The Spark producer test establishes the ISO contract for
`update-stats`. The local statistics importer also accepts `{"ts_day":"19723"}`
and preserves it through the partition path. Once selected alongside ISO
entries, that one value aborts construction of the whole job. Please handle
existing epoch-day entries or provide a migration path, while retaining the
explicit rejection of ambiguous compact dates such as `20260101`. A mixed
imported/ISO recommendation would cover both requirements.
##########
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:
[P1] For `O'Brien`, the generated CALL parses to `(region = "OBrien")` on
the pinned runtime. Please encode the outer argument with Spark’s
string-literal rules. Add a regression that inserts distinct `O'Brien` and
`OBrien` values through a value-preserving API, makes both partitions
rewrite-eligible, and verifies that only the requested partition’s files change.
--
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]