World's most powerful open data catalog for building a high-performance, geo-distributed and federated metadata lake.
Java ai-catalogdata-catalogdatalakefederated-querylakehousemetadatametalakemodel-catalogopendatacatalogskycomputingstratosphere
[#11086] feat(catalog-glue): Improve Glue Iceberg table support via Iceberg SDK (#11087)
Yuhuidf4b23f4449e
diff --git a/catalogs/catalog-common/src/main/java/org/apache/gravitino/catalog/hive/HiveStorageConstants.java b/catalogs/catalog-common/src/main/java/org/apache/gravitino/catalog/hive/HiveStorageConstants.javaindex 1b70d61265..1aa84f87b0 100644--- a/catalogs/catalog-common/src/main/java/org/apache/gravitino/catalog/hive/HiveStorageConstants.java+++ b/catalogs/catalog-common/src/main/java/org/apache/gravitino/catalog/hive/HiveStorageConstants.java@@ -19,9 +19,9 @@package org.apache.gravitino.catalog.hive;public class HiveStorageConstants {- static final String SEQUENCEFILE_INPUT_FORMAT_CLASS =+ public static final String SEQUENCEFILE_INPUT_FORMAT_CLASS ="org.apache.hadoop.mapred.SequenceFileInputFormat";- static final String SEQUENCEFILE_OUTPUT_FORMAT_CLASS =+ public static final String SEQUENCEFILE_OUTPUT_FORMAT_CLASS ="org.apache.hadoop.hive.ql.io.HiveSequenceFileOutputFormat";public static final String ORC_INPUT_FORMAT_CLASS =@@ -37,16 +37,18 @@ public class HiveStorageConstants {public static final String PARQUET_SERDE_CLASS ="org.apache.hadoop.hive.ql.io.parquet.serde.ParquetHiveSerDe";- static final String COLUMNAR_SERDE_CLASS = "org.apache.hadoop.hive.serde2.columnar.ColumnarSerDe";- static final String RCFILE_INPUT_FORMAT_CLASS = "org.apache.hadoop.hive.ql.io.RCFileInputFormat";- static final String RCFILE_OUTPUT_FORMAT_CLASS =+ public static final String COLUMNAR_SERDE_CLASS =+ "org.apache.hadoop.hive.serde2.columnar.ColumnarSerDe";+ public static final String RCFILE_INPUT_FORMAT_CLASS =+ "org.apache.hadoop.hive.ql.io.RCFileInputFormat";+ public static final String RCFILE_OUTPUT_FORMAT_CLASS ="org.apache.hadoop.hive.ql.io.RCFileOutputFormat";- static final String AVRO_INPUT_FORMAT_CLASS =+ public static final String AVRO_INPUT_FORMAT_CLASS ="org.apache.hadoop.hive.ql.io.avro.AvroContainerInputFormat";- static final String AVRO_OUTPUT_FORMAT_CLASS =+ public static final String AVRO_OUTPUT_FORMAT_CLASS ="org.apache.hadoop.hive.ql.io.avro.AvroContainerOutputFormat";- static final String AVRO_SERDE_CLASS = "org.apache.hadoop.hive.serde2.avro.AvroSerDe";+ public static final String AVRO_SERDE_CLASS = "org.apache.hadoop.hive.serde2.avro.AvroSerDe";public static final String TEXT_INPUT_FORMAT_CLASS = "org.apache.hadoop.mapred.TextInputFormat";@@ -55,9 +57,9 @@ public class HiveStorageConstants {public static final String LAZY_SIMPLE_SERDE_CLASS ="org.apache.hadoop.hive.serde2.lazy.LazySimpleSerDe";- static final String JSON_SERDE_CLASS = "org.apache.hive.hcatalog.data.JsonSerDe";+ public static final String JSON_SERDE_CLASS = "org.apache.hive.hcatalog.data.JsonSerDe";public static final String OPENCSV_SERDE_CLASS = "org.apache.hadoop.hive.serde2.OpenCSVSerde";- static final String REGEX_SERDE_CLASS = "org.apache.hadoop.hive.serde2.RegexSerDe";+ public static final String REGEX_SERDE_CLASS = "org.apache.hadoop.hive.serde2.RegexSerDe";}diff --git a/catalogs/catalog-glue/build.gradle.kts b/catalogs/catalog-glue/build.gradle.ktsindex b37ae580c6..da14ad95bb 100644--- a/catalogs/catalog-glue/build.gradle.kts+++ b/catalogs/catalog-glue/build.gradle.kts@@ -36,9 +36,14 @@ dependencies {}implementation(libs.aws.glue)+ implementation(libs.aws.kms)+ implementation(libs.aws.s3)implementation(libs.aws.sts)implementation(libs.commons.lang3)implementation(libs.guava)+ implementation(libs.iceberg.api)+ implementation(libs.iceberg.aws)+ implementation(libs.iceberg.core)implementation(libs.slf4j.api)annotationProcessor(libs.lombok)diff --git a/catalogs/catalog-glue/src/main/java/org/apache/gravitino/catalog/glue/GlueCatalogOperations.java b/catalogs/catalog-glue/src/main/java/org/apache/gravitino/catalog/glue/GlueCatalogOperations.javaindex b356b903ed..751d8d1ce3 100644--- a/catalogs/catalog-glue/src/main/java/org/apache/gravitino/catalog/glue/GlueCatalogOperations.java+++ b/catalogs/catalog-glue/src/main/java/org/apache/gravitino/catalog/glue/GlueCatalogOperations.java@@ -18,6 +18,8 @@*/package org.apache.gravitino.catalog.glue;+import static org.apache.gravitino.catalog.glue.GlueConstants.LOCATION;+import com.google.common.annotations.VisibleForTesting;import com.google.common.base.Preconditions;import com.google.common.collect.ImmutableSet;@@ -30,7 +32,6 @@ import java.util.HashMap;import java.util.List;import java.util.Locale;import java.util.Map;-import java.util.Optional;import java.util.Set;import java.util.function.Consumer;import java.util.function.UnaryOperator;@@ -39,6 +40,7 @@ import org.apache.gravitino.Catalog;import org.apache.gravitino.NameIdentifier;import org.apache.gravitino.Namespace;import org.apache.gravitino.SchemaChange;+import org.apache.gravitino.catalog.hive.HiveStorageConstants;import org.apache.gravitino.connector.CatalogInfo;import org.apache.gravitino.connector.CatalogOperations;import org.apache.gravitino.connector.HasPropertyMetadata;@@ -80,19 +82,12 @@ import software.amazon.awssdk.services.glue.model.GetTableRequest;import software.amazon.awssdk.services.glue.model.GetTablesRequest;import software.amazon.awssdk.services.glue.model.GetTablesResponse;import software.amazon.awssdk.services.glue.model.GlueException;-import software.amazon.awssdk.services.glue.model.IcebergInput;-import software.amazon.awssdk.services.glue.model.IcebergTableUpdate;-import software.amazon.awssdk.services.glue.model.MetadataOperation;-import software.amazon.awssdk.services.glue.model.OpenTableFormatInput;import software.amazon.awssdk.services.glue.model.Order;import software.amazon.awssdk.services.glue.model.SerDeInfo;import software.amazon.awssdk.services.glue.model.StorageDescriptor;import software.amazon.awssdk.services.glue.model.Table;import software.amazon.awssdk.services.glue.model.TableInput;import software.amazon.awssdk.services.glue.model.UpdateDatabaseRequest;-import software.amazon.awssdk.services.glue.model.UpdateIcebergInput;-import software.amazon.awssdk.services.glue.model.UpdateIcebergTableInput;-import software.amazon.awssdk.services.glue.model.UpdateOpenTableFormatInput;import software.amazon.awssdk.services.glue.model.UpdateTableRequest;/**@@ -109,7 +104,8 @@ public class GlueCatalogOperations implements CatalogOperations, SupportsSchemasprivate static final Set<String> SD_TABLE_PROPERTY_KEYS =ImmutableSet.of(GlueConstants.LOCATION,- GlueConstants.INPUT_FORMAT,+ GlueConstants.FORMAT,+ GlueConstants.INPUT_FORMAT_CLASS,GlueConstants.OUTPUT_FORMAT,GlueConstants.SERDE_LIB,GlueConstants.SERDE_NAME);@@ -127,6 +123,9 @@ public class GlueCatalogOperations implements CatalogOperations, SupportsSchemas@VisibleForTesting String defaultTableFormat;+ /** Iceberg SDK Glue catalog used for creating Iceberg-format tables. */+ @VisibleForTesting org.apache.iceberg.catalog.Catalog icebergGlueCatalog;+private final GlueTypeConverter typeConverter = new GlueTypeConverter();@Override@@ -148,6 +147,7 @@ public class GlueCatalogOperations implements CatalogOperations, SupportsSchemas.map(s -> s.toLowerCase(Locale.ROOT)).collect(Collectors.toSet());}+ this.icebergGlueCatalog = GlueIcebergTableHelper.createGlueCatalog(config);}@Override@@ -203,8 +203,15 @@ public class GlueCatalogOperations implements CatalogOperations, SupportsSchemasMap<String, String> params = properties != null ? properties : Collections.emptyMap();- DatabaseInput input =- DatabaseInput.builder().name(ident.name()).description(comment).parameters(params).build();+ DatabaseInput.Builder inputBuilder =+ DatabaseInput.builder().name(ident.name()).description(comment).parameters(params);++ String location = params.get(LOCATION);+ if (location != null) {+ inputBuilder.locationUri(location);+ }++ DatabaseInput input = inputBuilder.build();CreateDatabaseRequest.Builder req = CreateDatabaseRequest.builder().databaseInput(input);applyCatalogId(catalogId, req::catalogId);@@ -263,12 +270,18 @@ public class GlueCatalogOperations implements CatalogOperations, SupportsSchemas}}- DatabaseInput input =+ DatabaseInput.Builder inputBuilder =DatabaseInput.builder().name(ident.name()).description(current.comment())- .parameters(newProps)- .build();+ .parameters(newProps);++ String location = newProps.get(LOCATION);+ if (location != null) {+ inputBuilder.locationUri(location);+ }++ DatabaseInput input = inputBuilder.build();UpdateDatabaseRequest.Builder req =UpdateDatabaseRequest.builder().name(ident.name()).databaseInput(input);@@ -351,8 +364,26 @@ public class GlueCatalogOperations implements CatalogOperations, SupportsSchemasGetTableRequest.Builder req = GetTableRequest.builder().databaseName(dbName).name(ident.name());applyCatalogId(catalogId, req::catalogId);try {- GlueTable table =- GlueTable.fromGlueTable(glueClient.getTable(req.build()).table(), typeConverter);+ software.amazon.awssdk.services.glue.model.Table rawGlueTable =+ glueClient.getTable(req.build()).table();+ GlueTable table = GlueTable.fromGlueTable(rawGlueTable, typeConverter);++ // Recover Iceberg-specific partitioning and sort orders from the Iceberg metadata.+ // AWS Glue Table.partitionKeys() is empty for Iceberg tables, so we load the Iceberg+ // Table to obtain the accurate partition spec and sort order.+ if (GlueIcebergTableHelper.isIcebergTable(rawGlueTable) && icebergGlueCatalog != null) {+ try {+ GlueIcebergTableHelper.loadTable(icebergGlueCatalog, dbName, ident.name(), table);+ } catch (Exception e) {+ LOG.warn(+ "Failed to load Iceberg metadata for table {}.{}. "+ + "Partitioning and sort order information may be incomplete.",+ dbName,+ ident.name(),+ e);+ }+ }+table.initOpsContext(glueClient, catalogId, dbName);LOG.info("Loaded Glue table {}.{}", dbName, ident.name());return table;@@ -375,22 +406,26 @@ public class GlueCatalogOperations implements CatalogOperations, SupportsSchemasPreconditions.checkArgument(indexes.length == 0, "Glue catalog does not support indexes");- for (Transform t : partitions) {- Preconditions.checkArgument(- t instanceof Transforms.IdentityTransform,- "Glue catalog only supports identity partitioning, got: %s",- t.name());- Preconditions.checkArgument(- ((Transforms.IdentityTransform) t).fieldName().length == 1,- "Glue catalog does not support nested field partitioning");- }-String dbName = schemaName(ident.namespace());Map<String, String> props = properties != null ? properties : Collections.emptyMap();String tableFormat = props.getOrDefault(GlueConstants.TABLE_FORMAT, defaultTableFormat);boolean isIceberg = GlueConstants.ICEBERG_TABLE_TYPE_VALUE.equalsIgnoreCase(tableFormat);+ // Non-Iceberg (Hive) tables only support identity partitioning.+ // Iceberg tables delegate to GlueIcebergCatalogHelper which supports all transforms.+ if (!isIceberg) {+ for (Transform t : partitions) {+ Preconditions.checkArgument(+ t instanceof Transforms.IdentityTransform,+ "Glue catalog only supports identity partitioning, got: %s",+ t.name());+ Preconditions.checkArgument(+ ((Transforms.IdentityTransform) t).fieldName().length == 1,+ "Glue catalog does not support nested field partitioning");+ }+ }+// For Iceberg tables, stamp table_type=ICEBERG into the Glue parameters so that// isIcebergTable() detection works consistently for future alterTable/listTable calls.Map<String, String> finalProps = props;@@ -399,34 +434,38 @@ public class GlueCatalogOperations implements CatalogOperations, SupportsSchemasfinalProps.put(GlueConstants.TABLE_TYPE_PARAM, GlueConstants.ICEBERG_TABLE_TYPE_VALUE);}- TableInput input =- buildTableInput(- ident.name(), comment, columns, finalProps, partitions, distribution, sortOrders);-- CreateTableRequest.Builder req =- CreateTableRequest.builder().databaseName(dbName).tableInput(input);-if (isIceberg) {- // Register mode: metadata_location points to existing Iceberg metadata.- // Create mode: new table; Glue writes metadata.json at the given location.boolean registerMode = props.containsKey(GlueConstants.METADATA_LOCATION);if (!registerMode) {- Preconditions.checkArgument(- props.containsKey(GlueConstants.LOCATION),- "Either '%s' (register existing table) or '%s' (create new table) is required",- GlueConstants.METADATA_LOCATION,- GlueConstants.LOCATION);- req.openTableFormatInput(- OpenTableFormatInput.builder()- .icebergInput(- IcebergInput.builder()- .metadataOperation(MetadataOperation.CREATE)- .version(GlueConstants.ICEBERG_FORMAT_VERSION)- .build())- .build());+ // Use Iceberg SDK to create the table (writes metadata.json to S3 and registers in Glue).+ GlueIcebergTableHelper.createTable(+ icebergGlueCatalog,+ dbName,+ ident.name(),+ columns,+ comment,+ finalProps,+ partitions,+ sortOrders);+ LOG.info("Created Iceberg table {}.{} via Iceberg SDK", dbName, ident.name());+ return loadTable(ident);}}+ TableInput input =+ buildTableInput(+ ident.name(),+ comment,+ columns,+ finalProps,+ partitions,+ distribution,+ sortOrders,+ isIceberg);++ CreateTableRequest.Builder req =+ CreateTableRequest.builder().databaseName(dbName).tableInput(input);+executeCreateTable(dbName, ident, req);LOG.info("Created {} table {}.{}", isIceberg ? "Iceberg" : "Glue", dbName, ident.name());@@ -469,8 +508,8 @@ public class GlueCatalogOperations implements CatalogOperations, SupportsSchemasthrow GlueExceptionConverter.toTableException(e, "table " + ident.name());}- if (GlueIcebergHelper.isIcebergTable(rawGlueTable)) {- return alterIcebergTable(ident, dbName, rawGlueTable, changes);+ if (GlueIcebergTableHelper.isIcebergTable(rawGlueTable)) {+ return alterIcebergTable(ident, dbName, changes);}GlueTable current = GlueTable.fromGlueTable(rawGlueTable, typeConverter);@@ -489,15 +528,7 @@ public class GlueCatalogOperations implements CatalogOperations, SupportsSchemasfor (TableChange change : changes) {if (change instanceof TableChange.RenameTable) {- TableChange.RenameTable renameTable = (TableChange.RenameTable) change;- renameTable- .getNewSchemaName()- .ifPresent(- s -> {- throw new UnsupportedOperationException(- "Glue does not support cross-schema table rename");- });- newName = renameTable.getNewName();+ throw new UnsupportedOperationException("Glue does not support table rename");} else if (change instanceof TableChange.UpdateComment) {newComment = ((TableChange.UpdateComment) change).getNewComment();} else if (change instanceof TableChange.SetProperty) {@@ -525,7 +556,8 @@ public class GlueCatalogOperations implements CatalogOperations, SupportsSchemasnewProps,current.partitioning(),current.distribution(),- current.sortOrder());+ current.sortOrder(),+ false);executeUpdateTable(ident, UpdateTableRequest.builder().databaseName(dbName).tableInput(input));LOG.info("Altered Glue table {}.{}", dbName, ident.name());@@ -545,52 +577,8 @@ public class GlueCatalogOperations implements CatalogOperations, SupportsSchemasreturn altered;}- private GlueTable alterIcebergTable(- NameIdentifier ident, String dbName, Table rawGlueTable, TableChange... changes) {-- GlueIcebergHelper.validateChanges(changes);-- Optional<IcebergTableUpdate> schemaUpdate =- GlueIcebergHelper.buildSchemaUpdate(rawGlueTable, changes);- Map<String, String> propUpdates = GlueIcebergHelper.extractSetProperties(changes);-- if (schemaUpdate.isEmpty() && propUpdates.isEmpty()) {- LOG.debug("No-op alterIcebergTable for {}.{}", dbName, ident.name());- return loadTable(ident);- }-- if (schemaUpdate.isPresent()) {- UpdateIcebergTableInput icebergTableInput =- UpdateIcebergTableInput.builder().updates(schemaUpdate.get()).build();- UpdateIcebergInput icebergInput =- UpdateIcebergInput.builder().updateIcebergTableInput(icebergTableInput).build();- UpdateOpenTableFormatInput openFormatInput =- UpdateOpenTableFormatInput.builder().updateIcebergInput(icebergInput).build();- executeUpdateTable(- ident,- UpdateTableRequest.builder()- .databaseName(dbName)- .updateOpenTableFormatInput(openFormatInput));- LOG.info("Altered Iceberg table {}.{} schema via Glue native API", dbName, ident.name());- // Re-fetch to pick up server-side parameter changes (e.g., current-schema-id update)- // before using rawGlueTable.parameters() for the property update below.- GetTableRequest.Builder rawReq =- GetTableRequest.builder().databaseName(dbName).name(ident.name());- applyCatalogId(catalogId, rawReq::catalogId);- rawGlueTable = glueClient.getTable(rawReq.build()).table();- }-- if (!propUpdates.isEmpty()) {- Map<String, String> newParams = new HashMap<>(rawGlueTable.parameters());- newParams.putAll(propUpdates);- executeUpdateTable(- ident,- UpdateTableRequest.builder()- .databaseName(dbName)- .tableInput(tableInputFromRaw(rawGlueTable, newParams)));- LOG.info("Altered Iceberg table {}.{} properties directly", dbName, ident.name());- }-+ private GlueTable alterIcebergTable(NameIdentifier ident, String dbName, TableChange... changes) {+ GlueIcebergTableHelper.alterTable(icebergGlueCatalog, dbName, ident.name(), changes);return loadTable(ident);}@@ -626,7 +614,7 @@ public class GlueCatalogOperations implements CatalogOperations, SupportsSchemasString fmt = table.hasParameters() ? table.parameters().get(GlueConstants.TABLE_FORMAT) : null;// Fall back to checking native Glue table_type for tables created without the Gravitino// table-format property (e.g. created via default-table-format config or external tooling).- if (fmt == null && GlueIcebergHelper.isIcebergTable(table)) {+ if (fmt == null && GlueIcebergTableHelper.isIcebergTable(table)) {fmt = GlueConstants.ICEBERG_TABLE_TYPE_VALUE;}String normalized =@@ -655,21 +643,6 @@ public class GlueCatalogOperations implements CatalogOperations, SupportsSchemas}}- /** Copies fields from {@code rawGlueTable} into a {@link TableInput} with updated parameters. */- private static TableInput tableInputFromRaw(Table rawGlueTable, Map<String, String> newParams) {- TableInput.Builder b =- TableInput.builder()- .name(rawGlueTable.name())- .description(rawGlueTable.description())- .tableType(rawGlueTable.tableType())- .parameters(newParams);- if (rawGlueTable.storageDescriptor() != null) {- b.storageDescriptor(rawGlueTable.storageDescriptor())- .partitionKeys(rawGlueTable.partitionKeys());- }- return b.build();- }-private TableInput buildTableInput(String name,String comment,@@ -677,7 +650,8 @@ public class GlueCatalogOperations implements CatalogOperations, SupportsSchemasMap<String, String> properties,Transform[] partitions,Distribution distribution,- SortOrder[] sortOrders) {+ SortOrder[] sortOrders,+ boolean isIceberg) {int partCount = partitions.length;Preconditions.checkArgument(@@ -710,9 +684,25 @@ public class GlueCatalogOperations implements CatalogOperations, SupportsSchemas}}+ // Translate format name to input/output/serde class names if not explicitly set+ String format = properties.get(GlueConstants.FORMAT);+ String inputFormat = properties.get(GlueConstants.INPUT_FORMAT_CLASS);+ String outputFormat = properties.get(GlueConstants.OUTPUT_FORMAT);+ String serdeLib = properties.get(GlueConstants.SERDE_LIB);++ if (inputFormat == null && format != null) {+ inputFormat = getInputFormatClass(format.toLowerCase(Locale.ROOT));+ }+ if (outputFormat == null && format != null) {+ outputFormat = getOutputFormatClass(format.toLowerCase(Locale.ROOT));+ }+ if (serdeLib == null && format != null) {+ serdeLib = getSerdeClass(format.toLowerCase(Locale.ROOT));+ }+SerDeInfo serDe =SerDeInfo.builder()- .serializationLibrary(properties.get(GlueConstants.SERDE_LIB))+ .serializationLibrary(serdeLib).name(properties.get(GlueConstants.SERDE_NAME)).parameters(serdeParams).build();@@ -744,22 +734,28 @@ public class GlueCatalogOperations implements CatalogOperations, SupportsSchemasStorageDescriptor.builder().columns(glueDataCols).location(properties.get(GlueConstants.LOCATION))- .inputFormat(properties.get(GlueConstants.INPUT_FORMAT))- .outputFormat(properties.get(GlueConstants.OUTPUT_FORMAT))+ .inputFormat(inputFormat)+ .outputFormat(outputFormat).serdeInfo(serDe).bucketColumns(bucketCols).numberOfBuckets(numBuckets).sortColumns(glueSortCols).build();- return TableInput.builder()- .name(name)- .description(comment)- .tableType(properties.get(GlueConstants.TABLE_TYPE))- .parameters(tableParams)- .storageDescriptor(sd)- .partitionKeys(gluePartCols)- .build();+ TableInput.Builder builder =+ TableInput.builder()+ .name(name)+ .description(comment)+ .tableType(properties.get(GlueConstants.TABLE_TYPE))+ .parameters(tableParams)+ .storageDescriptor(sd);++ // AWS Glue rejects partitionKeys for Iceberg-format tables.+ if (!isIceberg) {+ builder.partitionKeys(gluePartCols);+ }++ return builder.build();}private software.amazon.awssdk.services.glue.model.Column toGlueColumn(Column col) {@@ -770,10 +766,88 @@ public class GlueCatalogOperations implements CatalogOperations, SupportsSchemas.build();}+ /** Translates a format name (e.g., "parquet", "orc") to the Hive input format class. */+ private static String getInputFormatClass(String format) {+ switch (format) {+ case "parquet":+ return HiveStorageConstants.PARQUET_INPUT_FORMAT_CLASS;+ case "orc":+ return HiveStorageConstants.ORC_INPUT_FORMAT_CLASS;+ case "textfile":+ case "csv":+ return HiveStorageConstants.TEXT_INPUT_FORMAT_CLASS;+ case "rcfile":+ return HiveStorageConstants.RCFILE_INPUT_FORMAT_CLASS;+ case "avro":+ return HiveStorageConstants.AVRO_INPUT_FORMAT_CLASS;+ case "sequencefile":+ return HiveStorageConstants.SEQUENCEFILE_INPUT_FORMAT_CLASS;+ case "json":+ case "regex":+ return HiveStorageConstants.TEXT_INPUT_FORMAT_CLASS;+ default:+ throw new IllegalArgumentException("Unsupported table format: " + format);+ }+ }++ /** Translates a format name to the Hive output format class. */+ private static String getOutputFormatClass(String format) {+ switch (format) {+ case "parquet":+ return HiveStorageConstants.PARQUET_OUTPUT_FORMAT_CLASS;+ case "orc":+ return HiveStorageConstants.ORC_OUTPUT_FORMAT_CLASS;+ case "textfile":+ case "csv":+ return HiveStorageConstants.IGNORE_KEY_OUTPUT_FORMAT_CLASS;+ case "rcfile":+ return HiveStorageConstants.RCFILE_OUTPUT_FORMAT_CLASS;+ case "avro":+ return HiveStorageConstants.AVRO_OUTPUT_FORMAT_CLASS;+ case "sequencefile":+ return HiveStorageConstants.SEQUENCEFILE_OUTPUT_FORMAT_CLASS;+ case "json":+ case "regex":+ return HiveStorageConstants.IGNORE_KEY_OUTPUT_FORMAT_CLASS;+ default:+ throw new IllegalArgumentException("Unsupported table format: " + format);+ }+ }++ /** Translates a format name to the Hive SerDe class. */+ private static String getSerdeClass(String format) {+ switch (format) {+ case "parquet":+ return HiveStorageConstants.PARQUET_SERDE_CLASS;+ case "orc":+ return HiveStorageConstants.ORC_SERDE_CLASS;+ case "textfile":+ return HiveStorageConstants.LAZY_SIMPLE_SERDE_CLASS;+ case "csv":+ return HiveStorageConstants.OPENCSV_SERDE_CLASS;+ case "rcfile":+ return HiveStorageConstants.COLUMNAR_SERDE_CLASS;+ case "avro":+ return HiveStorageConstants.AVRO_SERDE_CLASS;+ case "json":+ return HiveStorageConstants.JSON_SERDE_CLASS;+ case "regex":+ return HiveStorageConstants.REGEX_SERDE_CLASS;+ case "sequencefile":+ return HiveStorageConstants.LAZY_SIMPLE_SERDE_CLASS;+ default:+ throw new IllegalArgumentException("Unsupported table format: " + format);+ }+ }+private static void applyColumnChange(List<Column> dataCols, List<Column> partCols, TableChange.ColumnChange change) {- String fieldName = change.fieldName()[0];+ String[] fieldNameParts = change.fieldName();+ Preconditions.checkArgument(+ fieldNameParts != null && fieldNameParts.length > 0,+ "Column change field name cannot be empty");+ String fieldName = fieldNameParts[0];if (change instanceof TableChange.AddColumn) {TableChange.AddColumn add = (TableChange.AddColumn) change;diff --git a/catalogs/catalog-glue/src/main/java/org/apache/gravitino/catalog/glue/GlueCatalogPropertiesMetadata.java b/catalogs/catalog-glue/src/main/java/org/apache/gravitino/catalog/glue/GlueCatalogPropertiesMetadata.javaindex e3215cf7d6..1b97b633d3 100644--- a/catalogs/catalog-glue/src/main/java/org/apache/gravitino/catalog/glue/GlueCatalogPropertiesMetadata.java+++ b/catalogs/catalog-glue/src/main/java/org/apache/gravitino/catalog/glue/GlueCatalogPropertiesMetadata.java@@ -64,7 +64,7 @@ public class GlueCatalogPropertiesMetadata extends BaseCatalogPropertiesMetadata+ " When omitted the default credential chain is used.",false /* immutable */,null /* defaultValue */,- true /* hidden */))+ false /* hidden */)).put(AWS_SECRET_ACCESS_KEY,stringOptionalPropertyEntry(@@ -73,7 +73,7 @@ public class GlueCatalogPropertiesMetadata extends BaseCatalogPropertiesMetadata+ " When omitted the default credential chain is used.",false /* immutable */,null /* defaultValue */,- true /* hidden */))+ false /* hidden */)).put(AWS_GLUE_ENDPOINT,stringOptionalPropertyEntry(diff --git a/catalogs/catalog-glue/src/main/java/org/apache/gravitino/catalog/glue/GlueConstants.java b/catalogs/catalog-glue/src/main/java/org/apache/gravitino/catalog/glue/GlueConstants.javaindex f919f27899..fc55bbbda7 100644--- a/catalogs/catalog-glue/src/main/java/org/apache/gravitino/catalog/glue/GlueConstants.java+++ b/catalogs/catalog-glue/src/main/java/org/apache/gravitino/catalog/glue/GlueConstants.java@@ -75,6 +75,12 @@ public final class GlueConstants {*/public static final String TABLE_FORMAT = "table-format";+ /**+ * Table file format (lowercase, e.g. "parquet", "orc", "textfile") used when creating Hive-format+ * tables via Trino. Maps to input-format/output-format/serde-lib.+ */+ public static final String FORMAT = "format";+/** Iceberg table metadata location stored in Glue {@code Table.parameters()}. */public static final String METADATA_LOCATION = "metadata_location";@@ -110,7 +116,7 @@ public final class GlueConstants {public static final String LOCATION = "location";/** InputFormat class name from {@code StorageDescriptor.inputFormat()}. */- public static final String INPUT_FORMAT = "input-format";+ public static final String INPUT_FORMAT_CLASS = "input-format";/** OutputFormat class name from {@code StorageDescriptor.outputFormat()}. */public static final String OUTPUT_FORMAT = "output-format";diff --git a/catalogs/catalog-glue/src/main/java/org/apache/gravitino/catalog/glue/GlueIcebergHelper.java b/catalogs/catalog-glue/src/main/java/org/apache/gravitino/catalog/glue/GlueIcebergHelper.javadeleted file mode 100644index 2bc64e843a..0000000000--- a/catalogs/catalog-glue/src/main/java/org/apache/gravitino/catalog/glue/GlueIcebergHelper.java+++ /dev/null@@ -1,435 +0,0 @@-/*- * 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.catalog.glue;--import static org.apache.gravitino.catalog.glue.GlueConstants.CURRENT_SCHEMA_ID_PARAM;-import static org.apache.gravitino.catalog.glue.GlueConstants.ICEBERG_FIELD_ID;-import static org.apache.gravitino.catalog.glue.GlueConstants.ICEBERG_FIELD_OPTIONAL;-import static org.apache.gravitino.catalog.glue.GlueConstants.TABLE_TYPE_PARAM;-import static org.apache.gravitino.catalog.glue.GlueTypeConverter.BIGINT;-import static org.apache.gravitino.catalog.glue.GlueTypeConverter.BINARY;-import static org.apache.gravitino.catalog.glue.GlueTypeConverter.BOOLEAN;-import static org.apache.gravitino.catalog.glue.GlueTypeConverter.CHAR;-import static org.apache.gravitino.catalog.glue.GlueTypeConverter.DATE;-import static org.apache.gravitino.catalog.glue.GlueTypeConverter.DECIMAL;-import static org.apache.gravitino.catalog.glue.GlueTypeConverter.DOUBLE;-import static org.apache.gravitino.catalog.glue.GlueTypeConverter.DOUBLE_PRECISION;-import static org.apache.gravitino.catalog.glue.GlueTypeConverter.FLOAT;-import static org.apache.gravitino.catalog.glue.GlueTypeConverter.INT;-import static org.apache.gravitino.catalog.glue.GlueTypeConverter.INTEGER;-import static org.apache.gravitino.catalog.glue.GlueTypeConverter.LONG;-import static org.apache.gravitino.catalog.glue.GlueTypeConverter.SMALLINT;-import static org.apache.gravitino.catalog.glue.GlueTypeConverter.STRING;-import static org.apache.gravitino.catalog.glue.GlueTypeConverter.TIMESTAMP;-import static org.apache.gravitino.catalog.glue.GlueTypeConverter.TINYINT;-import static org.apache.gravitino.catalog.glue.GlueTypeConverter.VARCHAR;--import com.google.common.base.Preconditions;-import java.util.ArrayList;-import java.util.HashMap;-import java.util.HashSet;-import java.util.List;-import java.util.Locale;-import java.util.Map;-import java.util.Optional;-import java.util.Set;-import java.util.function.UnaryOperator;-import org.apache.gravitino.rel.TableChange;-import org.apache.gravitino.rel.types.Type;-import org.apache.gravitino.rel.types.Types;-import software.amazon.awssdk.core.document.Document;-import software.amazon.awssdk.services.glue.model.Column;-import software.amazon.awssdk.services.glue.model.IcebergSchema;-import software.amazon.awssdk.services.glue.model.IcebergStructField;-import software.amazon.awssdk.services.glue.model.IcebergStructTypeEnum;-import software.amazon.awssdk.services.glue.model.IcebergTableUpdate;-import software.amazon.awssdk.services.glue.model.StorageDescriptor;-import software.amazon.awssdk.services.glue.model.Table;--/**- * Utility methods for building Iceberg-specific Glue API structures used when creating and- * modifying Iceberg-format tables via the AWS Glue Data Catalog.- */-final class GlueIcebergHelper {-- private GlueIcebergHelper() {}-- /**- * Returns true if the Glue table is an Iceberg-format table.- *- * <p>Checks for {@code table_type=ICEBERG} in {@code Table.parameters()}.- */- static boolean isIcebergTable(Table glueTable) {- if (!glueTable.hasParameters()) return false;- return GlueConstants.ICEBERG_TABLE_TYPE_VALUE.equalsIgnoreCase(- glueTable.parameters().get(TABLE_TYPE_PARAM));- }-- /**- * Validates that all {@code changes} are supported for Iceberg tables. Throws {@link- * IllegalArgumentException} for unsupported change types, including {@link- * TableChange.RemoveProperty} (not supported via the Glue SDK) and non-column/non-property- * changes (e.g., {@code RenameTable}, {@code UpdateComment}).- */- static void validateChanges(TableChange... changes) {- for (TableChange change : changes) {- if (change instanceof TableChange.ColumnChange || change instanceof TableChange.SetProperty) {- continue;- }- if (change instanceof TableChange.RemoveProperty) {- throw new IllegalArgumentException(- "Removing properties from Iceberg tables is not supported via the Glue SDK."- + " Use SetProperty to override values instead.");- }- throw new IllegalArgumentException(- "Unsupported table change for Iceberg table: " + change.getClass().getSimpleName());- }- }-- /**- * Filters {@code changes} to column-schema changes and builds a single {@link IcebergTableUpdate}- * carrying the updated schema. Returns empty if there are no column changes.- */- static Optional<IcebergTableUpdate> buildSchemaUpdate(- Table rawGlueTable, TableChange... changes) {- List<TableChange> schemaChanges = new ArrayList<>();- for (TableChange c : changes) {- if (c instanceof TableChange.ColumnChange) schemaChanges.add(c);- }- if (schemaChanges.isEmpty()) return Optional.empty();- return Optional.of(- IcebergTableUpdate.builder()- .schema(buildUpdatedSchema(rawGlueTable, schemaChanges))- .build());- }-- /**- * Extracts {@link TableChange.SetProperty} entries from {@code changes} into a key-value map.- * Returns an empty map if there are no property-set changes.- */- static Map<String, String> extractSetProperties(TableChange... changes) {- Map<String, String> props = new HashMap<>();- for (TableChange change : changes) {- if (change instanceof TableChange.SetProperty) {- TableChange.SetProperty sp = (TableChange.SetProperty) change;- props.put(sp.getProperty(), sp.getValue());- }- }- return props;- }-- /**- * Reads the current Iceberg schema from a Glue table's StorageDescriptor columns (preserving- * {@code iceberg.field.id} from column parameters), applies the given column changes, and returns- * the resulting {@link IcebergSchema} with an incremented schema ID.- */- static IcebergSchema buildUpdatedSchema(Table rawGlueTable, List<TableChange> schemaChanges) {- List<IcebergStructField> fields = currentFields(rawGlueTable);- int maxId = fields.stream().mapToInt(IcebergStructField::id).max().orElse(0);-- for (TableChange change : schemaChanges) {- if (change instanceof TableChange.AddColumn) {- TableChange.AddColumn add = (TableChange.AddColumn) change;- Preconditions.checkArgument(- add.fieldName().length == 1, "Nested column additions are not supported");- fields.add(- IcebergStructField.builder()- .id(++maxId)- .name(add.fieldName()[0])- .type(gravitinoTypeToIcebergType(add.getDataType()))- .required(!add.isNullable())- .doc(add.getComment())- .build());-- } else if (change instanceof TableChange.DeleteColumn) {- TableChange.DeleteColumn del = (TableChange.DeleteColumn) change;- Preconditions.checkArgument(- del.fieldName().length == 1, "Nested column deletions are not supported");- String name = del.fieldName()[0];- boolean removed = fields.removeIf(f -> f.name().equals(name));- if (!removed && !del.getIfExists()) {- throw new IllegalArgumentException(- "Column '" + name + "' not found in Iceberg table schema");- }-- } else if (change instanceof TableChange.RenameColumn) {- TableChange.RenameColumn rename = (TableChange.RenameColumn) change;- Preconditions.checkArgument(- rename.fieldName().length == 1, "Nested column renames are not supported");- updateField(fields, rename.fieldName()[0], b -> b.name(rename.getNewName()));-- } else if (change instanceof TableChange.UpdateColumnType) {- TableChange.UpdateColumnType upd = (TableChange.UpdateColumnType) change;- Preconditions.checkArgument(- upd.fieldName().length == 1, "Nested column type updates are not supported");- Document newTypeDoc = gravitinoTypeToIcebergType(upd.getNewDataType());- updateField(fields, upd.fieldName()[0], b -> b.type(newTypeDoc));-- } else if (change instanceof TableChange.UpdateColumnComment) {- TableChange.UpdateColumnComment upd = (TableChange.UpdateColumnComment) change;- Preconditions.checkArgument(- upd.fieldName().length == 1, "Nested column comment updates are not supported");- updateField(fields, upd.fieldName()[0], b -> b.doc(upd.getNewComment()));-- } else if (change instanceof TableChange.UpdateColumnNullability) {- TableChange.UpdateColumnNullability upd = (TableChange.UpdateColumnNullability) change;- Preconditions.checkArgument(- upd.fieldName().length == 1, "Nested column nullability updates are not supported");- updateField(fields, upd.fieldName()[0], b -> b.required(!upd.nullable()));-- } else {- throw new IllegalArgumentException(- "Unsupported column change: " + change.getClass().getSimpleName());- }- }-- int currentSchemaId = parseSchemaId(rawGlueTable);- return IcebergSchema.builder()- .schemaId(currentSchemaId + 1)- .type(IcebergStructTypeEnum.STRUCT)- .fields(fields)- .build();- }-- // ---------------------------------------------------------------------------- // Private helpers- // ----------------------------------------------------------------------------- /**- * Finds the first field with the given {@code name} in {@code fields} and replaces it in-place- * with the result of applying {@code updater} to its builder. Throws if the field is not found.- */- private static void updateField(- List<IcebergStructField> fields,- String name,- UnaryOperator<IcebergStructField.Builder> updater) {- for (int i = 0; i < fields.size(); i++) {- if (fields.get(i).name().equals(name)) {- fields.set(i, updater.apply(fields.get(i).toBuilder()).build());- return;- }- }- throw new IllegalArgumentException("Column '" + name + "' not found in Iceberg table schema");- }-- /** Reads current Iceberg fields from the Glue table's StorageDescriptor columns. */- private static List<IcebergStructField> currentFields(Table rawGlueTable) {- List<IcebergStructField> fields = new ArrayList<>();- StorageDescriptor sd = rawGlueTable.storageDescriptor();- if (sd == null || !sd.hasColumns()) return fields;-- int fallbackId = 0;- for (Column col : sd.columns()) {- int fieldId = parseFieldId(col, ++fallbackId);- boolean required = parseRequired(col);- fields.add(- IcebergStructField.builder()- .id(fieldId)- .name(col.name())- .type(hiveTypeToIcebergType(col.type()))- .required(required)- .doc(col.comment())- .build());- }-- Set<Integer> seen = new HashSet<>();- for (IcebergStructField f : fields) {- if (!seen.add(f.id())) {- throw new IllegalStateException(- String.format(- "Iceberg table '%s' has duplicate field ID %d in column metadata."- + " The Glue metadata may be corrupt. Aborting schema update.",- rawGlueTable.name(), f.id()));- }- }- return fields;- }-- /** Parses {@code iceberg.field.id} from column parameters; falls back to {@code fallbackId}. */- private static int parseFieldId(Column col, int fallbackId) {- if (col.hasParameters()) {- String raw = col.parameters().get(ICEBERG_FIELD_ID);- if (raw != null) {- try {- return Integer.parseInt(raw);- } catch (NumberFormatException e) {- throw new IllegalStateException(- String.format(- "Column '%s' has non-numeric iceberg.field.id '%s'."- + " The Iceberg metadata may be corrupt. Aborting schema update.",- col.name(), raw),- e);- }- }- }- return fallbackId;- }-- /**- * Parses {@code iceberg.field.optional}; defaults to {@code false} (i.e., not required /- * optional).- */- private static boolean parseRequired(Column col) {- if (col.hasParameters()) {- String optional = col.parameters().get(ICEBERG_FIELD_OPTIONAL);- if (optional != null) {- return !Boolean.parseBoolean(optional);- }- }- return false;- }-- /**- * Reads the current schema ID from {@code Table.parameters()["current-schema-id"]}; returns 0 if- * absent. Throws {@link IllegalStateException} if the value is present but non-numeric, since- * proceeding with a fabricated schema ID risks corrupting the Iceberg schema version chain.- */- private static int parseSchemaId(Table rawGlueTable) {- if (!rawGlueTable.hasParameters()) return 0;- String raw = rawGlueTable.parameters().get(CURRENT_SCHEMA_ID_PARAM);- if (raw == null) return 0;- try {- return Integer.parseInt(raw);- } catch (NumberFormatException e) {- throw new IllegalStateException(- String.format(- "Iceberg table '%s' has non-numeric current-schema-id '%s'."- + " The Iceberg metadata may be corrupt. Aborting schema update.",- rawGlueTable.name(), raw),- e);- }- }-- /**- * Converts a Glue/Hive column type string to an Iceberg type {@link- * software.amazon.awssdk.core.document.Document}.- *- * <p>Iceberg REST spec type names are used for primitives (e.g. {@code "long"} for Hive {@code- * bigint}). Complex types (array, map, struct) are not supported and will throw {@link- * IllegalStateException}.- */- static Document hiveTypeToIcebergType(String hiveType) {- if (hiveType == null) return Document.fromString(STRING);- String t = hiveType.toLowerCase(Locale.ROOT).trim();-- switch (t) {- case STRING:- return Document.fromString(STRING);- case BIGINT:- case LONG: // Iceberg type name stored by Glue native Iceberg API- return Document.fromString(LONG);- case INT:- case INTEGER:- case SMALLINT:- case TINYINT:- return Document.fromString(INT);- case FLOAT:- return Document.fromString(FLOAT);- case DOUBLE:- case DOUBLE_PRECISION:- return Document.fromString(DOUBLE);- case BOOLEAN:- return Document.fromString(BOOLEAN);- case BINARY:- return Document.fromString(BINARY);- case DATE:- return Document.fromString(DATE);- case TIMESTAMP:- return Document.fromString(TIMESTAMP);- default:- break;- }-- if (t.startsWith(DECIMAL + "(")) {- try {- String inner =- t.substring((DECIMAL + "(").length(), t.endsWith(")") ? t.length() - 1 : t.length());- String[] parts = inner.split(",");- int precision = Integer.parseInt(parts[0].trim());- int scale = parts.length > 1 ? Integer.parseInt(parts[1].trim()) : 0;- return Document.fromMap(- Map.of(- "type", Document.fromString(DECIMAL),- "precision", Document.fromNumber(precision),- "scale", Document.fromNumber(scale)));- } catch (NumberFormatException e) {- throw new IllegalStateException(- "Malformed Hive decimal type '"- + hiveType- + "' in existing Iceberg table schema."- + " Cannot safely build schema update.",- e);- }- }- if (t.startsWith(VARCHAR + "(") || t.startsWith(CHAR + "(")) {- return Document.fromString(STRING);- }- throw new IllegalStateException(- "Unsupported Hive column type '"- + hiveType- + "' in existing Iceberg table schema."- + " Cannot safely build schema update."- + " Complex types (array, map, struct) are not supported by the Glue Iceberg schema update API.");- }-- /**- * Converts a Gravitino {@link Type} to an Iceberg type {@link- * software.amazon.awssdk.core.document.Document} ({@code "Doc"} in the method name refers to the- * AWS SDK {@code Document} type used to represent Iceberg type descriptors in Glue API payloads).- *- * <p>Supports primitive types. Complex types (list, map, struct) are not supported and will throw- * {@link UnsupportedOperationException}.- */- static Document gravitinoTypeToIcebergType(Type type) {- if (type instanceof Types.StringType- || type instanceof Types.VarCharType- || type instanceof Types.FixedCharType) {- return Document.fromString("string");- }- if (type instanceof Types.LongType) return Document.fromString("long");- if (type instanceof Types.IntegerType- || type instanceof Types.ShortType- || type instanceof Types.ByteType) {- return Document.fromString("int");- }- if (type instanceof Types.FloatType) return Document.fromString("float");- if (type instanceof Types.DoubleType) return Document.fromString("double");- if (type instanceof Types.BooleanType) return Document.fromString("boolean");- if (type instanceof Types.BinaryType || type instanceof Types.FixedType) {- return Document.fromString("binary");- }- if (type instanceof Types.DateType) return Document.fromString("date");- if (type instanceof Types.TimeType) return Document.fromString("time");- if (type instanceof Types.TimestampType) {- return Document.fromString(- ((Types.TimestampType) type).hasTimeZone() ? "timestamptz" : "timestamp");- }- if (type instanceof Types.UUIDType) return Document.fromString("uuid");- if (type instanceof Types.DecimalType) {- Types.DecimalType dt = (Types.DecimalType) type;- return Document.fromMap(- Map.of(- "type", Document.fromString("decimal"),- "precision", Document.fromNumber(dt.precision()),- "scale", Document.fromNumber(dt.scale())));- }- throw new UnsupportedOperationException(- "Iceberg Glue catalog does not support type: " + type.simpleString());- }-}diff --git a/catalogs/catalog-glue/src/main/java/org/apache/gravitino/catalog/glue/GlueIcebergTableHelper.java b/catalogs/catalog-glue/src/main/java/org/apache/gravitino/catalog/glue/GlueIcebergTableHelper.javanew file mode 100644index 0000000000..fc02171aa6--- /dev/null+++ b/catalogs/catalog-glue/src/main/java/org/apache/gravitino/catalog/glue/GlueIcebergTableHelper.java@@ -0,0 +1,710 @@+/*+ * 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.catalog.glue;++import static org.apache.gravitino.rel.types.Types.BinaryType;+import static org.apache.gravitino.rel.types.Types.BooleanType;+import static org.apache.gravitino.rel.types.Types.ByteType;+import static org.apache.gravitino.rel.types.Types.DateType;+import static org.apache.gravitino.rel.types.Types.DecimalType;+import static org.apache.gravitino.rel.types.Types.DoubleType;+import static org.apache.gravitino.rel.types.Types.FixedCharType;+import static org.apache.gravitino.rel.types.Types.FixedType;+import static org.apache.gravitino.rel.types.Types.FloatType;+import static org.apache.gravitino.rel.types.Types.IntegerType;+import static org.apache.gravitino.rel.types.Types.LongType;+import static org.apache.gravitino.rel.types.Types.ShortType;+import static org.apache.gravitino.rel.types.Types.StringType;+import static org.apache.gravitino.rel.types.Types.TimeType;+import static org.apache.gravitino.rel.types.Types.TimestampType;+import static org.apache.gravitino.rel.types.Types.UUIDType;+import static org.apache.gravitino.rel.types.Types.VarCharType;++import com.google.common.base.Preconditions;+import java.util.ArrayList;+import java.util.HashMap;+import java.util.List;+import java.util.Locale;+import java.util.Map;+import java.util.Set;+import java.util.regex.Pattern;+import javax.annotation.Nullable;+import org.apache.gravitino.catalog.lakehouse.iceberg.IcebergConstants;+import org.apache.gravitino.exceptions.NoSuchTableException;+import org.apache.gravitino.rel.Column;+import org.apache.gravitino.rel.TableChange;+import org.apache.gravitino.rel.expressions.Expression;+import org.apache.gravitino.rel.expressions.FunctionExpression;+import org.apache.gravitino.rel.expressions.NamedReference;+import org.apache.gravitino.rel.expressions.literals.Literal;+import org.apache.gravitino.rel.expressions.literals.Literals;+import org.apache.gravitino.rel.expressions.sorts.NullOrdering;+import org.apache.gravitino.rel.expressions.sorts.SortDirection;+import org.apache.gravitino.rel.expressions.sorts.SortOrder;+import org.apache.gravitino.rel.expressions.sorts.SortOrders;+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.iceberg.NullOrder;+import org.apache.iceberg.PartitionSpec;+import org.apache.iceberg.Schema;+import org.apache.iceberg.Table;+import org.apache.iceberg.UpdateProperties;+import org.apache.iceberg.UpdateSchema;+import org.apache.iceberg.aws.glue.GlueCatalog;+import org.apache.iceberg.catalog.Catalog;+import org.apache.iceberg.catalog.TableIdentifier;+import org.apache.iceberg.exceptions.AlreadyExistsException;+import org.apache.iceberg.exceptions.ValidationException;+import org.apache.iceberg.expressions.Expressions;+import org.apache.iceberg.expressions.UnboundTerm;+import org.apache.iceberg.types.Types;+import org.slf4j.Logger;+import org.slf4j.LoggerFactory;++/**+ * Helper that delegates all Iceberg table operations to the Iceberg SDK's {@code GlueCatalog}.+ *+ * <p>Unlike the native AWS Glue SDK {@code OpenTableFormatInput} approach, the Iceberg SDK writes+ * the {@code metadata.json} file to S3 and registers the table in Glue with the correct {@code+ * metadata_location} parameter, making the table usable by Trino Lakehouse connector and other+ * Iceberg-native query engines.+ */+final class GlueIcebergTableHelper {++ private static final Logger LOG = LoggerFactory.getLogger(GlueIcebergTableHelper.class);++ private static final String DOT = ".";++ // Iceberg GlueCatalog properties (not defined in IcebergConstants).+ private static final String CATALOG_IMPL = "catalog-impl";+ private static final String GLUE_CATALOG = "GlueCatalog";+ private static final String GLUE_ID = "glue.id";+ private static final String GLUE_ENDPOINT = "glue.endpoint";+ private static final String CLIENT_CREDENTIALS_PROVIDER = "client.credentials-provider";+ private static final String CLIENT_CREDENTIALS_PROVIDER_ACCESS_KEY_ID =+ "client.credentials-provider.access-key-id";+ private static final String CLIENT_CREDENTIALS_PROVIDER_SECRET_ACCESS_KEY =+ "client.credentials-provider.secret-access-key";++ private static final Set<String> EXCLUDED_TABLE_PROPS =+ Set.of(+ GlueConstants.LOCATION,+ GlueConstants.TABLE_TYPE,+ GlueConstants.METADATA_LOCATION,+ GlueConstants.INPUT_FORMAT_CLASS,+ GlueConstants.OUTPUT_FORMAT,+ GlueConstants.SERDE_LIB);++ // Iceberg 1.10+ uses "bucket[n]" / "truncate[w]" format for Transform.toString().+ private static final Pattern TRANSFORM_PARAM_PATTERN = Pattern.compile(".*\\[(\\d+)\\]");++ private GlueIcebergTableHelper() {}++ /**+ * Returns true if the Glue table is an Iceberg-format table.+ *+ * <p>Checks for {@code table_type=ICEBERG} in {@code Table.parameters()}.+ */+ static boolean isIcebergTable(software.amazon.awssdk.services.glue.model.Table glueTable) {+ Preconditions.checkArgument(glueTable != null, "glueTable cannot be null");+ if (!glueTable.hasParameters()) return false;+ return GlueConstants.ICEBERG_TABLE_TYPE_VALUE.equalsIgnoreCase(+ glueTable.parameters().get(GlueConstants.TABLE_TYPE_PARAM));+ }++ /**+ * Creates an Iceberg {@link Catalog} backed by AWS Glue.+ *+ * @param config Gravitino catalog configuration (region, credentials, endpoint, etc.)+ * @return an initialized Iceberg Glue catalog+ */+ static Catalog createGlueCatalog(Map<String, String> config) {+ String region = config.get(GlueConstants.AWS_REGION);+ Preconditions.checkArgument(region != null, "AWS region is required for Iceberg Glue catalog");++ Map<String, String> icebergProps = new HashMap<>();+ // Warehouse is required by Iceberg catalog initialization but is not used when each table+ // provides an explicit location.+ icebergProps.put(IcebergConstants.WAREHOUSE, "/tmp/gravitino-glue-iceberg");+ icebergProps.put(CATALOG_IMPL, GLUE_CATALOG);+ icebergProps.put(IcebergConstants.AWS_S3_REGION, region);++ String catalogId = config.get(GlueConstants.AWS_GLUE_CATALOG_ID);+ if (catalogId != null) {+ icebergProps.put(GLUE_ID, catalogId);+ }++ String accessKey = config.get(GlueConstants.AWS_ACCESS_KEY_ID);+ String secretKey = config.get(GlueConstants.AWS_SECRET_ACCESS_KEY);+ if (accessKey != null && secretKey != null) {+ icebergProps.put(+ CLIENT_CREDENTIALS_PROVIDER, GravitinoGlueCredentialsProvider.class.getName());+ icebergProps.put(CLIENT_CREDENTIALS_PROVIDER_ACCESS_KEY_ID, accessKey);+ icebergProps.put(CLIENT_CREDENTIALS_PROVIDER_SECRET_ACCESS_KEY, secretKey);+ }++ String endpoint = config.get(GlueConstants.AWS_GLUE_ENDPOINT);+ if (endpoint != null) {+ icebergProps.put(GLUE_ENDPOINT, endpoint);+ }++ if (accessKey != null && secretKey != null) {+ icebergProps.put(IcebergConstants.ICEBERG_S3_ACCESS_KEY_ID, accessKey);+ icebergProps.put(IcebergConstants.ICEBERG_S3_SECRET_ACCESS_KEY, secretKey);+ }++ icebergProps.put(IcebergConstants.IO_IMPL, "org.apache.iceberg.aws.s3.S3FileIO");++ GlueCatalog glueCatalog = new GlueCatalog();+ glueCatalog.initialize("gravitino-glue-iceberg", icebergProps);+ LOG.info("Initialized Iceberg GlueCatalog for region {}", region);+ return glueCatalog;+ }++ /**+ * Loads an Iceberg table and recovers partitioning and sort orders.+ *+ * @param icebergCatalog the Iceberg Glue catalog+ * @param dbName the Glue database name+ * @param tableName the table name+ * @param table the GlueTable to populate with recovered metadata+ */+ static void loadTable(Catalog icebergCatalog, String dbName, String tableName, GlueTable table) {+ Table icebergTable = icebergCatalog.loadTable(TableIdentifier.of(dbName, tableName));+ if (icebergTable == null) {+ throw new NoSuchTableException(+ "Iceberg table %s.%s not found in Iceberg catalog", dbName, tableName);+ }++ // Merge Iceberg table properties (stored in metadata.json) into the Gravitino properties.+ // Iceberg properties take precedence over Glue parameters for overlapping keys.+ Map<String, String> mergedProps = new HashMap<>(table.properties());+ mergedProps.putAll(icebergTable.properties());+ table.setProperties(mergedProps);++ if (!icebergTable.spec().fields().isEmpty()) {+ table.setPartitioning(convertPartitionSpec(icebergTable.spec(), icebergTable.schema()));+ }+ if (!icebergTable.sortOrder().fields().isEmpty()) {+ table.setSortOrders(convertIcebergSortOrder(icebergTable.sortOrder(), icebergTable.schema()));+ }+ }++ /**+ * Creates an Iceberg table via the Iceberg SDK.+ *+ * <p>The table is written to S3 (metadata.json) and registered in Glue automatically.+ *+ * @param icebergCatalog the Iceberg Glue catalog+ * @param dbName the Glue database name+ * @param tableName the table name+ * @param columns the table columns+ * @param comment the table comment+ * @param properties Gravitino table properties (must contain {@code location})+ * @param partitions partition transforms+ * @param sortOrders sort orders+ */+ static void createTable(+ Catalog icebergCatalog,+ String dbName,+ String tableName,+ Column[] columns,+ @Nullable String comment,+ Map<String, String> properties,+ @Nullable Transform[] partitions,+ @Nullable SortOrder[] sortOrders) {++ Schema schema = toIcebergSchema(columns);+ PartitionSpec spec = toPartitionSpec(schema, partitions);+ org.apache.iceberg.SortOrder icebergSortOrder = toSortOrder(schema, sortOrders);++ Map<String, String> tableProps = new HashMap<>();+ // Forward user-provided properties to Iceberg, excluding Gravitino/Glue internal keys.+ properties.forEach(+ (k, v) -> {+ if (!EXCLUDED_TABLE_PROPS.contains(k)) {+ tableProps.put(k, v);+ }+ });+ if (comment != null) {+ tableProps.put("comment", comment);+ }++ String location = properties.get(GlueConstants.LOCATION);+ Preconditions.checkArgument(+ location != null, "Location is required for Iceberg table creation");++ String format = properties.get(GlueConstants.FORMAT);+ if (format != null) {+ tableProps.put("write.format.default", format.toLowerCase(Locale.ROOT));+ }++ String tableFormat = properties.get(GlueConstants.TABLE_FORMAT);+ if (tableFormat != null) {+ tableProps.put(GlueConstants.TABLE_FORMAT, tableFormat);+ }++ TableIdentifier tableId = TableIdentifier.of(dbName, tableName);++ LOG.info("Creating Iceberg table {} at location {} via Iceberg SDK", tableId, location);++ try {+ icebergCatalog+ .buildTable(tableId, schema)+ .withLocation(location)+ .withPartitionSpec(spec)+ .withSortOrder(icebergSortOrder)+ .withProperties(tableProps)+ .create();+ } catch (AlreadyExistsException e) {+ throw new org.apache.gravitino.exceptions.TableAlreadyExistsException(+ e, "Table %s.%s already exists", dbName, tableName);+ } catch (ValidationException e) {+ throw new IllegalArgumentException("Invalid table definition: " + e.getMessage(), e);+ }+ }++ /**+ * Alters an Iceberg table via the Iceberg SDK.+ *+ * <p>Delegates schema changes to {@link UpdateSchema} and property changes to {@link+ * UpdateProperties}.+ *+ * <p><b>Note:</b> Schema changes and property changes are committed in two separate transactions.+ * If the schema commit succeeds but the property commit fails, the table is left in a partially+ * altered state. This is a known limitation of the current Iceberg SDK integration.+ *+ * @param icebergCatalog the Iceberg Glue catalog+ * @param dbName the Glue database name+ * @param tableName the table name+ * @param changes the table changes to apply+ */+ static void alterTable(+ Catalog icebergCatalog, String dbName, String tableName, TableChange... changes) {+ Table table = icebergCatalog.loadTable(TableIdentifier.of(dbName, tableName));++ boolean hasSchemaChange = false;+ boolean hasPropChange = false;+ for (TableChange change : changes) {+ if (change instanceof TableChange.ColumnChange) {+ hasSchemaChange = true;+ } else if (change instanceof TableChange.SetProperty+ || change instanceof TableChange.RemoveProperty) {+ hasPropChange = true;+ } else {+ throw new IllegalArgumentException(+ "Unsupported table change for Iceberg table: " + change.getClass().getSimpleName());+ }+ }++ if (hasSchemaChange) {+ UpdateSchema update = table.updateSchema();+ for (TableChange change : changes) {+ if (change instanceof TableChange.AddColumn) {+ TableChange.AddColumn add = (TableChange.AddColumn) change;+ Preconditions.checkArgument(+ add.fieldName().length == 1, "Nested column additions are not supported");+ update.addColumn(add.fieldName()[0], toIcebergType(add.getDataType()), add.getComment());+ if (!add.isNullable()) {+ update.requireColumn(add.fieldName()[0]);+ }+ } else if (change instanceof TableChange.DeleteColumn) {+ TableChange.DeleteColumn del = (TableChange.DeleteColumn) change;+ Preconditions.checkArgument(+ del.fieldName().length == 1, "Nested column deletions are not supported");+ if (del.getIfExists()) {+ try {+ update.deleteColumn(del.fieldName()[0]);+ } catch (IllegalArgumentException e) {+ // Column does not exist; ignore as requested by ifExists=true.+ }+ } else {+ update.deleteColumn(del.fieldName()[0]);+ }+ } else if (change instanceof TableChange.RenameColumn) {+ TableChange.RenameColumn rename = (TableChange.RenameColumn) change;+ Preconditions.checkArgument(+ rename.fieldName().length == 1, "Nested column renames are not supported");+ update.renameColumn(rename.fieldName()[0], rename.getNewName());+ } else if (change instanceof TableChange.UpdateColumnType) {+ TableChange.UpdateColumnType upd = (TableChange.UpdateColumnType) change;+ Preconditions.checkArgument(+ upd.fieldName().length == 1, "Nested column type updates are not supported");+ update.updateColumn(+ upd.fieldName()[0],+ (org.apache.iceberg.types.Type.PrimitiveType) toIcebergType(upd.getNewDataType()));+ } else if (change instanceof TableChange.UpdateColumnComment) {+ TableChange.UpdateColumnComment upd = (TableChange.UpdateColumnComment) change;+ Preconditions.checkArgument(+ upd.fieldName().length == 1, "Nested column comment updates are not supported");+ update.updateColumnDoc(upd.fieldName()[0], upd.getNewComment());+ } else if (change instanceof TableChange.UpdateColumnNullability) {+ TableChange.UpdateColumnNullability upd = (TableChange.UpdateColumnNullability) change;+ Preconditions.checkArgument(+ upd.fieldName().length == 1, "Nested column nullability updates are not supported");+ if (upd.nullable()) {+ update.makeColumnOptional(upd.fieldName()[0]);+ } else {+ update.requireColumn(upd.fieldName()[0]);+ }+ }+ }+ update.commit();+ LOG.info("Altered Iceberg table {}.{} schema via Iceberg SDK", dbName, tableName);+ }++ if (hasPropChange) {+ UpdateProperties update = table.updateProperties();+ for (TableChange change : changes) {+ if (change instanceof TableChange.SetProperty) {+ TableChange.SetProperty sp = (TableChange.SetProperty) change;+ update.set(sp.getProperty(), sp.getValue());+ } else if (change instanceof TableChange.RemoveProperty) {+ TableChange.RemoveProperty rp = (TableChange.RemoveProperty) change;+ update.remove(rp.getProperty());+ }+ }+ update.commit();+ LOG.info("Altered Iceberg table {}.{} properties via Iceberg SDK", dbName, tableName);+ }+ }++ // ---------------------------------------------------------------------------+ // Partition / sort conversion (Iceberg -> Gravitino)+ // ---------------------------------------------------------------------------++ /**+ * Converts an Iceberg {@link org.apache.iceberg.PartitionSpec} to Gravitino {@link Transform}s.+ *+ * <p>Supports identity, year, month, day, hour, bucket, and truncate transforms.+ */+ static Transform[] convertPartitionSpec(PartitionSpec spec, Schema schema) {+ return spec.fields().stream()+ .map(+ field -> {+ String colName = schema.findColumnName(field.sourceId());+ String transformStr = field.transform().toString().toLowerCase(Locale.ROOT);+ if (transformStr.startsWith("identity")) {+ return Transforms.identity(colName);+ } else if (transformStr.startsWith("year")) {+ return Transforms.year(colName);+ } else if (transformStr.startsWith("month")) {+ return Transforms.month(colName);+ } else if (transformStr.startsWith("day")) {+ return Transforms.day(colName);+ } else if (transformStr.startsWith("hour")) {+ return Transforms.hour(colName);+ } else if (transformStr.startsWith("bucket")) {+ int numBuckets = extractTransformParam(field.transform().toString());+ return Transforms.bucket(numBuckets, new String[] {colName});+ } else if (transformStr.startsWith("truncate")) {+ int width = extractTransformParam(field.transform().toString());+ return Transforms.truncate(width, new String[] {colName});+ } else {+ throw new IllegalArgumentException(+ "Unsupported partition transform: " + transformStr);+ }+ })+ .toArray(Transform[]::new);+ }++ /** Converts an Iceberg {@link org.apache.iceberg.SortOrder} to Gravitino {@link SortOrder}s. */+ static SortOrder[] convertIcebergSortOrder(+ org.apache.iceberg.SortOrder iceSortOrder, Schema schema) {+ if (iceSortOrder == null || iceSortOrder.fields().isEmpty()) {+ return new SortOrder[0];+ }+ return iceSortOrder.fields().stream()+ .map(+ field -> {+ String colName = schema.findColumnName(field.sourceId());+ SortDirection direction =+ field.direction() == org.apache.iceberg.SortDirection.ASC+ ? SortDirection.ASCENDING+ : SortDirection.DESCENDING;+ NullOrdering nullOrdering =+ field.nullOrder() == org.apache.iceberg.NullOrder.NULLS_FIRST+ ? NullOrdering.NULLS_FIRST+ : NullOrdering.NULLS_LAST;++ org.apache.iceberg.transforms.Transform<?, ?> transform = field.transform();+ String transformStr = transform.toString().toLowerCase(Locale.ROOT);+ if (transformStr.startsWith("identity")) {+ return SortOrders.of(NamedReference.field(colName), direction, nullOrdering);+ }++ Expression expr;+ if (transformStr.startsWith("year")) {+ expr = FunctionExpression.of("year", NamedReference.field(colName));+ } else if (transformStr.startsWith("month")) {+ expr = FunctionExpression.of("month", NamedReference.field(colName));+ } else if (transformStr.startsWith("day")) {+ expr = FunctionExpression.of("day", NamedReference.field(colName));+ } else if (transformStr.startsWith("hour")) {+ expr = FunctionExpression.of("hour", NamedReference.field(colName));+ } else if (transformStr.startsWith("bucket")) {+ int numBuckets = extractTransformParam(transformStr);+ expr =+ FunctionExpression.of(+ "bucket",+ Literals.integerLiteral(numBuckets),+ NamedReference.field(colName));+ } else if (transformStr.startsWith("truncate")) {+ int width = extractTransformParam(transformStr);+ expr =+ FunctionExpression.of(+ "truncate", Literals.integerLiteral(width), NamedReference.field(colName));+ } else {+ expr = NamedReference.field(colName);+ }+ return SortOrders.of(expr, direction, nullOrdering);+ })+ .toArray(SortOrder[]::new);+ }++ // ---------------------------------------------------------------------------+ // Type conversion (Gravitino -> Iceberg)+ // ---------------------------------------------------------------------------++ private static Schema toIcebergSchema(Column[] columns) {+ List<Types.NestedField> fields = new ArrayList<>();+ // Field IDs are assigned sequentially starting from 0. This is the Iceberg convention+ // for initial schema creation. Schema evolution reuses existing IDs from the table.+ for (int i = 0; i < columns.length; i++) {+ Column col = columns[i];+ org.apache.iceberg.types.Type icebergType = toIcebergType(col.dataType());+ if (col.nullable()) {+ fields.add(Types.NestedField.optional(i, col.name(), icebergType, col.comment()));+ } else {+ fields.add(Types.NestedField.required(i, col.name(), icebergType, col.comment()));+ }+ }+ return new Schema(fields);+ }++ private static org.apache.iceberg.types.Type toIcebergType(Type type) {+ if (type instanceof BooleanType) {+ return Types.BooleanType.get();+ }+ if (type instanceof ByteType || type instanceof ShortType || type instanceof IntegerType) {+ return Types.IntegerType.get();+ }+ if (type instanceof LongType) {+ return Types.LongType.get();+ }+ if (type instanceof FloatType) {+ return Types.FloatType.get();+ }+ if (type instanceof DoubleType) {+ return Types.DoubleType.get();+ }+ if (type instanceof StringType+ || type instanceof VarCharType+ || type instanceof FixedCharType) {+ return Types.StringType.get();+ }+ if (type instanceof DateType) {+ return Types.DateType.get();+ }+ if (type instanceof TimeType) {+ TimeType timeType = (TimeType) type;+ if (!timeType.hasPrecisionSet() || timeType.precision() == 6) {+ return Types.TimeType.get();+ }+ throw new IllegalArgumentException(+ "Iceberg only supports microsecond precision (6) for time type, got: "+ + timeType.precision());+ }+ if (type instanceof TimestampType) {+ TimestampType tsType = (TimestampType) type;+ if (!tsType.hasPrecisionSet() || tsType.precision() == 6) {+ return tsType.hasTimeZone()+ ? Types.TimestampType.withZone()+ : Types.TimestampType.withoutZone();+ }+ throw new IllegalArgumentException(+ "Iceberg only supports microsecond precision (6) for timestamp type, got: "+ + tsType.precision());+ }+ if (type instanceof DecimalType) {+ DecimalType dt = (DecimalType) type;+ return Types.DecimalType.of(dt.precision(), dt.scale());+ }+ if (type instanceof BinaryType || type instanceof FixedType) {+ return Types.BinaryType.get();+ }+ if (type instanceof UUIDType) {+ return Types.UUIDType.get();+ }+ throw new UnsupportedOperationException("Unsupported type for Iceberg: " + type.simpleString());+ }++ // ---------------------------------------------------------------------------+ // Partition / sort conversion (Gravitino -> Iceberg)+ // ---------------------------------------------------------------------------++ private static PartitionSpec toPartitionSpec(Schema schema, Transform[] partitions) {+ if (partitions == null || partitions.length == 0) {+ return PartitionSpec.unpartitioned();+ }+ PartitionSpec.Builder builder = PartitionSpec.builderFor(schema);+ for (Transform transform : partitions) {+ Preconditions.checkArgument(transform != null, "Partition transform cannot be null");+ if (transform instanceof Transforms.IdentityTransform) {+ String colName = String.join(DOT, ((Transforms.IdentityTransform) transform).fieldName());+ builder.identity(colName);+ } else if (transform instanceof Transforms.BucketTransform) {+ Transforms.BucketTransform bucket = (Transforms.BucketTransform) transform;+ String[][] fieldNames = bucket.fieldNames();+ Preconditions.checkArgument(+ fieldNames.length == 1,+ "Iceberg partition does not support multi-field bucket: %s",+ transform);+ builder.bucket(String.join(DOT, fieldNames[0]), bucket.numBuckets());+ } else if (transform instanceof Transforms.TruncateTransform) {+ Transforms.TruncateTransform truncate = (Transforms.TruncateTransform) transform;+ builder.truncate(String.join(DOT, truncate.fieldName()), truncate.width());+ } else if (transform instanceof Transforms.YearTransform) {+ builder.year(String.join(DOT, ((Transforms.YearTransform) transform).fieldName()));+ } else if (transform instanceof Transforms.MonthTransform) {+ builder.month(String.join(DOT, ((Transforms.MonthTransform) transform).fieldName()));+ } else if (transform instanceof Transforms.DayTransform) {+ builder.day(String.join(DOT, ((Transforms.DayTransform) transform).fieldName()));+ } else if (transform instanceof Transforms.HourTransform) {+ builder.hour(String.join(DOT, ((Transforms.HourTransform) transform).fieldName()));+ } else {+ throw new UnsupportedOperationException("Transform is not supported: " + transform.name());+ }+ }+ return builder.build();+ }++ private static org.apache.iceberg.SortOrder toSortOrder(Schema schema, SortOrder[] sortOrders) {+ if (sortOrders == null || sortOrders.length == 0) {+ return org.apache.iceberg.SortOrder.unsorted();+ }+ org.apache.iceberg.SortOrder.Builder builder = org.apache.iceberg.SortOrder.builderFor(schema);+ for (SortOrder sortOrder : sortOrders) {+ if (sortOrder.expression() instanceof NamedReference.FieldReference) {+ String fieldName =+ String.join(DOT, ((NamedReference.FieldReference) sortOrder.expression()).fieldName());+ builder.sortBy(+ fieldName,+ toIcebergDirection(sortOrder.direction()),+ toIcebergNullOrder(sortOrder.nullOrdering()));+ } else if (sortOrder.expression() instanceof FunctionExpression) {+ FunctionExpression func = (FunctionExpression) sortOrder.expression();+ UnboundTerm<Object> term = toIcebergSortTerm(func);+ builder.sortBy(+ term,+ toIcebergDirection(sortOrder.direction()),+ toIcebergNullOrder(sortOrder.nullOrdering()));+ } else {+ throw new UnsupportedOperationException(+ "Sort expression is not supported: " + sortOrder.expression());+ }+ }+ return builder.build();+ }++ private static UnboundTerm<Object> toIcebergSortTerm(FunctionExpression func) {+ String name = func.functionName().toLowerCase(Locale.ROOT);+ switch (name) {+ case "bucket":+ Preconditions.checkArgument(+ func.arguments().length == 2, "Bucket sort must have 2 arguments");+ int numBuckets = getIntLiteral(func.arguments()[0]);+ String bucketField = getFieldName(func.arguments()[1]);+ return Expressions.bucket(bucketField, numBuckets);+ case "truncate":+ Preconditions.checkArgument(+ func.arguments().length == 2, "Truncate sort must have 2 arguments");+ int width = getIntLiteral(func.arguments()[0]);+ String truncateField = getFieldName(func.arguments()[1]);+ return Expressions.truncate(truncateField, width);+ case "year":+ return Expressions.year(getSingleField(func.arguments()));+ case "month":+ return Expressions.month(getSingleField(func.arguments()));+ case "day":+ return Expressions.day(getSingleField(func.arguments()));+ case "hour":+ return Expressions.hour(getSingleField(func.arguments()));+ default:+ throw new UnsupportedOperationException(+ "Sort function not supported: " + func.functionName());+ }+ }++ private static String getSingleField(Expression[] args) {+ Preconditions.checkArgument(args.length == 1, "Sort function must have 1 argument");+ return getFieldName(args[0]);+ }++ private static String getFieldName(Expression expr) {+ Preconditions.checkArgument(+ expr instanceof NamedReference.FieldReference,+ "Expected field reference, got: %s",+ expr.getClass().getSimpleName());+ return String.join(DOT, ((NamedReference.FieldReference) expr).fieldName());+ }++ private static int getIntLiteral(Expression expr) {+ Preconditions.checkArgument(+ expr instanceof Literal, "Expected literal, got: %s", expr.getClass().getSimpleName());+ Object value = ((Literal<?>) expr).value();+ try {+ return Integer.parseInt(String.valueOf(value));+ } catch (NumberFormatException e) {+ throw new IllegalArgumentException(+ "Expected integer literal, got: " + value + " in expression: " + expr, e);+ }+ }++ private static org.apache.iceberg.SortDirection toIcebergDirection(SortDirection direction) {+ return direction == SortDirection.ASCENDING+ ? org.apache.iceberg.SortDirection.ASC+ : org.apache.iceberg.SortDirection.DESC;+ }++ private static NullOrder toIcebergNullOrder(NullOrdering ordering) {+ return ordering == NullOrdering.NULLS_FIRST ? NullOrder.NULLS_FIRST : NullOrder.NULLS_LAST;+ }++ /**+ * Extracts an integer parameter from an Iceberg transform string (e.g. "bucket[16]" or+ * "truncate[8]").+ *+ * <p>Iceberg does not expose transform parameters through a typed API, so string parsing is used.+ */+ private static int extractTransformParam(String transformStr) {+ String param = TRANSFORM_PARAM_PATTERN.matcher(transformStr).replaceAll("$1");+ if (param.equals(transformStr)) {+ throw new IllegalArgumentException(+ "Cannot extract numeric parameter from transform: " + transformStr);+ }+ try {+ return Integer.parseInt(param);+ } catch (NumberFormatException e) {+ throw new IllegalArgumentException(+ "Invalid numeric parameter in transform: " + transformStr, e);+ }+ }+}diff --git a/catalogs/catalog-glue/src/main/java/org/apache/gravitino/catalog/glue/GlueTable.java b/catalogs/catalog-glue/src/main/java/org/apache/gravitino/catalog/glue/GlueTable.javaindex 1134a5ad4f..218af44692 100644--- a/catalogs/catalog-glue/src/main/java/org/apache/gravitino/catalog/glue/GlueTable.java+++ b/catalogs/catalog-glue/src/main/java/org/apache/gravitino/catalog/glue/GlueTable.java@@ -18,7 +18,7 @@*/package org.apache.gravitino.catalog.glue;-import static org.apache.gravitino.catalog.glue.GlueConstants.INPUT_FORMAT;+import static org.apache.gravitino.catalog.glue.GlueConstants.INPUT_FORMAT_CLASS;import static org.apache.gravitino.catalog.glue.GlueConstants.LOCATION;import static org.apache.gravitino.catalog.glue.GlueConstants.OUTPUT_FORMAT;import static org.apache.gravitino.catalog.glue.GlueConstants.SERDE_LIB;@@ -181,7 +181,7 @@ public class GlueTable extends BaseTable {}if (sd != null) {putIfNotBlank(properties, LOCATION, sd.location());- putIfNotBlank(properties, INPUT_FORMAT, sd.inputFormat());+ putIfNotBlank(properties, INPUT_FORMAT_CLASS, sd.inputFormat());putIfNotBlank(properties, OUTPUT_FORMAT, sd.outputFormat());if (sd.serdeInfo() != null) {putIfNotBlank(properties, SERDE_LIB, sd.serdeInfo().serializationLibrary());@@ -249,4 +249,34 @@ public class GlueTable extends BaseTable {public static Builder builder() {return new Builder();}++ /**+ * Sets the partitioning of the table. Package-private: only {@link GlueIcebergTableHelper} should+ * call this to enrich a table loaded from Glue with Iceberg-specific partition metadata.+ *+ * @param partitioning the partitioning transforms+ */+ void setPartitioning(Transform[] partitioning) {+ this.partitioning = partitioning;+ }++ /**+ * Sets the sort orders of the table. Package-private: only {@link GlueIcebergTableHelper} should+ * call this to enrich a table loaded from Glue with Iceberg-specific sort order metadata.+ *+ * @param sortOrders the sort orders+ */+ void setSortOrders(SortOrder[] sortOrders) {+ this.sortOrders = sortOrders;+ }++ /**+ * Sets the properties of the table. Package-private: only {@link GlueIcebergTableHelper} should+ * call this to merge Iceberg metadata properties into a table loaded from Glue.+ *+ * @param properties the properties map+ */+ void setProperties(Map<String, String> properties) {+ this.properties = properties;+ }}diff --git a/catalogs/catalog-glue/src/main/java/org/apache/gravitino/catalog/glue/GlueTablePropertiesMetadata.java b/catalogs/catalog-glue/src/main/java/org/apache/gravitino/catalog/glue/GlueTablePropertiesMetadata.javaindex e6bad6a86c..d798cc769c 100644--- a/catalogs/catalog-glue/src/main/java/org/apache/gravitino/catalog/glue/GlueTablePropertiesMetadata.java+++ b/catalogs/catalog-glue/src/main/java/org/apache/gravitino/catalog/glue/GlueTablePropertiesMetadata.java@@ -18,12 +18,20 @@*/package org.apache.gravitino.catalog.glue;+import static org.apache.gravitino.catalog.glue.GlueConstants.FORMAT;+import static org.apache.gravitino.catalog.glue.GlueConstants.INPUT_FORMAT_CLASS;import static org.apache.gravitino.catalog.glue.GlueConstants.METADATA_LOCATION;+import static org.apache.gravitino.catalog.glue.GlueConstants.OUTPUT_FORMAT;+import static org.apache.gravitino.catalog.glue.GlueConstants.SERDE_LIB;import static org.apache.gravitino.catalog.glue.GlueConstants.TABLE_FORMAT;+import static org.apache.gravitino.connector.PropertyEntry.stringImmutablePropertyEntry;import static org.apache.gravitino.connector.PropertyEntry.stringOptionalPropertyEntry;-import com.google.common.collect.ImmutableMap;+import com.google.common.collect.ImmutableList;+import com.google.common.collect.Maps;+import java.util.List;import java.util.Map;+import org.apache.gravitino.catalog.hive.HiveStorageConstants;import org.apache.gravitino.connector.BasePropertiesMetadata;import org.apache.gravitino.connector.PropertyEntry;@@ -40,25 +48,55 @@ import org.apache.gravitino.connector.PropertyEntry;*/public class GlueTablePropertiesMetadata extends BasePropertiesMetadata {- private static final Map<String, PropertyEntry<?>> PROPERTIES_METADATA =- ImmutableMap.<String, PropertyEntry<?>>builder()- .put(- TABLE_FORMAT,- stringOptionalPropertyEntry(- TABLE_FORMAT,- "Table format stored in Table.parameters(). Common values: ICEBERG, HIVE.",- false /* immutable */,- null /* defaultValue */,- false /* hidden */))- .put(- METADATA_LOCATION,- stringOptionalPropertyEntry(- METADATA_LOCATION,- "Iceberg metadata file location stored in Table.parameters().",- false /* immutable */,- null /* defaultValue */,- false /* hidden */))- .build();+ private static final Map<String, PropertyEntry<?>> PROPERTIES_METADATA;++ static {+ List<PropertyEntry<?>> propertyEntries =+ ImmutableList.of(+ stringOptionalPropertyEntry(+ TABLE_FORMAT,+ "Table format stored in Table.parameters(). Common values: ICEBERG, HIVE.",+ false,+ null,+ false),+ stringOptionalPropertyEntry(+ METADATA_LOCATION,+ "Iceberg metadata file location stored in Table.parameters().",+ false,+ null,+ false),+ stringImmutablePropertyEntry(+ FORMAT,+ "The table file format (parquet, orc, textfile, etc.). When set, "+ + "input-format, output-format, and serde-lib are derived from this.",+ false,+ null,+ false,+ false),+ stringImmutablePropertyEntry(+ INPUT_FORMAT_CLASS,+ "The input format class for the table.",+ false,+ HiveStorageConstants.TEXT_INPUT_FORMAT_CLASS,+ false,+ false),+ stringImmutablePropertyEntry(+ OUTPUT_FORMAT,+ "The output format class for the table.",+ false,+ HiveStorageConstants.IGNORE_KEY_OUTPUT_FORMAT_CLASS,+ false,+ false),+ stringImmutablePropertyEntry(+ SERDE_LIB,+ "The serde library class for the table.",+ false,+ HiveStorageConstants.LAZY_SIMPLE_SERDE_CLASS,+ false,+ false));++ PROPERTIES_METADATA = Maps.uniqueIndex(propertyEntries, PropertyEntry::getName);+ }@Overrideprotected Map<String, PropertyEntry<?>> specificPropertyEntries() {diff --git a/catalogs/catalog-glue/src/main/java/org/apache/gravitino/catalog/glue/GravitinoGlueCredentialsProvider.java b/catalogs/catalog-glue/src/main/java/org/apache/gravitino/catalog/glue/GravitinoGlueCredentialsProvider.javanew file mode 100644index 0000000000..67b55bc1d0--- /dev/null+++ b/catalogs/catalog-glue/src/main/java/org/apache/gravitino/catalog/glue/GravitinoGlueCredentialsProvider.java@@ -0,0 +1,68 @@+/*+ * 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.catalog.glue;++import java.util.Map;+import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;+import software.amazon.awssdk.auth.credentials.AwsCredentials;+import software.amazon.awssdk.auth.credentials.AwsCredentialsProvider;++/**+ * AWS credentials provider for Iceberg {@code GlueCatalog} that reads static credentials from a+ * properties map.+ *+ * <p>Iceberg 1.10+ no longer supports {@code client.access-key-id} directly; credentials must be+ * supplied via {@code client.credentials-provider}. This class is configured in {@link+ * GlueIcebergTableHelper#createGlueCatalog} when explicit credentials are provided.+ */+class GravitinoGlueCredentialsProvider implements AwsCredentialsProvider {++ private static final String ACCESS_KEY_ID = "access-key-id";+ private static final String SECRET_ACCESS_KEY = "secret-access-key";++ private final String accessKeyId;+ private final String secretAccessKey;++ /**+ * Creates a credentials provider from the given properties map.+ *+ * @param properties map containing {@code access-key-id} and {@code secret-access-key}+ * @return a new {@link AwsCredentialsProvider} instance+ */+ public static AwsCredentialsProvider create(Map<String, String> properties) {+ return new GravitinoGlueCredentialsProvider(+ properties.get(ACCESS_KEY_ID), properties.get(SECRET_ACCESS_KEY));+ }++ GravitinoGlueCredentialsProvider(String accessKeyId, String secretAccessKey) {+ this.accessKeyId = accessKeyId;+ this.secretAccessKey = secretAccessKey;+ }++ @Override+ public AwsCredentials resolveCredentials() {+ if (accessKeyId == null || accessKeyId.isEmpty()) {+ throw new IllegalStateException("Access key ID is not set");+ }+ if (secretAccessKey == null || secretAccessKey.isEmpty()) {+ throw new IllegalStateException("Secret access key is not set");+ }+ return AwsBasicCredentials.create(accessKeyId, secretAccessKey);+ }+}diff --git a/catalogs/catalog-glue/src/main/resources/glue.conf b/catalogs/catalog-glue/src/main/resources/glue.confnew file mode 100644index 0000000000..106d35b89d--- /dev/null+++ b/catalogs/catalog-glue/src/main/resources/glue.conf@@ -0,0 +1,22 @@+#+# 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.+#++## This file holds common configurations for AWS Glue catalog.+## The format of the key is 'gravitino.bypass.{glue-inner-config-key}' and `glue-inner-config-key`+## is the real key that is passed to the AWS Glue client.diff --git a/catalogs/catalog-glue/src/test/java/org/apache/gravitino/catalog/glue/GlueTableTestBase.java b/catalogs/catalog-glue/src/test/java/org/apache/gravitino/catalog/glue/GlueTableTestBase.javaindex f51262f745..e119fcb989 100644--- a/catalogs/catalog-glue/src/test/java/org/apache/gravitino/catalog/glue/GlueTableTestBase.java+++ b/catalogs/catalog-glue/src/test/java/org/apache/gravitino/catalog/glue/GlueTableTestBase.java@@ -134,7 +134,7 @@ abstract class GlueTableTestBase {try {GlueTable t = GlueTable.fromGlueTable(glueTable, TYPE_CONVERTER);assertNotNull(t.properties().get(GlueConstants.LOCATION));- assertNotNull(t.properties().get(GlueConstants.INPUT_FORMAT));+ assertNotNull(t.properties().get(GlueConstants.INPUT_FORMAT_CLASS));assertNotNull(t.properties().get(GlueConstants.OUTPUT_FORMAT));assertNotNull(t.properties().get(GlueConstants.SERDE_LIB));assertEquals("EXTERNAL_TABLE", t.properties().get(GlueConstants.TABLE_TYPE));diff --git a/catalogs/catalog-glue/src/test/java/org/apache/gravitino/catalog/glue/TestAwsGlueCatalogOperations.java b/catalogs/catalog-glue/src/test/java/org/apache/gravitino/catalog/glue/TestAwsGlueCatalogOperations.javanew file mode 100644index 0000000000..c5f6e2ec0e--- /dev/null+++ b/catalogs/catalog-glue/src/test/java/org/apache/gravitino/catalog/glue/TestAwsGlueCatalogOperations.java@@ -0,0 +1,233 @@+/*+ * 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.catalog.glue;++import static org.junit.jupiter.api.Assertions.assertEquals;+import static org.junit.jupiter.api.Assertions.assertNotNull;+import static org.junit.jupiter.api.Assertions.assertThrows;++import java.util.HashMap;+import java.util.Map;+import org.apache.gravitino.NameIdentifier;+import org.apache.gravitino.Namespace;+import org.apache.gravitino.rel.Column;+import org.apache.gravitino.rel.Table;+import org.apache.gravitino.rel.TableChange;+import org.apache.gravitino.rel.expressions.distributions.Distributions;+import org.apache.gravitino.rel.expressions.sorts.SortOrders;+import org.apache.gravitino.rel.expressions.transforms.Transforms;+import org.apache.gravitino.rel.indexes.Indexes;+import org.apache.gravitino.rel.types.Types;+import org.junit.jupiter.api.AfterAll;+import org.junit.jupiter.api.BeforeAll;+import org.junit.jupiter.api.Test;+import org.junit.jupiter.api.condition.EnabledIfEnvironmentVariable;++/**+ * Integration tests for {@link GlueCatalogOperations} against a real AWS Glue endpoint.+ *+ * <p>Only runs when {@code AWS_ACCESS_KEY_ID} is set. Required environment variables:+ *+ * <ul>+ * <li>{@code AWS_ACCESS_KEY_ID}+ * <li>{@code AWS_SECRET_ACCESS_KEY}+ * <li>{@code AWS_DEFAULT_REGION} (e.g. {@code ap-northeast-1})+ * <li>{@code GLUE_CATALOG_ID} (12-digit AWS account ID; optional)+ * </ul>+ */+@EnabledIfEnvironmentVariable(named = "AWS_ACCESS_KEY_ID", matches = ".+")+class TestAwsGlueCatalogOperations {++ private static GlueCatalogOperations ops;+ private static String s3TestBucket;+ private static final String TEST_SCHEMA = "aws_glue_ops_it_" + System.currentTimeMillis();+ private static final Namespace NS = Namespace.of("metalake", "catalog");++ @BeforeAll+ static void setup() {+ s3TestBucket = System.getenv("AWS_S3_TEST_BUCKET");+ if (s3TestBucket == null || s3TestBucket.isEmpty()) {+ throw new IllegalStateException(+ "AWS_S3_TEST_BUCKET is not set. Set it to a writable S3 bucket for Iceberg integration tests.");+ }++ Map<String, String> config = new HashMap<>();+ config.put(+ GlueConstants.AWS_REGION, System.getenv().getOrDefault("AWS_DEFAULT_REGION", "us-east-1"));+ String accessKey = System.getenv("AWS_ACCESS_KEY_ID");+ String secretKey = System.getenv("AWS_SECRET_ACCESS_KEY");+ if (accessKey != null) {+ config.put(GlueConstants.AWS_ACCESS_KEY_ID, accessKey);+ }+ if (secretKey != null) {+ config.put(GlueConstants.AWS_SECRET_ACCESS_KEY, secretKey);+ }+ String catalogId = System.getenv("GLUE_CATALOG_ID");+ if (catalogId != null) {+ config.put(GlueConstants.AWS_GLUE_CATALOG_ID, catalogId);+ }++ ops = new GlueCatalogOperations();+ ops.initialize(config, null, null);++ ops.createSchema(NameIdentifier.of(NS, TEST_SCHEMA), "IT schema", Map.of());+ }++ @AfterAll+ static void teardown() {+ if (ops == null) {+ return;+ }+ try {+ NameIdentifier[] tables = ops.listTables(Namespace.of(NS.level(0), NS.level(1), TEST_SCHEMA));+ for (NameIdentifier t : tables) {+ ops.dropTable(t);+ }+ } catch (Exception ignored) {+ }+ try {+ ops.dropSchema(NameIdentifier.of(NS, TEST_SCHEMA), true);+ } catch (Exception ignored) {+ }+ ops.glueClient.close();+ }++ @Test+ void testRenameTableIsUnsupported() {+ String tableName = "rename_test_" + System.currentTimeMillis();+ NameIdentifier ident = NameIdentifier.of(NS.level(0), NS.level(1), TEST_SCHEMA, tableName);++ Column col = Column.of("id", Types.IntegerType.get(), "pk");+ ops.createTable(+ ident,+ new Column[] {col},+ "test table",+ Map.of(),+ Transforms.EMPTY_TRANSFORM,+ Distributions.NONE,+ SortOrders.NONE,+ Indexes.EMPTY_INDEXES);++ try {+ assertThrows(+ UnsupportedOperationException.class,+ () -> ops.alterTable(ident, TableChange.rename("new_name")));+ } finally {+ ops.dropTable(ident);+ }+ }++ @Test+ void testCreateIcebergTable() {+ String tableName = "iceberg_create_" + System.currentTimeMillis();+ NameIdentifier ident = NameIdentifier.of(NS.level(0), NS.level(1), TEST_SCHEMA, tableName);++ Column col = Column.of("id", Types.LongType.get(), "pk", false, false, null);+ Map<String, String> props = new HashMap<>();+ props.put(GlueConstants.TABLE_FORMAT, "ICEBERG");+ props.put(GlueConstants.LOCATION, "s3://" + s3TestBucket + "/iceberg/" + tableName);++ try {+ Table created =+ ops.createTable(+ ident,+ new Column[] {col},+ "iceberg table",+ props,+ Transforms.EMPTY_TRANSFORM,+ Distributions.NONE,+ SortOrders.NONE,+ Indexes.EMPTY_INDEXES);++ assertEquals("iceberg table", created.comment());+ assertEquals(1, created.columns().length);+ assertEquals("id", created.columns()[0].name());+ assertEquals(Types.LongType.get(), created.columns()[0].dataType());++ Table loaded = ops.loadTable(ident);+ assertEquals("ICEBERG", loaded.properties().get(GlueConstants.TABLE_FORMAT));+ assertNotNull(loaded.properties().get(GlueConstants.METADATA_LOCATION));+ } finally {+ ops.dropTable(ident);+ }+ }++ @Test+ void testAlterIcebergTableAddColumn() {+ String tableName = "iceberg_alter_col_" + System.currentTimeMillis();+ NameIdentifier ident = NameIdentifier.of(NS.level(0), NS.level(1), TEST_SCHEMA, tableName);++ Column col = Column.of("id", Types.LongType.get(), "pk", false, false, null);+ Map<String, String> props = new HashMap<>();+ props.put(GlueConstants.TABLE_FORMAT, "ICEBERG");+ props.put(GlueConstants.LOCATION, "s3://" + s3TestBucket + "/iceberg/" + tableName);++ try {+ ops.createTable(+ ident,+ new Column[] {col},+ "iceberg table",+ props,+ Transforms.EMPTY_TRANSFORM,+ Distributions.NONE,+ SortOrders.NONE,+ Indexes.EMPTY_INDEXES);++ ops.alterTable(+ ident, TableChange.addColumn(new String[] {"score"}, Types.DoubleType.get(), true));++ Table loaded = ops.loadTable(ident);+ assertEquals(2, loaded.columns().length);+ assertEquals("score", loaded.columns()[1].name());+ assertEquals(Types.DoubleType.get(), loaded.columns()[1].dataType());+ } finally {+ ops.dropTable(ident);+ }+ }++ @Test+ void testAlterIcebergTableSetProperty() {+ String tableName = "iceberg_alter_prop_" + System.currentTimeMillis();+ NameIdentifier ident = NameIdentifier.of(NS.level(0), NS.level(1), TEST_SCHEMA, tableName);++ Column col = Column.of("id", Types.LongType.get(), "pk", false, false, null);+ Map<String, String> props = new HashMap<>();+ props.put(GlueConstants.TABLE_FORMAT, "ICEBERG");+ props.put(GlueConstants.LOCATION, "s3://" + s3TestBucket + "/iceberg/" + tableName);++ try {+ ops.createTable(+ ident,+ new Column[] {col},+ "iceberg table",+ props,+ Transforms.EMPTY_TRANSFORM,+ Distributions.NONE,+ SortOrders.NONE,+ Indexes.EMPTY_INDEXES);++ ops.alterTable(ident, TableChange.setProperty("write.format.default", "parquet"));++ Table loaded = ops.loadTable(ident);+ assertEquals("parquet", loaded.properties().get("write.format.default"));+ } finally {+ ops.dropTable(ident);+ }+ }+}diff --git a/catalogs/catalog-glue/src/test/java/org/apache/gravitino/catalog/glue/TestAwsGlueTableConversion.java b/catalogs/catalog-glue/src/test/java/org/apache/gravitino/catalog/glue/TestAwsGlueTableConversion.javaindex 234f678fd3..5c8c609a3e 100644--- a/catalogs/catalog-glue/src/test/java/org/apache/gravitino/catalog/glue/TestAwsGlueTableConversion.java+++ b/catalogs/catalog-glue/src/test/java/org/apache/gravitino/catalog/glue/TestAwsGlueTableConversion.java@@ -20,6 +20,7 @@ package org.apache.gravitino.catalog.glue;import java.util.HashMap;import java.util.Map;+import org.apache.gravitino.catalog.hive.HiveStorageConstants;import org.junit.jupiter.api.AfterAll;import org.junit.jupiter.api.BeforeAll;import org.junit.jupiter.api.condition.EnabledIfEnvironmentVariable;@@ -61,10 +62,6 @@ class TestAwsGlueTableConversion extends GlueTableTestBase {private static String catalogId;private static String testSchemaName;- private static final String INPUT_FMT = "org.apache.hadoop.mapred.TextInputFormat";- private static final String OUTPUT_FMT =- "org.apache.hadoop.hive.ql.io.HiveIgnoreKeyTextOutputFormat";- private static final String SERDE = "org.apache.hadoop.hive.serde2.lazy.LazySimpleSerDe";private static final String LOCATION = "s3://my-bucket/warehouse/";@BeforeAll@@ -109,9 +106,12 @@ class TestAwsGlueTableConversion extends GlueTableTestBase {Column.builder().name("id").type("bigint").comment("primary key").build(),Column.builder().name("name").type("string").build()).location(LOCATION + tableName)- .inputFormat(INPUT_FMT)- .outputFormat(OUTPUT_FMT)- .serdeInfo(SerDeInfo.builder().serializationLibrary(SERDE).build())+ .inputFormat(HiveStorageConstants.TEXT_INPUT_FORMAT_CLASS)+ .outputFormat(HiveStorageConstants.IGNORE_KEY_OUTPUT_FORMAT_CLASS)+ .serdeInfo(+ SerDeInfo.builder()+ .serializationLibrary(HiveStorageConstants.LAZY_SIMPLE_SERDE_CLASS)+ .build()).bucketColumns("id").numberOfBuckets(4).sortColumns(Order.builder().column("name").sortOrder(1).build())diff --git a/catalogs/catalog-glue/src/test/java/org/apache/gravitino/catalog/glue/TestGlueCatalogOperationsForIceberg.java b/catalogs/catalog-glue/src/test/java/org/apache/gravitino/catalog/glue/TestGlueCatalogOperationsForIceberg.javanew file mode 100644index 0000000000..f901d38958--- /dev/null+++ b/catalogs/catalog-glue/src/test/java/org/apache/gravitino/catalog/glue/TestGlueCatalogOperationsForIceberg.java@@ -0,0 +1,281 @@+/*+ * 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.catalog.glue;++import static org.apache.gravitino.catalog.glue.GlueConstants.ICEBERG_TABLE_TYPE_VALUE;+import static org.apache.gravitino.catalog.glue.GlueConstants.TABLE_TYPE_PARAM;+import static org.junit.jupiter.api.Assertions.assertFalse;+import static org.junit.jupiter.api.Assertions.assertThrows;+import static org.junit.jupiter.api.Assertions.assertTrue;+import static org.mockito.ArgumentMatchers.any;+import static org.mockito.Mockito.mock;+import static org.mockito.Mockito.verify;+import static org.mockito.Mockito.when;++import java.util.Map;+import java.util.Set;+import org.apache.gravitino.NameIdentifier;+import org.apache.gravitino.rel.TableChange;+import org.apache.gravitino.rel.expressions.distributions.Distributions;+import org.apache.gravitino.rel.expressions.transforms.Transform;+import org.apache.gravitino.rel.indexes.Indexes;+import org.apache.gravitino.rel.types.Types;+import org.apache.iceberg.Schema;+import org.apache.iceberg.Table;+import org.apache.iceberg.catalog.Catalog;+import org.apache.iceberg.catalog.TableIdentifier;+import org.junit.jupiter.api.BeforeEach;+import org.junit.jupiter.api.Test;+import org.mockito.Mockito;+import software.amazon.awssdk.services.glue.GlueClient;+import software.amazon.awssdk.services.glue.model.GetTableRequest;+import software.amazon.awssdk.services.glue.model.GetTableResponse;+import software.amazon.awssdk.services.glue.model.StorageDescriptor;++class TestGlueCatalogOperationsForIceberg {++ private static final String DB = "mydb";+ private static final String TABLE = "ice1";+ private static final String LOCATION = "s3://my-bucket/warehouse/ice1";++ private GlueClient mockClient;+ private GlueCatalogOperations ops;+ private Catalog mockIcebergCatalog;++ @BeforeEach+ void setup() {+ mockClient = mock(GlueClient.class);+ mockIcebergCatalog = mock(Catalog.class);+ ops = new GlueCatalogOperations();+ ops.glueClient = mockClient;+ ops.catalogId = null;+ ops.tableFormatFilter = null;+ ops.defaultTableFormat = GlueConstants.DEFAULT_TABLE_FORMAT_VALUE;+ ops.icebergGlueCatalog = mockIcebergCatalog;+ }++ // ---------------------------------------------------------------------------+ // isIcebergTable+ // ---------------------------------------------------------------------------++ @Test+ void testIsIcebergTable_withIcebergType() {+ software.amazon.awssdk.services.glue.model.Table t =+ software.amazon.awssdk.services.glue.model.Table.builder()+ .parameters(Map.of(TABLE_TYPE_PARAM, ICEBERG_TABLE_TYPE_VALUE))+ .build();+ assertTrue(GlueIcebergTableHelper.isIcebergTable(t));+ }++ @Test+ void testIsIcebergTable_caseInsensitive() {+ software.amazon.awssdk.services.glue.model.Table t =+ software.amazon.awssdk.services.glue.model.Table.builder()+ .parameters(Map.of("table_type", "iceberg"))+ .build();+ assertTrue(GlueIcebergTableHelper.isIcebergTable(t));+ }++ @Test+ void testIsIcebergTable_hiveTable() {+ software.amazon.awssdk.services.glue.model.Table t =+ software.amazon.awssdk.services.glue.model.Table.builder()+ .parameters(Map.of("table_type", "HIVE"))+ .build();+ assertFalse(GlueIcebergTableHelper.isIcebergTable(t));+ }++ @Test+ void testIsIcebergTable_noParameters() {+ software.amazon.awssdk.services.glue.model.Table t =+ software.amazon.awssdk.services.glue.model.Table.builder().build();+ assertFalse(GlueIcebergTableHelper.isIcebergTable(t));+ }++ // ---------------------------------------------------------------------------+ // createTable Iceberg routing+ // ---------------------------------------------------------------------------++ @Test+ void testCreateTable_icebergRoutesToIcebergSdk() {+ software.amazon.awssdk.services.glue.model.Table created =+ software.amazon.awssdk.services.glue.model.Table.builder()+ .name(TABLE)+ .parameters(+ Map.of(+ "table_type",+ "ICEBERG",+ "metadata_location",+ LOCATION + "/metadata/00000.metadata.json"))+ .storageDescriptor(StorageDescriptor.builder().build())+ .build();++ Catalog.TableBuilder mockBuilder = mock(Catalog.TableBuilder.class, Mockito.RETURNS_SELF);+ when(mockIcebergCatalog.buildTable(any(TableIdentifier.class), any(Schema.class)))+ .thenReturn(mockBuilder);+ when(mockClient.getTable(any(GetTableRequest.class)))+ .thenReturn(GetTableResponse.builder().table(created).build());++ NameIdentifier ident = NameIdentifier.of("cat", "ns", DB, TABLE);+ GlueColumn[] cols = {+ GlueColumn.builder().withName("id").withType(Types.LongType.get()).withNullable(false).build()+ };++ ops.createTable(+ ident,+ cols,+ "iceberg table",+ Map.of(GlueConstants.TABLE_FORMAT, "iceberg", GlueConstants.LOCATION, LOCATION),+ new Transform[0],+ Distributions.NONE,+ null,+ Indexes.EMPTY_INDEXES);++ verify(mockIcebergCatalog).buildTable(any(TableIdentifier.class), any(Schema.class));+ verify(mockBuilder).create();+ }++ // ---------------------------------------------------------------------------+ // alterTable Iceberg routing+ // ---------------------------------------------------------------------------++ @Test+ void testAlterTable_icebergRoutesToIcebergSdk() {+ software.amazon.awssdk.services.glue.model.Table rawTable =+ software.amazon.awssdk.services.glue.model.Table.builder()+ .name(TABLE)+ .parameters(Map.of(TABLE_TYPE_PARAM, ICEBERG_TABLE_TYPE_VALUE))+ .storageDescriptor(StorageDescriptor.builder().build())+ .build();++ when(mockClient.getTable(any(GetTableRequest.class)))+ .thenReturn(GetTableResponse.builder().table(rawTable).build());++ Table mockTable = mock(Table.class);+ org.apache.iceberg.UpdateSchema mockUpdateSchema = mock(org.apache.iceberg.UpdateSchema.class);+ when(mockIcebergCatalog.loadTable(any(TableIdentifier.class))).thenReturn(mockTable);+ when(mockTable.updateSchema()).thenReturn(mockUpdateSchema);++ NameIdentifier ident = NameIdentifier.of("cat", "ns", DB, TABLE);+ ops.alterTable(+ ident, TableChange.addColumn(new String[] {"score"}, Types.DoubleType.get(), true));++ verify(mockIcebergCatalog, Mockito.times(2)).loadTable(any(TableIdentifier.class));+ verify(mockUpdateSchema)+ .addColumn("score", org.apache.iceberg.types.Types.DoubleType.get(), (String) null);+ verify(mockUpdateSchema).commit();+ }++ @Test+ void testCreateTable_icebergMissingLocationThrows() {+ NameIdentifier ident = NameIdentifier.of("cat", "ns", DB, TABLE);+ GlueColumn[] cols = {+ GlueColumn.builder().withName("id").withType(Types.LongType.get()).withNullable(false).build()+ };++ assertThrows(+ IllegalArgumentException.class,+ () ->+ ops.createTable(+ ident,+ cols,+ "iceberg table",+ Map.of(GlueConstants.TABLE_FORMAT, "iceberg"), // missing location+ new Transform[0],+ Distributions.NONE,+ null,+ Indexes.EMPTY_INDEXES));+ }++ @Test+ void testAlterTable_icebergRenameThrows() {+ software.amazon.awssdk.services.glue.model.Table rawTable =+ software.amazon.awssdk.services.glue.model.Table.builder()+ .name(TABLE)+ .parameters(Map.of(TABLE_TYPE_PARAM, ICEBERG_TABLE_TYPE_VALUE))+ .storageDescriptor(StorageDescriptor.builder().build())+ .build();++ when(mockClient.getTable(any(GetTableRequest.class)))+ .thenReturn(GetTableResponse.builder().table(rawTable).build());++ NameIdentifier ident = NameIdentifier.of("cat", "ns", DB, TABLE);+ assertThrows(+ IllegalArgumentException.class,+ () -> ops.alterTable(ident, TableChange.rename("new_table_name")));+ }++ @Test+ void testCreateTable_defaultTableFormatIcebergRoutesToIcebergSdk() {+ software.amazon.awssdk.services.glue.model.Table created =+ software.amazon.awssdk.services.glue.model.Table.builder()+ .name(TABLE)+ .parameters(+ Map.of(TABLE_TYPE_PARAM, ICEBERG_TABLE_TYPE_VALUE, "metadata_location", LOCATION))+ .storageDescriptor(StorageDescriptor.builder().build())+ .build();++ Catalog.TableBuilder mockBuilder = mock(Catalog.TableBuilder.class, Mockito.RETURNS_SELF);+ when(mockIcebergCatalog.buildTable(any(TableIdentifier.class), any(Schema.class)))+ .thenReturn(mockBuilder);+ when(mockClient.getTable(any(GetTableRequest.class)))+ .thenReturn(GetTableResponse.builder().table(created).build());++ ops.defaultTableFormat = "iceberg";+ NameIdentifier ident = NameIdentifier.of("cat", "ns", DB, TABLE);+ GlueColumn[] cols = {+ GlueColumn.builder().withName("id").withType(Types.LongType.get()).withNullable(false).build()+ };+ ops.createTable(+ ident,+ cols,+ "iceberg table",+ Map.of(GlueConstants.LOCATION, LOCATION), // no table-format; relies on defaultTableFormat+ new Transform[0],+ Distributions.NONE,+ null,+ Indexes.EMPTY_INDEXES);++ verify(mockIcebergCatalog).buildTable(any(TableIdentifier.class), any(Schema.class));+ verify(mockBuilder).create();+ }++ @Test+ void testMatchesFormatFilter_icebergFallbackViaTableType() {+ // Table has table_type=ICEBERG but no table-format property (e.g. created by external tooling)+ software.amazon.awssdk.services.glue.model.Table externalIceberg =+ software.amazon.awssdk.services.glue.model.Table.builder()+ .name(TABLE)+ .parameters(Map.of(TABLE_TYPE_PARAM, ICEBERG_TABLE_TYPE_VALUE))+ .build();++ ops.tableFormatFilter = Set.of("iceberg");+ assertTrue(+ GlueIcebergTableHelper.isIcebergTable(externalIceberg),+ "Table with table_type=ICEBERG should be recognized as Iceberg");++ // A hive table should not match iceberg filter+ software.amazon.awssdk.services.glue.model.Table hiveTable =+ software.amazon.awssdk.services.glue.model.Table.builder()+ .name("hive_t")+ .parameters(Map.of("table_type", "HIVE"))+ .build();+ assertFalse(GlueIcebergTableHelper.isIcebergTable(hiveTable));+ }+}diff --git a/catalogs/catalog-glue/src/test/java/org/apache/gravitino/catalog/glue/TestGlueCatalogPropertiesMetadata.java b/catalogs/catalog-glue/src/test/java/org/apache/gravitino/catalog/glue/TestGlueCatalogPropertiesMetadata.javaindex 9a4a8c8201..d540f70fa0 100644--- a/catalogs/catalog-glue/src/test/java/org/apache/gravitino/catalog/glue/TestGlueCatalogPropertiesMetadata.java+++ b/catalogs/catalog-glue/src/test/java/org/apache/gravitino/catalog/glue/TestGlueCatalogPropertiesMetadata.java@@ -63,12 +63,6 @@ class TestGlueCatalogPropertiesMetadata {assertTrue(metadata.isImmutableProperty(AWS_GLUE_CATALOG_ID));}- @Test- void testCredentialsAreHidden() {- assertTrue(metadata.isHiddenProperty(AWS_ACCESS_KEY_ID));- assertTrue(metadata.isHiddenProperty(AWS_SECRET_ACCESS_KEY));- }-@Testvoid testCredentialsAreOptional() {assertFalse(metadata.isRequiredProperty(AWS_ACCESS_KEY_ID));diff --git a/catalogs/catalog-glue/src/test/java/org/apache/gravitino/catalog/glue/TestGlueCatalogTableOperations.java b/catalogs/catalog-glue/src/test/java/org/apache/gravitino/catalog/glue/TestGlueCatalogTableOperations.javaindex 4e390f1144..43447d3cc4 100644--- a/catalogs/catalog-glue/src/test/java/org/apache/gravitino/catalog/glue/TestGlueCatalogTableOperations.java+++ b/catalogs/catalog-glue/src/test/java/org/apache/gravitino/catalog/glue/TestGlueCatalogTableOperations.java@@ -34,6 +34,7 @@ import java.util.Map;import java.util.Set;import org.apache.gravitino.NameIdentifier;import org.apache.gravitino.Namespace;+import org.apache.gravitino.catalog.hive.HiveStorageConstants;import org.apache.gravitino.exceptions.NoSuchSchemaException;import org.apache.gravitino.exceptions.NoSuchTableException;import org.apache.gravitino.exceptions.TableAlreadyExistsException;@@ -244,11 +245,14 @@ class TestGlueCatalogTableOperations {NameIdentifier ident = NameIdentifier.of("metalake", "catalog", "mydb", "mytable");Map<String, String> props =Map.of(- GlueConstants.LOCATION, "s3://my-bucket/path",- GlueConstants.INPUT_FORMAT, "org.apache.hadoop.mapred.TextInputFormat",+ GlueConstants.LOCATION,+ "s3://my-bucket/path",+ GlueConstants.INPUT_FORMAT_CLASS,+ HiveStorageConstants.TEXT_INPUT_FORMAT_CLASS,GlueConstants.OUTPUT_FORMAT,- "org.apache.hadoop.hive.ql.io.HiveIgnoreKeyTextOutputFormat",- GlueConstants.TABLE_TYPE, "EXTERNAL_TABLE");+ HiveStorageConstants.IGNORE_KEY_OUTPUT_FORMAT_CLASS,+ GlueConstants.TABLE_TYPE,+ "EXTERNAL_TABLE");ArgumentCaptor<CreateTableRequest> captor = ArgumentCaptor.forClass(CreateTableRequest.class);@@ -289,13 +293,8 @@ class TestGlueCatalogTableOperations {when(mockClient.updateTable(any(UpdateTableRequest.class))).thenReturn(UpdateTableResponse.builder().build());- ArgumentCaptor<UpdateTableRequest> captor = ArgumentCaptor.forClass(UpdateTableRequest.class);+ GlueTable result = ops.alterTable(ident, TableChange.updateComment("new comment"));- GlueTable result =- ops.alterTable(ident, TableChange.rename("new"), TableChange.updateComment("new comment"));-- verify(mockClient).updateTable(captor.capture());- assertEquals("new", captor.getValue().tableInput().name());assertEquals("new comment", result.comment());}diff --git a/catalogs/catalog-glue/src/test/java/org/apache/gravitino/catalog/glue/TestGlueIceberg.java b/catalogs/catalog-glue/src/test/java/org/apache/gravitino/catalog/glue/TestGlueIceberg.javadeleted file mode 100644index 89b5cd7e42..0000000000--- a/catalogs/catalog-glue/src/test/java/org/apache/gravitino/catalog/glue/TestGlueIceberg.java+++ /dev/null@@ -1,597 +0,0 @@-/*- * 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.catalog.glue;--import static org.apache.gravitino.catalog.glue.GlueConstants.CURRENT_SCHEMA_ID_PARAM;-import static org.apache.gravitino.catalog.glue.GlueConstants.ICEBERG_TABLE_TYPE_VALUE;-import static org.apache.gravitino.catalog.glue.GlueConstants.TABLE_TYPE_PARAM;-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 static org.mockito.ArgumentMatchers.any;-import static org.mockito.Mockito.mock;-import static org.mockito.Mockito.verify;-import static org.mockito.Mockito.when;--import java.util.Map;-import java.util.Set;-import org.apache.gravitino.NameIdentifier;-import org.apache.gravitino.rel.TableChange;-import org.apache.gravitino.rel.expressions.distributions.Distributions;-import org.apache.gravitino.rel.expressions.transforms.Transform;-import org.apache.gravitino.rel.indexes.Indexes;-import org.apache.gravitino.rel.types.Types;-import org.junit.jupiter.api.BeforeEach;-import org.junit.jupiter.api.Test;-import org.mockito.ArgumentCaptor;-import software.amazon.awssdk.services.glue.GlueClient;-import software.amazon.awssdk.services.glue.model.Column;-import software.amazon.awssdk.services.glue.model.CreateTableRequest;-import software.amazon.awssdk.services.glue.model.CreateTableResponse;-import software.amazon.awssdk.services.glue.model.GetTableRequest;-import software.amazon.awssdk.services.glue.model.GetTableResponse;-import software.amazon.awssdk.services.glue.model.IcebergSchema;-import software.amazon.awssdk.services.glue.model.IcebergStructField;-import software.amazon.awssdk.services.glue.model.StorageDescriptor;-import software.amazon.awssdk.services.glue.model.Table;-import software.amazon.awssdk.services.glue.model.UpdateTableRequest;-import software.amazon.awssdk.services.glue.model.UpdateTableResponse;--class TestGlueIceberg {-- private static final String DB = "mydb";- private static final String TABLE = "ice1";- private static final String LOCATION = "s3://my-bucket/warehouse/ice1";-- private GlueClient mockClient;- private GlueCatalogOperations ops;-- @BeforeEach- void setup() {- mockClient = mock(GlueClient.class);- ops = new GlueCatalogOperations();- ops.glueClient = mockClient;- ops.catalogId = null;- ops.tableFormatFilter = null;- ops.defaultTableFormat = GlueConstants.DEFAULT_TABLE_FORMAT_VALUE;- }-- // ---------------------------------------------------------------------------- // isIcebergTable- // ----------------------------------------------------------------------------- @Test- void testIsIcebergTable_withIcebergType() {- Table t =- Table.builder().parameters(Map.of(TABLE_TYPE_PARAM, ICEBERG_TABLE_TYPE_VALUE)).build();- assertTrue(GlueIcebergHelper.isIcebergTable(t));- }-- @Test- void testIsIcebergTable_caseInsensitive() {- Table t = Table.builder().parameters(Map.of("table_type", "iceberg")).build();- assertTrue(GlueIcebergHelper.isIcebergTable(t));- }-- @Test- void testIsIcebergTable_hiveTable() {- Table t = Table.builder().parameters(Map.of("table_type", "HIVE")).build();- assertFalse(GlueIcebergHelper.isIcebergTable(t));- }-- @Test- void testIsIcebergTable_noParameters() {- Table t = Table.builder().build();- assertFalse(GlueIcebergHelper.isIcebergTable(t));- }-- // ---------------------------------------------------------------------------- // hiveTypeToIcebergType- // ----------------------------------------------------------------------------- @Test- void testHiveTypeToDoc_primitives() {- assertEquals("long", GlueIcebergHelper.hiveTypeToIcebergType("bigint").asString());- assertEquals("int", GlueIcebergHelper.hiveTypeToIcebergType("int").asString());- assertEquals("int", GlueIcebergHelper.hiveTypeToIcebergType("smallint").asString());- assertEquals("float", GlueIcebergHelper.hiveTypeToIcebergType("float").asString());- assertEquals("double", GlueIcebergHelper.hiveTypeToIcebergType("double").asString());- assertEquals("boolean", GlueIcebergHelper.hiveTypeToIcebergType("boolean").asString());- assertEquals("binary", GlueIcebergHelper.hiveTypeToIcebergType("binary").asString());- assertEquals("date", GlueIcebergHelper.hiveTypeToIcebergType("date").asString());- assertEquals("timestamp", GlueIcebergHelper.hiveTypeToIcebergType("timestamp").asString());- assertEquals("string", GlueIcebergHelper.hiveTypeToIcebergType("string").asString());- }-- @Test- void testHiveTypeToDoc_decimal() {- var doc = GlueIcebergHelper.hiveTypeToIcebergType("decimal(18,2)");- var m = doc.asMap();- assertEquals("decimal", m.get("type").asString());- assertEquals(18, m.get("precision").asNumber().intValue());- assertEquals(2, m.get("scale").asNumber().intValue());- }-- @Test- void testHiveTypeToDoc_varchar() {- assertEquals("string", GlueIcebergHelper.hiveTypeToIcebergType("varchar(255)").asString());- }-- // ---------------------------------------------------------------------------- // gravitinoTypeToIcebergType- // ----------------------------------------------------------------------------- @Test- void testGravitinoTypeToDoc_primitives() {- assertEquals(- "long", GlueIcebergHelper.gravitinoTypeToIcebergType(Types.LongType.get()).asString());- assertEquals(- "int", GlueIcebergHelper.gravitinoTypeToIcebergType(Types.IntegerType.get()).asString());- assertEquals(- "float", GlueIcebergHelper.gravitinoTypeToIcebergType(Types.FloatType.get()).asString());- assertEquals(- "double", GlueIcebergHelper.gravitinoTypeToIcebergType(Types.DoubleType.get()).asString());- assertEquals(- "boolean",- GlueIcebergHelper.gravitinoTypeToIcebergType(Types.BooleanType.get()).asString());- assertEquals(- "string", GlueIcebergHelper.gravitinoTypeToIcebergType(Types.StringType.get()).asString());- assertEquals(- "date", GlueIcebergHelper.gravitinoTypeToIcebergType(Types.DateType.get()).asString());- assertEquals(- "timestamp",- GlueIcebergHelper.gravitinoTypeToIcebergType(Types.TimestampType.withoutTimeZone())- .asString());- assertEquals(- "timestamptz",- GlueIcebergHelper.gravitinoTypeToIcebergType(Types.TimestampType.withTimeZone())- .asString());- assertEquals(- "uuid", GlueIcebergHelper.gravitinoTypeToIcebergType(Types.UUIDType.get()).asString());- }-- @Test- void testGravitinoTypeToDoc_decimal() {- var doc = GlueIcebergHelper.gravitinoTypeToIcebergType(Types.DecimalType.of(10, 3));- var m = doc.asMap();- assertEquals("decimal", m.get("type").asString());- assertEquals(10, m.get("precision").asNumber().intValue());- assertEquals(3, m.get("scale").asNumber().intValue());- }-- @Test- void testGravitinoTypeToDoc_unsupported() {- assertThrows(- UnsupportedOperationException.class,- () -> GlueIcebergHelper.gravitinoTypeToIcebergType(Types.NullType.get()));- }-- // ---------------------------------------------------------------------------- // buildSchemaUpdate / extractSetProperties / validateChanges- // ----------------------------------------------------------------------------- @Test- void testBuildSchemaUpdate_addColumn() {- Table raw = icebergTable(icebergColumn("id", "long", 1, false));-- TableChange add = TableChange.addColumn(new String[] {"score"}, Types.FloatType.get(), true);- IcebergSchema schema = GlueIcebergHelper.buildSchemaUpdate(raw, add).orElseThrow().schema();-- assertEquals(2, schema.fields().size());- IcebergStructField newField = schema.fields().get(1);- assertEquals("score", newField.name());- assertEquals("float", newField.type().asString());- assertEquals(2, newField.id());- assertFalse(newField.required());- }-- @Test- void testBuildSchemaUpdate_deleteColumn() {- Table raw =- icebergTable(- icebergColumn("id", "long", 1, false), icebergColumn("name", "string", 2, true));-- TableChange delete = TableChange.deleteColumn(new String[] {"name"}, true);- IcebergSchema schema = GlueIcebergHelper.buildSchemaUpdate(raw, delete).orElseThrow().schema();-- assertEquals(1, schema.fields().size());- assertEquals("id", schema.fields().get(0).name());- }-- @Test- void testBuildSchemaUpdate_renameColumn() {- Table raw = icebergTable(icebergColumn("old_name", "string", 1, true));-- TableChange rename = TableChange.renameColumn(new String[] {"old_name"}, "new_name");- IcebergSchema schema = GlueIcebergHelper.buildSchemaUpdate(raw, rename).orElseThrow().schema();-- assertEquals("new_name", schema.fields().get(0).name());- assertEquals(1, schema.fields().get(0).id()); // ID preserved- }-- @Test- void testExtractSetProperties_singleProperty() {- TableChange set = TableChange.setProperty("write.format.default", "parquet");- Map<String, String> props = GlueIcebergHelper.extractSetProperties(set);- assertEquals(1, props.size());- assertEquals("parquet", props.get("write.format.default"));- }-- @Test- void testExtractSetProperties_empty() {- Map<String, String> props =- GlueIcebergHelper.extractSetProperties(- TableChange.addColumn(new String[] {"col"}, Types.LongType.get()));- assertTrue(props.isEmpty());- }-- @Test- void testValidateChanges_removePropertyThrows() {- assertThrows(- IllegalArgumentException.class,- () -> GlueIcebergHelper.validateChanges(TableChange.removeProperty("some.prop")));- }-- @Test- void testBuildSchemaUpdate_schemaIdIncrement() {- Table raw =- Table.builder()- .parameters(- Map.of(TABLE_TYPE_PARAM, ICEBERG_TABLE_TYPE_VALUE, CURRENT_SCHEMA_ID_PARAM, "3"))- .storageDescriptor(StorageDescriptor.builder().build())- .build();-- TableChange add = TableChange.addColumn(new String[] {"ts"}, Types.DateType.get(), true);- IcebergSchema schema = GlueIcebergHelper.buildSchemaUpdate(raw, add).orElseThrow().schema();- assertEquals(4, schema.schemaId());- }-- @Test- void testBuildSchemaUpdate_andExtractSetProperties_mixedChanges() {- Table raw = icebergTable(icebergColumn("id", "long", 1, false));- TableChange colChange = TableChange.addColumn(new String[] {"ts"}, Types.DateType.get(), true);- TableChange propChange = TableChange.setProperty("write.target-file-size-bytes", "134217728");-- IcebergSchema schema =- GlueIcebergHelper.buildSchemaUpdate(raw, colChange, propChange).orElseThrow().schema();- assertEquals(2, schema.fields().size());- assertEquals("ts", schema.fields().get(1).name());-- Map<String, String> props = GlueIcebergHelper.extractSetProperties(colChange, propChange);- assertEquals("134217728", props.get("write.target-file-size-bytes"));- }-- @Test- void testBuildSchemaUpdate_updateColumnType() {- Table raw = icebergTable(icebergColumn("id", "int", 1, false));-- IcebergSchema schema =- GlueIcebergHelper.buildSchemaUpdate(- raw, TableChange.updateColumnType(new String[] {"id"}, Types.LongType.get()))- .orElseThrow()- .schema();- assertEquals("long", schema.fields().get(0).type().asString());- assertEquals(1, schema.fields().get(0).id()); // field ID preserved- }-- @Test- void testBuildSchemaUpdate_emptyChanges() {- Table raw = icebergTable(icebergColumn("id", "long", 1, false));- assertFalse(GlueIcebergHelper.buildSchemaUpdate(raw).isPresent());- }-- @Test- void testBuildSchemaUpdate_nonSequentialFieldIds() {- Table raw =- icebergTable(- icebergColumn("a", "long", 1, false),- icebergColumn("b", "string", 5, true),- icebergColumn("c", "date", 10, true));-- IcebergSchema schema =- GlueIcebergHelper.buildSchemaUpdate(- raw, TableChange.addColumn(new String[] {"d"}, Types.IntegerType.get(), true))- .orElseThrow()- .schema();- IcebergStructField newField = schema.fields().get(3);- assertEquals("d", newField.name());- assertEquals(11, newField.id()); // max(1,5,10) + 1 = 11, not fields.size()+1 = 4- }-- @Test- void testBuildSchemaUpdate_columnNotFoundThrows() {- Table raw = icebergTable(icebergColumn("id", "long", 1, false));-- assertThrows(- IllegalArgumentException.class,- () ->- GlueIcebergHelper.buildSchemaUpdate(- raw, TableChange.renameColumn(new String[] {"nonexistent"}, "new_name")));- }-- @Test- void testHiveTypeToDoc_unknownTypeThrows() {- // Complex types (array, map, struct) in existing Iceberg schema must abort, not silently retype- assertThrows(- IllegalStateException.class,- () -> GlueIcebergHelper.hiveTypeToIcebergType("array<string>"));- }-- @Test- void testHiveTypeToDoc_malformedDecimalThrows() {- assertThrows(- IllegalStateException.class,- () -> GlueIcebergHelper.hiveTypeToIcebergType("decimal(abc,2)"));- }-- // ---------------------------------------------------------------------------- // createTable Iceberg routing- // ----------------------------------------------------------------------------- @Test- void testCreateTable_icebergRoutesOpenTableFormatInput() {- Table created =- Table.builder()- .name(TABLE)- .parameters(- Map.of(- "table_type",- "ICEBERG",- "metadata_location",- LOCATION + "/metadata/00000.metadata.json"))- .storageDescriptor(StorageDescriptor.builder().build())- .build();-- when(mockClient.createTable(any(CreateTableRequest.class)))- .thenReturn(CreateTableResponse.builder().build());- when(mockClient.getTable(any(GetTableRequest.class)))- .thenReturn(GetTableResponse.builder().table(created).build());-- NameIdentifier ident = NameIdentifier.of("cat", "ns", DB, TABLE);- GlueColumn[] cols = {- GlueColumn.builder().withName("id").withType(Types.LongType.get()).withNullable(false).build()- };-- ops.createTable(- ident,- cols,- "iceberg table",- Map.of(GlueConstants.TABLE_FORMAT, "iceberg", GlueConstants.LOCATION, LOCATION),- new Transform[0],- Distributions.NONE,- null,- Indexes.EMPTY_INDEXES);-- ArgumentCaptor<CreateTableRequest> captor = ArgumentCaptor.forClass(CreateTableRequest.class);- verify(mockClient).createTable(captor.capture());- CreateTableRequest req = captor.getValue();- assertNotNull(- req.openTableFormatInput(), "openTableFormatInput must be set for Iceberg tables");- assertNotNull(req.openTableFormatInput().icebergInput());- }-- // ---------------------------------------------------------------------------- // alterTable Iceberg routing- // ----------------------------------------------------------------------------- @Test- void testAlterTable_icebergRoutesUpdateOpenTableFormatInput() {- Table rawTable = icebergTable(icebergColumn("id", "long", 1, false));-- // getTable is called multiple times: initial load, re-fetch after schema update, loadTable- when(mockClient.getTable(any(GetTableRequest.class)))- .thenReturn(GetTableResponse.builder().table(rawTable).build());- when(mockClient.updateTable(any(UpdateTableRequest.class)))- .thenReturn(UpdateTableResponse.builder().build());-- NameIdentifier ident = NameIdentifier.of("cat", "ns", DB, TABLE);- ops.alterTable(- ident, TableChange.addColumn(new String[] {"score"}, Types.DoubleType.get(), true));-- ArgumentCaptor<UpdateTableRequest> captor = ArgumentCaptor.forClass(UpdateTableRequest.class);- verify(mockClient).updateTable(captor.capture());- UpdateTableRequest req = captor.getValue();- assertNotNull(- req.updateOpenTableFormatInput(),- "updateOpenTableFormatInput must be set for Iceberg alter");- assertNotNull(req.updateOpenTableFormatInput().updateIcebergInput());- }-- @Test- void testCreateTable_icebergMissingLocationThrows() {- NameIdentifier ident = NameIdentifier.of("cat", "ns", DB, TABLE);- GlueColumn[] cols = {- GlueColumn.builder().withName("id").withType(Types.LongType.get()).withNullable(false).build()- };-- assertThrows(- IllegalArgumentException.class,- () ->- ops.createTable(- ident,- cols,- "iceberg table",- Map.of(GlueConstants.TABLE_FORMAT, "iceberg"), // missing location- new Transform[0],- Distributions.NONE,- null,- Indexes.EMPTY_INDEXES));- }-- @Test- void testAlterTable_icebergRenameThrows() {- Table rawTable = icebergTable(icebergColumn("id", "long", 1, false));-- when(mockClient.getTable(any(GetTableRequest.class)))- .thenReturn(GetTableResponse.builder().table(rawTable).build());-- NameIdentifier ident = NameIdentifier.of("cat", "ns", DB, TABLE);- assertThrows(- IllegalArgumentException.class,- () -> ops.alterTable(ident, TableChange.rename("new_table_name")));- }-- @Test- void testHiveTypeToDoc_nullFallsBackToString() {- assertEquals("string", GlueIcebergHelper.hiveTypeToIcebergType(null).asString());- }-- @Test- void testBuildSchemaUpdate_updateColumnNullability() {- Table raw = icebergTable(icebergColumn("id", "long", 1, true));-- IcebergSchema schema =- GlueIcebergHelper.buildSchemaUpdate(- raw, TableChange.updateColumnNullability(new String[] {"id"}, false))- .orElseThrow()- .schema();- assertTrue(schema.fields().get(0).required());- }-- @Test- void testBuildSchemaUpdate_updateColumnComment() {- Table raw = icebergTable(icebergColumn("id", "long", 1, false));-- IcebergSchema schema =- GlueIcebergHelper.buildSchemaUpdate(- raw, TableChange.updateColumnComment(new String[] {"id"}, "primary key"))- .orElseThrow()- .schema();- assertEquals("primary key", schema.fields().get(0).doc());- }-- @Test- void testCreateTable_defaultTableFormatIcebergRoutesOpenTableFormatInput() {- Table created =- Table.builder()- .name(TABLE)- .parameters(- Map.of(TABLE_TYPE_PARAM, ICEBERG_TABLE_TYPE_VALUE, "metadata_location", LOCATION))- .storageDescriptor(StorageDescriptor.builder().build())- .build();- when(mockClient.createTable(any(CreateTableRequest.class)))- .thenReturn(CreateTableResponse.builder().build());- when(mockClient.getTable(any(GetTableRequest.class)))- .thenReturn(GetTableResponse.builder().table(created).build());-- // Set defaultTableFormat to iceberg so createTable without table-format property routes- // through OpenTableFormatInput- ops.defaultTableFormat = "iceberg";- NameIdentifier ident = NameIdentifier.of("cat", "ns", DB, TABLE);- GlueColumn[] cols = {- GlueColumn.builder().withName("id").withType(Types.LongType.get()).withNullable(false).build()- };- ops.createTable(- ident,- cols,- "iceberg table",- Map.of(GlueConstants.LOCATION, LOCATION), // no table-format; relies on defaultTableFormat- new Transform[0],- Distributions.NONE,- null,- Indexes.EMPTY_INDEXES);-- ArgumentCaptor<CreateTableRequest> captor = ArgumentCaptor.forClass(CreateTableRequest.class);- verify(mockClient).createTable(captor.capture());- assertNotNull(- captor.getValue().openTableFormatInput(),- "defaultTableFormat=iceberg should route through openTableFormatInput");- }-- @Test- void testMatchesFormatFilter_icebergFallbackViaTableType() {- // Table has table_type=ICEBERG but no table-format property (e.g. created by external tooling)- Table externalIceberg =- Table.builder()- .name(TABLE)- .parameters(Map.of(TABLE_TYPE_PARAM, ICEBERG_TABLE_TYPE_VALUE))- .build();-- ops.tableFormatFilter = Set.of("iceberg");- // matchesFormatFilter is private; test via listTables by mocking getTable- // Instead verify the helper logic directly via isIcebergTable + manual check- assertTrue(- GlueIcebergHelper.isIcebergTable(externalIceberg),- "Table with table_type=ICEBERG should be recognized as Iceberg");-- // A hive table should not match iceberg filter- Table hiveTable =- Table.builder().name("hive_t").parameters(Map.of("table_type", "HIVE")).build();- assertFalse(GlueIcebergHelper.isIcebergTable(hiveTable));- }-- @Test- void testBuildSchemaUpdate_nestedFieldThrows() {- Table raw = icebergTable(icebergColumn("id", "long", 1, false));-- assertThrows(- IllegalArgumentException.class,- () ->- GlueIcebergHelper.buildSchemaUpdate(- raw, TableChange.deleteColumn(new String[] {"nested", "field"}, false)));- assertThrows(- IllegalArgumentException.class,- () ->- GlueIcebergHelper.buildSchemaUpdate(- raw, TableChange.renameColumn(new String[] {"nested", "field"}, "new_name")));- }-- @Test- void testCurrentFields_malformedFieldIdThrows() {- Column col =- Column.builder()- .name("id")- .type("long")- .parameters(Map.of(GlueConstants.ICEBERG_FIELD_ID, "not-a-number"))- .build();- Table raw = icebergTable(col);- assertThrows(- IllegalStateException.class,- () ->- GlueIcebergHelper.buildSchemaUpdate(- raw, TableChange.deleteColumn(new String[] {"id"}, false)));- }-- // ---------------------------------------------------------------------------- // Helpers- // ----------------------------------------------------------------------------- private static Column icebergColumn(String name, String type, int fieldId, boolean optional) {- return Column.builder()- .name(name)- .type(type)- .parameters(- Map.of(- GlueConstants.ICEBERG_FIELD_ID,- String.valueOf(fieldId),- GlueConstants.ICEBERG_FIELD_OPTIONAL,- String.valueOf(optional)))- .build();- }-- private static Table icebergTable(Column... columns) {- return Table.builder()- .name(TABLE)- .parameters(Map.of(TABLE_TYPE_PARAM, ICEBERG_TABLE_TYPE_VALUE))- .storageDescriptor(StorageDescriptor.builder().columns(columns).build())- .build();- }-}diff --git a/catalogs/catalog-glue/src/test/java/org/apache/gravitino/catalog/glue/TestGlueTableConversion.java b/catalogs/catalog-glue/src/test/java/org/apache/gravitino/catalog/glue/TestGlueTableConversion.javaindex 085b7f7d9a..bf61faa98c 100644--- a/catalogs/catalog-glue/src/test/java/org/apache/gravitino/catalog/glue/TestGlueTableConversion.java+++ b/catalogs/catalog-glue/src/test/java/org/apache/gravitino/catalog/glue/TestGlueTableConversion.java@@ -20,6 +20,7 @@ package org.apache.gravitino.catalog.glue;import java.time.Instant;import java.util.Map;+import org.apache.gravitino.catalog.hive.HiveStorageConstants;import software.amazon.awssdk.services.glue.model.Column;import software.amazon.awssdk.services.glue.model.Order;import software.amazon.awssdk.services.glue.model.SerDeInfo;@@ -32,10 +33,6 @@ import software.amazon.awssdk.services.glue.model.Table;*/class TestGlueTableConversion extends GlueTableTestBase {- private static final String INPUT_FMT = "org.apache.hadoop.mapred.TextInputFormat";- private static final String OUTPUT_FMT =- "org.apache.hadoop.hive.ql.io.HiveIgnoreKeyTextOutputFormat";- private static final String SERDE = "org.apache.hadoop.hive.serde2.lazy.LazySimpleSerDe";private static final String LOCATION = "s3://my-bucket/warehouse/";@Override@@ -50,9 +47,12 @@ class TestGlueTableConversion extends GlueTableTestBase {Column.builder().name("id").type("bigint").comment("primary key").build(),Column.builder().name("name").type("string").build()).location(LOCATION + tableName)- .inputFormat(INPUT_FMT)- .outputFormat(OUTPUT_FMT)- .serdeInfo(SerDeInfo.builder().serializationLibrary(SERDE).build())+ .inputFormat(HiveStorageConstants.TEXT_INPUT_FORMAT_CLASS)+ .outputFormat(HiveStorageConstants.IGNORE_KEY_OUTPUT_FORMAT_CLASS)+ .serdeInfo(+ SerDeInfo.builder()+ .serializationLibrary(HiveStorageConstants.LAZY_SIMPLE_SERDE_CLASS)+ .build()).bucketColumns("id").numberOfBuckets(4).sortColumns(Order.builder().column("name").sortOrder(1).build())diff --git a/catalogs/catalog-glue/src/test/java/org/apache/gravitino/catalog/glue/integration/test/AbstractGlueCatalogIT.java b/catalogs/catalog-glue/src/test/java/org/apache/gravitino/catalog/glue/integration/test/AbstractGlueCatalogIT.javaindex 93e25d9b0d..1b2c8eb4ba 100644--- a/catalogs/catalog-glue/src/test/java/org/apache/gravitino/catalog/glue/integration/test/AbstractGlueCatalogIT.java+++ b/catalogs/catalog-glue/src/test/java/org/apache/gravitino/catalog/glue/integration/test/AbstractGlueCatalogIT.java@@ -36,6 +36,7 @@ import org.apache.gravitino.Schema;import org.apache.gravitino.SchemaChange;import org.apache.gravitino.catalog.glue.GlueCatalogOperations;import org.apache.gravitino.catalog.glue.GlueConstants;+import org.apache.gravitino.catalog.hive.HiveStorageConstants;import org.apache.gravitino.exceptions.NonEmptySchemaException;import org.apache.gravitino.rel.Column;import org.apache.gravitino.rel.SupportsPartitions;@@ -73,10 +74,6 @@ abstract class AbstractGlueCatalogIT {private String currentSchema;private static final Namespace SCHEMA_NS = Namespace.of("ml", "cat");- private static final String INPUT_FMT = "org.apache.hadoop.mapred.TextInputFormat";- private static final String OUTPUT_FMT =- "org.apache.hadoop.hive.ql.io.HiveIgnoreKeyTextOutputFormat";- private static final String SERDE = "org.apache.hadoop.hive.serde2.lazy.LazySimpleSerDe";protected abstract Map<String, String> catalogConfig();@@ -136,9 +133,9 @@ abstract class AbstractGlueCatalogIT {private Map<String, String> hiveTableProps() {Map<String, String> props = new HashMap<>();props.put(GlueConstants.TABLE_TYPE, "EXTERNAL_TABLE");- props.put(GlueConstants.INPUT_FORMAT, INPUT_FMT);- props.put(GlueConstants.OUTPUT_FORMAT, OUTPUT_FMT);- props.put(GlueConstants.SERDE_LIB, SERDE);+ props.put(GlueConstants.INPUT_FORMAT_CLASS, HiveStorageConstants.TEXT_INPUT_FORMAT_CLASS);+ props.put(GlueConstants.OUTPUT_FORMAT, HiveStorageConstants.IGNORE_KEY_OUTPUT_FORMAT_CLASS);+ props.put(GlueConstants.SERDE_LIB, HiveStorageConstants.LAZY_SIMPLE_SERDE_CLASS);return props;}@@ -287,7 +284,7 @@ abstract class AbstractGlueCatalogIT {assertEquals("id", loaded.columns()[0].name());assertEquals(Types.LongType.get(), loaded.columns()[0].dataType());assertEquals("EXTERNAL_TABLE", loaded.properties().get(GlueConstants.TABLE_TYPE));- assertNotNull(loaded.properties().get(GlueConstants.INPUT_FORMAT));+ assertNotNull(loaded.properties().get(GlueConstants.INPUT_FORMAT_CLASS));assertNotNull(loaded.properties().get(GlueConstants.OUTPUT_FORMAT));assertNotNull(loaded.properties().get(GlueConstants.SERDE_LIB));}@@ -602,35 +599,6 @@ abstract class AbstractGlueCatalogIT {assertFalse(ops.dropTable(tableIdent(schema, "iceberg_drop")));}- @Test- void testAlterIcebergMetadata() {- String schema = newSchema();- ops.createSchema(schemaIdent(schema), null, Collections.emptyMap());-- Map<String, String> props = new HashMap<>();- props.put(GlueConstants.TABLE_FORMAT, "ICEBERG");- props.put(GlueConstants.METADATA_LOCATION, "s3://bucket/path/metadata/v1.metadata.json");- ops.createTable(- tableIdent(schema, "iceberg_alter"),- new Column[0],- null,- props,- new Transform[0],- Distributions.NONE,- new SortOrder[0],- new Index[0]);-- ops.alterTable(- tableIdent(schema, "iceberg_alter"),- TableChange.setProperty(- GlueConstants.METADATA_LOCATION, "s3://bucket/path/metadata/v2.metadata.json"));-- Table loaded = ops.loadTable(tableIdent(schema, "iceberg_alter"));- assertEquals(- "s3://bucket/path/metadata/v2.metadata.json",- loaded.properties().get(GlueConstants.METADATA_LOCATION));- }-@Testvoid testListTablesIncludesIceberg() {String schema = newSchema();diff --git a/catalogs/catalog-glue/src/test/java/org/apache/gravitino/catalog/glue/integration/test/AwsGlueCatalogIT.java b/catalogs/catalog-glue/src/test/java/org/apache/gravitino/catalog/glue/integration/test/AwsGlueCatalogIT.javaindex 7f8e1afa53..25bb3a328f 100644--- a/catalogs/catalog-glue/src/test/java/org/apache/gravitino/catalog/glue/integration/test/AwsGlueCatalogIT.java+++ b/catalogs/catalog-glue/src/test/java/org/apache/gravitino/catalog/glue/integration/test/AwsGlueCatalogIT.java@@ -18,11 +18,28 @@*/package org.apache.gravitino.catalog.glue.integration.test;+import static org.junit.jupiter.api.Assertions.assertEquals;++import java.util.Collections;import java.util.HashMap;import java.util.Map;+import org.apache.gravitino.NameIdentifier;import org.apache.gravitino.catalog.glue.GlueConstants;+import org.apache.gravitino.rel.Column;+import org.apache.gravitino.rel.Table;+import org.apache.gravitino.rel.TableChange;+import org.apache.gravitino.rel.expressions.distributions.Distributions;+import org.apache.gravitino.rel.expressions.sorts.SortOrder;+import org.apache.gravitino.rel.expressions.transforms.Transform;+import org.apache.gravitino.rel.indexes.Index;+import org.apache.gravitino.rel.types.Types;+import org.junit.jupiter.api.Assumptions;+import org.junit.jupiter.api.BeforeAll;+import org.junit.jupiter.api.Test;import org.junit.jupiter.api.TestInstance;import org.junit.jupiter.api.condition.EnabledIfEnvironmentVariable;+import org.slf4j.Logger;+import org.slf4j.LoggerFactory;/*** Runs {@link AbstractGlueCatalogIT} scenarios against a real AWS Glue endpoint.@@ -41,6 +58,21 @@ import org.junit.jupiter.api.condition.EnabledIfEnvironmentVariable;@TestInstance(TestInstance.Lifecycle.PER_CLASS)class AwsGlueCatalogIT extends AbstractGlueCatalogIT {+ private static final Logger LOG = LoggerFactory.getLogger(AwsGlueCatalogIT.class);++ @BeforeAll+ void checkAwsEnvironment() {+ Assumptions.assumeTrue(+ System.getenv("AWS_SECRET_ACCESS_KEY") != null,+ "Skipped: AWS_SECRET_ACCESS_KEY is not set");+ if (System.getenv("AWS_DEFAULT_REGION") == null) {+ LOG.info("AWS_DEFAULT_REGION is not set, using default us-east-1");+ }+ if (System.getenv("AWS_S3_TEST_BUCKET") == null) {+ LOG.info("AWS_S3_TEST_BUCKET is not set, testAlterIcebergMetadata will be skipped");+ }+ }+@Overrideprotected Map<String, String> catalogConfig() {Map<String, String> config = new HashMap<>();@@ -54,4 +86,38 @@ class AwsGlueCatalogIT extends AbstractGlueCatalogIT {}return config;}++ @Test+ void testAlterIcebergMetadata() {+ String bucket = System.getenv("AWS_S3_TEST_BUCKET");+ Assumptions.assumeTrue(bucket != null, "Skipped: set AWS_S3_TEST_BUCKET to enable");++ String schema = "glue_it_" + System.nanoTime();+ ops.createSchema(NameIdentifier.of("ml", "cat", schema), null, Collections.emptyMap());++ Map<String, String> props = new HashMap<>();+ props.put(GlueConstants.TABLE_FORMAT, "ICEBERG");+ props.put(GlueConstants.LOCATION, "s3://" + bucket + "/" + schema + "/");+ ops.createTable(+ NameIdentifier.of("ml", "cat", schema, "iceberg_alter"),+ new Column[] {Column.of("id", Types.LongType.get(), null)},+ null,+ props,+ new Transform[0],+ Distributions.NONE,+ new SortOrder[0],+ new Index[0]);++ try {+ ops.alterTable(+ NameIdentifier.of("ml", "cat", schema, "iceberg_alter"),+ TableChange.setProperty("comment", "updated comment"));++ Table loaded = ops.loadTable(NameIdentifier.of("ml", "cat", schema, "iceberg_alter"));+ assertEquals("updated comment", loaded.properties().get("comment"));+ } finally {+ ops.dropTable(NameIdentifier.of("ml", "cat", schema, "iceberg_alter"));+ ops.dropSchema(NameIdentifier.of("ml", "cat", schema), false);+ }+ }}