lasdf1234 commented on code in PR #14883:
URL: https://github.com/apache/gravitino/pull/14883#discussion_r4560760339
##########
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:
The TMS producer already writes ISO day values.
`IcebergUpdateStatsAndMetricsJob.toPartitionPath` uses `String.valueOf` on
Spark `DateType` partition fields, which are `yyyy-MM-dd`.
Covered by existing tests:
- Producer (real Spark):
`TestIcebergUpdateStatsJobWithSpark.testUpdateMultiLevelPartitionedTableStatistics`
asserts `event_ts_day=2026-01-01` / `2026-01-02` (not epoch-day ints).
- Consumer contract:
`TestPartitionUtils.testDayPartitionUsesIcebergDaysFunctionWithDateLiteral` /
`testDayPartitionAcceptsIsoDateFromUpdateStatsPath`, plus
`testDayPartitionRejectsEpochDayIntegerString` and
`testDayPartitionRejectsCompactDigitDate`.
Re-accepting epoch-day would reopen the compact `20260101` → ~year 57000
silent miss you flagged earlier, so we keep ISO-only and fail fast.
##########
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:
We kept SQL-standard `'` → `''` in `escapeSqlString`. With the default
`escapedStringLiterals=false`, that is the reliable form; switching to `\'` is
riskier under that setting.
Already verified end-to-end with an apostrophe partition value:
-
`TestIcebergRewriteDataFilesJobWithSpark.testPartitionUtilsWhereWithSingleQuoteThroughJobEscapeAndSpark`
— `O'Brien` → CALL `where => '(region = "O''Brien")'` → real
`rewrite_data_files`.
-
`TestBuiltinIcebergRewriteDataFiles.assertRewriteCallForIdentityStringWithSingleQuote`
— same path via production-equivalent `escapeSqlString`.
No code change planned.
##########
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:
A top-level column name containing `.` is not a Gravitino-supported name
(`Capability.DEFAULT` / `^\w[\w/=-]{0,63}$`; see
`TestCapability.testDefaultNameSpecification`). Dotted paths here are nested
field paths (`String[]{"event","ts"}` → `event.ts`), not a column literally
named `a.b`.
For a missing nested field, the struct walk already fails clearly — covered
by `TestPartitionUtils.testNestedFieldNotFoundThrowsClearError`. Successful
nested resolution is covered by
`testDayPartitionOnNestedStructFieldResolvesTopLevelColumn` /
`testIdentityPartitionOnNestedTimestampUsesTypedLiteral`.
No code change planned.
--
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]