World's most powerful open data catalog for building a high-performance, geo-distributed and federated metadata lake.
Java ai-catalogdata-catalogdatalakefederated-querylakehousemetadatametalakemodel-catalogopendatacatalogskycomputingstratosphere
[#10587] fix(tms): Iceberg system-function predicates with CALL-safe literals (#14883)
MaSai23f1d861ea0f
diff --git a/catalogs/catalog-lakehouse-iceberg/src/main/java/org/apache/gravitino/catalog/lakehouse/iceberg/converter/ConvertUtil.java b/catalogs/catalog-lakehouse-iceberg/src/main/java/org/apache/gravitino/catalog/lakehouse/iceberg/converter/ConvertUtil.javaindex 6441667d82..7c97e30511 100644--- a/catalogs/catalog-lakehouse-iceberg/src/main/java/org/apache/gravitino/catalog/lakehouse/iceberg/converter/ConvertUtil.java+++ b/catalogs/catalog-lakehouse-iceberg/src/main/java/org/apache/gravitino/catalog/lakehouse/iceberg/converter/ConvertUtil.java@@ -215,5 +215,22 @@ public class ConvertUtil {return org.apache.gravitino.rel.types.Types.StructType.of(fields);}+ /**+ * Splits an Iceberg {@code schema.idToName()} value into Gravitino field-name components.+ *+ * <p>Iceberg joins nested levels with {@code '.'} (e.g. {@code event.user-id}). Callers must not+ * pass the dotted string to {@code Transforms.*(String)} / {@code NamedReference.field(String)},+ * which would keep a single component {@code ["event.user-id"]}.+ *+ * @param icebergIdToName dotted nested name from {@code Schema.idToName()}+ * @return field path components (e.g. {@code ["event", "user-id"]})+ */+ public static String[] splitIcebergNameToFieldPath(String icebergIdToName) {+ Preconditions.checkArgument(+ icebergIdToName != null && !icebergIdToName.isEmpty(),+ "Iceberg idToName value cannot be null or empty");+ return icebergIdToName.split("\\.", -1);+ }+private ConvertUtil() {}}diff --git a/catalogs/catalog-lakehouse-iceberg/src/main/java/org/apache/gravitino/catalog/lakehouse/iceberg/converter/FromIcebergPartitionSpec.java b/catalogs/catalog-lakehouse-iceberg/src/main/java/org/apache/gravitino/catalog/lakehouse/iceberg/converter/FromIcebergPartitionSpec.javaindex a28b14624a..9b0c70fa03 100644--- a/catalogs/catalog-lakehouse-iceberg/src/main/java/org/apache/gravitino/catalog/lakehouse/iceberg/converter/FromIcebergPartitionSpec.java+++ b/catalogs/catalog-lakehouse-iceberg/src/main/java/org/apache/gravitino/catalog/lakehouse/iceberg/converter/FromIcebergPartitionSpec.java@@ -44,37 +44,42 @@ public class FromIcebergPartitionSpec implements PartitionSpecVisitor<Transform>@Overridepublic Transform identity(String sourceName, int sourceId) {- return Transforms.identity(idToName.get(sourceId));+ return Transforms.identity(fieldName(sourceId));}@Overridepublic Transform bucket(String sourceName, int sourceId, int numBuckets) {- return Transforms.bucket(numBuckets, new String[] {idToName.get(sourceId)});+ // String[]...: wrap as one nested path, not multiple top-level fields.+ return Transforms.bucket(numBuckets, new String[][] {fieldName(sourceId)});}@Overridepublic Transform truncate(String sourceName, int sourceId, int width) {- return Transforms.truncate(width, idToName.get(sourceId));+ return Transforms.truncate(width, fieldName(sourceId));}@Overridepublic Transform year(String sourceName, int sourceId) {- return Transforms.year(idToName.get(sourceId));+ return Transforms.year(fieldName(sourceId));}@Overridepublic Transform month(String sourceName, int sourceId) {- return Transforms.month(idToName.get(sourceId));+ return Transforms.month(fieldName(sourceId));}@Overridepublic Transform day(String sourceName, int sourceId) {- return Transforms.day(idToName.get(sourceId));+ return Transforms.day(fieldName(sourceId));}@Overridepublic Transform hour(String sourceName, int sourceId) {- return Transforms.hour(idToName.get(sourceId));+ return Transforms.hour(fieldName(sourceId));+ }++ private String[] fieldName(int sourceId) {+ return ConvertUtil.splitIcebergNameToFieldPath(idToName.get(sourceId));}@Overridediff --git a/catalogs/catalog-lakehouse-iceberg/src/main/java/org/apache/gravitino/catalog/lakehouse/iceberg/converter/FromIcebergSortOrder.java b/catalogs/catalog-lakehouse-iceberg/src/main/java/org/apache/gravitino/catalog/lakehouse/iceberg/converter/FromIcebergSortOrder.javaindex 3e34bdd282..88f59a511a 100644--- a/catalogs/catalog-lakehouse-iceberg/src/main/java/org/apache/gravitino/catalog/lakehouse/iceberg/converter/FromIcebergSortOrder.java+++ b/catalogs/catalog-lakehouse-iceberg/src/main/java/org/apache/gravitino/catalog/lakehouse/iceberg/converter/FromIcebergSortOrder.java@@ -84,13 +84,13 @@ public class FromIcebergSortOrder implements SortOrderVisitor<SortOrder> {private SortOrder fieldSortOrder(int id, SortDirection direction, NullOrder nullOrder) {return SortOrders.of(- NamedReference.field(idToName.get(id)), toGravitino(direction), toGravitino(nullOrder));+ NamedReference.field(fieldName(id)), toGravitino(direction), toGravitino(nullOrder));}private SortOrder functionSortOrder(String name, int id, SortDirection direction, NullOrder nullOrder) {return SortOrders.of(- FunctionExpression.of(name, NamedReference.field(idToName.get(id))),+ FunctionExpression.of(name, NamedReference.field(fieldName(id))),toGravitino(direction),toGravitino(nullOrder));}@@ -99,11 +99,15 @@ public class FromIcebergSortOrder implements SortOrderVisitor<SortOrder> {String name, int width, int id, SortDirection direction, NullOrder nullOrder) {return SortOrders.of(FunctionExpression.of(- name, Literals.integerLiteral(width), NamedReference.field(idToName.get(id))),+ name, Literals.integerLiteral(width), NamedReference.field(fieldName(id))),toGravitino(direction),toGravitino(nullOrder));}+ private String[] fieldName(int id) {+ return ConvertUtil.splitIcebergNameToFieldPath(idToName.get(id));+ }+private org.apache.gravitino.rel.expressions.sorts.SortDirection toGravitino(SortDirection direction) {return direction == SortDirection.ASCdiff --git a/catalogs/catalog-lakehouse-iceberg/src/test/java/org/apache/gravitino/catalog/lakehouse/iceberg/converter/TestBaseConvert.java b/catalogs/catalog-lakehouse-iceberg/src/test/java/org/apache/gravitino/catalog/lakehouse/iceberg/converter/TestBaseConvert.javaindex 377e62856e..e813111a3c 100644--- a/catalogs/catalog-lakehouse-iceberg/src/test/java/org/apache/gravitino/catalog/lakehouse/iceberg/converter/TestBaseConvert.java+++ b/catalogs/catalog-lakehouse-iceberg/src/test/java/org/apache/gravitino/catalog/lakehouse/iceberg/converter/TestBaseConvert.java@@ -177,14 +177,16 @@ public class TestBaseConvert {if (sortOrderExpression instanceof NamedReference.FieldReference) {NamedReference.FieldReference fieldReference =(NamedReference.FieldReference) sortOrderExpression;- return String.format("identity(%s)", fieldReference.fieldName()[0]);+ return String.format("identity(%s)", String.join(".", fieldReference.fieldName()));} else if (sortOrderExpression instanceof FunctionExpression) {FunctionExpression functionExpression = (FunctionExpression) sortOrderExpression;String functionName = functionExpression.functionName();Expression[] arguments = functionExpression.arguments();if (arguments.length == 1) {return String.format(- "%s(%s)", functionName, ((NamedReference.FieldReference) arguments[0]).fieldName()[0]);+ "%s(%s)",+ functionName,+ String.join(".", ((NamedReference.FieldReference) arguments[0]).fieldName()));} else if (arguments.length == 2) {Expression firstArg = arguments[0];Preconditions.checkArgument(@@ -196,7 +198,7 @@ public class TestBaseConvert {"%s(%s, %s)",functionName,Integer.parseInt(String.valueOf(((Literal<?>) firstArg).value())),- ((NamedReference.FieldReference) arguments[1]).fieldName()[0]);+ String.join(".", ((NamedReference.FieldReference) arguments[1]).fieldName()));} else {throw new IllegalArgumentException(String.format(diff --git a/catalogs/catalog-lakehouse-iceberg/src/test/java/org/apache/gravitino/catalog/lakehouse/iceberg/converter/TestFromIcebergPartitionSpec.java b/catalogs/catalog-lakehouse-iceberg/src/test/java/org/apache/gravitino/catalog/lakehouse/iceberg/converter/TestFromIcebergPartitionSpec.javaindex a7abc08560..8fae4c6c61 100644--- a/catalogs/catalog-lakehouse-iceberg/src/test/java/org/apache/gravitino/catalog/lakehouse/iceberg/converter/TestFromIcebergPartitionSpec.java+++ b/catalogs/catalog-lakehouse-iceberg/src/test/java/org/apache/gravitino/catalog/lakehouse/iceberg/converter/TestFromIcebergPartitionSpec.java@@ -86,4 +86,61 @@ public class TestFromIcebergPartitionSpec extends TestBaseConvert {}}}++ @Test+ public void testNestedHyphenatedIdentityKeepsFieldComponents() {+ // Iceberg idToName is "event.user-id"; Gravitino must keep ["event", "user-id"], not one+ // dotted component.+ Schema schema =+ new Schema(+ Types.NestedField.required(+ 1,+ "event",+ Types.StructType.of(+ Types.NestedField.required(2, "user-id", Types.IntegerType.get()))));+ PartitionSpec partitionSpec =+ PartitionSpec.builderFor(schema).identity("event.user-id").build();++ Transform[] transforms = FromIcebergPartitionSpec.fromPartitionSpec(partitionSpec, schema);++ Assertions.assertEquals(1, transforms.length);+ Assertions.assertInstanceOf(Transforms.IdentityTransform.class, transforms[0]);+ Assertions.assertArrayEquals(+ new String[] {"event", "user-id"},+ ((Transforms.IdentityTransform) transforms[0]).fieldName());+ Assertions.assertEquals("event.user-id", schema.idToName().get(2));+ }++ @Test+ public void testNestedHyphenatedDayKeepsFieldComponents() {+ Schema schema =+ new Schema(+ Types.NestedField.required(+ 1,+ "event",+ Types.StructType.of(+ Types.NestedField.required(2, "event-ts", Types.TimestampType.withoutZone()))));+ PartitionSpec partitionSpec = PartitionSpec.builderFor(schema).day("event.event-ts").build();++ Transform[] transforms = FromIcebergPartitionSpec.fromPartitionSpec(partitionSpec, schema);++ Assertions.assertEquals(1, transforms.length);+ Assertions.assertInstanceOf(Transforms.DayTransform.class, transforms[0]);+ Assertions.assertArrayEquals(+ new String[] {"event", "event-ts"}, ((Transforms.DayTransform) transforms[0]).fieldName());+ }++ @Test+ public void testSplitIcebergNameToFieldPath() {+ Assertions.assertArrayEquals(+ new String[] {"col_1"}, ConvertUtil.splitIcebergNameToFieldPath("col_1"));+ Assertions.assertArrayEquals(+ new String[] {"event", "user-id"},+ ConvertUtil.splitIcebergNameToFieldPath("event.user-id"));+ Assertions.assertArrayEquals(+ new String[] {"event", "meta", "user-id"},+ ConvertUtil.splitIcebergNameToFieldPath("event.meta.user-id"));+ Assertions.assertThrows(+ IllegalArgumentException.class, () -> ConvertUtil.splitIcebergNameToFieldPath(""));+ }}diff --git a/catalogs/catalog-lakehouse-iceberg/src/test/java/org/apache/gravitino/catalog/lakehouse/iceberg/converter/TestFromIcebergSortOrder.java b/catalogs/catalog-lakehouse-iceberg/src/test/java/org/apache/gravitino/catalog/lakehouse/iceberg/converter/TestFromIcebergSortOrder.javaindex 39cb1c59c2..f4ad1a813b 100644--- a/catalogs/catalog-lakehouse-iceberg/src/test/java/org/apache/gravitino/catalog/lakehouse/iceberg/converter/TestFromIcebergSortOrder.java+++ b/catalogs/catalog-lakehouse-iceberg/src/test/java/org/apache/gravitino/catalog/lakehouse/iceberg/converter/TestFromIcebergSortOrder.java@@ -84,15 +84,18 @@ public class TestFromIcebergSortOrder extends TestBaseConvert {Collectors.toMap(sortOrder -> {if (sortOrder.expression() instanceof NamedReference.FieldReference) {- return ((NamedReference.FieldReference) sortOrder.expression())- .fieldName()[0];+ return String.join(+ ".",+ ((NamedReference.FieldReference) sortOrder.expression()).fieldName());} else if (sortOrder.expression() instanceof FunctionExpression) {Expression[] arguments =((FunctionExpression) sortOrder.expression()).arguments();if (arguments.length == 1) {- return ((NamedReference.FieldReference) arguments[0]).fieldName()[0];+ return String.join(+ ".", ((NamedReference.FieldReference) arguments[0]).fieldName());} else {- return ((NamedReference.FieldReference) arguments[1]).fieldName()[0];+ return String.join(+ ".", ((NamedReference.FieldReference) arguments[1]).fieldName());}}throw new RuntimeException("Unsupported sort expression type");@@ -121,4 +124,27 @@ public class TestFromIcebergSortOrder extends TestBaseConvert {Assertions.assertEquals(icebergSortOrderString, gravitinoSortOrderString);}}++ @Test+ public void testNestedHyphenatedFieldSortKeepsFieldComponents() {+ Schema schema =+ new Schema(+ Types.NestedField.required(+ 1,+ "event",+ Types.StructType.of(+ Types.NestedField.required(2, "user-id", Types.IntegerType.get()))));+ org.apache.iceberg.SortOrder icebergSortOrder =+ org.apache.iceberg.SortOrder.builderFor(schema)+ .sortBy("event.user-id", org.apache.iceberg.SortDirection.ASC, NullOrder.NULLS_LAST)+ .build();++ SortOrder[] sortOrders = FromIcebergSortOrder.fromSortOrder(icebergSortOrder);++ Assertions.assertEquals(1, sortOrders.length);+ Assertions.assertInstanceOf(NamedReference.FieldReference.class, sortOrders[0].expression());+ Assertions.assertArrayEquals(+ new String[] {"event", "user-id"},+ ((NamedReference.FieldReference) sortOrders[0].expression()).fieldName());+ }}diff --git a/docs/table-maintenance-service/optimizer-troubleshooting.md b/docs/table-maintenance-service/optimizer-troubleshooting.mdindex 5581f1d4bb..7e52275aa0 100644--- a/docs/table-maintenance-service/optimizer-troubleshooting.md+++ b/docs/table-maintenance-service/optimizer-troubleshooting.md@@ -120,12 +120,28 @@ layouts. A **direct** `builtin-iceberg-rewrite-data-files` submit with an emptyrewrites the whole table and succeeds on `PARTITIONED BY (p, days(ts))` (and similar). You maystill see `Rewritten data files: 0` when files are not rewrite-eligible (`min-input-files`).-The failure mode-`Cannot translate Spark expression ... day(...) ... to data source filter` still happens when-the submit uses a **partition `where_clause` that applies time/bucket transforms** — the form-the compaction adapter builds via `PartitionUtils` (for example `p = "a" AND day(ts) = 19723`).-That is a strategy-generated filter path, not a limitation of empty-`where_clause` direct-submits. Confirm in job run status and `error.log` under `builtin-iceberg-rewrite-data-files`.+Strategy-generated partition filters use Iceberg Spark system functions (for example+`catalog.system.days(ts) = DATE '2024-01-01'`, `catalog.system.years(ts) = 54`,+`catalog.system.bucket(16, id) = 3`), not Spark builtins such+as `day()`. The `days()` UDF returns `DATE`, so the strategy emits a date literal (not the raw+epoch-day int). Identity `DATE`/`TIMESTAMP`/`TIME` partitions use the same single-quoted typed+literals (`dt = DATE '2024-01-01'`): the job embeds them in `CALL ... where => '...'` via Spark+`\'` escaping. With Iceberg Spark runtime 1.4+ these forms are translated by `SparkV2Filters`.+If `Cannot translate Spark expression ...` still appears, confirm the job classpath uses a+matching Iceberg Spark runtime and that the predicate resolved as an Iceberg function (not Spark+`day()`/`year()`). Empty-`where_clause` direct submits remain the whole-table fallback. Confirm+in job run status and `error.log` under `builtin-iceberg-rewrite-data-files`.++**`Day partition value must be an ISO date`** — day-transform stats must be ISO `yyyy-MM-dd`.+Epoch-day (`19723`) and compact (`20260101`) fail while building `where_clause` (no migration or+guessing). `update-stats` alone is not enough if an imported non-ISO row remains: it adds an+ISO-keyed row but leaves the old one selectable, so the next recommendation can still abort. List+partition statistics, drop the non-ISO partition's statistic names+([Drop partition statistics](../manage-statistics-in-gravitino.md#drop-partition-statistics)),+re-run `update-stats`, then resubmit.++**`spark.sql.parser.escapedStringLiterals must be false`** — built-in Iceberg jobs require+Spark's default. Remove the key from `spark_conf` or set it to `false`.## Relateddiff --git a/docs/table-maintenance-service/optimizer.md b/docs/table-maintenance-service/optimizer.mdindex 73bc061dc8..c9fc7f53a3 100644--- a/docs/table-maintenance-service/optimizer.md+++ b/docs/table-maintenance-service/optimizer.md@@ -25,11 +25,16 @@ Confirm your environment matches this list before starting an evaluation againstrewrite data files (compaction), rewrite manifests, expire snapshots, and remove orphan files.Scheduling and `minIntervalMs` stay outside strategy evaluation. Sort and cluster maintenancestill need custom strategies.-- Compaction's **policy/strategy** path prefers identity partitions (time/bucket filters can fail- Spark translation). Direct `builtin-iceberg-rewrite-data-files` with an empty `where_clause`- covers broader layouts such as `PARTITIONED BY (p, days(ts))`; see- [Troubleshooting](./optimizer-troubleshooting.md#job-execution-failures). The other three jobs- are not limited by that partition caveat.+- Compaction's **policy/strategy** path generates Iceberg Spark system-function predicates (for+ example `catalog.system.days(ts) = DATE 'yyyy-MM-dd'`,+ `catalog.system.years|months|hours(ts) = N`, `catalog.system.bucket(16, id) = V`) for+ non-identity partitions, and single-quoted typed literals for identity `DATE`/`TIMESTAMP`+ columns (`dt = DATE 'yyyy-MM-dd'`). Day-transform partition values must be ISO `yyyy-MM-dd`+ (as built-in `update-stats` stores); non-ISO values fail while building `where_clause`—see+ [Troubleshooting](./optimizer-troubleshooting.md#job-execution-failures) for recovery when an+ imported epoch-day row remains after refresh. Direct+ `builtin-iceberg-rewrite-data-files` with an empty `where_clause` still covers whole-table+ rewrite on broader layouts.- The in-process service, `timeTrigger`, and the cron path are documented in [Service](./service.md). The rest of this page is the manual CLI workflow.## How It Worksdiff --git a/maintenance/jobs/src/main/java/org/apache/gravitino/maintenance/jobs/iceberg/IcebergJobUtils.java b/maintenance/jobs/src/main/java/org/apache/gravitino/maintenance/jobs/iceberg/IcebergJobUtils.javaindex b132d3d7b4..590e068706 100644--- a/maintenance/jobs/src/main/java/org/apache/gravitino/maintenance/jobs/iceberg/IcebergJobUtils.java+++ b/maintenance/jobs/src/main/java/org/apache/gravitino/maintenance/jobs/iceberg/IcebergJobUtils.java@@ -176,10 +176,16 @@ public final class IcebergJobUtils {}/**- * Escape single quotes in SQL string literals by replacing ' with ''.+ * Escape single quotes in SQL string literals by replacing {@code '} with {@code ''}.+ *+ * <p>Suitable for expression-level literals such as {@code map('k','v')} entries. <b>Do not use+ * for Spark {@code CALL} named-arg strings</b> ({@code table => '...'}, {@code where => '...'},+ * …): with default {@code spark.sql.parser.escapedStringLiterals=false}, Spark treats {@code ''}+ * there as empty and drops the apostrophe. Use {@link #escapeSparkCallStringArg(String)} for+ * those CALL arguments.** @param value the string value to escape- * @return escaped string safe for use in SQL string literals+ * @return escaped string using SQL-standard quote doubling*/public static String escapeSqlString(String value) {if (value == null) {@@ -188,6 +194,26 @@ public final class IcebergJobUtils {return value.replace("'", "''");}+ /**+ * Escapes a value for a Spark {@code CALL} named-arg single-quoted string (e.g. {@code table =>+ * '...'}, {@code where => '...'}).+ *+ * <p>With the default {@code spark.sql.parser.escapedStringLiterals=false}, Spark still consumes+ * backslash escapes inside the outer single-quoted argument ({@code \\}, {@code \"}, {@code \'}),+ * but treats SQL-standard {@code ''} as empty and drops the apostrophe ({@code O''Brien} → {@code+ * OBrien}). Double every backslash first so one outer parse leaves inner escapes (from a+ * single-quoted predicate literal) intact, then encode {@code '} as {@code \'}.+ *+ * @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 value.replace("\\", "\\\\").replace("'", "\\'");+ }+/*** Escape and quote a SQL identifier with backticks.*@@ -358,16 +384,34 @@ public final class IcebergJobUtils {requireClass(ICEBERG_SPARK_CATALOG, "Iceberg Spark catalog");}+ /**+ * Requires {@code spark.sql.parser.escapedStringLiterals=false} (Spark's default).+ *+ * <p>Built-in CALL builders that use {@link #escapeSparkCallStringArg(String)} ({@code '} →+ * {@code \'}), and orphan-file literals rendered via Spark {@code lit().expr().sql()}, depend on+ * backslash escapes. With {@code escapedStringLiterals=true}, those encodings are not reliable.+ *+ * @param spark active Spark session+ * @throws IllegalArgumentException when the setting is enabled+ */+ public static void requireEscapedStringLiteralsDisabled(SparkSession spark) {+ Preconditions.checkNotNull(spark, "spark");+ Preconditions.checkArgument(+ !Boolean.parseBoolean(spark.conf().get("spark.sql.parser.escapedStringLiterals", "false")),+ "spark.sql.parser.escapedStringLiterals must be false");+ }+/*** Checks the Iceberg Spark runtime after the session is created, then stops Spark and exits the- * process on failure.+ * process on failure. Also requires {@link #requireEscapedStringLiteralsDisabled(SparkSession)}.** @param spark Spark session created for this job; stopped if the runtime check fails*/public static void requireIcebergSparkRuntimeOrExit(SparkSession spark) {try {requireIcebergSparkRuntime();- } catch (IllegalStateException e) {+ requireEscapedStringLiteralsDisabled(spark);+ } catch (IllegalStateException | IllegalArgumentException e) {System.err.println("Error: " + e.getMessage());spark.stop();System.exit(1);diff --git a/maintenance/jobs/src/main/java/org/apache/gravitino/maintenance/jobs/iceberg/IcebergMaintenanceJob.java b/maintenance/jobs/src/main/java/org/apache/gravitino/maintenance/jobs/iceberg/IcebergMaintenanceJob.javaindex 5b31d4d997..17dcb4a6d6 100644--- a/maintenance/jobs/src/main/java/org/apache/gravitino/maintenance/jobs/iceberg/IcebergMaintenanceJob.java+++ b/maintenance/jobs/src/main/java/org/apache/gravitino/maintenance/jobs/iceberg/IcebergMaintenanceJob.java@@ -205,7 +205,8 @@ public class IcebergMaintenanceJob implements BuiltInJob {if (sparkConfJson != null && !sparkConfJson.isEmpty()) {Map<String, String> sparkConfigs =new HashMap<>(IcebergJobUtils.parseCustomSparkConfigs(sparkConfJson));- ensureIcebergCatalogImpl(sparkConfigs);+ // Session defaultCatalog follows the first target table's catalog (single-catalog TMS path).+ IcebergSparkConfigUtils.ensureIcebergCatalogConfigs(sparkConfigs, tables.get(0).catalogName);sparkConfigs.forEach(sparkBuilder::config);}@@ -498,36 +499,6 @@ public class IcebergMaintenanceJob implements BuiltInJob {}}- /**- * Ensures {@code spark.sql.catalog.<name>} points at Iceberg {@code SparkCatalog} whenever nested- * catalog connection keys are present. Needed because TMS schedule {@code spark_conf} may only- * carry {@code .type}/{@code .uri}/{@code .warehouse}.- */- private static void ensureIcebergCatalogImpl(Map<String, String> sparkConfigs) {- String prefix = "spark.sql.catalog.";- Set<String> catalogs = new HashSet<>();- for (String key : sparkConfigs.keySet()) {- if (!key.startsWith(prefix)) {- continue;- }- String rest = key.substring(prefix.length());- int dot = rest.indexOf('.');- if (dot <= 0) {- continue;- }- String prop = rest.substring(dot + 1);- if ("type".equals(prop) || "uri".equals(prop) || "warehouse".equals(prop)) {- catalogs.add(rest.substring(0, dot));- }- }- for (String catalog : catalogs) {- sparkConfigs.putIfAbsent(prefix + catalog, "org.apache.iceberg.spark.SparkCatalog");- sparkConfigs.putIfAbsent("spark.sql.defaultCatalog", catalog);- }- sparkConfigs.putIfAbsent(- "spark.sql.extensions", IcebergSparkConfigUtils.ICEBERG_SPARK_EXTENSIONS);- }-private static List<String> templateArguments() {return Arrays.asList("--maintenance-types",diff --git a/maintenance/jobs/src/main/java/org/apache/gravitino/maintenance/jobs/iceberg/IcebergRemoveOrphanFilesJob.java b/maintenance/jobs/src/main/java/org/apache/gravitino/maintenance/jobs/iceberg/IcebergRemoveOrphanFilesJob.javaindex d2f2451313..282991d215 100644--- a/maintenance/jobs/src/main/java/org/apache/gravitino/maintenance/jobs/iceberg/IcebergRemoveOrphanFilesJob.java+++ b/maintenance/jobs/src/main/java/org/apache/gravitino/maintenance/jobs/iceberg/IcebergRemoveOrphanFilesJob.java@@ -175,7 +175,7 @@ public class IcebergRemoveOrphanFilesJob implements BuiltInJob, IcebergMaintenan@Nullable String location,boolean dryRun)throws IOException {- requireEscapedStringLiteralsDisabled(spark);+ IcebergJobUtils.requireEscapedStringLiteralsDisabled(spark);String normalizedLocation =resolveAndValidateLocation(spark, catalogName, tableIdentifier, location);return callRemoveOrphanFiles(@@ -194,7 +194,7 @@ public class IcebergRemoveOrphanFilesJob implements BuiltInJob, IcebergMaintenan@Nullable String location,boolean dryRun)throws IOException {- requireEscapedStringLiteralsDisabled(spark);+ IcebergJobUtils.requireEscapedStringLiteralsDisabled(spark);Table table = IcebergJobUtils.loadIcebergTable(spark, catalogName, tableIdentifier);String normalizedLocation = resolveAndValidateLocation(spark, table, location);List<Row> listed =@@ -318,13 +318,6 @@ public class IcebergRemoveOrphanFilesJob implements BuiltInJob, IcebergMaintenan}}- private static void requireEscapedStringLiteralsDisabled(SparkSession spark) {- // Backslash escapes in string literals must retain Spark's default interpretation.- Preconditions.checkArgument(- !Boolean.parseBoolean(spark.conf().get("spark.sql.parser.escapedStringLiterals", "false")),- "spark.sql.parser.escapedStringLiterals must be false");- }-private static String resolveAndValidateLocation(SparkSession spark, String catalogName, String tableIdentifier, @Nullable String location)throws IOException {diff --git a/maintenance/jobs/src/main/java/org/apache/gravitino/maintenance/jobs/iceberg/IcebergRewriteDataFilesJob.java b/maintenance/jobs/src/main/java/org/apache/gravitino/maintenance/jobs/iceberg/IcebergRewriteDataFilesJob.javaindex e90ad35869..d4018aa822 100644--- a/maintenance/jobs/src/main/java/org/apache/gravitino/maintenance/jobs/iceberg/IcebergRewriteDataFilesJob.java+++ b/maintenance/jobs/src/main/java/org/apache/gravitino/maintenance/jobs/iceberg/IcebergRewriteDataFilesJob.java@@ -153,10 +153,11 @@ public class IcebergRewriteDataFilesJob implements BuiltInJob, IcebergMaintenanc// Apply custom Spark configurations if providedif (sparkConfJson != null && !sparkConfJson.isEmpty()) {try {- Map<String, String> customConfigs = IcebergJobUtils.parseCustomSparkConfigs(sparkConfJson);- for (Map.Entry<String, String> entry : customConfigs.entrySet()) {- sparkBuilder.config(entry.getKey(), entry.getValue());- }+ Map<String, String> customConfigs =+ new HashMap<>(IcebergJobUtils.parseCustomSparkConfigs(sparkConfJson));+ // Stock spark_conf may omit defaultCatalog; bare years()/months() need the Iceberg catalog.+ IcebergSparkConfigUtils.ensureIcebergCatalogConfigs(customConfigs, catalogName);+ customConfigs.forEach(sparkBuilder::config);} catch (IllegalArgumentException e) {System.err.println("Error: " + e.getMessage());printUsage();@@ -230,20 +231,26 @@ public class IcebergRewriteDataFilesJob implements BuiltInJob, IcebergMaintenancsql.append("CALL ").append(IcebergJobUtils.escapeSqlIdentifier(catalogName)).append(".system.rewrite_data_files(");- sql.append("table => '").append(IcebergJobUtils.escapeSqlString(tableIdentifier)).append("'");+ sql.append("table => '")+ .append(IcebergJobUtils.escapeSparkCallStringArg(tableIdentifier))+ .append("'");if (strategy != null && !strategy.isEmpty()) {- sql.append(", strategy => '").append(IcebergJobUtils.escapeSqlString(strategy)).append("'");+ sql.append(", strategy => '")+ .append(IcebergJobUtils.escapeSparkCallStringArg(strategy))+ .append("'");}if (sortOrder != null && !sortOrder.isEmpty()) {sql.append(", sort_order => '")- .append(IcebergJobUtils.escapeSqlString(sortOrder))+ .append(IcebergJobUtils.escapeSparkCallStringArg(sortOrder)).append("'");}if (whereClause != null && !whereClause.isEmpty()) {- sql.append(", where => '").append(IcebergJobUtils.escapeSqlString(whereClause)).append("'");+ sql.append(", where => '")+ .append(IcebergJobUtils.escapeSparkCallStringArg(whereClause))+ .append("'");}if (optionsJson != null && !optionsJson.isEmpty()) {@@ -256,6 +263,7 @@ public class IcebergRewriteDataFilesJob implements BuiltInJob, IcebergMaintenancif (!first) {sql.append(", ");}+ // map('k','v') are expression literals (not CALL arg => '...'); SQL '' escaping is fine.sql.append("'").append(IcebergJobUtils.escapeSqlString(entry.getKey())).append("', '")diff --git a/maintenance/jobs/src/main/java/org/apache/gravitino/maintenance/jobs/iceberg/IcebergUpdateStatsAndMetricsJob.java b/maintenance/jobs/src/main/java/org/apache/gravitino/maintenance/jobs/iceberg/IcebergUpdateStatsAndMetricsJob.javaindex 60238506c7..f266acde11 100644--- a/maintenance/jobs/src/main/java/org/apache/gravitino/maintenance/jobs/iceberg/IcebergUpdateStatsAndMetricsJob.java+++ b/maintenance/jobs/src/main/java/org/apache/gravitino/maintenance/jobs/iceberg/IcebergUpdateStatsAndMetricsJob.java@@ -370,6 +370,8 @@ public class IcebergUpdateStatsAndMetricsJob implements BuiltInJob {throw new IllegalArgumentException(String.format(Locale.ROOT, "Partition value for column '%s' is null", name));}+ // Spark/Iceberg partition fields keep transform-native values (years/months/hours as+ // Iceberg ints, days as DateType → ISO via String.valueOf). Do not reinterpret here.entries.add(new PartitionEntryImpl(name, String.valueOf(value)));}return PartitionPath.of(entries);diff --git a/maintenance/jobs/src/test/java/org/apache/gravitino/maintenance/jobs/iceberg/TestIcebergExpireSnapshotsJob.java b/maintenance/jobs/src/test/java/org/apache/gravitino/maintenance/jobs/iceberg/TestIcebergExpireSnapshotsJob.javaindex 5c16c98cf3..2f2bf30131 100644--- a/maintenance/jobs/src/test/java/org/apache/gravitino/maintenance/jobs/iceberg/TestIcebergExpireSnapshotsJob.java+++ b/maintenance/jobs/src/test/java/org/apache/gravitino/maintenance/jobs/iceberg/TestIcebergExpireSnapshotsJob.java@@ -116,6 +116,7 @@ public class TestIcebergExpireSnapshotsJob {assertTrue(configs.containsKey("spark.sql.catalog.{{catalog_name}}.type"));assertTrue(configs.containsKey("spark.sql.catalog.{{catalog_name}}.uri"));assertTrue(configs.containsKey("spark.sql.catalog.{{catalog_name}}.warehouse"));+ assertEquals("{{catalog_name}}", configs.get("spark.sql.defaultCatalog"));// Verify Iceberg extensionsassertTrue(configs.containsKey("spark.sql.extensions"));@@ -326,6 +327,19 @@ public class TestIcebergExpireSnapshotsJob {assertEquals("", IcebergJobUtils.escapeSqlString(""));}+ @Test+ public void testEscapeSparkCallStringArg() {+ // Doubles backslashes first, then encodes ' as \' (Spark CALL where => '...').+ assertEquals(+ "region = \\'a\"b\\\\\\\\c\\'",+ IcebergJobUtils.escapeSparkCallStringArg("region = 'a\"b\\\\c'"));+ assertEquals(+ "(region = \\'O\\\\\\'Brien\\')",+ IcebergJobUtils.escapeSparkCallStringArg("(region = 'O\\'Brien')"));+ assertEquals(null, IcebergJobUtils.escapeSparkCallStringArg(null));+ assertEquals("", IcebergJobUtils.escapeSparkCallStringArg(""));+ }+@Testpublic void testEscapeSqlIdentifier() {// Test basic escaping and quoting of backticksdiff --git a/maintenance/jobs/src/test/java/org/apache/gravitino/maintenance/jobs/iceberg/TestIcebergRewriteDataFilesJob.java b/maintenance/jobs/src/test/java/org/apache/gravitino/maintenance/jobs/iceberg/TestIcebergRewriteDataFilesJob.javaindex fab1e8dbdb..2d540b492f 100644--- a/maintenance/jobs/src/test/java/org/apache/gravitino/maintenance/jobs/iceberg/TestIcebergRewriteDataFilesJob.java+++ b/maintenance/jobs/src/test/java/org/apache/gravitino/maintenance/jobs/iceberg/TestIcebergRewriteDataFilesJob.java@@ -118,6 +118,7 @@ public class TestIcebergRewriteDataFilesJob {assertTrue(configs.containsKey("spark.sql.catalog.{{catalog_name}}.type"));assertTrue(configs.containsKey("spark.sql.catalog.{{catalog_name}}.uri"));assertTrue(configs.containsKey("spark.sql.catalog.{{catalog_name}}.warehouse"));+ assertEquals("{{catalog_name}}", configs.get("spark.sql.defaultCatalog"));// Verify Iceberg extensionsassertTrue(configs.containsKey("spark.sql.extensions"));@@ -411,10 +412,10 @@ public class TestIcebergRewriteDataFilesJob {IcebergRewriteDataFilesJob.buildProcedureCall("iceberg_prod", "db.sample", null, null, whereClause, null);- // Single quotes in the WHERE clause should be escaped+ // WHERE uses Spark CALL escaping (' → \'), not SQL-standard ''.assertTrue(sql.contains(- "where => 'year = 2024 AND month >= 1 AND month <= 12 AND status = ''active'''"));+ "where => 'year = 2024 AND month >= 1 AND month <= 12 AND status = \\'active\\''"));}@Test@@ -438,8 +439,8 @@ public class TestIcebergRewriteDataFilesJob {IcebergRewriteDataFilesJob.buildProcedureCall("iceberg_catalog", maliciousTable, null, null, null, null);- // Verify single quotes are escaped (becomes '')- assertTrue(sql.contains("db.table'' OR ''1''=''1"));+ // CALL table => '...' uses Spark escaping (' → \')+ assertTrue(sql.contains("db.table\\' OR \\'1\\'=\\'1"));assertFalse(sql.contains("' OR '1'='1"));// Test SQL injection attempt in where clause@@ -448,7 +449,7 @@ public class TestIcebergRewriteDataFilesJob {IcebergRewriteDataFilesJob.buildProcedureCall("iceberg_catalog", "db.table", null, null, maliciousWhere, null);- assertTrue(sql.contains("year = 2024'' OR ''1''=''1"));+ assertTrue(sql.contains("year = 2024\\' OR \\'1\\'=\\'1"));// Test SQL injection attempt in catalog nameString maliciousCatalog = "catalog`; DROP TABLE users; --";@@ -468,11 +469,12 @@ public class TestIcebergRewriteDataFilesJob {// Catalog name should be quoted as an identifierassertTrue(sql.contains("`cat'alog`"));- // All single quotes in string literals should be escaped- assertTrue(sql.contains("db''.table"));- assertTrue(sql.contains("sort''"));- assertTrue(sql.contains("id'' DESC"));- assertTrue(sql.contains("year'' = 2024"));+ // CALL named-arg strings (table/strategy/sort_order/where) use Spark escaping (' → \')+ assertTrue(sql.contains("db\\'.table"));+ assertTrue(sql.contains("sort\\'"));+ assertTrue(sql.contains("id\\' DESC"));+ assertTrue(sql.contains("year\\' = 2024"));+ // options map('k','v') still uses SQL-standard ''assertTrue(sql.contains("key''"));assertTrue(sql.contains("val''ue"));}diff --git a/maintenance/jobs/src/test/java/org/apache/gravitino/maintenance/jobs/iceberg/TestIcebergRewriteDataFilesJobWithSpark.java b/maintenance/jobs/src/test/java/org/apache/gravitino/maintenance/jobs/iceberg/TestIcebergRewriteDataFilesJobWithSpark.javaindex a0181c2bad..a82df5045b 100644--- a/maintenance/jobs/src/test/java/org/apache/gravitino/maintenance/jobs/iceberg/TestIcebergRewriteDataFilesJobWithSpark.java+++ b/maintenance/jobs/src/test/java/org/apache/gravitino/maintenance/jobs/iceberg/TestIcebergRewriteDataFilesJobWithSpark.java@@ -18,15 +18,36 @@*/package org.apache.gravitino.maintenance.jobs.iceberg;+import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;import static org.junit.jupiter.api.Assertions.assertEquals;import static org.junit.jupiter.api.Assertions.assertFalse;import static org.junit.jupiter.api.Assertions.assertNotNull;+import static org.junit.jupiter.api.Assertions.assertThrows;import static org.junit.jupiter.api.Assertions.assertTrue;import java.io.File;+import java.util.ArrayList;+import java.util.Arrays;+import java.util.Collections;+import java.util.LinkedHashSet;+import java.util.List;+import java.util.Set;+import java.util.stream.Collectors;+import org.apache.gravitino.dto.rel.ColumnDTO;+import org.apache.gravitino.maintenance.optimizer.api.common.PartitionPath;+import org.apache.gravitino.maintenance.optimizer.common.PartitionEntryImpl;+import org.apache.gravitino.maintenance.optimizer.recommender.job.PartitionUtils;+import org.apache.gravitino.rel.Column;+import org.apache.gravitino.rel.expressions.transforms.Transform;+import org.apache.gravitino.rel.expressions.transforms.Transforms;+import org.apache.gravitino.rel.types.Types;import org.apache.spark.sql.Dataset;import org.apache.spark.sql.Row;+import org.apache.spark.sql.RowFactory;+import org.apache.spark.sql.SaveMode;import org.apache.spark.sql.SparkSession;+import org.apache.spark.sql.types.DataTypes;+import org.apache.spark.sql.types.StructType;import org.junit.jupiter.api.AfterAll;import org.junit.jupiter.api.BeforeAll;import org.junit.jupiter.api.Test;@@ -79,7 +100,8 @@ public class TestIcebergRewriteDataFilesJobWithSpark {public static void tearDown() {if (spark != null) {spark.sql("DROP TABLE IF EXISTS " + catalogName + ".db.test_table");- spark.sql("DROP NAMESPACE IF EXISTS " + catalogName + ".db");+ spark.sql("DROP TABLE IF EXISTS " + catalogName + ".db.pu_sq");+ spark.sql("DROP NAMESPACE IF EXISTS " + catalogName + ".db CASCADE");spark.stop();}}@@ -95,6 +117,21 @@ public class TestIcebergRewriteDataFilesJobWithSpark {assertTrue(sql.contains("table => 'db.test_table'"));}+ @Test+ public void testRequireEscapedStringLiteralsDisabled() {+ assertDoesNotThrow(() -> IcebergJobUtils.requireEscapedStringLiteralsDisabled(spark));+ spark.conf().set("spark.sql.parser.escapedStringLiterals", "true");+ try {+ IllegalArgumentException ex =+ assertThrows(+ IllegalArgumentException.class,+ () -> IcebergJobUtils.requireEscapedStringLiteralsDisabled(spark));+ assertTrue(ex.getMessage().contains("escapedStringLiterals"));+ } finally {+ spark.conf().set("spark.sql.parser.escapedStringLiterals", "false");+ }+ }+@Testpublic void testExecuteRewriteDataFilesMinimal() {String sql =@@ -244,8 +281,8 @@ public class TestIcebergRewriteDataFilesJobWithSpark {IcebergRewriteDataFilesJob.buildProcedureCall(catalogName, maliciousTable, null, null, null, null);- // Verify the SQL is escaped (single quotes become double quotes)- assertTrue(sql.contains("db_test.special_table'' OR ''1''=''1"));+ // CALL table => '...' uses Spark escaping (' → \')+ assertTrue(sql.contains("db_test.special_table\\' OR \\'1\\'=\\'1"));// The SQL should fail with table not found (not execute malicious code)// because the escaped table name doesn't exist@@ -275,8 +312,8 @@ public class TestIcebergRewriteDataFilesJobWithSpark {IcebergRewriteDataFilesJob.buildProcedureCall(catalogName, "db.test_table", null, null, maliciousWhere, null);- // Verify escaping occurred- assertTrue(sql.contains("id > 0'' OR ''1''=''1"));+ // WHERE uses Spark CALL escaping (' → \')+ assertTrue(sql.contains("id > 0\\' OR \\'1\\'=\\'1"));// The SQL should fail because the WHERE clause is invalid (not execute malicious code)try {@@ -308,14 +345,13 @@ public class TestIcebergRewriteDataFilesJobWithSpark {+ ".db_special.data_table VALUES (1, 'test'), (2, 'O''Brien'), (3, 'It''s working')");try {- // Use a WHERE clause with single quotes in legitimate string comparison- String whereClause = "description = 'O''Brien'";+ // Match PartitionUtils inner literal form (' → \'), then CALL outer escape.+ String whereClause = "`description` = 'O\\'Brien'";String sql =IcebergRewriteDataFilesJob.buildProcedureCall(catalogName, "db_special.data_table", null, null, whereClause, null);- // Verify double quotes are further escaped (becomes 4 single quotes)- assertTrue(sql.contains("description = ''O''''Brien''"));+ assertTrue(sql.contains("`description` = \\'O\\\\\\'Brien\\'"), sql);// Execute - this should work or fail gracefully without injectiontry {@@ -432,4 +468,502 @@ public class TestIcebergRewriteDataFilesJobWithSpark {sql.contains("'description', 'Rewrite with \"quoted\" text'")|| sql.contains("description"));}++ /**+ * End-to-end: {@code O'Brien} must not collapse to {@code OBrien} through CALL escaping.+ *+ * <p>Inserts both partition values via the DataFrame API (value-preserving), makes both rewrite+ * eligible, rewrites only {@code O'Brien}, and asserts only that partition's data files change.+ */+ @Test+ public void testPartitionUtilsWhereWithSingleQuoteSelectsOnlyRequestedPartition() {+ String table = catalogName + ".db.pu_sq";+ String apostrophe = "O'Brien";+ String plain = "OBrien";+ try {+ spark.sql("DROP TABLE IF EXISTS " + table);+ spark.sql(+ "CREATE TABLE "+ + table+ + " (id INT, region STRING) USING iceberg PARTITIONED BY (region)");+ spark.sql(+ "ALTER TABLE " + table + " SET TBLPROPERTIES ('write.target-file-size-bytes'='1024')");++ // Value-preserving inserts: do not round-trip partition values through SQL string literals.+ StructType schema =+ new StructType()+ .add("id", DataTypes.IntegerType, false)+ .add("region", DataTypes.StringType, false);+ List<Row> rows = new ArrayList<>();+ for (int commit = 0; commit < 3; commit++) {+ rows.clear();+ for (int i = 0; i < 30; i++) {+ rows.add(RowFactory.create(commit * 100 + i, apostrophe));+ rows.add(RowFactory.create(1000 + commit * 100 + i, plain));+ }+ spark+ .createDataFrame(rows, schema)+ .write()+ .format("iceberg")+ .mode(SaveMode.Append)+ .saveAsTable(table);+ }++ List<String> regions =+ spark.table(table).select("region").distinct().collectAsList().stream()+ .map(r -> r.getString(0))+ .sorted()+ .collect(Collectors.toList());+ assertEquals(Arrays.asList(apostrophe, plain), regions);++ Set<String> beforeApostrophe = dataFilePathsForRegion(table, apostrophe);+ Set<String> beforePlain = dataFilePathsForRegion(table, plain);+ assertTrue(beforeApostrophe.size() >= 2, "O'Brien should have multiple data files");+ assertTrue(beforePlain.size() >= 2, "OBrien should have multiple data files");++ String where =+ PartitionUtils.getWhereClauseForPartitions(+ Collections.singletonList(+ PartitionPath.of(List.of(new PartitionEntryImpl("region", apostrophe)))),+ new Column[] {column("region", Types.StringType.get())},+ new Transform[] {Transforms.identity("region")},+ catalogName);+ assertEquals("(`region` = 'O\\'Brien')", where);++ String sql =+ IcebergRewriteDataFilesJob.buildProcedureCall(+ catalogName,+ "db.pu_sq",+ "binpack",+ null,+ where,+ "{\"rewrite-all\":\"true\",\"min-input-files\":\"1\"}");+ // Outer CALL uses \'; inner apostrophe is \\' after escapeSparkCallStringArg.+ assertTrue(sql.contains("where => '(`region` = \\'O\\\\\\'Brien\\')'"), sql);+ spark.sql(sql).collect();+ spark.sql("REFRESH TABLE " + table);++ Set<String> afterApostrophe = dataFilePathsForRegion(table, apostrophe);+ Set<String> afterPlain = dataFilePathsForRegion(table, plain);+ assertFalse(+ beforeApostrophe.equals(afterApostrophe),+ "Requested O'Brien partition files should change");+ assertEquals(+ beforePlain, afterPlain, "Unrequested OBrien partition files must stay unchanged");+ } finally {+ spark.sql("DROP TABLE IF EXISTS " + table);+ }+ }++ private static Set<String> dataFilePathsForRegion(String table, String region) {+ return spark+ .table(table + ".files")+ .where("`content` = 0")+ .select("file_path", "partition.region")+ .collectAsList()+ .stream()+ .filter(r -> region.equals(r.getString(1)))+ .map(r -> r.getString(0))+ .collect(Collectors.toCollection(LinkedHashSet::new));+ }++ /**+ * End-to-end: single-quoted string/DATE literals survive CALL embedding under all four ANSI+ * combinations of {@code spark.sql.ansi.enabled} × {@code+ * spark.sql.ansi.doubleQuotedIdentifiers}.+ */+ @Test+ public void testPartitionUtilsWhereAnsiLiteralModesThroughJobEscapeAndSpark() {+ String partitionValue = "a\"b\\c";+ // PartitionUtils: one-level \\ / \' ; job builder re-escapes for CALL where => '...'.+ String expectedWhere = "(`region` = 'a\"b\\\\c')";+ String expectedCallWhere = "(`region` = \\'a\"b\\\\\\\\c\\')";+ boolean[][] modes =+ new boolean[][] {+ {false, false},+ {true, false},+ {false, true},+ {true, true},+ };+ for (boolean[] mode : modes) {+ boolean ansiEnabled = mode[0];+ boolean doubleQuotedIds = mode[1];+ withAnsiModes(+ ansiEnabled,+ doubleQuotedIds,+ () -> {+ String tableSuffix =+ "pu_ansi_" + (ansiEnabled ? "e1" : "e0") + "_" + (doubleQuotedIds ? "d1" : "d0");+ String table = catalogName + ".db." + tableSuffix;+ spark.sql("DROP TABLE IF EXISTS " + table);+ spark.sql(+ "CREATE TABLE "+ + table+ + " (id INT, region STRING, ts TIMESTAMP) USING iceberg "+ + "PARTITIONED BY (region, days(ts))");+ List<Row> rows = new ArrayList<>();+ for (int i = 0; i < 20; i++) {+ rows.add(+ RowFactory.create(+ i, partitionValue, java.sql.Timestamp.valueOf("2024-01-01 00:00:00")));+ }+ StructType schema =+ new StructType()+ .add("id", DataTypes.IntegerType, false)+ .add("region", DataTypes.StringType, false)+ .add("ts", DataTypes.TimestampType, false);+ spark+ .createDataFrame(rows, schema)+ .write()+ .format("iceberg")+ .mode(SaveMode.Append)+ .saveAsTable(table);++ String stringWhere =+ PartitionUtils.getWhereClauseForPartitions(+ Collections.singletonList(+ PartitionPath.of(+ List.of(new PartitionEntryImpl("region", partitionValue)))),+ new Column[] {column("region", Types.StringType.get())},+ new Transform[] {Transforms.identity("region")},+ catalogName);+ assertEquals(expectedWhere, stringWhere, ansiModeLabel(ansiEnabled, doubleQuotedIds));+ String stringSql =+ IcebergRewriteDataFilesJob.buildProcedureCall(+ catalogName, "db." + tableSuffix, "binpack", null, stringWhere, null);+ assertTrue(+ stringSql.contains("where => '" + expectedCallWhere + "'"),+ ansiModeLabel(ansiEnabled, doubleQuotedIds) + ": " + stringSql);+ assertDoesNotThrow(+ () -> spark.sql(stringSql).collect(),+ ansiModeLabel(ansiEnabled, doubleQuotedIds) + " string");++ String dateWhere =+ PartitionUtils.getWhereClauseForPartitions(+ Collections.singletonList(+ PartitionPath.of(List.of(new PartitionEntryImpl("ts_day", "2024-01-01")))),+ new Column[] {column("ts", Types.TimestampType.withoutTimeZone())},+ new Transform[] {Transforms.day("ts")},+ catalogName);+ assertEquals(+ "(`" + catalogName + "`.system.days(`ts`) = DATE '2024-01-01')",+ dateWhere,+ ansiModeLabel(ansiEnabled, doubleQuotedIds));+ String dateSql =+ IcebergRewriteDataFilesJob.buildProcedureCall(+ catalogName, "db." + tableSuffix, "binpack", null, dateWhere, null);+ assertTrue(+ dateSql.contains(+ "where => '(`" + catalogName + "`.system.days(`ts`) = DATE \\'2024-01-01\\')'"),+ ansiModeLabel(ansiEnabled, doubleQuotedIds) + ": " + dateSql);+ assertDoesNotThrow(+ () -> spark.sql(dateSql).collect(),+ ansiModeLabel(ansiEnabled, doubleQuotedIds) + " date");++ spark.sql("DROP TABLE IF EXISTS " + table);+ });+ }+ }++ /**+ * Top-level hyphenated identity field {@code user-id} must be rendered as {@code `user-id`}; bare+ * {@code user-id} is parsed as subtraction by Spark.+ */+ @Test+ public void testPartitionUtilsWhereTopLevelHyphenatedFieldThroughSparkCall() {+ String table = catalogName + ".db.pu_hyphen_top";+ try {+ spark.sql("DROP TABLE IF EXISTS " + table);+ spark.sql(+ "CREATE TABLE "+ + table+ + " (id INT, `user-id` INT) USING iceberg PARTITIONED BY (`user-id`)");+ spark.sql("INSERT INTO " + table + " SELECT id, 7 FROM range(0, 20)");++ String where =+ PartitionUtils.getWhereClauseForPartitions(+ Collections.singletonList(+ PartitionPath.of(List.of(new PartitionEntryImpl("user-id", "7")))),+ new Column[] {column("user-id", Types.IntegerType.get())},+ new Transform[] {Transforms.identity("user-id")},+ catalogName);+ assertEquals("(`user-id` = 7)", where);++ String sql =+ IcebergRewriteDataFilesJob.buildProcedureCall(+ catalogName, "db.pu_hyphen_top", "binpack", null, where, null);+ assertDoesNotThrow(() -> spark.sql(sql).collect());+ } finally {+ spark.sql("DROP TABLE IF EXISTS " + table);+ }+ }++ /**+ * Nested hyphenated identity field {@code user-id} must be rendered as {@code `event`.`user-id`};+ * bare {@code event.user-id} is parsed as subtraction by Spark.+ */+ @Test+ public void testPartitionUtilsWhereNestedHyphenatedFieldThroughSparkCall() {+ String table = catalogName + ".db.pu_hyphen";+ try {+ spark.sql("DROP TABLE IF EXISTS " + table);+ spark.sql(+ "CREATE TABLE "+ + table+ + " (id INT, event STRUCT<`user-id`: INT>) USING iceberg "+ + "PARTITIONED BY (event.`user-id`)");+ spark.sql(+ "INSERT INTO " + table + " SELECT id, named_struct('user-id', 7) FROM range(0, 20)");++ String where =+ PartitionUtils.getWhereClauseForPartitions(+ Collections.singletonList(+ PartitionPath.of(List.of(new PartitionEntryImpl("event.user-id", "7")))),+ new Column[] {+ column(+ "event",+ Types.StructType.of(+ Types.StructType.Field.notNullField("user-id", Types.IntegerType.get())))+ },+ new Transform[] {Transforms.identity(new String[] {"event", "user-id"})},+ catalogName);+ assertEquals("(`event`.`user-id` = 7)", where);++ String sql =+ IcebergRewriteDataFilesJob.buildProcedureCall(+ catalogName, "db.pu_hyphen", "binpack", null, where, null);+ assertDoesNotThrow(() -> spark.sql(sql).collect());+ } finally {+ spark.sql("DROP TABLE IF EXISTS " + table);+ }+ }++ /**+ * Struct-in-struct identity path {@code event.meta.user-id} must quote every component: {@code+ * `event`.`meta`.`user-id`}.+ */+ @Test+ public void testPartitionUtilsWhereStructInStructHyphenatedFieldThroughSparkCall() {+ String table = catalogName + ".db.pu_struct2_hyphen";+ try {+ spark.sql("DROP TABLE IF EXISTS " + table);+ spark.sql(+ "CREATE TABLE "+ + table+ + " (id INT, event STRUCT<meta: STRUCT<`user-id`: INT>>) USING iceberg "+ + "PARTITIONED BY (event.meta.`user-id`)");+ spark.sql(+ "INSERT INTO "+ + table+ + " SELECT id, named_struct('meta', named_struct('user-id', 7)) FROM range(0, 20)");++ String where =+ PartitionUtils.getWhereClauseForPartitions(+ Collections.singletonList(+ PartitionPath.of(List.of(new PartitionEntryImpl("event.meta.user-id", "7")))),+ new Column[] {+ column(+ "event",+ Types.StructType.of(+ Types.StructType.Field.notNullField(+ "meta",+ Types.StructType.of(+ Types.StructType.Field.notNullField(+ "user-id", Types.IntegerType.get())))))+ },+ new Transform[] {Transforms.identity(new String[] {"event", "meta", "user-id"})},+ catalogName);+ assertEquals("(`event`.`meta`.`user-id` = 7)", where);++ String sql =+ IcebergRewriteDataFilesJob.buildProcedureCall(+ catalogName, "db.pu_struct2_hyphen", "binpack", null, where, null);+ assertDoesNotThrow(() -> spark.sql(sql).collect());+ } finally {+ spark.sql("DROP TABLE IF EXISTS " + table);+ }+ }++ /**+ * Struct-in-struct + system function: quote the full path, leave {@code system.days} unquoted.+ */+ @Test+ public void testPartitionUtilsWhereDayOnStructInStructHyphenatedFieldThroughSparkCall() {+ String table = catalogName + ".db.pu_struct2_hyphen_day";+ try {+ spark.sql("DROP TABLE IF EXISTS " + table);+ spark.sql(+ "CREATE TABLE "+ + table+ + " (id INT, event STRUCT<meta: STRUCT<`event-ts`: TIMESTAMP>>) USING iceberg "+ + "PARTITIONED BY (days(event.meta.`event-ts`))");+ spark.sql(+ "INSERT INTO "+ + table+ + " SELECT id, named_struct('meta', named_struct('event-ts', TIMESTAMP"+ + " '2026-03-18 12:00:00')) FROM range(0, 20)");++ String where =+ PartitionUtils.getWhereClauseForPartitions(+ Collections.singletonList(+ PartitionPath.of(+ List.of(new PartitionEntryImpl("event.meta.event-ts", "2026-03-18")))),+ new Column[] {+ column(+ "event",+ Types.StructType.of(+ Types.StructType.Field.notNullField(+ "meta",+ Types.StructType.of(+ Types.StructType.Field.notNullField(+ "event-ts", Types.TimestampType.withoutTimeZone())))))+ },+ new Transform[] {Transforms.day(new String[] {"event", "meta", "event-ts"})},+ catalogName);+ assertEquals(+ "(`" + catalogName + "`.system.days(`event`.`meta`.`event-ts`) = DATE '2026-03-18')",+ where);++ String sql =+ IcebergRewriteDataFilesJob.buildProcedureCall(+ catalogName, "db.pu_struct2_hyphen_day", "binpack", null, where, null);+ assertDoesNotThrow(() -> spark.sql(sql).collect());+ } finally {+ spark.sql("DROP TABLE IF EXISTS " + table);+ }+ }++ /**+ * Hyphenated nested field inside a system function: quote the path, leave {@code system.days}+ * unquoted.+ */+ @Test+ public void testPartitionUtilsWhereDayOnNestedHyphenatedFieldThroughSparkCall() {+ String table = catalogName + ".db.pu_hyphen_day";+ try {+ spark.sql("DROP TABLE IF EXISTS " + table);+ spark.sql(+ "CREATE TABLE "+ + table+ + " (id INT, event STRUCT<`event-ts`: TIMESTAMP>) USING iceberg "+ + "PARTITIONED BY (days(event.`event-ts`))");+ spark.sql(+ "INSERT INTO "+ + table+ + " SELECT id, named_struct('event-ts', TIMESTAMP '2026-03-18 12:00:00') FROM"+ + " range(0, 20)");++ String where =+ PartitionUtils.getWhereClauseForPartitions(+ Collections.singletonList(+ PartitionPath.of(+ List.of(new PartitionEntryImpl("event.event-ts", "2026-03-18")))),+ new Column[] {+ column(+ "event",+ Types.StructType.of(+ Types.StructType.Field.notNullField(+ "event-ts", Types.TimestampType.withoutTimeZone())))+ },+ new Transform[] {Transforms.day(new String[] {"event", "event-ts"})},+ catalogName);+ assertEquals(+ "(`" + catalogName + "`.system.days(`event`.`event-ts`) = DATE '2026-03-18')", where);++ String sql =+ IcebergRewriteDataFilesJob.buildProcedureCall(+ catalogName, "db.pu_hyphen_day", "binpack", null, where, null);+ assertDoesNotThrow(() -> spark.sql(sql).collect());+ } finally {+ spark.sql("DROP TABLE IF EXISTS " + table);+ }+ }++ /**+ * With catalog {@code default-namespace}, unqualified {@code years(ts)} is rewritten to {@code+ * catalog.<ns>.years}; {@code catalog.system.years} stays a system function.+ *+ * <p>Uses a fresh Spark catalog alias configured with {@code default-namespace} before first use+ * (setting it on an already-cached catalog is ignored).+ */+ @Test+ public void testCatalogSystemYearsWithDefaultNamespace() {+ String dnsCatalog = "dns_catalog";+ String table = dnsCatalog + ".db.pu_years_dns";+ // Register before any use so default-namespace is applied at catalog init.+ spark.conf().set("spark.sql.catalog." + dnsCatalog, "org.apache.iceberg.spark.SparkCatalog");+ spark.conf().set("spark.sql.catalog." + dnsCatalog + ".type", "hadoop");+ spark.conf().set("spark.sql.catalog." + dnsCatalog + ".warehouse", warehousePath);+ spark.conf().set("spark.sql.catalog." + dnsCatalog + ".default-namespace", "db");+ spark.conf().set("spark.sql.defaultCatalog", dnsCatalog);+ try {+ spark.sql("CREATE NAMESPACE IF NOT EXISTS " + dnsCatalog + ".db");+ spark.sql("DROP TABLE IF EXISTS " + table);+ spark.sql(+ "CREATE TABLE "+ + table+ + " (id INT, ts TIMESTAMP) USING iceberg PARTITIONED BY (years(ts))");+ List<Row> rows = new ArrayList<>();+ for (int i = 0; i < 20; i++) {+ rows.add(RowFactory.create(i, java.sql.Timestamp.valueOf("2024-06-15 12:00:00")));+ }+ StructType schema =+ new StructType()+ .add("id", DataTypes.IntegerType, false)+ .add("ts", DataTypes.TimestampType, false);+ spark+ .createDataFrame(rows, schema)+ .write()+ .format("iceberg")+ .mode(SaveMode.Append)+ .saveAsTable(table);++ String where =+ PartitionUtils.getWhereClauseForPartitions(+ Collections.singletonList(+ PartitionPath.of(List.of(new PartitionEntryImpl("ts_year", "54")))),+ new Column[] {column("ts", Types.TimestampType.withoutTimeZone())},+ new Transform[] {Transforms.year("ts")},+ dnsCatalog);+ assertEquals("(`" + dnsCatalog + "`.system.years(`ts`) = 54)", where);++ // Prefer CatalogManager over SQL current_namespace(): with default-namespace set, Spark may+ // resolve the SQL function under catalog.db and fail UNRESOLVED_ROUTINE.+ String[] currentNs = spark.sessionState().catalogManager().currentNamespace();+ assertTrue(+ Arrays.asList(currentNs).contains("db"),+ "default-namespace must be active before CALL, got: " + Arrays.toString(currentNs));++ String sql =+ IcebergRewriteDataFilesJob.buildProcedureCall(+ dnsCatalog, "db.pu_years_dns", "binpack", null, where, null);+ assertDoesNotThrow(() -> spark.sql(sql).collect());+ } finally {+ spark.sql("DROP TABLE IF EXISTS " + table);+ spark.conf().set("spark.sql.defaultCatalog", catalogName);+ }+ }++ private static void withAnsiModes(+ boolean ansiEnabled, boolean doubleQuotedIdentifiers, Runnable body) {+ spark.conf().set("spark.sql.ansi.enabled", Boolean.toString(ansiEnabled));+ spark+ .conf()+ .set("spark.sql.ansi.doubleQuotedIdentifiers", Boolean.toString(doubleQuotedIdentifiers));+ spark.conf().set("spark.sql.defaultCatalog", catalogName);+ try {+ body.run();+ } finally {+ spark.conf().set("spark.sql.ansi.enabled", "false");+ spark.conf().set("spark.sql.ansi.doubleQuotedIdentifiers", "false");+ }+ }++ private static String ansiModeLabel(boolean ansiEnabled, boolean doubleQuotedIdentifiers) {+ return "ansi.enabled=" + ansiEnabled + ", doubleQuotedIdentifiers=" + doubleQuotedIdentifiers;+ }++ private static Column column(String name, org.apache.gravitino.rel.types.Type type) {+ return ColumnDTO.builder().withName(name).withDataType(type).build();+ }}diff --git a/maintenance/jobs/src/test/java/org/apache/gravitino/maintenance/jobs/iceberg/TestIcebergRewriteManifestsJob.java b/maintenance/jobs/src/test/java/org/apache/gravitino/maintenance/jobs/iceberg/TestIcebergRewriteManifestsJob.javaindex 85b7eb61cb..6c89a17fdd 100644--- a/maintenance/jobs/src/test/java/org/apache/gravitino/maintenance/jobs/iceberg/TestIcebergRewriteManifestsJob.java+++ b/maintenance/jobs/src/test/java/org/apache/gravitino/maintenance/jobs/iceberg/TestIcebergRewriteManifestsJob.java@@ -186,6 +186,7 @@ public class TestIcebergRewriteManifestsJob {assertTrue(configs.containsKey("spark.sql.catalog.{{catalog_name}}.type"));assertTrue(configs.containsKey("spark.sql.catalog.{{catalog_name}}.uri"));assertTrue(configs.containsKey("spark.sql.catalog.{{catalog_name}}.warehouse"));+ assertEquals("{{catalog_name}}", configs.get("spark.sql.defaultCatalog"));}@Testdiff --git a/maintenance/jobs/src/test/java/org/apache/gravitino/maintenance/jobs/iceberg/TestIcebergUpdateStatsJob.java b/maintenance/jobs/src/test/java/org/apache/gravitino/maintenance/jobs/iceberg/TestIcebergUpdateStatsJob.javaindex 3e7d6a488d..08162d42a2 100644--- a/maintenance/jobs/src/test/java/org/apache/gravitino/maintenance/jobs/iceberg/TestIcebergUpdateStatsJob.java+++ b/maintenance/jobs/src/test/java/org/apache/gravitino/maintenance/jobs/iceberg/TestIcebergUpdateStatsJob.java@@ -81,6 +81,7 @@ public class TestIcebergUpdateStatsJob {assertTrue(configs.containsKey("spark.sql.catalog.{{catalog_name}}.type"));assertTrue(configs.containsKey("spark.sql.catalog.{{catalog_name}}.uri"));assertTrue(configs.containsKey("spark.sql.catalog.{{catalog_name}}.warehouse"));+ assertEquals("{{catalog_name}}", configs.get("spark.sql.defaultCatalog"));assertEquals("org.apache.iceberg.spark.extensions.IcebergSparkSessionExtensions",configs.get("spark.sql.extensions"));diff --git a/maintenance/optimizer-api/src/main/java/org/apache/gravitino/maintenance/optimizer/common/util/IcebergSparkConfigUtils.java b/maintenance/optimizer-api/src/main/java/org/apache/gravitino/maintenance/optimizer/common/util/IcebergSparkConfigUtils.javaindex b0e9c60983..c60f798c45 100644--- a/maintenance/optimizer-api/src/main/java/org/apache/gravitino/maintenance/optimizer/common/util/IcebergSparkConfigUtils.java+++ b/maintenance/optimizer-api/src/main/java/org/apache/gravitino/maintenance/optimizer/common/util/IcebergSparkConfigUtils.java@@ -25,10 +25,12 @@ import com.google.common.base.Preconditions;import com.google.common.collect.ImmutableMap;import java.util.Collections;import java.util.HashMap;+import java.util.HashSet;import java.util.LinkedHashMap;import java.util.List;import java.util.Locale;import java.util.Map;+import java.util.Set;import org.apache.commons.lang3.StringUtils;/** Shared utilities for Iceberg Spark template configs and config validation. */@@ -37,6 +39,7 @@ public final class IcebergSparkConfigUtils {private static final ObjectMapper MAPPER = new ObjectMapper();private static final String SPARK_SQL_EXTENSIONS_KEY = "spark.sql.extensions";+ private static final String SPARK_SQL_DEFAULT_CATALOG_KEY = "spark.sql.defaultCatalog";private static final String SPARK_SQL_CATALOG_PREFIX = "spark.sql.catalog.";private static final String CATALOG_TYPE_REST = "rest";private static final String CATALOG_TYPE_HIVE = "hive";@@ -63,10 +66,60 @@ public final class IcebergSparkConfigUtils {configs.put(SPARK_SQL_CATALOG_PREFIX + "{{catalog_name}}.type", "{{catalog_type}}");configs.put(SPARK_SQL_CATALOG_PREFIX + "{{catalog_name}}.uri", "{{catalog_uri}}");configs.put(SPARK_SQL_CATALOG_PREFIX + "{{catalog_name}}.warehouse", "{{warehouse_location}}");+ // Bare years()/months()/days() in rewrite where clauses resolve via the current catalog's+ // FunctionCatalog. Keep the session catalog on the target Iceberg catalog, not spark_catalog.+ configs.put(SPARK_SQL_DEFAULT_CATALOG_KEY, "{{catalog_name}}");configs.put(SPARK_SQL_EXTENSIONS_KEY, ICEBERG_SPARK_EXTENSIONS);return Collections.unmodifiableMap(configs);}+ /**+ * Fills missing Iceberg SparkCatalog impl and extensions when nested catalog connection keys are+ * present, and sets {@code spark.sql.defaultCatalog} from the job's {@code catalogName}.+ *+ * <p>TMS {@code spark_conf} may only carry {@code .type}/{@code .uri}/{@code .warehouse}. Without+ * {@code spark.sql.defaultCatalog}, {@code CALL catalog.system.rewrite_data_files(...)} still+ * finds the procedure, but bare {@code years(ts)} in {@code where} resolves against {@code+ * spark_catalog} and fails. Callers must not put {@code spark.sql.defaultCatalog} in {@code+ * spark_conf}; the job owns that key via {@code catalog_name}. Template configs may still set+ * {@code {{catalog_name}}} separately from the {@code spark_conf} JSON overlay.+ *+ * @param sparkConfigs mutable Spark configs from {@code spark_conf} applied to the session+ * builder+ * @param catalogName Iceberg catalog for this job ({@code catalog_name} / {@code --catalog})+ */+ public static void ensureIcebergCatalogConfigs(+ Map<String, String> sparkConfigs, String catalogName) {+ Preconditions.checkNotNull(sparkConfigs, "sparkConfigs");+ Preconditions.checkArgument(StringUtils.isNotBlank(catalogName), "catalogName is blank");+ Preconditions.checkArgument(+ !sparkConfigs.containsKey(SPARK_SQL_DEFAULT_CATALOG_KEY),+ "Do not set spark.sql.defaultCatalog in spark_conf; the job sets it from catalog_name (%s)",+ catalogName);++ Set<String> catalogs = new HashSet<>();+ for (String key : sparkConfigs.keySet()) {+ if (!key.startsWith(SPARK_SQL_CATALOG_PREFIX)) {+ continue;+ }+ String rest = key.substring(SPARK_SQL_CATALOG_PREFIX.length());+ int dot = rest.indexOf('.');+ if (dot <= 0) {+ continue;+ }+ String prop = rest.substring(dot + 1);+ if ("type".equals(prop) || "uri".equals(prop) || "warehouse".equals(prop)) {+ catalogs.add(rest.substring(0, dot));+ }+ }+ for (String catalog : catalogs) {+ sparkConfigs.putIfAbsent(+ SPARK_SQL_CATALOG_PREFIX + catalog, "org.apache.iceberg.spark.SparkCatalog");+ }+ sparkConfigs.put(SPARK_SQL_DEFAULT_CATALOG_KEY, catalogName);+ sparkConfigs.putIfAbsent(SPARK_SQL_EXTENSIONS_KEY, ICEBERG_SPARK_EXTENSIONS);+ }+/*** Parse a flat JSON map from CLI/config option.*diff --git a/maintenance/optimizer-api/src/test/java/org/apache/gravitino/maintenance/optimizer/common/util/TestIcebergSparkConfigUtils.java b/maintenance/optimizer-api/src/test/java/org/apache/gravitino/maintenance/optimizer/common/util/TestIcebergSparkConfigUtils.javaindex c2dead444b..b206c47880 100644--- a/maintenance/optimizer-api/src/test/java/org/apache/gravitino/maintenance/optimizer/common/util/TestIcebergSparkConfigUtils.java+++ b/maintenance/optimizer-api/src/test/java/org/apache/gravitino/maintenance/optimizer/common/util/TestIcebergSparkConfigUtils.java@@ -42,10 +42,40 @@ public class TestIcebergSparkConfigUtils {assertTrue(configs.containsKey("spark.sql.catalog.{{catalog_name}}.type"));assertTrue(configs.containsKey("spark.sql.catalog.{{catalog_name}}.uri"));assertTrue(configs.containsKey("spark.sql.catalog.{{catalog_name}}.warehouse"));+ assertEquals("{{catalog_name}}", configs.get("spark.sql.defaultCatalog"));assertEquals(IcebergSparkConfigUtils.ICEBERG_SPARK_EXTENSIONS, configs.get("spark.sql.extensions"));}+ @Test+ public void testEnsureIcebergCatalogConfigsSetsDefaultCatalogFromCatalogName() {+ Map<String, String> configs = new HashMap<>();+ configs.put("spark.sql.catalog.ice_prod.type", "rest");+ configs.put("spark.sql.catalog.ice_prod.uri", "http://localhost:9001/iceberg");++ IcebergSparkConfigUtils.ensureIcebergCatalogConfigs(configs, "ice_prod");++ assertEquals(+ "org.apache.iceberg.spark.SparkCatalog", configs.get("spark.sql.catalog.ice_prod"));+ assertEquals("ice_prod", configs.get("spark.sql.defaultCatalog"));+ assertEquals(+ IcebergSparkConfigUtils.ICEBERG_SPARK_EXTENSIONS, configs.get("spark.sql.extensions"));+ }++ @Test+ public void testEnsureIcebergCatalogConfigsRejectsUserDefaultCatalog() {+ Map<String, String> configs = new HashMap<>();+ configs.put("spark.sql.catalog.ice_prod.type", "rest");+ configs.put("spark.sql.defaultCatalog", "spark_catalog");++ IllegalArgumentException e =+ assertThrows(+ IllegalArgumentException.class,+ () -> IcebergSparkConfigUtils.ensureIcebergCatalogConfigs(configs, "ice_prod"));+ assertTrue(e.getMessage().contains("spark.sql.defaultCatalog"));+ assertTrue(e.getMessage().contains("catalog_name"));+ }+@Testpublic void testBuildTemplateSparkConfigsLeavesMasterUnsetByDefault() {Map<String, String> configs = IcebergSparkConfigUtils.buildTemplateSparkConfigs();diff --git a/maintenance/optimizer/build.gradle.kts b/maintenance/optimizer/build.gradle.ktsindex 8043e6afd3..79c28b3681 100644--- a/maintenance/optimizer/build.gradle.kts+++ b/maintenance/optimizer/build.gradle.kts@@ -93,6 +93,7 @@ dependencies {testImplementation(libs.testcontainers.mysql)testImplementation(libs.testcontainers.postgresql)testImplementation(project(":integration-test-common", "testArtifacts"))+ testImplementation(project(":catalogs:catalog-lakehouse-iceberg"))testImplementation(project(":server"))testRuntimeOnly(libs.mysql.driver)testRuntimeOnly(libs.postgresql.driver)@@ -126,6 +127,12 @@ configurations.testRuntimeClasspath {exclude(group = "org.apache.logging.log4j", module = "log4j-slf4j2-impl")}+// The lakehouse-iceberg catalog packages runtime jars beside its module jar in build/libs+// (same pattern as jobs → optimizer:copyDepends). Order compileTestJava after that.+tasks.compileTestJava {+ dependsOn(":catalogs:catalog-lakehouse-iceberg:jar", ":catalogs:catalog-lakehouse-iceberg:runtimeJars")+}+tasks.test {val skipITs = project.hasProperty("skipITs")if (skipITs) {diff --git a/maintenance/optimizer/src/main/java/org/apache/gravitino/maintenance/optimizer/recommender/job/GravitinoCompactionJobAdapter.java b/maintenance/optimizer/src/main/java/org/apache/gravitino/maintenance/optimizer/recommender/job/GravitinoCompactionJobAdapter.javaindex 8010957dde..03afec03d8 100644--- a/maintenance/optimizer/src/main/java/org/apache/gravitino/maintenance/optimizer/recommender/job/GravitinoCompactionJobAdapter.java+++ b/maintenance/optimizer/src/main/java/org/apache/gravitino/maintenance/optimizer/recommender/job/GravitinoCompactionJobAdapter.java@@ -26,6 +26,7 @@ import com.google.common.base.Preconditions;import com.google.common.collect.ImmutableMap;import java.util.Map;import java.util.TreeMap;+import org.apache.commons.lang3.StringUtils;import org.apache.gravitino.maintenance.optimizer.api.recommender.JobExecutionContext;import org.apache.gravitino.maintenance.optimizer.common.util.IdentifierUtils;import org.apache.gravitino.maintenance.optimizer.recommender.handler.compaction.CompactionJobContext;@@ -38,6 +39,17 @@ public class GravitinoCompactionJobAdapter implements GravitinoJobAdapter {@Overridepublic Map<String, String> jobConfig(JobExecutionContext jobExecutionContext) {+ return jobConfig(jobExecutionContext, Map.of());+ }++ /**+ * Builds compaction jobConf. {@code where_clause} qualifies Iceberg system functions with the+ * same Spark {@code catalog_name} the CALL uses (submitter config), not the Gravitino catalog+ * segment of the table identifier when those differ.+ */+ @Override+ public Map<String, String> jobConfig(+ JobExecutionContext jobExecutionContext, Map<String, String> submitterConfigs) {Preconditions.checkArgument(jobExecutionContext instanceof CompactionJobContext,"jobExecutionContext must be CompactionJobExecutionContext");@@ -52,7 +64,7 @@ public class GravitinoCompactionJobAdapter implements GravitinoJobAdapter {: jobContext.getSortOrder();return ImmutableMap.of("table_identifier", getTableName(jobContext),- "where_clause", getWhereClause(jobContext),+ "where_clause", getWhereClause(jobContext, submitterConfigs),"sort_order", sortOrder,"strategy", rewriteStrategy,"options", getOptions(jobContext));@@ -62,16 +74,24 @@ public class GravitinoCompactionJobAdapter implements GravitinoJobAdapter {return IdentifierUtils.removeCatalogFromIdentifier(jobContext.nameIdentifier()).toString();}- private String getWhereClause(CompactionJobContext jobContext) {+ private String getWhereClause(+ CompactionJobContext jobContext, Map<String, String> submitterConfigs) {if (jobContext.getPartitions().isEmpty()) {return "";}- // generate where clause from jobContext.partitionNames()- // 1. get partition column type- // 2. generate partition filter name, like day(xxx)- // 3. generate partition filter value, like '2023-10-01', TIMESTAMP 'xxx'+ // Same Spark catalog alias as CALL (jobSubmitterConfig.catalog_name); fall back to the+ // Gravitino table catalog when unset.+ String sparkCatalog = submitterConfigs == null ? null : submitterConfigs.get("catalog_name");+ if (StringUtils.isBlank(sparkCatalog)) {+ sparkCatalog = IdentifierUtils.getCatalogNameFromTableIdentifier(jobContext.nameIdentifier());+ } else {+ sparkCatalog = sparkCatalog.trim();+ }return PartitionUtils.getWhereClauseForPartitions(- jobContext.getPartitions(), jobContext.getColumns(), jobContext.getPartitioning());+ jobContext.getPartitions(),+ jobContext.getColumns(),+ jobContext.getPartitioning(),+ sparkCatalog);}private String getOptions(JobExecutionContext jobExecutionContext) {diff --git a/maintenance/optimizer/src/main/java/org/apache/gravitino/maintenance/optimizer/recommender/job/GravitinoJobAdapter.java b/maintenance/optimizer/src/main/java/org/apache/gravitino/maintenance/optimizer/recommender/job/GravitinoJobAdapter.javaindex 8e030d4988..458ae9ad7d 100644--- a/maintenance/optimizer/src/main/java/org/apache/gravitino/maintenance/optimizer/recommender/job/GravitinoJobAdapter.java+++ b/maintenance/optimizer/src/main/java/org/apache/gravitino/maintenance/optimizer/recommender/job/GravitinoJobAdapter.java@@ -26,8 +26,8 @@ import org.apache.gravitino.maintenance.optimizer.api.recommender.JobExecutionCo* Translates optimizer job execution context into Gravitino job submission inputs.** <p>Usage: {@link GravitinoJobSubmitter} looks up an adapter for the requested job template,- * creates a new instance, and calls {@link #jobConfig(JobExecutionContext)} when submitting the job- * to Gravitino.+ * creates a new instance, and calls {@link #jobConfig(JobExecutionContext, Map)} when submitting+ * the job to Gravitino.*/public interface GravitinoJobAdapter {@@ -40,4 +40,20 @@ public interface GravitinoJobAdapter {* @return job configuration map*/Map<String, String> jobConfig(JobExecutionContext jobExecutionContext);++ /**+ * Same as {@link #jobConfig(JobExecutionContext)}, with access to optimizer job-submitter+ * defaults (for example Spark {@code catalog_name}) before they are merged over.+ *+ * <p>Default delegates to {@link #jobConfig(JobExecutionContext)}. Compaction overrides this so+ * partition {@code where_clause} functions use the same Spark catalog alias as the CALL.+ *+ * @param jobExecutionContext job execution context+ * @param submitterConfigs {@code gravitino.optimizer.jobSubmitterConfig.*} values (may be empty)+ * @return job configuration map+ */+ default Map<String, String> jobConfig(+ JobExecutionContext jobExecutionContext, Map<String, String> submitterConfigs) {+ return jobConfig(jobExecutionContext);+ }}diff --git a/maintenance/optimizer/src/main/java/org/apache/gravitino/maintenance/optimizer/recommender/job/GravitinoJobSubmitter.java b/maintenance/optimizer/src/main/java/org/apache/gravitino/maintenance/optimizer/recommender/job/GravitinoJobSubmitter.javaindex 1a6f62b377..cb3737b988 100644--- a/maintenance/optimizer/src/main/java/org/apache/gravitino/maintenance/optimizer/recommender/job/GravitinoJobSubmitter.java+++ b/maintenance/optimizer/src/main/java/org/apache/gravitino/maintenance/optimizer/recommender/job/GravitinoJobSubmitter.java@@ -128,7 +128,7 @@ public class GravitinoJobSubmitter implements JobSubmitter {Map<String, String> submitterConfigs =optimizerConfig == null ? Map.of() : optimizerConfig.jobSubmitterConfigs();Map<String, String> adapterConfigs =- jobAdapter == null ? Map.of() : jobAdapter.jobConfig(jobExecutionContext);+ jobAdapter == null ? Map.of() : jobAdapter.jobConfig(jobExecutionContext, submitterConfigs);Map<String, String> mergedConfigs = new LinkedHashMap<>();mergedConfigs.putAll(submitterConfigs);diff --git a/maintenance/optimizer/src/main/java/org/apache/gravitino/maintenance/optimizer/recommender/job/PartitionUtils.java b/maintenance/optimizer/src/main/java/org/apache/gravitino/maintenance/optimizer/recommender/job/PartitionUtils.javaindex 1d6251ab40..6c4c314236 100644--- a/maintenance/optimizer/src/main/java/org/apache/gravitino/maintenance/optimizer/recommender/job/PartitionUtils.java+++ b/maintenance/optimizer/src/main/java/org/apache/gravitino/maintenance/optimizer/recommender/job/PartitionUtils.java@@ -21,6 +21,10 @@ package org.apache.gravitino.maintenance.optimizer.recommender.job;import com.google.common.base.Preconditions;import com.google.common.collect.Lists;+import java.math.BigDecimal;+import java.time.LocalDate;+import java.time.format.DateTimeFormatter;+import java.time.format.DateTimeParseException;import java.util.Arrays;import java.util.List;import java.util.Locale;@@ -34,11 +38,40 @@ import org.apache.gravitino.rel.Column;import org.apache.gravitino.rel.expressions.transforms.Transform;import org.apache.gravitino.rel.expressions.transforms.Transforms;import org.apache.gravitino.rel.types.Type;+import org.apache.gravitino.rel.types.Types;+/**+ * Builds Iceberg Spark {@code rewrite_data_files} {@code where} predicates from partition paths.+ *+ * <p>Expressions must match Iceberg Spark system functions ({@code years}/{@code months}/{@code+ * days}/{@code hours}/{@code bucket}/{@code truncate}) so {@code SparkV2Filters} can push them+ * down. Spark builtins such as {@code day()} / {@code year()} are intentionally not used.+ *+ * <p>String and typed literals ({@code DATE}/{@code TIMESTAMP}/{@code TIME}) use single quotes so+ * predicates stay valid when {@code spark.sql.ansi.doubleQuotedIdentifiers} is enabled (double+ * quotes are identifiers there). The job embeds the clause in {@code CALL ... where => '...'} via+ * {@code IcebergJobUtils.escapeSparkCallStringArg} ({@code '} → {@code \'}), which preserves these+ * inner literals through the outer Spark parse.+ *+ * <p>Non-identity transforms are qualified as {@code catalog.system.years|months|days|hours|...} so+ * resolution does not depend on {@code spark.sql.defaultCatalog} or a catalog {@code+ * default-namespace} (which would otherwise turn bare {@code years(ts)} into {@code+ * catalog.db.years}).+ */public class PartitionUtils {+ /**+ * Builds an OR of per-partition predicates, each wrapped in parentheses.+ *+ * <p>Example: {@code (a = 'x' AND b = 1) OR (a = 'y' AND b = 2)}.+ *+ * @param catalogName Iceberg Spark catalog used to qualify system functions+ */public static String getWhereClauseForPartitions(- List<PartitionPath> partitions, Column[] columns, Transform[] partitioning) {+ List<PartitionPath> partitions,+ Column[] columns,+ Transform[] partitioning,+ String catalogName) {Preconditions.checkArgument(partitions != null && !partitions.isEmpty(), "partitions cannot be null or empty");Preconditions.checkArgument(ArrayUtils.isNotEmpty(columns), "columns cannot be null or empty");@@ -47,28 +80,42 @@ public class PartitionUtils {List<String> predicates = Lists.newArrayListWithExpectedSize(partitions.size());for (PartitionPath partition : partitions) {- predicates.add(getWhereClauseForPartition(partition.entries(), columns, partitioning));+ predicates.add(+ getWhereClauseForPartition(partition.entries(), columns, partitioning, catalogName));}- // Wrap each partition-level predicate in parentheses to preserve logical grouping- // e.g. "(col1 = v1 AND col2 = v2) OR (col1 = v3 AND col2 = v4)"return predicates.stream().map(p -> "(" + p + ")").collect(Collectors.joining(" OR "));}- // For Identity transform, the where clause is like "columnName = value"- // For bucket transform, the where clause is like "bucket(columnName, numBuckets) = value"- // For truncate transform, the where clause is like "truncate(columnName, width) = value"- // For year/month/day/hour transform, the where clause is like "year(columnName) = value"- // We could get value from partition.get(i).partitionValue(), if the value type is string, we need- // to add quotes like "value", if the value type is number, we don't need to add quotes. if the- // value type is date/datetime, we need to add quotes like TIMESTAMP '2024-01-01'+ /**+ * Builds a single-partition AND predicate.+ *+ * <ul>+ * <li>Identity: {@code column = literal}+ * <li>Bucket / truncate: Iceberg argument order ({@code catalog.system.bucket(N, col)}, {@code+ * catalog.system.truncate(W, col)})+ * <li>{@code years}/{@code months}/{@code hours}: compare to the stored Iceberg int (years+ * since 1970, etc.)—not a calendar year/month+ * <li>{@code days}: Iceberg Spark {@code days()} returns {@code DateType}, so the RHS is {@code+ * DATE 'yyyy-MM-dd'}. Stored partition strings must be ISO {@code yyyy-MM-dd} (same as+ * Iceberg {@code DateTimeUtil.isoDateToDays})+ * </ul>+ *+ * @param catalogName Iceberg Spark catalog used to qualify system functions+ */public static String getWhereClauseForPartition(- List<PartitionEntry> partition, Column[] columns, Transform[] partitioning) {+ List<PartitionEntry> partition,+ Column[] columns,+ Transform[] partitioning,+ String catalogName) {Preconditions.checkArgument(partition != null && !partition.isEmpty(), "partition cannot be null or empty");Preconditions.checkArgument(ArrayUtils.isNotEmpty(columns), "columns cannot be null or empty");Preconditions.checkArgument(partitioning != null && partitioning.length == partition.size(),"partitioning must match the size of partition entries");+ Preconditions.checkArgument(+ catalogName != null && !catalogName.trim().isEmpty(),+ "catalogName cannot be null or empty");Map<String, Column> columnMap =Arrays.stream(columns)@@ -81,93 +128,260 @@ public class PartitionUtils {PartitionEntry entry = partition.get(i);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);+ // Keep transform field-name components (do not join/split on '.') so names like user-id+ // stay one component through schema lookup and SQL rendering.+ String[] fieldName = getFieldName(transform);+ Preconditions.checkArgument(+ fieldName != null && fieldName.length > 0, "transform field name cannot be empty");+ Column column = columnMap.get(fieldName[0].toLowerCase(Locale.ROOT));+ Preconditions.checkNotNull(+ column, "Column '%s' not found in table schema", joinFieldName(fieldName));- String expression = buildExpression(transform, columnName);- String literal = formatLiteral(transform, column, entry.partitionValue());+ String quotedPath = quoteFieldPath(fieldName);+ String expression = buildExpression(transform, quotedPath, catalogName.trim());+ // Walk into struct fields so nested identity uses TIMESTAMP/INT/... not STRUCT→string.+ String literal =+ formatLiteral(transform, resolveLeafDataType(column, fieldName), entry.partitionValue());predicates.add(String.format("%s = %s", expression, literal));}return String.join(" AND ", predicates);}- private static String getColumnName(Transform transform) {+ private static String[] getFieldName(Transform transform) {if (transform instanceof Transform.SingleFieldTransform) {- return joinFieldName(((Transform.SingleFieldTransform) transform).fieldName());+ return ((Transform.SingleFieldTransform) transform).fieldName();} else if (transform instanceof Transforms.TruncateTransform) {- return joinFieldName(((Transforms.TruncateTransform) transform).fieldName());+ return ((Transforms.TruncateTransform) transform).fieldName();} else if (transform instanceof Transforms.BucketTransform) {String[][] fieldNames = ((Transforms.BucketTransform) transform).fieldNames();Preconditions.checkArgument(fieldNames.length > 0, "Bucket transform must have at least one field");- return joinFieldName(fieldNames[0]);+ return fieldNames[0];}throw new IllegalArgumentException("Unsupported transform: " + transform.getClass().getName());}- private static String buildExpression(Transform transform, String columnName) {+ /**+ * Resolves the leaf type by walking every transform field-name component after the top-level+ * column (supports struct-in-struct, e.g. {@code event} → {@code meta} → {@code user-id}).+ */+ private static Type resolveLeafDataType(Column column, String[] fieldName) {+ if (fieldName.length == 1) {+ return column.dataType();+ }+ Type type = column.dataType();+ String path = joinFieldName(fieldName);+ for (int i = 1; i < fieldName.length; i++) {+ if (!(type instanceof Types.StructType)) {+ throw new IllegalArgumentException(+ "Cannot resolve nested field '"+ + path+ + "': '"+ + joinFieldName(Arrays.copyOf(fieldName, i))+ + "' is not a struct");+ }+ Types.StructType.Field matched = null;+ for (Types.StructType.Field field : ((Types.StructType) type).fields()) {+ if (field.name().equalsIgnoreCase(fieldName[i])) {+ matched = field;+ break;+ }+ }+ if (matched == null) {+ throw new IllegalArgumentException("Nested field '" + path + "' 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.+ * Non-identity functions are qualified as {@code catalog.system.<fn>} so a catalog {@code+ * default-namespace} cannot rewrite them to {@code catalog.<ns>.<fn>}.+ *+ * @param quotedFieldPath backtick-quoted field path ({@code `event`.`meta`.`user-id`})+ */+ private static String buildExpression(+ Transform transform, String quotedFieldPath, String catalogName) {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 + ")";+ return quotedFieldPath;+ }+ String systemFn = quoteIdentifier(catalogName) + ".system.";+ if (transform instanceof Transforms.YearTransform) {+ return systemFn + "years(" + quotedFieldPath + ")";+ } else if (transform instanceof Transforms.MonthTransform) {+ return systemFn + "months(" + quotedFieldPath + ")";+ } else if (transform instanceof Transforms.DayTransform) {+ return systemFn + "days(" + quotedFieldPath + ")";+ } else if (transform instanceof Transforms.HourTransform) {+ return systemFn + "hours(" + quotedFieldPath + ")";} else if (transform instanceof Transforms.BucketTransform) {- return "bucket("- + columnName- + ", "+ return systemFn+ + "bucket("+ ((Transforms.BucketTransform) transform).numBuckets()+ + ", "+ + quotedFieldPath+ ")";} else if (transform instanceof Transforms.TruncateTransform) {- return "truncate("- + columnName- + ", "+ return systemFn+ + "truncate("+ ((Transforms.TruncateTransform) transform).width()+ + ", "+ + quotedFieldPath+ ")";}throw new IllegalArgumentException("Unsupported transform: " + transform.getClass().getName());}- private static String formatLiteral(Transform transform, Column column, String rawValue) {+ /**+ * Backtick-quotes each field-name component, including multi-level struct paths ({@code+ * `event`.`meta`.`user-id`}).+ */+ private static String quoteFieldPath(String[] fieldNameParts) {+ return Arrays.stream(fieldNameParts)+ .map(PartitionUtils::quoteIdentifier)+ .collect(Collectors.joining("."));+ }++ /** Backtick-quotes a Spark identifier (internal backticks are doubled). */+ private static String quoteIdentifier(String name) {+ return "`" + name.replace("`", "``") + "`";+ }++ private static String formatLiteral(Transform transform, Type type, String rawValue) {+ Preconditions.checkArgument(rawValue != null, "Partition value cannot be null");++ // 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;+ // Same trim + parse as identity integrals so " 54 " does not fail only on one path.+ return formatIntegralLiteral(+ rawValue, "Partition value for years/months/hours/bucket must be an integer");+ }++ // days() → DateType; single-quoted DATE survives ANSI doubleQuotedIdentifiers.+ if (transform instanceof Transforms.DayTransform) {+ return "DATE '" + escapeStringLiteral(toIsoDateFromDayPartitionValue(rawValue)) + "'";}- Type type = column.dataType();switch (type.name()) {case BOOLEAN:- return rawValue.toLowerCase(Locale.ROOT);+ return formatBooleanLiteral(rawValue);case BYTE:case SHORT:case INTEGER:case LONG:+ return formatIntegralLiteral(+ rawValue, "Partition value for identity integral column must be an integer");case FLOAT:case DOUBLE:+ return formatFloatingLiteral(rawValue);case DECIMAL:- return rawValue;+ return formatDecimalLiteral(rawValue);case DATE:- return "DATE '" + rawValue + "'";case TIMESTAMP:- return "TIMESTAMP '" + rawValue + "'";case TIME:- return "TIME '" + rawValue + "'";+ return type.name() + " '" + escapeStringLiteral(rawValue) + "'";default:- return "\"" + escapeStringLiteral(rawValue) + "\"";+ return "'" + escapeStringLiteral(rawValue) + "'";+ }+ }++ /**+ * Parses identity boolean partition values. Only {@code true}/{@code false} (any case) are+ * accepted so malformed imports cannot inject SQL.+ */+ private static String formatBooleanLiteral(String rawValue) {+ String normalized = rawValue.trim().toLowerCase(Locale.ROOT);+ if (!"true".equals(normalized) && !"false".equals(normalized)) {+ throw new IllegalArgumentException(+ "Partition value for boolean must be true or false, but got: " + rawValue);+ }+ return normalized;+ }++ /**+ * Parses integral partition values so inputs like {@code 7 OR 1 = 1} fail instead of broadening+ * the predicate.+ *+ * @param messagePrefix context-specific prefix before {@code , but got: ...}+ */+ private static String formatIntegralLiteral(String rawValue, String messagePrefix) {+ try {+ return Long.toString(Long.parseLong(rawValue.trim()));+ } catch (NumberFormatException e) {+ throw new IllegalArgumentException(messagePrefix + ", but got: " + rawValue, e);+ }+ }++ /**+ * Parses floating partition values and emits a canonical numeric literal.+ *+ * <p>{@link Double#parseDouble(String)} accepts Java hex floats such as {@code 0X1P0}, but Spark+ * SQL tokenizes that spelling as an identifier. Re-emit via {@link Double#toString(double)} so+ * the predicate always uses a numeric literal Spark can parse.+ */+ private static String formatFloatingLiteral(String rawValue) {+ try {+ double parsed = Double.parseDouble(rawValue.trim());+ if (Double.isInfinite(parsed) || Double.isNaN(parsed)) {+ throw new NumberFormatException("non-finite");+ }+ return Double.toString(parsed);+ } catch (NumberFormatException e) {+ throw new IllegalArgumentException(+ "Partition value for floating type must be a finite number, but got: " + rawValue, e);+ }+ }++ private static String formatDecimalLiteral(String rawValue) {+ String trimmed = rawValue.trim();+ try {+ new BigDecimal(trimmed);+ return trimmed;+ } catch (NumberFormatException | ArithmeticException e) {+ throw new IllegalArgumentException(+ "Partition value for decimal must be a number, but got: " + rawValue, e);+ }+ }++ /**+ * 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)+ .format(DateTimeFormatter.ISO_LOCAL_DATE);+ } catch (DateTimeParseException e) {+ throw new IllegalArgumentException(+ "Day partition value must be an ISO date (yyyy-MM-dd), but got: " + rawValue, e);}}+ /**+ * Escapes a value for a single-quoted Iceberg Spark literal ({@code \} → {@code \\}, {@code '} →+ * {@code \'}).+ *+ * <p>Does not apply CALL {@code where => '...'} outer escaping; the job builder doubles+ * backslashes (and re-encodes {@code '}) when embedding this clause.+ */private static String escapeStringLiteral(String value) {- return value.replace("\\", "\\\\").replace("\"", "\\\"");+ return value.replace("\\", "\\\\").replace("'", "\\'");}private static String joinFieldName(String[] fieldNameParts) {diff --git a/maintenance/optimizer/src/test/java/org/apache/gravitino/maintenance/optimizer/recommender/job/TestBuiltinIcebergRewriteDataFiles.java b/maintenance/optimizer/src/test/java/org/apache/gravitino/maintenance/optimizer/recommender/job/TestBuiltinIcebergRewriteDataFiles.javaindex f1f0a54267..b38f4528c3 100644--- a/maintenance/optimizer/src/test/java/org/apache/gravitino/maintenance/optimizer/recommender/job/TestBuiltinIcebergRewriteDataFiles.java+++ b/maintenance/optimizer/src/test/java/org/apache/gravitino/maintenance/optimizer/recommender/job/TestBuiltinIcebergRewriteDataFiles.java@@ -20,6 +20,7 @@package org.apache.gravitino.maintenance.optimizer.recommender.job;import java.time.Duration;+import java.util.ArrayList;import java.util.Arrays;import java.util.Collections;import java.util.HashMap;@@ -35,13 +36,18 @@ import org.apache.gravitino.job.JobHandle;import org.apache.gravitino.maintenance.optimizer.api.common.PartitionPath;import org.apache.gravitino.maintenance.optimizer.common.PartitionEntryImpl;import org.apache.gravitino.maintenance.optimizer.common.conf.OptimizerConfig;+import org.apache.gravitino.maintenance.optimizer.common.util.IcebergSparkConfigUtils;import org.apache.gravitino.maintenance.optimizer.recommender.handler.compaction.CompactionJobContext;import org.apache.gravitino.rel.Column;import org.apache.gravitino.rel.expressions.transforms.Transform;import org.apache.gravitino.rel.expressions.transforms.Transforms;import org.apache.gravitino.rel.types.Types;import org.apache.spark.sql.Row;+import org.apache.spark.sql.RowFactory;+import org.apache.spark.sql.SaveMode;import org.apache.spark.sql.SparkSession;+import org.apache.spark.sql.types.DataTypes;+import org.apache.spark.sql.types.StructType;import org.awaitility.Awaitility;import org.junit.jupiter.api.Assertions;import org.junit.jupiter.api.Test;@@ -56,7 +62,10 @@ public class TestBuiltinIcebergRewriteDataFiles {private static final String ICEBERG_REST_URI = "http://localhost:9001/iceberg";private static final String JOB_TEMPLATE_NAME = "builtin-iceberg-rewrite-data-files";private static final String SPARK_CATALOG_NAME = "rest_catalog";- private static final String WAREHOUSE_LOCATION = "";+ // Optional local overrides for GRAVITINO_ENV_IT (do not hardcode secrets in source).+ private static final String WAREHOUSE_LOCATION = envOrDefault("GRAVITINO_IT_WAREHOUSE", "");+ private static final String BASIC_AUTH_USER = envOrDefault("GRAVITINO_IT_USERNAME", "");+ private static final String BASIC_AUTH_PASSWORD = envOrDefault("GRAVITINO_IT_PASSWORD", "");@Testvoid testSubmitRewriteDataFilesJobByConfig() throws Exception {@@ -210,6 +219,682 @@ public class TestBuiltinIcebergRewriteDataFiles {});}+ @Test+ void testPartitionUtilsWhereClausesAgainstIcebergRewriteCall() {+ // Only needs Iceberg REST + Spark CALL; no Gravitino metalake / job submit.+ SparkSession spark = createSparkSession();+ try {+ spark.sql("CREATE NAMESPACE IF NOT EXISTS " + SPARK_CATALOG_NAME + ".db");+ // Iceberg Spark system functions are resolved inside rewrite_data_files where parsing+ // (SparkV2Filters), not always as free-standing Spark SQL routines in this classpath.++ boolean[][] ansiModes =+ new boolean[][] {+ {false, false},+ {true, false},+ {false, true},+ {true, true},+ };+ for (boolean[] mode : ansiModes) {+ boolean ansiEnabled = mode[0];+ boolean doubleQuotedIds = mode[1];+ spark.conf().set("spark.sql.ansi.enabled", Boolean.toString(ansiEnabled));+ spark+ .conf()+ .set("spark.sql.ansi.doubleQuotedIdentifiers", Boolean.toString(doubleQuotedIds));+ String ansi = ansiFlag(ansiEnabled, doubleQuotedIds);+ assertRewriteCallForIdentityString(spark, ansi);+ assertRewriteCallForIdentityStringWithSingleQuote(spark, ansi);+ assertRewriteCallForIdentityStringWithQuoteAndBackslash(spark, ansi);+ assertRewriteCallForIdentityDate(spark, ansi);+ assertRewriteCallForIdentityTimestamp(spark, ansi);+ assertRewriteCallForDays(spark, ansi);+ assertRewriteCallForYears(spark, ansi);+ assertRewriteCallForMonths(spark, ansi);+ assertRewriteCallForHours(spark, ansi);+ assertRewriteCallForBucket(spark, ansi);+ assertRewriteCallForTruncate(spark, ansi);+ assertRewriteCallForStructDay(spark, ansi);+ assertRewriteCallForStructYear(spark, ansi);+ assertRewriteCallForStructMonth(spark, ansi);+ assertRewriteCallForStructHour(spark, ansi);+ assertRewriteCallForStructBucket(spark, ansi);+ assertRewriteCallForStructTruncate(spark, ansi);+ assertRewriteCallForStructIdentityTimestamp(spark, ansi);+ assertRewriteCallForStructIdentityInt(spark, ansi);+ assertRewriteCallForStructIdentityHyphenatedInt(spark, ansi);+ assertRewriteCallForStructDayHyphenated(spark, ansi);+ assertRewriteCallForStructBucketHyphenated(spark, ansi);+ assertRewriteCallForStructInStructIdentityHyphenated(spark, ansi);+ assertRewriteCallForStructInStructDayHyphenated(spark, ansi);+ }+ spark.conf().set("spark.sql.ansi.enabled", "false");+ spark.conf().set("spark.sql.ansi.doubleQuotedIdentifiers", "false");+ } finally {+ spark.stop();+ }+ }++ private static void assertRewriteCallForIdentityString(SparkSession spark, String ansi) {+ String table = fullTable("id_str_" + ansi);+ recreateTable(+ spark,+ table,+ "(id INT, region STRING)",+ "region",+ "INSERT INTO " + table + " SELECT id, 'usa' FROM range(0, 20)");+ String where =+ PartitionUtils.getWhereClauseForPartitions(+ List.of(PartitionPath.of(List.of(new PartitionEntryImpl("region", "usa")))),+ new Column[] {column("region", Types.StringType.get())},+ new Transform[] {Transforms.identity("region")},+ SPARK_CATALOG_NAME);+ Assertions.assertEquals("(`region` = 'usa')", where);+ callRewrite(spark, table, where);+ }++ private static void assertRewriteCallForIdentityStringWithSingleQuote(+ SparkSession spark, String ansi) {+ String table = fullTable("id_str_sq_" + ansi);+ spark.sql("CREATE NAMESPACE IF NOT EXISTS " + SPARK_CATALOG_NAME + ".db");+ spark.sql("DROP TABLE IF EXISTS " + table);+ spark.sql(+ "CREATE TABLE " + table + " (id INT, region STRING) USING iceberg PARTITIONED BY (region)");+ // SQL '' drops the apostrophe under Spark's default parser; insert via DataFrame.+ StructType schema =+ new StructType()+ .add("id", DataTypes.IntegerType, false)+ .add("region", DataTypes.StringType, false);+ List<Row> rows = new ArrayList<>();+ for (int i = 0; i < 20; i++) {+ rows.add(RowFactory.create(i, "O'Brien"));+ }+ spark+ .createDataFrame(rows, schema)+ .write()+ .format("iceberg")+ .mode(SaveMode.Append)+ .saveAsTable(table);+ String where =+ PartitionUtils.getWhereClauseForPartitions(+ List.of(PartitionPath.of(List.of(new PartitionEntryImpl("region", "O'Brien")))),+ new Column[] {column("region", Types.StringType.get())},+ new Transform[] {Transforms.identity("region")},+ SPARK_CATALOG_NAME);+ Assertions.assertEquals("(`region` = 'O\\'Brien')", where);+ callRewrite(spark, table, where);+ }++ private static void assertRewriteCallForIdentityStringWithQuoteAndBackslash(+ SparkSession spark, String ansi) {+ String table = fullTable("id_str_qb_" + ansi);+ String partitionValue = "a\"b\\c";+ recreateTable(+ spark,+ table,+ "(id INT, region STRING)",+ "region",+ // Spark SQL string: \" → ", \\ → \+ "INSERT INTO " + table + " SELECT id, 'a\\\"b\\\\c' FROM range(0, 20)");+ String stored = spark.sql("SELECT region FROM " + table + " LIMIT 1").first().getString(0);+ Assertions.assertEquals(+ partitionValue, stored, "INSERT must store the intended partition value");+ String where =+ PartitionUtils.getWhereClauseForPartitions(+ List.of(PartitionPath.of(List.of(new PartitionEntryImpl("region", partitionValue)))),+ new Column[] {column("region", Types.StringType.get())},+ new Transform[] {Transforms.identity("region")},+ SPARK_CATALOG_NAME);+ Assertions.assertEquals("(`region` = 'a\"b\\\\c')", where);+ callRewrite(spark, table, where);+ }++ private static void assertRewriteCallForIdentityDate(SparkSession spark, String ansi) {+ String table = fullTable("id_date_" + ansi);+ recreateTable(+ spark,+ table,+ "(id INT, dt DATE)",+ "dt",+ "INSERT INTO " + table + " SELECT id, DATE '2024-01-01' FROM range(0, 20)");+ String where =+ PartitionUtils.getWhereClauseForPartitions(+ List.of(PartitionPath.of(List.of(new PartitionEntryImpl("dt", "2024-01-01")))),+ new Column[] {column("dt", Types.DateType.get())},+ new Transform[] {Transforms.identity("dt")},+ SPARK_CATALOG_NAME);+ Assertions.assertEquals("(`dt` = DATE '2024-01-01')", where);+ callRewrite(spark, table, where);+ }++ private static void assertRewriteCallForIdentityTimestamp(SparkSession spark, String ansi) {+ String table = fullTable("id_ts_" + ansi);+ recreateTable(+ spark,+ table,+ "(id INT, ts TIMESTAMP)",+ "ts",+ "INSERT INTO " + table + " SELECT id, TIMESTAMP '2024-01-01 00:00:00' FROM range(0, 20)");+ String where =+ PartitionUtils.getWhereClauseForPartitions(+ List.of(PartitionPath.of(List.of(new PartitionEntryImpl("ts", "2024-01-01 00:00:00")))),+ new Column[] {column("ts", Types.TimestampType.withoutTimeZone())},+ new Transform[] {Transforms.identity("ts")},+ SPARK_CATALOG_NAME);+ Assertions.assertEquals("(`ts` = TIMESTAMP '2024-01-01 00:00:00')", where);+ callRewrite(spark, table, where);+ }++ private static void assertRewriteCallForDays(SparkSession spark, String ansi) {+ String table = fullTable("days_" + ansi);+ recreateTable(+ spark,+ table,+ "(id INT, ts TIMESTAMP)",+ "days(ts)",+ "INSERT INTO " + table + " SELECT id, TIMESTAMP '2026-03-18 12:00:00' FROM range(0, 20)");+ Column[] columns = new Column[] {column("ts", Types.TimestampType.withoutTimeZone())};+ Transform[] partitioning = new Transform[] {Transforms.day("ts")};++ String where =+ PartitionUtils.getWhereClauseForPartitions(+ List.of(PartitionPath.of(List.of(new PartitionEntryImpl("ts_day", "2026-03-18")))),+ columns,+ partitioning,+ SPARK_CATALOG_NAME);+ Assertions.assertEquals(+ "(`" + SPARK_CATALOG_NAME + "`.system.days(`ts`) = DATE \'2026-03-18\')", where);+ callRewrite(spark, table, where);+ }++ private static void assertRewriteCallForYears(SparkSession spark, String ansi) {+ assertTemporalIntRewrite(spark, "years_" + ansi, "years(ts)", Transforms.year("ts"));+ }++ private static void assertRewriteCallForMonths(SparkSession spark, String ansi) {+ assertTemporalIntRewrite(spark, "months_" + ansi, "months(ts)", Transforms.month("ts"));+ }++ private static void assertRewriteCallForHours(SparkSession spark, String ansi) {+ assertTemporalIntRewrite(spark, "hours_" + ansi, "hours(ts)", Transforms.hour("ts"));+ }++ private static void assertTemporalIntRewrite(+ SparkSession spark, String tableSuffix, String partitionBy, Transform transform) {+ String table = fullTable(tableSuffix);+ recreateTable(+ spark,+ table,+ "(id INT, ts TIMESTAMP)",+ partitionBy,+ "INSERT INTO " + table + " SELECT id, TIMESTAMP '2026-03-18 12:00:00' FROM range(0, 20)");+ Row partition = spark.sql("SELECT partition FROM " + table + ".partitions LIMIT 1").first();+ Row partitionStruct = partition.getStruct(0);+ String fieldName = partitionStruct.schema().fields()[0].name();+ String value = String.valueOf(partitionStruct.get(0));+ String functionName = partitionBy.substring(0, partitionBy.indexOf('('));+ String where =+ PartitionUtils.getWhereClauseForPartitions(+ List.of(PartitionPath.of(List.of(new PartitionEntryImpl(fieldName, value)))),+ new Column[] {column("ts", Types.TimestampType.withoutTimeZone())},+ new Transform[] {transform},+ SPARK_CATALOG_NAME);+ Assertions.assertEquals(+ "(`" + SPARK_CATALOG_NAME + "`.system." + functionName + "(`ts`) = " + value + ")", where);+ callRewrite(spark, table, where);+ }++ private static void assertRewriteCallForBucket(SparkSession spark, String ansi) {+ String table = fullTable("bucket_" + ansi);+ recreateTable(+ spark,+ table,+ "(id INT, user_id BIGINT)",+ "bucket(16, user_id)",+ "INSERT INTO " + table + " SELECT id, 42 FROM range(0, 20)");+ Row partitionStruct =+ spark.sql("SELECT partition FROM " + table + ".partitions LIMIT 1").first().getStruct(0);+ String value = String.valueOf(partitionStruct.get(0));+ String where =+ PartitionUtils.getWhereClauseForPartitions(+ List.of(+ PartitionPath.of(+ List.of(+ new PartitionEntryImpl(+ partitionStruct.schema().fields()[0].name(), value)))),+ new Column[] {column("user_id", Types.LongType.get())},+ new Transform[] {Transforms.bucket(16, new String[] {"user_id"})},+ SPARK_CATALOG_NAME);+ Assertions.assertEquals(+ "(`" + SPARK_CATALOG_NAME + "`.system.bucket(16, `user_id`) = " + value + ")", where);+ callRewrite(spark, table, where);+ }++ private static void assertRewriteCallForTruncate(SparkSession spark, String ansi) {+ String table = fullTable("trunc_" + ansi);+ recreateTable(+ spark,+ table,+ "(id INT, country STRING)",+ "truncate(3, country)",+ "INSERT INTO " + table + " SELECT id, 'usaxxx' FROM range(0, 20)");+ String where =+ PartitionUtils.getWhereClauseForPartitions(+ List.of(PartitionPath.of(List.of(new PartitionEntryImpl("country_trunc", "usa")))),+ new Column[] {column("country", Types.StringType.get())},+ new Transform[] {Transforms.truncate(3, "country")},+ SPARK_CATALOG_NAME);+ Assertions.assertEquals(+ "(`" + SPARK_CATALOG_NAME + "`.system.truncate(3, `country`) = 'usa')", where);+ callRewrite(spark, table, where);+ }++ private static void assertRewriteCallForStructDay(SparkSession spark, String ansi) {+ assertStructTemporalRewrite(+ spark,+ "struct_day_" + ansi,+ "days(event.ts)",+ Transforms.day(new String[] {"event", "ts"}),+ "(`" + SPARK_CATALOG_NAME + "`.system.days(`event`.`ts`) = DATE '2026-03-18')",+ "2026-03-18");+ }++ private static void assertRewriteCallForStructYear(SparkSession spark, String ansi) {+ assertStructTemporalIntRewrite(+ spark,+ "struct_year_" + ansi,+ "years(event.ts)",+ Transforms.year(new String[] {"event", "ts"}));+ }++ private static void assertRewriteCallForStructMonth(SparkSession spark, String ansi) {+ assertStructTemporalIntRewrite(+ spark,+ "struct_month_" + ansi,+ "months(event.ts)",+ Transforms.month(new String[] {"event", "ts"}));+ }++ private static void assertRewriteCallForStructHour(SparkSession spark, String ansi) {+ assertStructTemporalIntRewrite(+ spark,+ "struct_hour_" + ansi,+ "hours(event.ts)",+ Transforms.hour(new String[] {"event", "ts"}));+ }++ private static void assertStructTemporalRewrite(+ SparkSession spark,+ String tableSuffix,+ String partitionBy,+ Transform transform,+ String expectedWhere,+ String partitionValue) {+ String table = fullTable(tableSuffix);+ recreateStructTsTable(spark, table, partitionBy);+ String where =+ PartitionUtils.getWhereClauseForPartitions(+ List.of(PartitionPath.of(List.of(new PartitionEntryImpl("event.ts", partitionValue)))),+ new Column[] {eventStructColumn()},+ new Transform[] {transform},+ SPARK_CATALOG_NAME);+ Assertions.assertEquals(expectedWhere, where);+ callRewrite(spark, table, where);+ }++ private static void assertStructTemporalIntRewrite(+ SparkSession spark, String tableSuffix, String partitionBy, Transform transform) {+ String table = fullTable(tableSuffix);+ recreateStructTsTable(spark, table, partitionBy);+ Row partitionStruct =+ spark.sql("SELECT partition FROM " + table + ".partitions LIMIT 1").first().getStruct(0);+ String value = String.valueOf(partitionStruct.get(0));+ String functionName = partitionBy.substring(0, partitionBy.indexOf('('));+ String where =+ PartitionUtils.getWhereClauseForPartitions(+ List.of(PartitionPath.of(List.of(new PartitionEntryImpl("event.ts", value)))),+ new Column[] {eventStructColumn()},+ new Transform[] {transform},+ SPARK_CATALOG_NAME);+ Assertions.assertEquals(+ "(`" + SPARK_CATALOG_NAME + "`.system." + functionName + "(`event`.`ts`) = " + value + ")",+ where);+ callRewrite(spark, table, where);+ }++ private static void assertRewriteCallForStructBucket(SparkSession spark, String ansi) {+ String table = fullTable("struct_bucket_" + ansi);+ spark.sql("CREATE NAMESPACE IF NOT EXISTS " + SPARK_CATALOG_NAME + ".db");+ spark.sql("DROP TABLE IF EXISTS " + table);+ spark.sql(+ "CREATE TABLE "+ + table+ + " (id INT, event STRUCT<uid: BIGINT>) USING iceberg "+ + "PARTITIONED BY (bucket(8, event.uid))");+ spark.sql("INSERT INTO " + table + " SELECT id, named_struct('uid', 42L) FROM range(0, 20)");+ Row partitionStruct =+ spark.sql("SELECT partition FROM " + table + ".partitions LIMIT 1").first().getStruct(0);+ String value = String.valueOf(partitionStruct.get(0));+ String where =+ PartitionUtils.getWhereClauseForPartitions(+ List.of(PartitionPath.of(List.of(new PartitionEntryImpl("event.uid_bucket", value)))),+ new Column[] {+ column(+ "event",+ Types.StructType.of(+ Types.StructType.Field.notNullField("uid", Types.LongType.get())))+ },+ new Transform[] {Transforms.bucket(8, new String[][] {new String[] {"event", "uid"}})},+ SPARK_CATALOG_NAME);+ Assertions.assertEquals(+ "(`" + SPARK_CATALOG_NAME + "`.system.bucket(8, `event`.`uid`) = " + value + ")", where);+ callRewrite(spark, table, where);+ }++ private static void assertRewriteCallForStructTruncate(SparkSession spark, String ansi) {+ String table = fullTable("struct_trunc_" + ansi);+ spark.sql("CREATE NAMESPACE IF NOT EXISTS " + SPARK_CATALOG_NAME + ".db");+ spark.sql("DROP TABLE IF EXISTS " + table);+ spark.sql(+ "CREATE TABLE "+ + table+ + " (id INT, event STRUCT<loc: STRING>) USING iceberg "+ + "PARTITIONED BY (truncate(2, event.loc))");+ spark.sql("INSERT INTO " + table + " SELECT id, named_struct('loc', 'abxx') FROM range(0, 20)");+ String where =+ PartitionUtils.getWhereClauseForPartitions(+ List.of(PartitionPath.of(List.of(new PartitionEntryImpl("event.loc_trunc", "ab")))),+ new Column[] {+ column(+ "event",+ Types.StructType.of(+ Types.StructType.Field.notNullField("loc", Types.StringType.get())))+ },+ new Transform[] {Transforms.truncate(2, new String[] {"event", "loc"})},+ SPARK_CATALOG_NAME);+ Assertions.assertEquals(+ "(`" + SPARK_CATALOG_NAME + "`.system.truncate(2, `event`.`loc`) = 'ab')", where);+ callRewrite(spark, table, where);+ }++ private static void assertRewriteCallForStructIdentityTimestamp(SparkSession spark, String ansi) {+ String table = fullTable("struct_id_ts_" + ansi);+ recreateStructTsTable(spark, table, "event.ts");+ String where =+ PartitionUtils.getWhereClauseForPartitions(+ List.of(+ PartitionPath.of(+ List.of(new PartitionEntryImpl("event.ts", "2026-03-18 12:00:00")))),+ new Column[] {eventStructColumn()},+ new Transform[] {Transforms.identity(new String[] {"event", "ts"})},+ SPARK_CATALOG_NAME);+ Assertions.assertEquals("(`event`.`ts` = TIMESTAMP '2026-03-18 12:00:00')", where);+ callRewrite(spark, table, where);+ }++ private static void assertRewriteCallForStructIdentityInt(SparkSession spark, String ansi) {+ String table = fullTable("struct_id_int_" + ansi);+ spark.sql("CREATE NAMESPACE IF NOT EXISTS " + SPARK_CATALOG_NAME + ".db");+ spark.sql("DROP TABLE IF EXISTS " + table);+ spark.sql(+ "CREATE TABLE "+ + table+ + " (id INT, event STRUCT<code: INT>) USING iceberg "+ + "PARTITIONED BY (event.code)");+ spark.sql("INSERT INTO " + table + " SELECT id, named_struct('code', 7) FROM range(0, 20)");+ String where =+ PartitionUtils.getWhereClauseForPartitions(+ List.of(PartitionPath.of(List.of(new PartitionEntryImpl("event.code", "7")))),+ new Column[] {+ column(+ "event",+ Types.StructType.of(+ Types.StructType.Field.notNullField("code", Types.IntegerType.get())))+ },+ new Transform[] {Transforms.identity(new String[] {"event", "code"})},+ SPARK_CATALOG_NAME);+ Assertions.assertEquals("(`event`.`code` = 7)", where);+ callRewrite(spark, table, where);+ }++ /**+ * Nested hyphenated field {@code user-id} must be backtick-quoted in the predicate; otherwise+ * Spark parses {@code event.user-id} as subtraction.+ */+ private static void assertRewriteCallForStructIdentityHyphenatedInt(+ SparkSession spark, String ansi) {+ String table = fullTable("struct_id_hyphen_" + ansi);+ spark.sql("CREATE NAMESPACE IF NOT EXISTS " + SPARK_CATALOG_NAME + ".db");+ spark.sql("DROP TABLE IF EXISTS " + table);+ spark.sql(+ "CREATE TABLE "+ + table+ + " (id INT, event STRUCT<`user-id`: INT>) USING iceberg "+ + "PARTITIONED BY (event.`user-id`)");+ spark.sql("INSERT INTO " + table + " SELECT id, named_struct('user-id', 7) FROM range(0, 20)");+ String where =+ PartitionUtils.getWhereClauseForPartitions(+ List.of(PartitionPath.of(List.of(new PartitionEntryImpl("event.user-id", "7")))),+ new Column[] {+ column(+ "event",+ Types.StructType.of(+ Types.StructType.Field.notNullField("user-id", Types.IntegerType.get())))+ },+ new Transform[] {Transforms.identity(new String[] {"event", "user-id"})},+ SPARK_CATALOG_NAME);+ Assertions.assertEquals("(`event`.`user-id` = 7)", where);+ callRewrite(spark, table, where);+ }++ /**+ * System function names stay unquoted; only the hyphenated nested field path is backtick-quoted.+ */+ private static void assertRewriteCallForStructDayHyphenated(SparkSession spark, String ansi) {+ String table = fullTable("struct_day_hyphen_" + ansi);+ spark.sql("CREATE NAMESPACE IF NOT EXISTS " + SPARK_CATALOG_NAME + ".db");+ spark.sql("DROP TABLE IF EXISTS " + table);+ spark.sql(+ "CREATE TABLE "+ + table+ + " (id INT, event STRUCT<`event-ts`: TIMESTAMP>) USING iceberg "+ + "PARTITIONED BY (days(event.`event-ts`))");+ spark.sql(+ "INSERT INTO "+ + table+ + " SELECT id, named_struct('event-ts', TIMESTAMP '2026-03-18 12:00:00') FROM range(0,"+ + " 20)");+ String where =+ PartitionUtils.getWhereClauseForPartitions(+ List.of(+ PartitionPath.of(List.of(new PartitionEntryImpl("event.event-ts", "2026-03-18")))),+ new Column[] {+ column(+ "event",+ Types.StructType.of(+ Types.StructType.Field.notNullField(+ "event-ts", Types.TimestampType.withoutTimeZone())))+ },+ new Transform[] {Transforms.day(new String[] {"event", "event-ts"})},+ SPARK_CATALOG_NAME);+ Assertions.assertEquals(+ "(`" + SPARK_CATALOG_NAME + "`.system.days(`event`.`event-ts`) = DATE '2026-03-18')",+ where);+ callRewrite(spark, table, where);+ }++ /** Struct-in-struct identity: {@code `event`.`meta`.`user-id`}. */+ private static void assertRewriteCallForStructInStructIdentityHyphenated(+ SparkSession spark, String ansi) {+ String table = fullTable("struct2_id_hyphen_" + ansi);+ spark.sql("CREATE NAMESPACE IF NOT EXISTS " + SPARK_CATALOG_NAME + ".db");+ spark.sql("DROP TABLE IF EXISTS " + table);+ spark.sql(+ "CREATE TABLE "+ + table+ + " (id INT, event STRUCT<meta: STRUCT<`user-id`: INT>>) USING iceberg "+ + "PARTITIONED BY (event.meta.`user-id`)");+ spark.sql(+ "INSERT INTO "+ + table+ + " SELECT id, named_struct('meta', named_struct('user-id', 7)) FROM range(0, 20)");+ String where =+ PartitionUtils.getWhereClauseForPartitions(+ List.of(PartitionPath.of(List.of(new PartitionEntryImpl("event.meta.user-id", "7")))),+ new Column[] {+ column(+ "event",+ Types.StructType.of(+ Types.StructType.Field.notNullField(+ "meta",+ Types.StructType.of(+ Types.StructType.Field.notNullField(+ "user-id", Types.IntegerType.get())))))+ },+ new Transform[] {Transforms.identity(new String[] {"event", "meta", "user-id"})},+ SPARK_CATALOG_NAME);+ Assertions.assertEquals("(`event`.`meta`.`user-id` = 7)", where);+ callRewrite(spark, table, where);+ }++ /** Struct-in-struct day: path quoted, {@code system.days} bare. */+ private static void assertRewriteCallForStructInStructDayHyphenated(+ SparkSession spark, String ansi) {+ String table = fullTable("struct2_day_hyphen_" + ansi);+ spark.sql("CREATE NAMESPACE IF NOT EXISTS " + SPARK_CATALOG_NAME + ".db");+ spark.sql("DROP TABLE IF EXISTS " + table);+ spark.sql(+ "CREATE TABLE "+ + table+ + " (id INT, event STRUCT<meta: STRUCT<`event-ts`: TIMESTAMP>>) USING iceberg "+ + "PARTITIONED BY (days(event.meta.`event-ts`))");+ spark.sql(+ "INSERT INTO "+ + table+ + " SELECT id, named_struct('meta', named_struct('event-ts', TIMESTAMP '2026-03-18"+ + " 12:00:00')) FROM range(0, 20)");+ String where =+ PartitionUtils.getWhereClauseForPartitions(+ List.of(+ PartitionPath.of(+ List.of(new PartitionEntryImpl("event.meta.event-ts", "2026-03-18")))),+ new Column[] {+ column(+ "event",+ Types.StructType.of(+ Types.StructType.Field.notNullField(+ "meta",+ Types.StructType.of(+ Types.StructType.Field.notNullField(+ "event-ts", Types.TimestampType.withoutTimeZone())))))+ },+ new Transform[] {Transforms.day(new String[] {"event", "meta", "event-ts"})},+ SPARK_CATALOG_NAME);+ Assertions.assertEquals(+ "(`" + SPARK_CATALOG_NAME + "`.system.days(`event`.`meta`.`event-ts`) = DATE '2026-03-18')",+ where);+ callRewrite(spark, table, where);+ }++ /** Same quoting contract for {@code bucket}: path quoted, {@code system.bucket} bare. */+ private static void assertRewriteCallForStructBucketHyphenated(SparkSession spark, String ansi) {+ String table = fullTable("struct_bucket_hyphen_" + ansi);+ spark.sql("CREATE NAMESPACE IF NOT EXISTS " + SPARK_CATALOG_NAME + ".db");+ spark.sql("DROP TABLE IF EXISTS " + table);+ spark.sql(+ "CREATE TABLE "+ + table+ + " (id INT, event STRUCT<`user-id`: INT>) USING iceberg "+ + "PARTITIONED BY (bucket(8, event.`user-id`))");+ spark.sql("INSERT INTO " + table + " SELECT id, named_struct('user-id', 42) FROM range(0, 20)");+ Row partitionStruct =+ spark.sql("SELECT partition FROM " + table + ".partitions LIMIT 1").first().getStruct(0);+ String value = String.valueOf(partitionStruct.get(0));+ String where =+ PartitionUtils.getWhereClauseForPartitions(+ List.of(+ PartitionPath.of(List.of(new PartitionEntryImpl("event.user-id_bucket", value)))),+ new Column[] {+ column(+ "event",+ Types.StructType.of(+ Types.StructType.Field.notNullField("user-id", Types.IntegerType.get())))+ },+ new Transform[] {+ Transforms.bucket(8, new String[][] {new String[] {"event", "user-id"}})+ },+ SPARK_CATALOG_NAME);+ Assertions.assertEquals(+ "(`" + SPARK_CATALOG_NAME + "`.system.bucket(8, `event`.`user-id`) = " + value + ")",+ where);+ callRewrite(spark, table, where);+ }++ private static void recreateStructTsTable(SparkSession spark, String table, String partitionBy) {+ spark.sql("CREATE NAMESPACE IF NOT EXISTS " + SPARK_CATALOG_NAME + ".db");+ spark.sql("DROP TABLE IF EXISTS " + table);+ spark.sql(+ "CREATE TABLE "+ + table+ + " (id INT, event STRUCT<ts: TIMESTAMP>) USING iceberg "+ + "PARTITIONED BY ("+ + partitionBy+ + ")");+ spark.sql(+ "INSERT INTO "+ + table+ + " SELECT id, named_struct('ts', TIMESTAMP '2026-03-18 12:00:00') FROM range(0, 20)");+ }++ private static Column eventStructColumn() {+ return column(+ "event",+ Types.StructType.of(+ Types.StructType.Field.notNullField("ts", Types.TimestampType.withoutTimeZone())));+ }++ private static String fullTable(String suffix) {+ return SPARK_CATALOG_NAME + ".db.pu_" + suffix;+ }++ private static String ansiFlag(boolean ansiEnabled, boolean doubleQuotedIds) {+ return (ansiEnabled ? "e1" : "e0") + "_" + (doubleQuotedIds ? "d1" : "d0");+ }++ private static void recreateTable(+ SparkSession spark, String table, String columns, String partitionBy, String insertSql) {+ spark.sql("CREATE NAMESPACE IF NOT EXISTS " + SPARK_CATALOG_NAME + ".db");+ spark.sql("DROP TABLE IF EXISTS " + table);+ spark.sql(+ "CREATE TABLE "+ + table+ + " "+ + columns+ + " USING iceberg PARTITIONED BY ("+ + partitionBy+ + ")");+ spark.sql(insertSql);+ }++ private static void callRewrite(SparkSession spark, String fullTableName, String whereClause) {+ String tableArg = fullTableName.substring(SPARK_CATALOG_NAME.length() + 1);+ // Mirror IcebergRewriteDataFilesJob.buildProcedureCall / IcebergJobUtils escaping.+ String sql =+ "CALL "+ + SPARK_CATALOG_NAME+ + ".system.rewrite_data_files(table => '"+ + escapeSparkCallStringArg(tableArg)+ + "', strategy => 'binpack', where => '"+ + escapeSparkCallStringArg(whereClause)+ + "')";+ Assertions.assertDoesNotThrow(() -> spark.sql(sql).collect());+ }++ /** Same as {@code IcebergJobUtils.escapeSparkCallStringArg}. */+ private static String escapeSparkCallStringArg(String value) {+ return value == null ? null : value.replace("\\", "\\\\").replace("'", "\\'");+ }+private static GravitinoMetalake loadOrCreateMetalake(GravitinoAdminClient client, String metalakeName) {try {@@ -226,7 +911,7 @@ public class TestBuiltinIcebergRewriteDataFiles {private static void runWithSparkAndMetalake(SparkMetalakeConsumer consumer) throws Exception {SparkSession spark = createSparkSession();- try (GravitinoAdminClient client = GravitinoAdminClient.builder(SERVER_URI).build()) {+ try (GravitinoAdminClient client = createGravitinoClient()) {GravitinoMetalake metalake = loadOrCreateMetalake(client, METALAKE_NAME);consumer.accept(spark, metalake);} finally {@@ -234,6 +919,20 @@ public class TestBuiltinIcebergRewriteDataFiles {}}+ private static GravitinoAdminClient createGravitinoClient() {+ if (StringUtils.isNotBlank(BASIC_AUTH_USER) && StringUtils.isNotBlank(BASIC_AUTH_PASSWORD)) {+ return GravitinoAdminClient.builder(SERVER_URI)+ .withBasicAuth(BASIC_AUTH_USER, BASIC_AUTH_PASSWORD)+ .build();+ }+ return GravitinoAdminClient.builder(SERVER_URI).build();+ }++ private static String envOrDefault(String key, String defaultValue) {+ String value = System.getenv(key);+ return value == null ? defaultValue : value;+ }+private static void submitCompactionJob(GravitinoMetalake metalake, Map<String, String> jobConf) {submitJob(metalake, JOB_TEMPLATE_NAME, jobConf);}@@ -380,18 +1079,54 @@ public class TestBuiltinIcebergRewriteDataFiles {}private static SparkSession createSparkSession() {- return SparkSession.builder()- .master("local[2]")- .appName("builtin-iceberg-rewrite-data-files-it")- .config(- "spark.sql.extensions",- "org.apache.iceberg.spark.extensions.IcebergSparkSessionExtensions")- .config("spark.sql.catalog." + SPARK_CATALOG_NAME, "org.apache.iceberg.spark.SparkCatalog")- .config("spark.sql.catalog." + SPARK_CATALOG_NAME + ".type", "rest")- .config("spark.sql.catalog." + SPARK_CATALOG_NAME + ".cache-enabled", "false")- .config("spark.sql.catalog." + SPARK_CATALOG_NAME + ".uri", ICEBERG_REST_URI)- .config("spark.sql.catalog." + SPARK_CATALOG_NAME + ".warehouse", WAREHOUSE_LOCATION)- .getOrCreate();+ // Resolve template keys and values the same way JobTemplateResolver does; keys also carry+ // {{catalog_name}} (e.g. spark.sql.catalog.{{catalog_name}}).+ Map<String, String> sparkConfigs = new HashMap<>();+ for (Map.Entry<String, String> entry :+ IcebergSparkConfigUtils.buildTemplateSparkConfigs().entrySet()) {+ String key = resolveTemplatePlaceholders(entry.getKey());+ String value = resolveTemplatePlaceholders(entry.getValue());+ if (StringUtils.isNotBlank(value)) {+ sparkConfigs.put(key, value);+ }+ }+ Assertions.assertEquals(+ "org.apache.iceberg.spark.SparkCatalog",+ sparkConfigs.get("spark.sql.catalog." + SPARK_CATALOG_NAME),+ "resolved template must register " + SPARK_CATALOG_NAME + " before starting Spark");+ // Template configs may already carry defaultCatalog; spark_conf overlay must not. ensure owns+ // the key from catalog_name (same as IcebergRewriteDataFilesJob / IcebergMaintenanceJob).+ sparkConfigs.remove("spark.sql.defaultCatalog");+ IcebergSparkConfigUtils.ensureIcebergCatalogConfigs(sparkConfigs, SPARK_CATALOG_NAME);+ // IT-only extras (not part of the stock template).+ sparkConfigs.put("spark.sql.catalog." + SPARK_CATALOG_NAME + ".cache-enabled", "false");+ if (StringUtils.isNotBlank(BASIC_AUTH_USER) && StringUtils.isNotBlank(BASIC_AUTH_PASSWORD)) {+ sparkConfigs.put("spark.sql.catalog." + SPARK_CATALOG_NAME + ".rest.auth.type", "basic");+ sparkConfigs.put(+ "spark.sql.catalog." + SPARK_CATALOG_NAME + ".rest.auth.basic.username", BASIC_AUTH_USER);+ sparkConfigs.put(+ "spark.sql.catalog." + SPARK_CATALOG_NAME + ".rest.auth.basic.password",+ BASIC_AUTH_PASSWORD);+ }++ SparkSession.Builder builder =+ SparkSession.builder().appName("builtin-iceberg-rewrite-data-files-it");+ sparkConfigs.forEach(builder::config);+ return builder.getOrCreate();+ }++ /** Mirrors production template substitution for both config keys and values. */+ private static String resolveTemplatePlaceholders(String template) {+ return template+ .replace("{{catalog_name}}", SPARK_CATALOG_NAME)+ .replace("{{catalog_type}}", "rest")+ .replace("{{catalog_uri}}", ICEBERG_REST_URI)+ .replace("{{warehouse_location}}", WAREHOUSE_LOCATION)+ .replace("{{spark_master:-}}", "local[2]")+ .replace("{{spark_executor_instances:-1}}", "1")+ .replace("{{spark_executor_cores:-1}}", "1")+ .replace("{{spark_executor_memory:-1g}}", "1g")+ .replace("{{spark_driver_memory:-1g}}", "1g");}private static void createPartitionTableAndInsertData(SparkSession spark, String fullTableName) {diff --git a/maintenance/optimizer/src/test/java/org/apache/gravitino/maintenance/optimizer/recommender/job/TestGravitinoCompactionJobAdapter.java b/maintenance/optimizer/src/test/java/org/apache/gravitino/maintenance/optimizer/recommender/job/TestGravitinoCompactionJobAdapter.javaindex dbad1c111b..2e9bd15ef5 100644--- a/maintenance/optimizer/src/test/java/org/apache/gravitino/maintenance/optimizer/recommender/job/TestGravitinoCompactionJobAdapter.java+++ b/maintenance/optimizer/src/test/java/org/apache/gravitino/maintenance/optimizer/recommender/job/TestGravitinoCompactionJobAdapter.java@@ -22,9 +22,15 @@ package org.apache.gravitino.maintenance.optimizer.recommender.job;import java.util.List;import java.util.Map;import org.apache.gravitino.NameIdentifier;+import org.apache.gravitino.dto.rel.ColumnDTO;+import org.apache.gravitino.maintenance.optimizer.api.common.PartitionPath;+import org.apache.gravitino.maintenance.optimizer.common.PartitionEntryImpl;+import org.apache.gravitino.maintenance.optimizer.common.conf.OptimizerConfig;import org.apache.gravitino.maintenance.optimizer.recommender.handler.compaction.CompactionJobContext;import org.apache.gravitino.rel.Column;import org.apache.gravitino.rel.expressions.transforms.Transform;+import org.apache.gravitino.rel.expressions.transforms.Transforms;+import org.apache.gravitino.rel.types.Types;import org.junit.jupiter.api.Assertions;import org.junit.jupiter.api.Test;@@ -56,6 +62,108 @@ public class TestGravitinoCompactionJobAdapter {jobAdapter.jobConfig(mockCompactionJobContext("sort", "zorder(c1,c2)")));}+ @Test+ public void testWhereClauseForDayPartitionUsesIsoDateFromStatsPath() {+ // Mirrors CLI submit-strategy-jobs: update-stats stores day as ISO date, adapter builds where.+ Column[] columns =+ new Column[] {+ ColumnDTO.builder()+ .withName("ts")+ .withDataType(Types.TimestampType.withoutTimeZone())+ .build()+ };+ Transform[] partitioning = new Transform[] {Transforms.day("ts")};+ List<PartitionPath> partitions =+ List.of(PartitionPath.of(List.of(new PartitionEntryImpl("ts_day", "2026-01-01"))));++ Map<String, String> conf =+ new GravitinoCompactionJobAdapter()+ .jobConfig(+ new CompactionJobContext(+ NameIdentifier.of("catalog", "db", "table"),+ Map.of("target_file_size_bytes", "1073741824"),+ "compaction-job-template",+ "binpack",+ "",+ columns,+ partitioning,+ partitions));++ Assertions.assertEquals(+ "(`catalog`.system.days(`ts`) = DATE '2026-01-01')", conf.get("where_clause"));+ }++ @Test+ public void testWhereClauseUsesSubmitterSparkCatalogWhenNamesDiffer() {+ // Gravitino table catalog "lake" vs Spark CALL catalog_name "ice" from jobSubmitterConfig.+ Column[] columns =+ new Column[] {+ ColumnDTO.builder()+ .withName("ts")+ .withDataType(Types.TimestampType.withoutTimeZone())+ .build()+ };+ Transform[] partitioning = new Transform[] {Transforms.day("ts")};+ List<PartitionPath> partitions =+ List.of(PartitionPath.of(List.of(new PartitionEntryImpl("ts_day", "2026-01-01"))));+ CompactionJobContext context =+ new CompactionJobContext(+ NameIdentifier.of("lake", "db", "events"),+ Map.of("target_file_size_bytes", "1073741824"),+ "compaction-job-template",+ "binpack",+ "",+ columns,+ partitioning,+ partitions);+ OptimizerConfig config =+ new OptimizerConfig(+ Map.of(OptimizerConfig.JOB_SUBMITTER_CONFIG_PREFIX + "catalog_name", "ice"));++ Map<String, String> conf =+ GravitinoJobSubmitter.buildJobConfig(config, context, new GravitinoCompactionJobAdapter());++ Assertions.assertEquals("ice", conf.get("catalog_name"));+ Assertions.assertEquals(+ "(`ice`.system.days(`ts`) = DATE '2026-01-01')", conf.get("where_clause"));+ }++ @Test+ public void testStructInStructHyphenatedFieldWhere() {+ Column[] columns =+ new Column[] {+ ColumnDTO.builder()+ .withName("event")+ .withDataType(+ Types.StructType.of(+ Types.StructType.Field.notNullField(+ "meta",+ Types.StructType.of(+ Types.StructType.Field.notNullField(+ "user-id", Types.IntegerType.get())))))+ .build()+ };+ Transform[] partitioning =+ new Transform[] {Transforms.identity(new String[] {"event", "meta", "user-id"})};+ List<PartitionPath> partitions =+ List.of(PartitionPath.of(List.of(new PartitionEntryImpl("event.meta.user-id", "7"))));++ Map<String, String> conf =+ new GravitinoCompactionJobAdapter()+ .jobConfig(+ new CompactionJobContext(+ NameIdentifier.of("catalog", "db", "events"),+ Map.of("target_file_size_bytes", "1073741824"),+ "compaction-job-template",+ "binpack",+ "",+ columns,+ partitioning,+ partitions));++ Assertions.assertEquals("(`event`.`meta`.`user-id` = 7)", conf.get("where_clause"));+ }+private CompactionJobContext mockCompactionJobContext(String rewriteStrategy, String sortOrder) {String jobTemplateName = "compaction-job-template";Column[] columns = new Column[0];diff --git a/maintenance/optimizer/src/test/java/org/apache/gravitino/maintenance/optimizer/recommender/job/TestPartitionUtils.java b/maintenance/optimizer/src/test/java/org/apache/gravitino/maintenance/optimizer/recommender/job/TestPartitionUtils.javaindex 6ff4859513..74ca237c18 100644--- a/maintenance/optimizer/src/test/java/org/apache/gravitino/maintenance/optimizer/recommender/job/TestPartitionUtils.java+++ b/maintenance/optimizer/src/test/java/org/apache/gravitino/maintenance/optimizer/recommender/job/TestPartitionUtils.java@@ -33,19 +33,76 @@ import org.junit.jupiter.api.Test;public class TestPartitionUtils {+ private static final String CATALOG = "ice";+private static Column column(String name, org.apache.gravitino.rel.types.Type type) {return ColumnDTO.builder().withName(name).withDataType(type).build();}+ private static Column eventStructColumn() {+ return column(+ "event",+ Types.StructType.of(+ Types.StructType.Field.notNullField("ts", Types.TimestampType.withoutTimeZone())));+ }++ /** {@code event STRUCT<meta: STRUCT<user-id: INT>>}. */+ private static Column eventMetaUserIdStructColumn() {+ return column(+ "event",+ Types.StructType.of(+ Types.StructType.Field.notNullField(+ "meta",+ Types.StructType.of(+ Types.StructType.Field.notNullField("user-id", Types.IntegerType.get())))));+ }++ /** {@code event STRUCT<meta: STRUCT<event-ts: TIMESTAMP>>}. */+ private static Column eventMetaEventTsStructColumn() {+ return column(+ "event",+ Types.StructType.of(+ Types.StructType.Field.notNullField(+ "meta",+ Types.StructType.of(+ Types.StructType.Field.notNullField(+ "event-ts", Types.TimestampType.withoutTimeZone())))));+ }+@Testvoid testIdentityStringPartition() {List<PartitionEntry> partitions = Arrays.asList(new PartitionEntryImpl("colA", "O'Hara"));Column[] columns = new Column[] {column("colA", Types.StringType.get())};Transform[] transforms = new Transform[] {Transforms.identity("colA")};- String where = PartitionUtils.getWhereClauseForPartition(partitions, columns, transforms);+ String where =+ PartitionUtils.getWhereClauseForPartition(partitions, columns, transforms, CATALOG);++ Assertions.assertEquals("`colA` = 'O\\'Hara'", where);+ }++ @Test+ void testIdentityIntegerPartition() {+ List<PartitionEntry> partitions = Arrays.asList(new PartitionEntryImpl("part", "7"));+ Column[] columns = new Column[] {column("part", Types.IntegerType.get())};+ Transform[] transforms = new Transform[] {Transforms.identity("part")};++ String where =+ PartitionUtils.getWhereClauseForPartition(partitions, columns, transforms, CATALOG);++ Assertions.assertEquals("`part` = 7", where);+ }++ @Test+ void testIdentityBooleanPartition() {+ List<PartitionEntry> partitions = Arrays.asList(new PartitionEntryImpl("flag", "true"));+ Column[] columns = new Column[] {column("flag", Types.BooleanType.get())};+ Transform[] transforms = new Transform[] {Transforms.identity("flag")};++ String where =+ PartitionUtils.getWhereClauseForPartition(partitions, columns, transforms, CATALOG);- Assertions.assertEquals("colA = \"O'Hara\"", where);+ Assertions.assertEquals("`flag` = true", where);}@Test@@ -54,9 +111,11 @@ public class TestPartitionUtils {Column[] columns = new Column[] {column("colA", Types.StringType.get())};Transform[] transforms = new Transform[] {Transforms.identity("colA")};- String where = PartitionUtils.getWhereClauseForPartition(partitions, columns, transforms);+ String where =+ PartitionUtils.getWhereClauseForPartition(partitions, columns, transforms, CATALOG);- Assertions.assertEquals("colA = \"a\\\"b\\\\c\"", where);+ // One-level single-quoted literal escapes; CALL outer escaping is done by the job builder.+ Assertions.assertEquals("`colA` = 'a\"b\\\\c'", where);}@Test@@ -66,9 +125,60 @@ public class TestPartitionUtils {Column[] columns = new Column[] {column("ts", Types.TimestampType.withTimeZone())};Transform[] transforms = new Transform[] {Transforms.identity("ts")};- String where = PartitionUtils.getWhereClauseForPartition(partitions, columns, transforms);+ String where =+ PartitionUtils.getWhereClauseForPartition(partitions, columns, transforms, CATALOG);++ // Double-quoted typed literal survives CALL where => '...' embedding.+ Assertions.assertEquals("`ts` = TIMESTAMP '2024-01-01 00:00:00'", where);+ }++ @Test+ void testIdentityTimePartitionUsesSingleQuotedLiteral() {+ List<PartitionEntry> partitions = Arrays.asList(new PartitionEntryImpl("t", "12:34:56"));+ Column[] columns = new Column[] {column("t", Types.TimeType.get())};+ Transform[] transforms = new Transform[] {Transforms.identity("t")};++ String where =+ PartitionUtils.getWhereClauseForPartition(partitions, columns, transforms, CATALOG);- Assertions.assertEquals("ts = TIMESTAMP '2024-01-01 00:00:00'", where);+ Assertions.assertEquals("`t` = TIME '12:34:56'", where);+ }++ @Test+ void testIdentityTimestampPartitionEscapesQuotesAndBackslashes() {+ List<PartitionEntry> partitions =+ Arrays.asList(new PartitionEntryImpl("ts", "2024-01-01 00:00:00\"x\\y"));+ Column[] columns = new Column[] {column("ts", Types.TimestampType.withoutTimeZone())};+ Transform[] transforms = new Transform[] {Transforms.identity("ts")};++ String where =+ PartitionUtils.getWhereClauseForPartition(partitions, columns, transforms, CATALOG);++ Assertions.assertEquals("`ts` = TIMESTAMP '2024-01-01 00:00:00\"x\\\\y'", where);+ }++ @Test+ void testBucketPartitionUsesIcebergArgumentOrder() {+ List<PartitionEntry> partitions = Arrays.asList(new PartitionEntryImpl("bucket", "14"));+ Column[] columns = new Column[] {column("user_id", Types.LongType.get())};+ Transform[] transforms = new Transform[] {Transforms.bucket(16, new String[] {"user_id"})};++ String where =+ PartitionUtils.getWhereClauseForPartition(partitions, columns, transforms, CATALOG);++ Assertions.assertEquals("`ice`.system.bucket(16, `user_id`) = 14", where);+ }++ @Test+ void testTruncatePartitionUsesIcebergArgumentOrder() {+ List<PartitionEntry> partitions = Arrays.asList(new PartitionEntryImpl("trunc", "usa"));+ Column[] columns = new Column[] {column("country", Types.StringType.get())};+ Transform[] transforms = new Transform[] {Transforms.truncate(3, "country")};++ String where =+ PartitionUtils.getWhereClauseForPartition(partitions, columns, transforms, CATALOG);++ Assertions.assertEquals("`ice`.system.truncate(3, `country`) = 'usa'", where);}@Test@@ -82,16 +192,18 @@ public class TestPartitionUtils {Transform[] transforms =new Transform[] {Transforms.identity("colA"), Transforms.bucket(2, new String[] {"colB"})};- String where = PartitionUtils.getWhereClauseForPartition(partitions, columns, transforms);+ String where =+ PartitionUtils.getWhereClauseForPartition(partitions, columns, transforms, CATALOG);- Assertions.assertEquals("colA = \"abc\" AND bucket(colB, 2) = 1", where);+ Assertions.assertEquals("`colA` = 'abc' AND `ice`.system.bucket(2, `colB`) = 1", where);}@Testvoid testTruncateAndYearPartition() {+ // `ice`.system.years() compares to Iceberg years-since-1970 (2024 → 54), not a calendar year.List<PartitionEntry> partitions =Arrays.asList(- new PartitionEntryImpl("truncate", "prefix"), new PartitionEntryImpl("year", "2024"));+ new PartitionEntryImpl("truncate", "prefix"), new PartitionEntryImpl("year", "54"));Column[] columns =new Column[] {column("colC", Types.StringType.get()),@@ -100,9 +212,468 @@ public class TestPartitionUtils {Transform[] transforms =new Transform[] {Transforms.truncate(5, "colC"), Transforms.year("colD")};- String where = PartitionUtils.getWhereClauseForPartition(partitions, columns, transforms);+ String where =+ PartitionUtils.getWhereClauseForPartition(partitions, columns, transforms, CATALOG);- Assertions.assertEquals("truncate(colC, 5) = \"prefix\" AND year(colD) = 2024", where);+ Assertions.assertEquals(+ "`ice`.system.truncate(5, `colC`) = 'prefix' AND `ice`.system.years(`colD`) = 54", where);+ }++ @Test+ void testDayPartitionUsesIcebergDaysFunctionWithDateLiteral() {+ List<PartitionEntry> partitions = Arrays.asList(new PartitionEntryImpl("day", "2024-01-01"));+ Column[] columns = new Column[] {column("event_time", Types.TimestampType.withoutTimeZone())};+ Transform[] transforms = new Transform[] {Transforms.day("event_time")};++ String where =+ PartitionUtils.getWhereClauseForPartition(partitions, columns, transforms, CATALOG);++ // ISO only (DateTimeUtil.isoDateToDays); Iceberg Spark `ice`.system.days() returns DateType+ Assertions.assertEquals("`ice`.system.days(`event_time`) = DATE '2024-01-01'", where);+ }++ @Test+ void testDayPartitionOnNestedStructFieldResolvesTopLevelColumn() {+ // Real schemas expose struct column "event", while the transform path is event.ts.+ List<PartitionEntry> partitions =+ Arrays.asList(new PartitionEntryImpl("event.ts_day", "2026-03-18"));+ Column[] columns = new Column[] {eventStructColumn()};+ Transform[] transforms = new Transform[] {Transforms.day(new String[] {"event", "ts"})};++ String where =+ PartitionUtils.getWhereClauseForPartition(partitions, columns, transforms, CATALOG);++ Assertions.assertEquals("`ice`.system.days(`event`.`ts`) = DATE '2026-03-18'", where);+ }++ @Test+ void testIdentityPartitionOnNestedTimestampUsesTypedLiteral() {+ // Must resolve leaf TIMESTAMP type; falling back to STRUCT would emit a plain string literal.+ List<PartitionEntry> partitions =+ Arrays.asList(new PartitionEntryImpl("event.ts", "2026-03-18 12:00:00"));+ Column[] columns = new Column[] {eventStructColumn()};+ Transform[] transforms = new Transform[] {Transforms.identity(new String[] {"event", "ts"})};++ String where =+ PartitionUtils.getWhereClauseForPartition(partitions, columns, transforms, CATALOG);++ Assertions.assertEquals("`event`.`ts` = TIMESTAMP '2026-03-18 12:00:00'", where);+ }++ @Test+ void testIdentityPartitionOnNestedIntegerUsesBareLiteral() {+ List<PartitionEntry> partitions = Arrays.asList(new PartitionEntryImpl("event.id", "7"));+ Column[] columns =+ new Column[] {+ column(+ "event",+ Types.StructType.of(+ Types.StructType.Field.notNullField("id", Types.IntegerType.get())))+ };+ Transform[] transforms = new Transform[] {Transforms.identity(new String[] {"event", "id"})};++ String where =+ PartitionUtils.getWhereClauseForPartition(partitions, columns, transforms, CATALOG);++ Assertions.assertEquals("`event`.`id` = 7", where);+ }++ @Test+ void testIdentityNestedHyphenatedFieldIsBacktickQuoted() {+ // event.user-id without quotes parses as subtraction; quote each component.+ List<PartitionEntry> partitions = Arrays.asList(new PartitionEntryImpl("event.user-id", "7"));+ Column[] columns =+ new Column[] {+ column(+ "event",+ Types.StructType.of(+ Types.StructType.Field.notNullField("user-id", Types.IntegerType.get())))+ };+ Transform[] transforms =+ new Transform[] {Transforms.identity(new String[] {"event", "user-id"})};++ String where =+ PartitionUtils.getWhereClauseForPartition(partitions, columns, transforms, CATALOG);++ Assertions.assertEquals("`event`.`user-id` = 7", where);+ }++ @Test+ void testIdentityTopLevelHyphenatedFieldIsBacktickQuoted() {+ // Bare user-id is subtraction in Spark SQL; identity must emit `user-id`.+ List<PartitionEntry> partitions = Arrays.asList(new PartitionEntryImpl("user-id", "7"));+ Column[] columns = new Column[] {column("user-id", Types.IntegerType.get())};+ Transform[] transforms = new Transform[] {Transforms.identity("user-id")};++ String where =+ PartitionUtils.getWhereClauseForPartition(partitions, columns, transforms, CATALOG);++ Assertions.assertEquals("`user-id` = 7", where);+ }++ @Test+ void testDayOnNestedHyphenatedFieldQuotesPathNotSystemFunction() {+ // Quote field components only: catalog + path get backticks; system/days stay bare+ // (not `system`.`days`).+ List<PartitionEntry> partitions =+ Arrays.asList(new PartitionEntryImpl("event.event-ts_day", "2026-03-18"));+ Column[] columns =+ new Column[] {+ column(+ "event",+ Types.StructType.of(+ Types.StructType.Field.notNullField(+ "event-ts", Types.TimestampType.withoutTimeZone())))+ };+ Transform[] transforms = new Transform[] {Transforms.day(new String[] {"event", "event-ts"})};++ String where =+ PartitionUtils.getWhereClauseForPartition(partitions, columns, transforms, CATALOG);++ Assertions.assertEquals("`ice`.system.days(`event`.`event-ts`) = DATE '2026-03-18'", where);+ }++ @Test+ void testBucketOnNestedHyphenatedFieldQuotesPathNotSystemFunction() {+ List<PartitionEntry> partitions =+ Arrays.asList(new PartitionEntryImpl("event.user-id_bucket", "3"));+ Column[] columns =+ new Column[] {+ column(+ "event",+ Types.StructType.of(+ Types.StructType.Field.notNullField("user-id", Types.IntegerType.get())))+ };+ Transform[] transforms =+ new Transform[] {Transforms.bucket(8, new String[][] {new String[] {"event", "user-id"}})};++ String where =+ PartitionUtils.getWhereClauseForPartition(partitions, columns, transforms, CATALOG);++ Assertions.assertEquals("`ice`.system.bucket(8, `event`.`user-id`) = 3", where);+ }++ @Test+ void testIdentityStructInStructHyphenatedFieldIsBacktickQuoted() {+ // event.meta.user-id: quote each component so Spark does not parse subtraction.+ List<PartitionEntry> partitions =+ Arrays.asList(new PartitionEntryImpl("event.meta.user-id", "7"));+ Column[] columns = new Column[] {eventMetaUserIdStructColumn()};+ Transform[] transforms =+ new Transform[] {Transforms.identity(new String[] {"event", "meta", "user-id"})};++ String where =+ PartitionUtils.getWhereClauseForPartition(partitions, columns, transforms, CATALOG);++ Assertions.assertEquals("`event`.`meta`.`user-id` = 7", where);+ }++ @Test+ void testDayOnStructInStructHyphenatedFieldQuotesPathNotSystemFunction() {+ List<PartitionEntry> partitions =+ Arrays.asList(new PartitionEntryImpl("event.meta.event-ts_day", "2026-03-18"));+ Column[] columns = new Column[] {eventMetaEventTsStructColumn()};+ Transform[] transforms =+ new Transform[] {Transforms.day(new String[] {"event", "meta", "event-ts"})};++ String where =+ PartitionUtils.getWhereClauseForPartition(partitions, columns, transforms, CATALOG);++ Assertions.assertEquals(+ "`ice`.system.days(`event`.`meta`.`event-ts`) = DATE '2026-03-18'", where);+ }++ @Test+ void testIdentityNestedIntegerRejectsSqlInjection() {+ List<PartitionEntry> partitions =+ Arrays.asList(new PartitionEntryImpl("event.id", "7 OR 1 = 1"));+ Column[] columns =+ new Column[] {+ column(+ "event",+ Types.StructType.of(+ Types.StructType.Field.notNullField("id", Types.IntegerType.get())))+ };+ Transform[] transforms = new Transform[] {Transforms.identity(new String[] {"event", "id"})};++ IllegalArgumentException ex =+ Assertions.assertThrows(+ IllegalArgumentException.class,+ () ->+ PartitionUtils.getWhereClauseForPartition(+ partitions, columns, transforms, CATALOG));+ Assertions.assertTrue(ex.getMessage().contains("7 OR 1 = 1"), ex.getMessage());+ }++ @Test+ void testIdentityBooleanRejectsNonLiteral() {+ List<PartitionEntry> partitions = Arrays.asList(new PartitionEntryImpl("flag", "true OR 1=1"));+ Column[] columns = new Column[] {column("flag", Types.BooleanType.get())};+ Transform[] transforms = new Transform[] {Transforms.identity("flag")};++ Assertions.assertThrows(+ IllegalArgumentException.class,+ () -> PartitionUtils.getWhereClauseForPartition(partitions, columns, transforms, CATALOG));+ }++ @Test+ void testNestedFieldNotFoundThrowsClearError() {+ List<PartitionEntry> partitions = Arrays.asList(new PartitionEntryImpl("event.missing", "x"));+ Column[] columns = new Column[] {eventStructColumn()};+ Transform[] transforms =+ new Transform[] {Transforms.identity(new String[] {"event", "missing"})};++ IllegalArgumentException ex =+ Assertions.assertThrows(+ IllegalArgumentException.class,+ () ->+ PartitionUtils.getWhereClauseForPartition(+ partitions, columns, transforms, CATALOG));+ Assertions.assertTrue(ex.getMessage().contains("event.missing"));+ }++ @Test+ void testNestedPathThroughNonStructLeafThrowsClearError() {+ // event.id is INT; a deeper component cannot be resolved as a struct walk.+ List<PartitionEntry> partitions = Arrays.asList(new PartitionEntryImpl("event.id.x", "1"));+ Column[] columns =+ new Column[] {+ column(+ "event",+ Types.StructType.of(+ Types.StructType.Field.notNullField("id", Types.IntegerType.get())))+ };+ Transform[] transforms =+ new Transform[] {Transforms.identity(new String[] {"event", "id", "x"})};++ IllegalArgumentException ex =+ Assertions.assertThrows(+ IllegalArgumentException.class,+ () ->+ PartitionUtils.getWhereClauseForPartition(+ partitions, columns, transforms, CATALOG));+ Assertions.assertTrue(ex.getMessage().contains("event.id.x"), ex.getMessage());+ Assertions.assertTrue(ex.getMessage().contains("is not a struct"), ex.getMessage());+ }++ @Test+ void testYearPartitionOnNestedStructField() {+ List<PartitionEntry> partitions = Arrays.asList(new PartitionEntryImpl("event.ts_year", "56"));+ Column[] columns = new Column[] {eventStructColumn()};+ Transform[] transforms = new Transform[] {Transforms.year(new String[] {"event", "ts"})};++ String where =+ PartitionUtils.getWhereClauseForPartition(partitions, columns, transforms, CATALOG);++ Assertions.assertEquals("`ice`.system.years(`event`.`ts`) = 56", where);+ }++ @Test+ void testMonthPartitionOnNestedStructField() {+ List<PartitionEntry> partitions =+ Arrays.asList(new PartitionEntryImpl("event.ts_month", "674"));+ Column[] columns = new Column[] {eventStructColumn()};+ Transform[] transforms = new Transform[] {Transforms.month(new String[] {"event", "ts"})};++ String where =+ PartitionUtils.getWhereClauseForPartition(partitions, columns, transforms, CATALOG);++ Assertions.assertEquals("`ice`.system.months(`event`.`ts`) = 674", where);+ }++ @Test+ void testHourPartitionOnNestedStructField() {+ List<PartitionEntry> partitions =+ Arrays.asList(new PartitionEntryImpl("event.ts_hour", "492724"));+ Column[] columns = new Column[] {eventStructColumn()};+ Transform[] transforms = new Transform[] {Transforms.hour(new String[] {"event", "ts"})};++ String where =+ PartitionUtils.getWhereClauseForPartition(partitions, columns, transforms, CATALOG);++ Assertions.assertEquals("`ice`.system.hours(`event`.`ts`) = 492724", where);+ }++ @Test+ void testBucketPartitionOnNestedStructField() {+ List<PartitionEntry> partitions = Arrays.asList(new PartitionEntryImpl("event.id_bucket", "3"));+ Column[] columns =+ new Column[] {+ column(+ "event",+ Types.StructType.of(Types.StructType.Field.notNullField("id", Types.LongType.get())))+ };+ Transform[] transforms =+ new Transform[] {Transforms.bucket(8, new String[][] {new String[] {"event", "id"}})};++ String where =+ PartitionUtils.getWhereClauseForPartition(partitions, columns, transforms, CATALOG);++ Assertions.assertEquals("`ice`.system.bucket(8, `event`.`id`) = 3", where);+ }++ @Test+ void testTruncatePartitionOnNestedStructField() {+ List<PartitionEntry> partitions =+ Arrays.asList(new PartitionEntryImpl("event.loc_trunc", "ab"));+ Column[] columns =+ new Column[] {+ column(+ "event",+ Types.StructType.of(+ Types.StructType.Field.notNullField("loc", Types.StringType.get())))+ };+ Transform[] transforms =+ new Transform[] {Transforms.truncate(2, new String[] {"event", "loc"})};++ String where =+ PartitionUtils.getWhereClauseForPartition(partitions, columns, transforms, CATALOG);++ Assertions.assertEquals("`ice`.system.truncate(2, `event`.`loc`) = 'ab'", where);+ }++ @Test+ void testDayPartitionAcceptsIsoDateFromUpdateStatsPath() {+ // Production path: IcebergUpdateStatsAndMetricsJob stores Spark date via String.valueOf.+ List<PartitionEntry> partitions = Arrays.asList(new PartitionEntryImpl("day", "2026-01-01"));+ Column[] columns = new Column[] {column("event_time", Types.TimestampType.withoutTimeZone())};+ Transform[] transforms = new Transform[] {Transforms.day("event_time")};++ String where =+ PartitionUtils.getWhereClauseForPartition(partitions, columns, transforms, CATALOG);++ Assertions.assertEquals("`ice`.system.days(`event_time`) = DATE '2026-01-01'", where);+ }++ @Test+ void testDayPartitionRejectsNonIntegerNonIsoValue() {+ List<PartitionEntry> partitions = Arrays.asList(new PartitionEntryImpl("day", "not-a-day"));+ Column[] columns = new Column[] {column("event_time", Types.TimestampType.withoutTimeZone())};+ Transform[] transforms = new Transform[] {Transforms.day("event_time")};++ IllegalArgumentException ex =+ Assertions.assertThrows(+ IllegalArgumentException.class,+ () ->+ PartitionUtils.getWhereClauseForPartition(+ partitions, columns, transforms, CATALOG));+ Assertions.assertTrue(ex.getMessage().contains("not-a-day"));+ }++ @Test+ void testDayPartitionRejectsEpochDayIntegerString() {+ List<PartitionEntry> partitions = Arrays.asList(new PartitionEntryImpl("day", "19723"));+ Column[] columns = new Column[] {column("event_time", Types.TimestampType.withoutTimeZone())};+ Transform[] transforms = new Transform[] {Transforms.day("event_time")};++ IllegalArgumentException ex =+ Assertions.assertThrows(+ IllegalArgumentException.class,+ () ->+ PartitionUtils.getWhereClauseForPartition(+ partitions, columns, transforms, CATALOG));+ Assertions.assertTrue(ex.getMessage().contains("ISO date"));+ Assertions.assertTrue(ex.getMessage().contains("19723"));+ }++ @Test+ void testDayPartitionRejectsCompactDigitDate() {+ // Compact yyyymmdd must not be guessed as epoch-day (would become ~year 57000).+ List<PartitionEntry> partitions = Arrays.asList(new PartitionEntryImpl("day", "20260101"));+ Column[] columns = new Column[] {column("event_time", Types.TimestampType.withoutTimeZone())};+ Transform[] transforms = new Transform[] {Transforms.day("event_time")};++ IllegalArgumentException ex =+ Assertions.assertThrows(+ IllegalArgumentException.class,+ () ->+ PartitionUtils.getWhereClauseForPartition(+ partitions, columns, transforms, CATALOG));+ Assertions.assertTrue(ex.getMessage().contains("ISO date"));+ Assertions.assertTrue(ex.getMessage().contains("20260101"));+ }++ @Test+ void testMonthPartitionUsesIcebergMonthsFunction() {+ List<PartitionEntry> partitions = Arrays.asList(new PartitionEntryImpl("month", "660"));+ Column[] columns = new Column[] {column("event_time", Types.TimestampType.withTimeZone())};+ Transform[] transforms = new Transform[] {Transforms.month("event_time")};++ String where =+ PartitionUtils.getWhereClauseForPartition(partitions, columns, transforms, CATALOG);++ Assertions.assertEquals("`ice`.system.months(`event_time`) = 660", where);+ }++ @Test+ void testYearPartitionUsesIcebergYearsFunctionWithIntLiteral() {+ List<PartitionEntry> partitions = Arrays.asList(new PartitionEntryImpl("year", "56"));+ Column[] columns = new Column[] {column("event_time", Types.TimestampType.withoutTimeZone())};+ Transform[] transforms = new Transform[] {Transforms.year("event_time")};++ String where =+ PartitionUtils.getWhereClauseForPartition(partitions, columns, transforms, CATALOG);++ Assertions.assertEquals("`ice`.system.years(`event_time`) = 56", where);+ }++ @Test+ void testYearPartitionRejectsNonIntegerValue() {+ List<PartitionEntry> partitions = Arrays.asList(new PartitionEntryImpl("year", "not-an-int"));+ Column[] columns = new Column[] {column("event_time", Types.TimestampType.withoutTimeZone())};+ Transform[] transforms = new Transform[] {Transforms.year("event_time")};++ IllegalArgumentException ex =+ Assertions.assertThrows(+ IllegalArgumentException.class,+ () ->+ PartitionUtils.getWhereClauseForPartition(+ partitions, columns, transforms, CATALOG));+ Assertions.assertTrue(ex.getMessage().contains("must be an integer"));+ Assertions.assertTrue(ex.getMessage().contains("not-an-int"));+ }++ @Test+ void testPartitionValueRejectsNull() {+ List<PartitionEntry> partitions = Arrays.asList(new PartitionEntryImpl("region", null));+ Column[] columns = new Column[] {column("region", Types.StringType.get())};+ Transform[] transforms = new Transform[] {Transforms.identity("region")};++ IllegalArgumentException ex =+ Assertions.assertThrows(+ IllegalArgumentException.class,+ () ->+ PartitionUtils.getWhereClauseForPartition(+ partitions, columns, transforms, CATALOG));+ Assertions.assertTrue(ex.getMessage().contains("cannot be null"));+ }++ @Test+ void testBucketPartitionRejectsNonIntegerValue() {+ List<PartitionEntry> partitions = Arrays.asList(new PartitionEntryImpl("bucket", "14.5"));+ Column[] columns = new Column[] {column("user_id", Types.LongType.get())};+ Transform[] transforms = new Transform[] {Transforms.bucket(16, new String[] {"user_id"})};++ IllegalArgumentException ex =+ Assertions.assertThrows(+ IllegalArgumentException.class,+ () ->+ PartitionUtils.getWhereClauseForPartition(+ partitions, columns, transforms, CATALOG));+ Assertions.assertTrue(ex.getMessage().contains("must be an integer"));+ Assertions.assertTrue(ex.getMessage().contains("14.5"));+ }++ @Test+ void testHourPartitionUsesIcebergHoursFunctionWithIntLiteral() {+ List<PartitionEntry> partitions = Arrays.asList(new PartitionEntryImpl("hour", "492724"));+ Column[] columns = new Column[] {column("event_time", Types.TimestampType.withoutTimeZone())};+ Transform[] transforms = new Transform[] {Transforms.hour("event_time")};++ String where =+ PartitionUtils.getWhereClauseForPartition(partitions, columns, transforms, CATALOG);++ Assertions.assertEquals("`ice`.system.hours(`event_time`) = 492724", where);}@Test@@ -118,9 +689,10 @@ public class TestPartitionUtils {Transform[] partitioning = new Transform[] {Transforms.identity("a"), Transforms.identity("b")};- String where = PartitionUtils.getWhereClauseForPartitions(partitions, columns, partitioning);+ String where =+ PartitionUtils.getWhereClauseForPartitions(partitions, columns, partitioning, CATALOG);- Assertions.assertEquals("(a = \"x1\" AND b = \"y1\") OR (a = \"x2\" AND b = \"y2\")", where);+ Assertions.assertEquals("(`a` = 'x1' AND `b` = 'y1') OR (`a` = 'x2' AND `b` = 'y2')", where);}@Test@@ -137,9 +709,25 @@ public class TestPartitionUtils {Transform[] partitioning =new Transform[] {Transforms.identity("id"), Transforms.identity("score")};- String where = PartitionUtils.getWhereClauseForPartitions(partitions, columns, partitioning);+ String where =+ PartitionUtils.getWhereClauseForPartitions(partitions, columns, partitioning, CATALOG);++ Assertions.assertEquals(+ "(`id` = 123 AND `score` = 45.6) OR (`id` = 456 AND `score` = 78.9)", where);+ }++ @Test+ void testIdentityFloatingHexFloatEmitsCanonicalLiteral() {+ // Jerry P2: Double.parseDouble accepts 0X1P0, but Spark 3.5.3 tokenizes that spelling as a+ // column name. Emit Double.toString so the predicate stays numeric.+ List<PartitionEntry> partitions = Arrays.asList(new PartitionEntryImpl("score", "0X1P0"));+ Column[] columns = new Column[] {column("score", Types.DoubleType.get())};+ Transform[] transforms = new Transform[] {Transforms.identity("score")};++ String where =+ PartitionUtils.getWhereClauseForPartition(partitions, columns, transforms, CATALOG);- Assertions.assertEquals("(id = 123 AND score = 45.6) OR (id = 456 AND score = 78.9)", where);+ Assertions.assertEquals("`score` = 1.0", where);}@Test@@ -151,16 +739,21 @@ public class TestPartitionUtils {Transform[] partitioning = new Transform[] {Transforms.identity("dt")};- String where = PartitionUtils.getWhereClauseForPartitions(partitions, columns, partitioning);+ String where =+ PartitionUtils.getWhereClauseForPartitions(partitions, columns, partitioning, CATALOG);- Assertions.assertEquals("(dt = DATE '2024-01-01')", where);+ Assertions.assertEquals("(`dt` = DATE '2024-01-01')", where);}@Testvoid testWhereClauseWithMixedTransformsAndMultiplePartitions() {Column[] columns =new Column[] {- column("event.ts", Types.TimestampType.withoutTimeZone()),+ column(+ "event",+ Types.StructType.of(+ Types.StructType.Field.notNullField(+ "ts", Types.TimestampType.withoutTimeZone()))),column("country", Types.StringType.get()),column("user_id", Types.LongType.get()),column("flag", Types.BooleanType.get())@@ -188,11 +781,12 @@ public class TestPartitionUtils {new PartitionEntryImpl("p", "true"));List<PartitionPath> partitions = Arrays.asList(PartitionPath.of(p1), PartitionPath.of(p2));- String where = PartitionUtils.getWhereClauseForPartitions(partitions, columns, partitioning);+ String where =+ PartitionUtils.getWhereClauseForPartitions(partitions, columns, partitioning, CATALOG);Assertions.assertEquals(- "(hour(event.ts) = 8 AND truncate(country, 3) = \"usa\" AND bucket(user_id, 16) = 5 AND flag = false) "- + "OR (hour(event.ts) = 12 AND truncate(country, 3) = \"can\" AND bucket(user_id, 16) = 9 AND flag = true)",+ "(`ice`.system.hours(`event`.`ts`) = 8 AND `ice`.system.truncate(3, `country`) = 'usa' AND `ice`.system.bucket(16, `user_id`) = 5 AND `flag` = false) "+ + "OR (`ice`.system.hours(`event`.`ts`) = 12 AND `ice`.system.truncate(3, `country`) = 'can' AND `ice`.system.bucket(16, `user_id`) = 9 AND `flag` = true)",where);}@@ -203,7 +797,7 @@ public class TestPartitionUtils {Assertions.assertThrows(IllegalArgumentException.class,- () -> PartitionUtils.getWhereClauseForPartitions(null, columns, partitioning));+ () -> PartitionUtils.getWhereClauseForPartitions(null, columns, partitioning, CATALOG));}@Test@@ -215,6 +809,7 @@ public class TestPartitionUtils {Assertions.assertThrows(IllegalArgumentException.class,- () -> PartitionUtils.getWhereClauseForPartitions(partitions, columns, partitioning));+ () ->+ PartitionUtils.getWhereClauseForPartitions(partitions, columns, partitioning, CATALOG));}}diff --git a/maintenance/optimizer/src/test/java/org/apache/gravitino/maintenance/optimizer/recommender/job/TestPartitionUtilsFromIcebergPartitionSpec.java b/maintenance/optimizer/src/test/java/org/apache/gravitino/maintenance/optimizer/recommender/job/TestPartitionUtilsFromIcebergPartitionSpec.javanew file mode 100644index 0000000000..5259469e7b--- /dev/null+++ b/maintenance/optimizer/src/test/java/org/apache/gravitino/maintenance/optimizer/recommender/job/TestPartitionUtilsFromIcebergPartitionSpec.java@@ -0,0 +1,70 @@+/*+ * Licensed to the Apache Software Foundation (ASF) under one+ * or more contributor license agreements. See the NOTICE file+ * distributed with this work for additional information+ * regarding copyright ownership. The ASF licenses this file+ * to you under the Apache License, Version 2.0 (the+ * "License"); you may not use this file except in compliance+ * with the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing,+ * software distributed under the License is distributed on an+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY+ * KIND, either express or implied. See the License for the+ * specific language governing permissions and limitations+ * under the License.+ */+package org.apache.gravitino.maintenance.optimizer.recommender.job;++import java.util.List;+import org.apache.gravitino.catalog.lakehouse.iceberg.converter.FromIcebergPartitionSpec;+import org.apache.gravitino.dto.rel.ColumnDTO;+import org.apache.gravitino.maintenance.optimizer.api.common.PartitionEntry;+import org.apache.gravitino.maintenance.optimizer.common.PartitionEntryImpl;+import org.apache.gravitino.rel.Column;+import org.apache.gravitino.rel.expressions.transforms.Transform;+import org.apache.gravitino.rel.types.Types;+import org.apache.iceberg.PartitionSpec;+import org.apache.iceberg.Schema;+import org.junit.jupiter.api.Assertions;+import org.junit.jupiter.api.Test;++/**+ * Regression for the production catalog path: Iceberg {@link PartitionSpec} → {@link+ * FromIcebergPartitionSpec} → {@link PartitionUtils} (not a hand-built multi-component transform).+ */+public class TestPartitionUtilsFromIcebergPartitionSpec {++ @Test+ void testWhereClauseFromConvertedNestedHyphenatedIdentity() {+ Schema schema =+ new Schema(+ org.apache.iceberg.types.Types.NestedField.required(+ 1,+ "event",+ org.apache.iceberg.types.Types.StructType.of(+ org.apache.iceberg.types.Types.NestedField.required(+ 2, "user-id", org.apache.iceberg.types.Types.IntegerType.get()))));+ PartitionSpec partitionSpec =+ PartitionSpec.builderFor(schema).identity("event.user-id").build();+ Transform[] transforms = FromIcebergPartitionSpec.fromPartitionSpec(partitionSpec, schema);++ Column[] columns =+ new Column[] {+ ColumnDTO.builder()+ .withName("event")+ .withDataType(+ Types.StructType.of(+ Types.StructType.Field.notNullField("user-id", Types.IntegerType.get())))+ .build()+ };+ List<PartitionEntry> partitions = List.of(new PartitionEntryImpl("event.user-id", "7"));++ String where =+ PartitionUtils.getWhereClauseForPartition(partitions, columns, transforms, "ice");++ Assertions.assertEquals("`event`.`user-id` = 7", where);+ }+}