World's most powerful open data catalog for building a high-performance, geo-distributed and federated metadata lake.
Java ai-catalogdata-catalogdatalakefederated-querylakehousemetadatametalakemodel-catalogopendatacatalogskycomputingstratosphere
[#14560] fix(catalog-glue): Fix Hive table, schema and partition handling (#14561)
Yuhui7ab9943c0cb2
diff --git a/catalogs/catalog-glue/src/main/java/org/apache/gravitino/catalog/glue/GlueCatalogCapability.java b/catalogs/catalog-glue/src/main/java/org/apache/gravitino/catalog/glue/GlueCatalogCapability.javaindex 8a613f9018..fd87f7cb89 100644--- a/catalogs/catalog-glue/src/main/java/org/apache/gravitino/catalog/glue/GlueCatalogCapability.java+++ b/catalogs/catalog-glue/src/main/java/org/apache/gravitino/catalog/glue/GlueCatalogCapability.java@@ -28,8 +28,8 @@ import org.apache.gravitino.connector.capability.CapabilityResult;* <p>AWS Glue constraints that deviate from Gravitino defaults:** <ul>- * <li><b>Case-insensitive names</b>: Glue folds database and table names to lowercase on storage.- * See <a+ * <li><b>Case-insensitive schema and table names</b>: Glue folds database and table names to+ * lowercase on storage. See <a* href="https://docs.aws.amazon.com/glue/latest/dg/aws-glue-api-catalog-databases.html">Database* API</a> and <a* href="https://docs.aws.amazon.com/glue/latest/dg/aws-glue-api-catalog-tables.html">Table@@ -65,7 +65,7 @@ public class GlueCatalogCapability implements Capability {switch (scope) {case SCHEMA:case TABLE:- // Glue folds database/table names to lowercase on storage.+ // Glue folds database and table names to lowercase on storage.// See https://docs.aws.amazon.com/glue/latest/dg/aws-glue-api-catalog-databases.html// See https://docs.aws.amazon.com/glue/latest/dg/aws-glue-api-catalog-tables.htmlreturn CapabilityResult.unsupported(@@ -73,6 +73,8 @@ public class GlueCatalogCapability implements Capability {+ scope.name().toLowerCase(Locale.ROOT)+ " names.");default:+ // Column names depend on the table format, which this check cannot see: Iceberg keeps their+ // case in its metadata, and GlueCatalogOperations folds those of Hive-format tables.return CapabilityResult.SUPPORTED;}}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 4a9f5e621c..bed6d8eff4 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@@ -29,13 +29,13 @@ import java.util.ArrayList;import java.util.Arrays;import java.util.Collections;import java.util.HashMap;+import java.util.HashSet;import java.util.List;import java.util.Locale;import java.util.Map;import java.util.Set;import java.util.function.Consumer;import java.util.function.Supplier;-import java.util.function.UnaryOperator;import java.util.stream.Collectors;import org.apache.commons.lang3.StringUtils;import org.apache.gravitino.NameIdentifier;@@ -56,15 +56,18 @@ import org.apache.gravitino.meta.AuditInfo;import org.apache.gravitino.rel.Column;import org.apache.gravitino.rel.TableCatalog;import org.apache.gravitino.rel.TableChange;+import org.apache.gravitino.rel.expressions.Expression;import org.apache.gravitino.rel.expressions.NamedReference;import org.apache.gravitino.rel.expressions.distributions.Distribution;import org.apache.gravitino.rel.expressions.distributions.Distributions;+import org.apache.gravitino.rel.expressions.distributions.Strategy;import org.apache.gravitino.rel.expressions.sorts.SortDirection;import org.apache.gravitino.rel.expressions.sorts.SortOrder;import org.apache.gravitino.rel.expressions.transforms.Transform;import org.apache.gravitino.rel.expressions.transforms.Transforms;import org.apache.gravitino.rel.indexes.Index;import org.apache.gravitino.rel.types.Type;+import org.apache.gravitino.rel.types.Types;import org.apache.gravitino.utils.PrincipalUtils;import org.apache.iceberg.catalog.TableIdentifier;import org.slf4j.Logger;@@ -73,6 +76,7 @@ import software.amazon.awssdk.core.exception.SdkException;import software.amazon.awssdk.services.glue.GlueClient;import software.amazon.awssdk.services.glue.model.CreateDatabaseRequest;import software.amazon.awssdk.services.glue.model.CreateTableRequest;+import software.amazon.awssdk.services.glue.model.Database;import software.amazon.awssdk.services.glue.model.DatabaseInput;import software.amazon.awssdk.services.glue.model.DeleteDatabaseRequest;import software.amazon.awssdk.services.glue.model.DeleteTableRequest;@@ -112,6 +116,10 @@ public class GlueCatalogOperations implements CatalogOperations, SupportsSchemasGlueConstants.SERDE_LIB,GlueConstants.SERDE_NAME);+ /** Storage formats whose files can only be read by the SerDe of the same format. */+ private static final Set<StorageFormat> SERDE_BOUND_FORMATS =+ ImmutableSet.of(StorageFormat.ORC, StorageFormat.PARQUET, StorageFormat.AVRO);+@VisibleForTesting GlueClient glueClient;/** Nullable — when null, Glue uses the caller's AWS account ID. */@@ -203,13 +211,13 @@ public class GlueCatalogOperations implements CatalogOperations, SupportsSchemasNameIdentifier ident, String comment, Map<String, String> properties)throws NoSuchCatalogException, SchemaAlreadyExistsException {- Map<String, String> params = properties != null ? properties : Collections.emptyMap();+ Map<String, String> params = properties != null ? new HashMap<>(properties) : new HashMap<>();+ // The location is stored only as the database LocationUri, which other engines read.+ String location = params.remove(LOCATION);DatabaseInput.Builder inputBuilder =DatabaseInput.builder().name(ident.name()).description(comment).parameters(params);-- String location = params.get(LOCATION);- if (location != null) {+ if (StringUtils.isNotBlank(location)) {inputBuilder.locationUri(location);}@@ -226,10 +234,15 @@ public class GlueCatalogOperations implements CatalogOperations, SupportsSchemasLOG.info("Created Glue schema (database) {}", ident.name());+ // The response carries the location like a later load, which reads it from LocationUri.+ Map<String, String> created = new HashMap<>(params);+ if (StringUtils.isNotBlank(location)) {+ created.put(LOCATION, location);+ }return GlueSchema.builder().withName(ident.name()).withComment(comment)- .withProperties(params)+ .withProperties(created).withAuditInfo(AuditInfo.builder().withCreator(PrincipalUtils.getCurrentUserName())@@ -257,35 +270,51 @@ public class GlueCatalogOperations implements CatalogOperations, SupportsSchemas@Overridepublic GlueSchema alterSchema(NameIdentifier ident, SchemaChange... changes)throws NoSuchSchemaException {+ Database current = getDatabase(ident.name());- GlueSchema current = loadSchema(ident);-- Map<String, String> newProps = new HashMap<>(current.properties());+ // UpdateDatabase replaces the whole definition, so start from what Glue holds and change+ // only what the request asks for.+ Map<String, String> newParams = new HashMap<>();+ if (current.parameters() != null) {+ newParams.putAll(current.parameters());+ }+ String location = current.locationUri();+ if (StringUtils.isBlank(location)) {+ location = newParams.get(LOCATION);+ }+ newParams.remove(LOCATION);for (SchemaChange change : changes) {if (change instanceof SchemaChange.SetProperty) {SchemaChange.SetProperty sp = (SchemaChange.SetProperty) change;- newProps.put(sp.getProperty(), sp.getValue());+ if (LOCATION.equals(sp.getProperty())) {+ location = sp.getValue();+ } else {+ newParams.put(sp.getProperty(), sp.getValue());+ }} else if (change instanceof SchemaChange.RemoveProperty) {- newProps.remove(((SchemaChange.RemoveProperty) change).getProperty());+ String property = ((SchemaChange.RemoveProperty) change).getProperty();+ if (LOCATION.equals(property)) {+ location = null;+ } else {+ newParams.remove(property);+ }} else {throw new IllegalArgumentException("Unsupported schema change: " + change.getClass().getSimpleName());}}- DatabaseInput.Builder inputBuilder =+ DatabaseInput input =DatabaseInput.builder()- .name(ident.name())- .description(current.comment())- .parameters(newProps);-- String location = newProps.get(LOCATION);- if (location != null) {- inputBuilder.locationUri(location);- }-- DatabaseInput input = inputBuilder.build();+ .name(current.name())+ .description(current.description())+ .locationUri(StringUtils.isBlank(location) ? null : location)+ .parameters(newParams)+ .createTableDefaultPermissions(current.createTableDefaultPermissions())+ .targetDatabase(current.targetDatabase())+ .federatedDatabase(current.federatedDatabase())+ .build();UpdateDatabaseRequest.Builder req =UpdateDatabaseRequest.builder().name(ident.name()).databaseInput(input);@@ -299,12 +328,34 @@ public class GlueCatalogOperations implements CatalogOperations, SupportsSchemasLOG.info("Altered Glue schema (database) {}", ident.name());- return GlueSchema.builder()- .withName(ident.name())- .withComment(current.comment())- .withProperties(newProps)- .withAuditInfo(current.auditInfo())- .build();+ // The change is committed at this point, so a failed read falls back to the definition that+ // was sent rather than reporting the alter as failed.+ try {+ return loadSchema(ident);+ } catch (RuntimeException e) {+ LOG.warn(+ "Altered schema {}, but failed to read it back; returning the submitted definition",+ ident.name(),+ e);+ return GlueSchema.fromGlueDatabase(+ Database.builder()+ .name(input.name())+ .description(input.description())+ .locationUri(input.locationUri())+ .parameters(input.parameters())+ .createTime(current.createTime())+ .build());+ }+ }++ private Database getDatabase(String name) {+ GetDatabaseRequest.Builder req = GetDatabaseRequest.builder().name(name);+ applyCatalogId(catalogId, req::catalogId);+ try {+ return callGlue(() -> glueClient.getDatabase(req.build()), "schema " + name).database();+ } catch (GlueException e) {+ throw GlueExceptionConverter.toSchemaException(e, "schema " + name);+ }}@Override@@ -383,6 +434,7 @@ public class GlueCatalogOperations implements CatalogOperations, SupportsSchemasrejectIfView(rawGlueTable, ident, dbName);rejectIfFormatHidden(rawGlueTable, ident, dbName);GlueTable table = GlueTable.fromGlueTable(rawGlueTable, typeConverter);+ rejectDuplicateColumns(table, dbName);// 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@@ -437,18 +489,23 @@ public class GlueCatalogOperations implements CatalogOperations, SupportsSchemasGlueConstants.TABLE_FORMAT_FILTER,tableFormatFilter);- // Non-Iceberg (Hive) tables only support identity partitioning.- // Iceberg tables delegate to GlueIcebergCatalogHelper which supports all transforms.+ // Glue readers take table_type=ICEBERG as an Iceberg table, so a Hive-format table cannot carry+ // it.+ Preconditions.checkArgument(+ isIceberg+ || !GlueConstants.ICEBERG_TABLE_TYPE_VALUE.equalsIgnoreCase(+ props.get(GlueConstants.TABLE_TYPE_PARAM)),+ "Set '%s'=ICEBERG to create an Iceberg table; '%s'=ICEBERG is not allowed on a Hive-format"+ + " table",+ GlueConstants.TABLE_FORMAT,+ GlueConstants.TABLE_TYPE_PARAM);++ validateColumns(columns);+ // Iceberg tables delegate partitioning and ordering to GlueIcebergTableHelper.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");- }+ validateHivePartitioning(columns, partitions);+ validateHiveDistribution(distribution);+ validateHiveSortOrders(sortOrders);}// For Iceberg tables, stamp table_type=ICEBERG into the Glue parameters so that@@ -490,7 +547,7 @@ public class GlueCatalogOperations implements CatalogOperations, SupportsSchemasdbName,ident.name(),comment,- columns,+ isIceberg ? columns : toLowerCaseColumns(columns),finalProps,partitions,distribution,@@ -503,27 +560,39 @@ public class GlueCatalogOperations implements CatalogOperations, SupportsSchemasexecuteCreateTable(dbName, ident, req);LOG.info("Created {} table {}.{}", isIceberg ? "Iceberg" : "Glue", dbName, ident.name());- if (isIceberg) {- // Load from Glue to pick up any server-set parameters (e.g. current-schema-id).+ return loadAfterWrite(ident, dbName, input);+ }++ /**+ * Reads back what Glue stored, so the response carries the derived location and storage classes,+ * as a later load does. The write is committed at this point, so a failed read falls back to the+ * definition that was sent rather than reporting the operation as failed.+ */+ private GlueTable loadAfterWrite(NameIdentifier ident, String dbName, TableInput input) {+ try {return loadTable(ident);+ } catch (RuntimeException e) {+ LOG.warn(+ "Wrote table {}.{}, but failed to read it back; returning the submitted definition",+ dbName,+ ident.name(),+ e);+ GlueTable table = GlueTable.fromGlueTable(toTable(dbName, input), typeConverter);+ table.initOpsContext(glueClient, catalogId, dbName);+ return table;}- GlueTable created =- GlueTable.builder()- .withName(ident.name())- .withComment(comment)- .withColumns(columns)- .withProperties(props)- .withPartitioning(partitions)- .withDistribution(distribution != null ? distribution : Distributions.NONE)- .withSortOrders(sortOrders != null ? sortOrders : new SortOrder[0])- .withAuditInfo(- AuditInfo.builder()- .withCreator(PrincipalUtils.getCurrentUserName())- .withCreateTime(Instant.now())- .build())- .build();- created.initOpsContext(glueClient, catalogId, dbName);- return created;+ }++ private static Table toTable(String dbName, TableInput input) {+ return Table.builder()+ .databaseName(dbName)+ .name(input.name())+ .description(input.description())+ .tableType(input.tableType())+ .parameters(input.parameters())+ .storageDescriptor(input.storageDescriptor())+ .partitionKeys(input.partitionKeys())+ .build();}@Override@@ -550,70 +619,316 @@ public class GlueCatalogOperations implements CatalogOperations, SupportsSchemasreturn alterIcebergTable(ident, dbName, rawGlueTable, changes);}- GlueTable current = GlueTable.fromGlueTable(rawGlueTable, typeConverter);- current.initOpsContext(glueClient, catalogId, dbName);-- String newName = current.name();- String newComment = current.comment();- Map<String, String> newProps = new HashMap<>(current.properties());+ return alterHiveTable(ident, dbName, rawGlueTable, changes);+ }- // Separate data columns from partition columns- int partCount = current.partitioning().length;- List<Column> allCols = new ArrayList<>(Arrays.asList(current.columns()));- List<Column> dataCols = new ArrayList<>(allCols.subList(0, allCols.size() - partCount));- List<Column> partCols =- new ArrayList<>(allCols.subList(allCols.size() - partCount, allCols.size()));+ /**+ * Alters a Hive-format table. Glue UpdateTable replaces the whole table definition, so the new+ * definition starts from the table as Glue holds it and only the requested parts change; fields+ * Gravitino does not model, and column types that are not changed, are written back as read. The+ * version read is sent along, so Glue refuses the update if the table changed in between.+ */+ private GlueTable alterHiveTable(+ NameIdentifier ident, String dbName, Table raw, TableChange... changes) {+ StorageDescriptor rawSd = raw.storageDescriptor();+ HiveColumns cols =+ new HiveColumns(+ rawSd != null && rawSd.hasColumns() ? rawSd.columns() : Collections.emptyList(),+ raw.hasPartitionKeys() ? raw.partitionKeys() : Collections.emptyList(),+ rawSd != null && rawSd.hasBucketColumns()+ ? rawSd.bucketColumns()+ : Collections.emptyList(),+ rawSd != null && rawSd.hasSortColumns() ? rawSd.sortColumns() : Collections.emptyList(),+ rawSd != null && rawSd.skewedInfo() != null && rawSd.skewedInfo().hasSkewedColumnNames()+ ? rawSd.skewedInfo().skewedColumnNames()+ : Collections.emptyList());+ String description = raw.description();+ Map<String, String> params =+ raw.hasParameters() ? new HashMap<>(raw.parameters()) : new HashMap<>();+ SerDeInfo rawSerde = rawSd != null ? rawSd.serdeInfo() : null;+ String location = rawSd != null ? rawSd.location() : null;+ String serdeName = rawSerde != null ? rawSerde.name() : null;+ Map<String, String> serdeParams =+ rawSerde != null && rawSerde.hasParameters()+ ? new HashMap<>(rawSerde.parameters())+ : new HashMap<>();+ boolean storageChanged = false;+ boolean changed = false;for (TableChange change : changes) {if (change instanceof TableChange.RenameTable) {throw new UnsupportedOperationException("Glue does not support table rename");} else if (change instanceof TableChange.UpdateComment) {- newComment = ((TableChange.UpdateComment) change).getNewComment();+ description = ((TableChange.UpdateComment) change).getNewComment();+ changed = true;} else if (change instanceof TableChange.SetProperty) {+ // Storage properties map to storage descriptor fields, the rest to table parameters.TableChange.SetProperty sp = (TableChange.SetProperty) change;- newProps.put(sp.getProperty(), sp.getValue());+ String property = sp.getProperty();+ // A table parameter of the same name would show again once the storage value is removed.+ if (isStorageProperty(property)) {+ params.remove(property);+ }+ if (GlueConstants.LOCATION.equals(property)) {+ location = sp.getValue();+ storageChanged = true;+ } else if (GlueConstants.SERDE_NAME.equals(property)) {+ serdeName = sp.getValue();+ storageChanged = true;+ } else if (property.startsWith(GlueConstants.SERDE_PARAMETER_PREFIX)) {+ serdeParams.put(+ property.substring(GlueConstants.SERDE_PARAMETER_PREFIX.length()), sp.getValue());+ storageChanged = true;+ } else {+ checkTableParameterKey(property);+ params.put(property, sp.getValue());+ }+ changed = true;} else if (change instanceof TableChange.RemoveProperty) {- newProps.remove(((TableChange.RemoveProperty) change).getProperty());+ String property = ((TableChange.RemoveProperty) change).getProperty();+ // A table parameter of the same name is shown when the storage descriptor has no value, so+ // it is removed as well.+ if (isStorageProperty(property)) {+ changed |= params.remove(property) != null;+ }+ if (GlueConstants.LOCATION.equals(property)) {+ storageChanged |= location != null;+ location = null;+ } else if (GlueConstants.SERDE_NAME.equals(property)) {+ storageChanged |= serdeName != null;+ serdeName = null;+ } else if (property.startsWith(GlueConstants.SERDE_PARAMETER_PREFIX)) {+ storageChanged |=+ serdeParams.remove(property.substring(GlueConstants.SERDE_PARAMETER_PREFIX.length()))+ != null;+ } else {+ checkTableParameterKey(property);+ changed |= params.remove(property) != null;+ }+ changed |= storageChanged;} else if (change instanceof TableChange.ColumnChange) {- applyColumnChange(dataCols, partCols, (TableChange.ColumnChange) change);+ changed |= cols.apply((TableChange.ColumnChange) change);} else {throw new IllegalArgumentException("Unsupported table change: " + change.getClass().getSimpleName());}}- List<Column> newAllCols = new ArrayList<>(dataCols);- newAllCols.addAll(partCols);- Column[] newColumns = newAllCols.toArray(new Column[0]);+ if (!changed) {+ return loadTable(ident);+ }++ StorageDescriptor sd = rawSd;+ if (rawSd != null || !cols.dataCols.isEmpty() || storageChanged) {+ StorageDescriptor.Builder sdBuilder =+ rawSd != null ? rawSd.toBuilder() : StorageDescriptor.builder();+ sdBuilder.columns(cols.dataCols).bucketColumns(cols.bucketCols).sortColumns(cols.sortCols);+ if (rawSd != null && rawSd.skewedInfo() != null) {+ sdBuilder.skewedInfo(+ rawSd.skewedInfo().toBuilder().skewedColumnNames(cols.skewCols).build());+ }+ if (storageChanged) {+ SerDeInfo.Builder serdeBuilder =+ rawSerde != null ? rawSerde.toBuilder() : SerDeInfo.builder();+ sdBuilder+ .location(location)+ .serdeInfo(serdeBuilder.name(serdeName).parameters(serdeParams).build());+ }+ sd = sdBuilder.build();+ }TableInput input =- buildTableInput(- dbName,- newName,- newComment,- newColumns,- newProps,- current.partitioning(),- current.distribution(),- current.sortOrder(),- false);+ TableInput.builder()+ .name(raw.name())+ .description(description)+ .owner(raw.owner())+ .lastAccessTime(raw.lastAccessTime())+ .lastAnalyzedTime(raw.lastAnalyzedTime())+ .retention(raw.retention())+ .storageDescriptor(sd)+ .partitionKeys(cols.partCols)+ .viewOriginalText(raw.viewOriginalText())+ .viewExpandedText(raw.viewExpandedText())+ .tableType(raw.tableType())+ .parameters(params)+ .targetTable(raw.targetTable())+ .build();- executeUpdateTable(ident, UpdateTableRequest.builder().databaseName(dbName).tableInput(input));+ executeUpdateTable(+ ident,+ UpdateTableRequest.builder()+ .databaseName(dbName)+ .tableInput(input)+ .versionId(raw.versionId()));LOG.info("Altered Glue table {}.{}", dbName, ident.name());+ return loadAfterWrite(ident, dbName, input);+ }- GlueTable altered =- GlueTable.builder()- .withName(newName)- .withComment(newComment)- .withColumns(newColumns)- .withProperties(newProps)- .withPartitioning(current.partitioning())- .withDistribution(current.distribution())- .withSortOrders(current.sortOrder())- .withAuditInfo(current.auditInfo())- .build();- altered.initOpsContext(glueClient, catalogId, dbName);- return altered;+ private static boolean isStorageProperty(String property) {+ return GlueConstants.LOCATION.equals(property)+ || GlueConstants.SERDE_NAME.equals(property)+ || property.startsWith(GlueConstants.SERDE_PARAMETER_PREFIX);+ }++ /**+ * The storage format and classes are set at create only, and so is the table format: changing it+ * would make a Hive-format table read as another format, or hide it behind the format filter.+ */+ private static void checkTableParameterKey(String property) {+ Preconditions.checkArgument(+ !SD_TABLE_PROPERTY_KEYS.contains(property)+ && !GlueConstants.TABLE_FORMAT.equals(property)+ && !GlueConstants.TABLE_TYPE_PARAM.equals(property),+ "Property %s of a Glue table cannot be changed",+ property);+ }++ /**+ * The column lists of a Hive-format table as Glue holds them, edited in place by column changes.+ * Glue column names are compared without regard to case, and new names are folded to lower case,+ * as Glue stores them.+ */+ private final class HiveColumns {+ private final List<software.amazon.awssdk.services.glue.model.Column> dataCols;+ private final List<software.amazon.awssdk.services.glue.model.Column> partCols;+ private final List<String> bucketCols;+ private final List<Order> sortCols;+ private final List<String> skewCols;++ private HiveColumns(+ List<software.amazon.awssdk.services.glue.model.Column> dataCols,+ List<software.amazon.awssdk.services.glue.model.Column> partCols,+ List<String> bucketCols,+ List<Order> sortCols,+ List<String> skewCols) {+ this.dataCols = new ArrayList<>(dataCols);+ this.partCols = new ArrayList<>(partCols);+ this.bucketCols = new ArrayList<>(bucketCols);+ this.sortCols = new ArrayList<>(sortCols);+ this.skewCols = new ArrayList<>(skewCols);+ }++ /**+ * Applies one column change.+ *+ * @return whether the table changed+ */+ private boolean apply(TableChange.ColumnChange change) {+ String[] fieldName = change.fieldName();+ Preconditions.checkArgument(+ fieldName != null && fieldName.length > 0, "Column change field name cannot be empty");+ Preconditions.checkArgument(+ fieldName.length == 1,+ "Glue Hive-format tables do not support changes to nested field %s; change the whole"+ + " column instead",+ String.join(".", fieldName));+ String name = fieldName[0];++ if (change instanceof TableChange.AddColumn) {+ TableChange.AddColumn add = (TableChange.AddColumn) change;+ Preconditions.checkArgument(+ !add.isAutoIncrement(), "Glue does not support auto-increment columns: %s", name);+ Preconditions.checkArgument(+ indexOf(dataCols, name) < 0 && indexOf(partCols, name) < 0,+ "Column %s already exists",+ name);+ software.amazon.awssdk.services.glue.model.Column column =+ software.amazon.awssdk.services.glue.model.Column.builder()+ .name(name.toLowerCase(Locale.ROOT))+ .type(toGlueType(name, add.getDataType()))+ .comment(add.getComment())+ .build();+ dataCols.add(insertIndex(add.getPosition(), dataCols.size()), column);+ return true;+ }++ if (change instanceof TableChange.UpdateColumnComment) {+ String comment = ((TableChange.UpdateColumnComment) change).getNewComment();+ List<software.amazon.awssdk.services.glue.model.Column> owner =+ indexOf(dataCols, name) >= 0 ? dataCols : partCols;+ int index = requireColumn(owner, name);+ owner.set(index, owner.get(index).toBuilder().comment(comment).build());+ return true;+ }++ Preconditions.checkArgument(+ indexOf(partCols, name) < 0,+ "Glue does not support %s on partition column %s",+ change.getClass().getSimpleName(),+ name);++ if (change instanceof TableChange.DeleteColumn) {+ int index = indexOf(dataCols, name);+ if (index < 0) {+ Boolean ifExists = ((TableChange.DeleteColumn) change).getIfExists();+ Preconditions.checkArgument(+ Boolean.TRUE.equals(ifExists), "Column %s does not exist", name);+ return false;+ }+ Preconditions.checkArgument(+ bucketCols.stream().noneMatch(name::equalsIgnoreCase)+ && sortCols.stream().noneMatch(o -> name.equalsIgnoreCase(o.column()))+ && skewCols.stream().noneMatch(name::equalsIgnoreCase),+ "Cannot delete column %s: it is a bucket, sort or skewed column of the table",+ name);+ dataCols.remove(index);+ return true;+ }++ int index = requireColumn(dataCols, name);+ software.amazon.awssdk.services.glue.model.Column old = dataCols.get(index);+ if (change instanceof TableChange.RenameColumn) {+ String newName = ((TableChange.RenameColumn) change).getNewName().toLowerCase(Locale.ROOT);+ Preconditions.checkArgument(+ (indexOf(dataCols, newName) < 0 || name.equalsIgnoreCase(newName))+ && indexOf(partCols, newName) < 0,+ "Column %s already exists",+ newName);+ dataCols.set(index, old.toBuilder().name(newName).build());+ bucketCols.replaceAll(c -> c.equalsIgnoreCase(name) ? newName : c);+ skewCols.replaceAll(c -> c.equalsIgnoreCase(name) ? newName : c);+ sortCols.replaceAll(+ o -> name.equalsIgnoreCase(o.column()) ? o.toBuilder().column(newName).build() : o);+ } else if (change instanceof TableChange.UpdateColumnType) {+ Type newType = ((TableChange.UpdateColumnType) change).getNewDataType();+ dataCols.set(index, old.toBuilder().type(toGlueType(name, newType)).build());+ } else if (change instanceof TableChange.UpdateColumnPosition) {+ dataCols.remove(index);+ dataCols.add(+ insertIndex(((TableChange.UpdateColumnPosition) change).getPosition(), dataCols.size()),+ old);+ } else {+ throw new IllegalArgumentException(+ "Unsupported column change: " + change.getClass().getSimpleName());+ }+ return true;+ }++ private int insertIndex(TableChange.ColumnPosition position, int defaultIndex) {+ if (position instanceof TableChange.First) {+ return 0;+ }+ if (position instanceof TableChange.After) {+ return requireColumn(dataCols, ((TableChange.After) position).getColumn()) + 1;+ }+ return defaultIndex;+ }++ private int requireColumn(+ List<software.amazon.awssdk.services.glue.model.Column> cols, String name) {+ int index = indexOf(cols, name);+ Preconditions.checkArgument(index >= 0, "Column %s does not exist", name);+ return index;+ }++ private int indexOf(List<software.amazon.awssdk.services.glue.model.Column> cols, String name) {+ for (int i = 0; i < cols.size(); i++) {+ if (cols.get(i).name().equalsIgnoreCase(name)) {+ return i;+ }+ }+ return -1;+ }}private GlueTable alterIcebergTable(@@ -732,6 +1047,143 @@ public class GlueCatalogOperations implements CatalogOperations, SupportsSchemasreturn GlueConstants.VIRTUAL_VIEW_TABLE_TYPE.equalsIgnoreCase(table.tableType());}+ /**+ * Glue accepts a table whose columns share a name (Glue folds names to lower case), but such a+ * table cannot be represented in Gravitino.+ */+ private static void rejectDuplicateColumns(GlueTable table, String dbName) {+ Set<String> names = new HashSet<>();+ for (Column column : table.columns()) {+ Preconditions.checkArgument(+ names.add(column.name().toLowerCase(Locale.ROOT)),+ "Table %s.%s has more than one column named %s; fix the table in Glue",+ dbName,+ table.name(),+ column.name());+ }+ }++ /** Returns the columns under the lower-case names Glue stores for a Hive-format table. */+ private static Column[] toLowerCaseColumns(Column[] columns) {+ return Arrays.stream(columns)+ .map(+ column ->+ Column.of(+ column.name().toLowerCase(Locale.ROOT),+ column.dataType(),+ column.comment(),+ column.nullable(),+ column.autoIncrement(),+ column.defaultValue()))+ .toArray(Column[]::new);+ }++ /** Returns a column reference as Glue stores it: Hive-format names are lower case. */+ private static String storedColumnName(String name, boolean isIceberg) {+ return isIceberg ? name : name.toLowerCase(Locale.ROOT);+ }++ /** Checks the column options Glue cannot store and the names Glue would fold together. */+ private static void validateColumns(Column[] columns) {+ Set<String> names = new HashSet<>();+ for (Column column : columns) {+ Preconditions.checkArgument(+ !column.autoIncrement(),+ "Glue does not support auto-increment columns: %s",+ column.name());+ // Glue stores column names in lower case.+ Preconditions.checkArgument(+ names.add(column.name().toLowerCase(Locale.ROOT)),+ "Duplicate column name: %s; Glue column names are case-insensitive",+ column.name());+ }+ }++ /**+ * Checks that a Hive-format table is partitioned by identity transforms on distinct primitive+ * columns that are the last columns of the table, in partitioning order, because Glue stores the+ * partition columns as a separate trailing list.+ */+ private static void validateHivePartitioning(Column[] columns, Transform[] partitions) {+ Preconditions.checkArgument(+ columns.length >= partitions.length,+ "The table has %s columns but %s partition columns",+ columns.length,+ partitions.length);+ int firstPartitionColumn = columns.length - partitions.length;+ for (int i = 0; i < partitions.length; i++) {+ Transform t = partitions[i];+ Preconditions.checkArgument(+ t instanceof Transforms.IdentityTransform,+ "Glue catalog only supports identity partitioning, got: %s",+ t.name());+ String[] fieldName = ((Transforms.IdentityTransform) t).fieldName();+ Preconditions.checkArgument(+ fieldName.length == 1, "Glue catalog does not support nested field partitioning");+ Column column = columns[firstPartitionColumn + i];+ Preconditions.checkArgument(+ column.name().equalsIgnoreCase(fieldName[0]),+ "Partition column %s must be at position %s: partition columns must be the last columns"+ + " of the table, in partitioning order",+ fieldName[0],+ firstPartitionColumn + i + 1);+ Type type = column.dataType();+ Preconditions.checkArgument(+ !(type instanceof Types.StructType+ || type instanceof Types.ListType+ || type instanceof Types.MapType+ || type instanceof Types.UnionType),+ "Partition column %s has type %s; Glue partition columns must have a primitive type",+ column.name(),+ type.simpleString());+ }+ }++ /** Checks that a distribution is one Glue can store: hash bucketing on plain columns. */+ private static void validateHiveDistribution(Distribution distribution) {+ if (distribution == null || distribution.strategy() == Strategy.NONE) {+ return;+ }+ Preconditions.checkArgument(+ distribution.strategy() == Strategy.HASH,+ "Glue only supports hash distribution (bucketing), got: %s",+ distribution.strategy());+ Preconditions.checkArgument(+ distribution.number() >= 1,+ "Glue bucketing needs a number of buckets of at least 1, got: %s",+ distribution.number());+ Preconditions.checkArgument(+ distribution.expressions().length > 0, "Glue bucketing needs at least one bucket column");+ for (Expression e : distribution.expressions()) {+ Preconditions.checkArgument(+ e instanceof NamedReference.FieldReference+ && ((NamedReference.FieldReference) e).fieldName().length == 1,+ "Glue only supports bucketing on plain columns, got: %s",+ e);+ }+ }++ /** Checks that sort orders are ones Glue can store: plain columns with the default nulls. */+ private static void validateHiveSortOrders(SortOrder[] sortOrders) {+ if (sortOrders == null) {+ return;+ }+ for (SortOrder so : sortOrders) {+ Preconditions.checkArgument(+ so.expression() instanceof NamedReference.FieldReference+ && ((NamedReference.FieldReference) so.expression()).fieldName().length == 1,+ "Glue only supports sort orders on plain columns, got: %s",+ so.expression());+ // Glue stores only the sort direction; the null ordering is implied by it.+ Preconditions.checkArgument(+ so.nullOrdering() == so.direction().defaultNullOrdering(),+ "Glue does not support %s for a %s sort order on %s",+ so.nullOrdering(),+ so.direction(),+ so.expression());+ }+ }+/** Rejects a Glue object that is a view, so that it is not acted on through the table API. */private static void rejectIfView(Table table, NameIdentifier ident, String dbName) {if (isView(table)) {@@ -837,24 +1289,22 @@ public class GlueCatalogOperations implements CatalogOperations, SupportsSchemas}}- // Translate format name to input/output/serde class names if not explicitly set.- String format = properties.getOrDefault(GlueConstants.FORMAT, StorageFormat.PARQUET.name());- String inputFormat = properties.get(GlueConstants.INPUT_FORMAT_CLASS);- String outputFormat = properties.get(GlueConstants.OUTPUT_FORMAT);- String serdeLib = properties.get(GlueConstants.SERDE_LIB);-- boolean needsFormatClasses =- !isIceberg && (inputFormat == null || outputFormat == null || serdeLib == null);- if (needsFormatClasses) {- String upperFormat = format.toUpperCase(Locale.ROOT);- Preconditions.checkArgument(- Arrays.stream(StorageFormat.values()).anyMatch(f -> f.name().equals(upperFormat)),- "Unsupported table format: %s",- format);- StorageFormat sf = StorageFormat.valueOf(upperFormat);- if (inputFormat == null) inputFormat = sf.getInputFormat();- if (outputFormat == null) outputFormat = sf.getOutputFormat();- if (serdeLib == null) serdeLib = sf.getSerde();+ // Blank classes cannot name a storage format, so they are treated as not set.+ String inputFormat = StringUtils.trimToNull(properties.get(GlueConstants.INPUT_FORMAT_CLASS));+ String outputFormat = StringUtils.trimToNull(properties.get(GlueConstants.OUTPUT_FORMAT));+ String serdeLib = StringUtils.trimToNull(properties.get(GlueConstants.SERDE_LIB));+ if (!isIceberg) {+ StorageFormat sf =+ resolveStorageFormat(+ StringUtils.trimToNull(properties.get(GlueConstants.FORMAT)),+ inputFormat,+ outputFormat,+ serdeLib);+ if (sf != null) {+ inputFormat = sf.getInputFormat();+ outputFormat = sf.getOutputFormat();+ serdeLib = sf.getSerde();+ }}SerDeInfo serDe =@@ -872,6 +1322,7 @@ public class GlueCatalogOperations implements CatalogOperations, SupportsSchemasArrays.stream(distribution.expressions()).filter(e -> e instanceof NamedReference.FieldReference).map(e -> String.join(".", ((NamedReference.FieldReference) e).fieldName()))+ .map(column -> storedColumnName(column, isIceberg)).collect(Collectors.toList());}@@ -880,7 +1331,9 @@ public class GlueCatalogOperations implements CatalogOperations, SupportsSchemasfor (SortOrder so : sortOrders) {if (so.expression() instanceof NamedReference.FieldReference) {String colName =- String.join(".", ((NamedReference.FieldReference) so.expression()).fieldName());+ storedColumnName(+ String.join(".", ((NamedReference.FieldReference) so.expression()).fieldName()),+ isIceberg);int order = so.direction() == SortDirection.ASCENDING ? 1 : 0;glueSortCols.add(Order.builder().column(colName).sortOrder(order).build());}@@ -918,11 +1371,110 @@ public class GlueCatalogOperations implements CatalogOperations, SupportsSchemasprivate software.amazon.awssdk.services.glue.model.Column toGlueColumn(Column col) {return software.amazon.awssdk.services.glue.model.Column.builder().name(col.name())- .type(typeConverter.fromGravitino(col.dataType()))+ .type(toGlueType(col.name(), col.dataType())).comment(col.comment()).build();}+ private String toGlueType(String columnName, Type type) {+ try {+ return typeConverter.fromGravitino(type);+ } catch (IllegalArgumentException e) {+ throw new IllegalArgumentException(+ String.format("Column %s: %s", columnName, e.getMessage()), e);+ }+ }++ /**+ * Resolves the storage classes of a Hive-format table. A {@code format} sets all three classes,+ * and any class given next to it must match. Without a format, either all three classes are+ * given, or none and the table is a text table, as in Hive and Athena.+ *+ * @return the storage format to apply, or null when all three classes are given explicitly+ */+ private static StorageFormat resolveStorageFormat(+ String format, String inputFormat, String outputFormat, String serdeLib) {+ if (format == null) {+ // Built-in input and output classes must come from the same storage format; a custom SerDe+ // over a built-in format, such as a JSON SerDe over text files, is allowed.+ Preconditions.checkArgument(+ !isBuiltInInputFormat(inputFormat)+ || !isBuiltInOutputFormat(outputFormat)+ || Arrays.stream(StorageFormat.values())+ .anyMatch(+ f ->+ f.getInputFormat().equals(inputFormat)+ && f.getOutputFormat().equals(outputFormat)),+ "'%s' %s and '%s' %s belong to different storage formats",+ GlueConstants.INPUT_FORMAT_CLASS,+ inputFormat,+ GlueConstants.OUTPUT_FORMAT,+ outputFormat);+ boolean anyClass = inputFormat != null || outputFormat != null || serdeLib != null;+ if (!anyClass) {+ return StorageFormat.TEXTFILE;+ }+ Preconditions.checkArgument(+ inputFormat != null && outputFormat != null && serdeLib != null,+ "Set all of '%s', '%s' and '%s', or set '%s' instead",+ GlueConstants.INPUT_FORMAT_CLASS,+ GlueConstants.OUTPUT_FORMAT,+ GlueConstants.SERDE_LIB,+ GlueConstants.FORMAT);+ // A custom class is taken as given, but these formats are read only by their own SerDe.+ Preconditions.checkArgument(+ !isBuiltInInputFormat(inputFormat)+ || !isBuiltInSerde(serdeLib)+ || SERDE_BOUND_FORMATS.stream()+ .allMatch(+ f -> f.getInputFormat().equals(inputFormat) == f.getSerde().equals(serdeLib)),+ "'%s' %s and '%s' %s belong to different storage formats",+ GlueConstants.INPUT_FORMAT_CLASS,+ inputFormat,+ GlueConstants.SERDE_LIB,+ serdeLib);+ return null;+ }++ String upperFormat = format.trim().toUpperCase(Locale.ROOT);+ Preconditions.checkArgument(+ Arrays.stream(StorageFormat.values()).anyMatch(f -> f.name().equals(upperFormat)),+ "Unsupported table format: %s. Supported formats: %s",+ format,+ Arrays.toString(StorageFormat.values()));+ StorageFormat sf = StorageFormat.valueOf(upperFormat);+ checkFormatClass(format, GlueConstants.INPUT_FORMAT_CLASS, inputFormat, sf.getInputFormat());+ checkFormatClass(format, GlueConstants.OUTPUT_FORMAT, outputFormat, sf.getOutputFormat());+ checkFormatClass(format, GlueConstants.SERDE_LIB, serdeLib, sf.getSerde());+ return sf;+ }++ private static boolean isBuiltInInputFormat(String inputFormat) {+ return Arrays.stream(StorageFormat.values())+ .anyMatch(f -> f.getInputFormat().equals(inputFormat));+ }++ private static boolean isBuiltInOutputFormat(String outputFormat) {+ return Arrays.stream(StorageFormat.values())+ .anyMatch(f -> f.getOutputFormat().equals(outputFormat));+ }++ private static boolean isBuiltInSerde(String serdeLib) {+ return Arrays.stream(StorageFormat.values()).anyMatch(f -> f.getSerde().equals(serdeLib));+ }++ private static void checkFormatClass(+ String format, String property, String given, String expected) {+ Preconditions.checkArgument(+ given == null || given.equals(expected),+ "'%s' is %s, which conflicts with '%s'=%s (expected %s)",+ property,+ given,+ GlueConstants.FORMAT,+ format,+ expected);+ }+/*** Resolves the storage location of a table, in order of precedence: the explicit {@code location}* property, the {@code LocationUri} the Glue database declares, and finally the catalog warehouse@@ -931,7 +1483,8 @@ public class GlueCatalogOperations implements CatalogOperations, SupportsSchemas* name in between.*/private String resolveTableLocation(String explicitLocation, String dbName, String tableName) {- if (explicitLocation != null) {+ // A blank location is treated as absent, so the documented fallbacks apply.+ if (StringUtils.isNotBlank(explicitLocation)) {return explicitLocation;}String databaseLocation = databaseLocationUri(dbName);@@ -962,59 +1515,6 @@ public class GlueCatalogOperations implements CatalogOperations, SupportsSchemas}}- private static void applyColumnChange(- List<Column> dataCols, List<Column> partCols, TableChange.ColumnChange change) {-- 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;- dataCols.add(- GlueColumn.builder()- .withName(add.fieldName()[0])- .withType(add.getDataType())- .withComment(add.getComment())- .withNullable(add.isNullable())- .build());-- } else if (change instanceof TableChange.DeleteColumn) {- boolean isPartition = partCols.stream().anyMatch(c -> c.name().equals(fieldName));- Preconditions.checkArgument(!isPartition, "Cannot delete partition column: %s", fieldName);- dataCols.removeIf(c -> c.name().equals(fieldName));-- } else if (change instanceof TableChange.RenameColumn) {- boolean isPartition = partCols.stream().anyMatch(c -> c.name().equals(fieldName));- Preconditions.checkArgument(!isPartition, "Cannot rename partition column: %s", fieldName);- String newColName = ((TableChange.RenameColumn) change).getNewName();- replaceColumn(- dataCols, fieldName, old -> copyColumn(old, newColName, old.dataType(), old.comment()));-- } else if (change instanceof TableChange.UpdateColumnType) {- boolean isPartition = partCols.stream().anyMatch(c -> c.name().equals(fieldName));- Preconditions.checkArgument(- !isPartition, "Cannot update type of partition column: %s", fieldName);- Type newType = ((TableChange.UpdateColumnType) change).getNewDataType();- replaceColumn(- dataCols, fieldName, old -> copyColumn(old, old.name(), newType, old.comment()));-- } else if (change instanceof TableChange.UpdateColumnComment) {- String newCmt = ((TableChange.UpdateColumnComment) change).getNewComment();- if (!replaceColumn(- dataCols, fieldName, old -> copyColumn(old, old.name(), old.dataType(), newCmt))) {- replaceColumn(- partCols, fieldName, old -> copyColumn(old, old.name(), old.dataType(), newCmt));- }-- } else {- throw new IllegalArgumentException(- "Unsupported column change: " + change.getClass().getSimpleName());- }- }-/** Passes {@code catalogId} to {@code setter} when it is non-null. */static void applyCatalogId(String catalogId, Consumer<String> setter) {if (catalogId != null) setter.accept(catalogId);@@ -1035,28 +1535,4 @@ public class GlueCatalogOperations implements CatalogOperations, SupportsSchemasthrow converted != null ? converted : e;}}-- /**- * Finds the first column matching {@code name} in {@code cols}, replaces it with the result of- * {@code updater}, and returns {@code true} if a replacement was made.- */- private static boolean replaceColumn(- List<Column> cols, String name, UnaryOperator<Column> updater) {- for (int i = 0; i < cols.size(); i++) {- if (cols.get(i).name().equals(name)) {- cols.set(i, updater.apply(cols.get(i)));- return true;- }- }- return false;- }-- private static Column copyColumn(Column src, String name, Type type, String comment) {- return GlueColumn.builder()- .withName(name)- .withType(type)- .withComment(comment)- .withNullable(src.nullable())- .build();- }}diff --git a/catalogs/catalog-glue/src/main/java/org/apache/gravitino/catalog/glue/GlueExceptionConverter.java b/catalogs/catalog-glue/src/main/java/org/apache/gravitino/catalog/glue/GlueExceptionConverter.javaindex bf3dbc7089..203e0b1db2 100644--- a/catalogs/catalog-glue/src/main/java/org/apache/gravitino/catalog/glue/GlueExceptionConverter.java+++ b/catalogs/catalog-glue/src/main/java/org/apache/gravitino/catalog/glue/GlueExceptionConverter.java@@ -261,6 +261,13 @@ final class GlueExceptionConverter {context,awsErrorDetail(glueException));}+ if (e instanceof ConcurrentModificationException) {+ return new OptimisticLockException(+ e,+ "%s was changed concurrently; the request can be retried. AWS error: %s",+ context,+ awsErrorDetail(glueException));+ }if (e instanceof InvalidInputException || e instanceof ValidationException) {return new IllegalArgumentException(String.format(diff --git a/catalogs/catalog-glue/src/main/java/org/apache/gravitino/catalog/glue/GlueSchema.java b/catalogs/catalog-glue/src/main/java/org/apache/gravitino/catalog/glue/GlueSchema.javaindex e252b41073..22945d5fc9 100644--- a/catalogs/catalog-glue/src/main/java/org/apache/gravitino/catalog/glue/GlueSchema.java+++ b/catalogs/catalog-glue/src/main/java/org/apache/gravitino/catalog/glue/GlueSchema.java@@ -18,9 +18,10 @@*/package org.apache.gravitino.catalog.glue;-import java.util.Collections;+import java.util.HashMap;import java.util.Map;import lombok.ToString;+import org.apache.commons.lang3.StringUtils;import org.apache.gravitino.connector.BaseSchema;import org.apache.gravitino.meta.AuditInfo;import software.amazon.awssdk.services.glue.model.Database;@@ -40,6 +41,7 @@ public class GlueSchema extends BaseSchema {* <li>{@code Database.name()} → {@code name}* <li>{@code Database.description()} → {@code comment} (nullable)* <li>{@code Database.parameters()} → {@code properties}+ * <li>{@code Database.locationUri()} → {@code properties["location"]}* <li>{@code Database.createTime()} → {@code auditInfo.createTime}* </ul>*@@ -49,8 +51,15 @@ public class GlueSchema extends BaseSchema {public static GlueSchema fromGlueDatabase(Database database) {AuditInfo auditInfo = AuditInfo.builder().withCreateTime(database.createTime()).build();- Map<String, String> props =- database.parameters() != null ? database.parameters() : Collections.emptyMap();+ Map<String, String> props = new HashMap<>();+ if (database.parameters() != null) {+ props.putAll(database.parameters());+ }+ // The database location lives in LocationUri; a "location" parameter left by earlier+ // versions is only used when LocationUri is not set.+ if (StringUtils.isNotBlank(database.locationUri())) {+ props.put(GlueConstants.LOCATION, database.locationUri());+ }return GlueSchema.builder().withName(database.name())diff --git a/catalogs/catalog-glue/src/main/java/org/apache/gravitino/catalog/glue/GlueTableOperations.java b/catalogs/catalog-glue/src/main/java/org/apache/gravitino/catalog/glue/GlueTableOperations.javaindex 98935ac169..436265c717 100644--- a/catalogs/catalog-glue/src/main/java/org/apache/gravitino/catalog/glue/GlueTableOperations.java+++ b/catalogs/catalog-glue/src/main/java/org/apache/gravitino/catalog/glue/GlueTableOperations.java@@ -18,13 +18,18 @@*/package org.apache.gravitino.catalog.glue;+import com.google.common.annotations.VisibleForTesting;import com.google.common.base.Preconditions;import java.util.ArrayList;+import java.util.Arrays;import java.util.Collections;import java.util.List;+import java.util.Locale;import java.util.Map;+import org.apache.commons.lang3.StringUtils;import org.apache.gravitino.connector.TableOperations;import org.apache.gravitino.exceptions.NoSuchPartitionException;+import org.apache.gravitino.exceptions.NoSuchTableException;import org.apache.gravitino.exceptions.PartitionAlreadyExistsException;import org.apache.gravitino.rel.SupportsPartitions;import org.apache.gravitino.rel.expressions.literals.Literal;@@ -43,6 +48,7 @@ import software.amazon.awssdk.services.glue.model.EntityNotFoundException;import software.amazon.awssdk.services.glue.model.GetPartitionRequest;import software.amazon.awssdk.services.glue.model.GetPartitionsRequest;import software.amazon.awssdk.services.glue.model.GetPartitionsResponse;+import software.amazon.awssdk.services.glue.model.GetTableRequest;import software.amazon.awssdk.services.glue.model.PartitionInput;import software.amazon.awssdk.services.glue.model.StorageDescriptor;@@ -62,6 +68,9 @@ class GlueTableOperations implements TableOperations, SupportsPartitions {private static final int MAX_PARTITION_VALUE_LENGTH = 1024;+ /** Characters Hive escapes in partition path names, besides control characters. */+ private static final String ESCAPED_PATH_CHARS = "\"#%'*/:=?\\{[]^";+private final GlueClient glueClient;/** Nullable — when null, Glue uses the caller's AWS account ID. */private final String catalogId;@@ -156,33 +165,56 @@ class GlueTableOperations implements TableOperations, SupportsPartitions {partition instanceof IdentityPartition, "Glue only supports identity partitions");IdentityPartition ip = (IdentityPartition) partition;Preconditions.checkArgument(- ip.values().length == partitionColNames.length,- "Partition values count (%s) must match partition columns count (%s)",- ip.values().length,- partitionColNames.length);+ ip.values().length == partitionColNames.length+ && ip.fieldNames().length == ip.values().length,+ "Partition must give one value for each partition column %s",+ Arrays.toString(partitionColNames));- List<String> values = new ArrayList<>(ip.values().length);+ // Glue stores values by position, so place each value under the column its field name names.+ String[] values = new String[partitionColNames.length];+ Literal<?>[] literals = new Literal<?>[partitionColNames.length];for (int i = 0; i < ip.values().length; i++) {+ String[] fieldName = ip.fieldNames()[i];+ int column = fieldName.length == 1 ? partitionColumnIndex(fieldName[0]) : -1;+ Preconditions.checkArgument(+ column >= 0,+ "Partition field %s is not a partition column of table %s; partition columns: %s",+ String.join(".", fieldName),+ tableName,+ Arrays.toString(partitionColNames));+ Preconditions.checkArgument(+ values[column] == null, "Partition column %s is given twice", partitionColNames[column]);Object value = ip.values()[i].value();- // Glue limits partition values to 1024 characters. Null and empty values are rejected because- // a Hive-style partition name cannot represent them.+ // Glue limits partition values to 1024 characters. Null and empty values are rejected, as+ // Hive stores them under its default partition name rather than by value.Preconditions.checkArgument(value != null && !value.toString().isEmpty(),"Value of partition column %s must not be null or empty",- partitionColNames[i]);+ partitionColNames[column]);Preconditions.checkArgument(value.toString().length() <= MAX_PARTITION_VALUE_LENGTH,"Value of partition column %s exceeds the Glue limit of %s characters",- partitionColNames[i],+ partitionColNames[column],MAX_PARTITION_VALUE_LENGTH);- values.add(value.toString());+ values[column] = value.toString();+ literals[column] = ip.values()[i];}+ List<String> valueList = Arrays.asList(values);+ String name = buildPartitionName(valueList);+ // A given name may be written with or without Hive escaping, but must match the values.+ Preconditions.checkArgument(+ partition.name() == null+ || matchesEscapedName(partition.name(), valueList)+ || matchesUnescapedName(partition.name(), valueList),+ "Partition name %s does not match its values; expected %s",+ partition.name(),+ name);PartitionInput input =PartitionInput.builder()- .values(values)+ .values(valueList).parameters(partition.properties())- .storageDescriptor(StorageDescriptor.builder().build())+ .storageDescriptor(partitionStorageDescriptor(name)).build();CreatePartitionRequest.Builder req =@@ -196,15 +228,20 @@ class GlueTableOperations implements TableOperations, SupportsPartitions {glueClient.createPartition(req.build());} catch (AlreadyExistsException e) {throw new PartitionAlreadyExistsException(- e, "Partition %s already exists in table %s", partition.name(), tableName);+ e, "Partition %s already exists in table %s", name, tableName);} catch (SdkException e) {throw GlueExceptionConverter.toGenericException(- e, "adding partition " + partition.name() + " to table " + tableName, glueClient);+ e, "adding partition " + name + " to table " + tableName, glueClient);}- LOG.info("Added partition {} to {}.{}", partition.name(), dbName, tableName);- return Partitions.identity(- partition.name(), ip.fieldNames(), ip.values(), partition.properties());+ LOG.info("Added partition {} to {}.{}", name, dbName, tableName);+ // The partition is built from the validated request: reading it back could fail after the+ // partition was created, and Glue returns every value as a string.+ String[][] fieldNames = new String[partitionColNames.length][];+ for (int i = 0; i < partitionColNames.length; i++) {+ fieldNames[i] = new String[] {partitionColNames[i]};+ }+ return Partitions.identity(name, fieldNames, literals, partition.properties());}@Override@@ -235,20 +272,24 @@ class GlueTableOperations implements TableOperations, SupportsPartitions {/*** Builds a Hive-style partition name (e.g. {@code dt=2024-01-01/country=us}) from an ordered list- * of Glue partition values.+ * of Glue partition values. Values are escaped as Hive does, so the name parses back to them.*/private String buildPartitionName(List<String> values) {StringBuilder sb = new StringBuilder();for (int i = 0; i < partitionColNames.length && i < values.size(); i++) {if (i > 0) sb.append('/');- sb.append(partitionColNames[i]).append('=').append(values.get(i));+ sb.append(escapePathName(partitionColNames[i].toLowerCase(Locale.ROOT)))+ .append('=')+ .append(escapePathName(values.get(i)));}return sb.toString();}/*** Parses a Hive-style partition name (e.g. {@code dt=2024-01-01/country=us}) into an ordered list- * of values, validating that the keys match the table's partition columns in order.+ * of unescaped values, validating that the keys match the table's partition columns in order. The+ * name must be in the escaped form that listing and adding partitions return, because an+ * unescaped {@code /} in a value cannot be told from a segment separator.*/private List<String> parsePartitionName(String partitionName) {String[] parts = partitionName.split("/");@@ -262,15 +303,124 @@ class GlueTableOperations implements TableOperations, SupportsPartitions {for (int i = 0; i < parts.length; i++) {int eq = parts[i].indexOf('=');Preconditions.checkArgument(- eq >= 0 && parts[i].substring(0, eq).equals(partitionColNames[i]),+ eq >= 0+ && unescapePathName(parts[i].substring(0, eq)).equalsIgnoreCase(partitionColNames[i]),"Partition segment '%s' does not match expected column '%s'",parts[i],partitionColNames[i]);- values.add(parts[i].substring(eq + 1));+ values.add(unescapePathName(parts[i].substring(eq + 1)));}return values;}+ /** Whether a Hive-escaped partition name names the values; column names ignore case. */+ private boolean matchesEscapedName(String name, List<String> values) {+ try {+ return parsePartitionName(name).equals(values);+ } catch (IllegalArgumentException e) {+ return false;+ }+ }++ /**+ * Whether an unescaped partition name, such as {@code p=a/b} for the value {@code a/b}, names the+ * values. Column names ignore case and values are compared as is.+ */+ private boolean matchesUnescapedName(String name, List<String> values) {+ int pos = 0;+ for (int i = 0; i < partitionColNames.length; i++) {+ if (i > 0) {+ if (!name.startsWith("/", pos)) {+ return false;+ }+ pos++;+ }+ String column = partitionColNames[i];+ if (!name.regionMatches(true, pos, column, 0, column.length())+ || !name.startsWith("=", pos + column.length())) {+ return false;+ }+ pos += column.length() + 1;+ if (!name.startsWith(values.get(i), pos)) {+ return false;+ }+ pos += values.get(i).length();+ }+ return pos == name.length();+ }++ private int partitionColumnIndex(String name) {+ for (int i = 0; i < partitionColNames.length; i++) {+ if (partitionColNames[i].equalsIgnoreCase(name)) {+ return i;+ }+ }+ return -1;+ }++ /**+ * Builds the storage descriptor of a new partition from the table's, as Hive does, so engines can+ * read it: the table's columns, formats and SerDe, and the table location plus the partition+ * path. Glue does not fill any of these in itself.+ */+ private StorageDescriptor partitionStorageDescriptor(String partitionName) {+ GetTableRequest.Builder req = GetTableRequest.builder().databaseName(dbName).name(tableName);+ GlueCatalogOperations.applyCatalogId(catalogId, req::catalogId);+ StorageDescriptor tableSd;+ try {+ tableSd = glueClient.getTable(req.build()).table().storageDescriptor();+ } catch (EntityNotFoundException e) {+ throw new NoSuchTableException(e, "Table %s.%s does not exist", dbName, tableName);+ } catch (SdkException e) {+ throw GlueExceptionConverter.toGenericException(e, "table " + tableName, glueClient);+ }+ Preconditions.checkArgument(+ tableSd != null && StringUtils.isNotBlank(tableSd.location()),+ "Cannot add a partition to table %s: the table has no storage location",+ tableName);+ return tableSd.toBuilder()+ .location(StringUtils.stripEnd(tableSd.location(), "/") + "/" + partitionName)+ .build();+ }++ /** Escapes a partition path segment the way Hive's FileUtils.escapePathName does. */+ @VisibleForTesting+ static String escapePathName(String value) {+ StringBuilder sb = new StringBuilder(value.length());+ for (int i = 0; i < value.length(); i++) {+ char c = value.charAt(i);+ if (needsEscaping(c)) {+ sb.append('%').append(String.format("%02X", (int) c));+ } else {+ sb.append(c);+ }+ }+ return sb.toString();+ }++ /** Reverses {@link #escapePathName(String)}; text that is not a valid escape is kept as is. */+ @VisibleForTesting+ static String unescapePathName(String value) {+ StringBuilder sb = new StringBuilder(value.length());+ for (int i = 0; i < value.length(); i++) {+ char c = value.charAt(i);+ if (c == '%'+ && i + 2 < value.length()+ && Character.digit(value.charAt(i + 1), 16) >= 0+ && Character.digit(value.charAt(i + 2), 16) >= 0) {+ sb.append((char) Integer.parseInt(value.substring(i + 1, i + 3), 16));+ i += 2;+ } else {+ sb.append(c);+ }+ }+ return sb.toString();+ }++ private static boolean needsEscaping(char c) {+ return c < ' ' || c == '\u007F' || ESCAPED_PATH_CHARS.indexOf(c) >= 0;+ }+private IdentityPartition toGravitinoPartition(software.amazon.awssdk.services.glue.model.Partition gluePartition) {List<String> values = gluePartition.values();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 d798cc769c..81f562a108 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@@ -53,11 +53,12 @@ public class GlueTablePropertiesMetadata extends BasePropertiesMetadata {static {List<PropertyEntry<?>> propertyEntries =ImmutableList.of(- stringOptionalPropertyEntry(+ stringImmutablePropertyEntry(TABLE_FORMAT,"Table format stored in Table.parameters(). Common values: ICEBERG, HIVE.",false,null,+ false,false),stringOptionalPropertyEntry(METADATA_LOCATION,diff --git a/catalogs/catalog-glue/src/main/java/org/apache/gravitino/catalog/glue/GlueTypeConverter.java b/catalogs/catalog-glue/src/main/java/org/apache/gravitino/catalog/glue/GlueTypeConverter.javaindex e4756ef411..d3530dfe73 100644--- a/catalogs/catalog-glue/src/main/java/org/apache/gravitino/catalog/glue/GlueTypeConverter.java+++ b/catalogs/catalog-glue/src/main/java/org/apache/gravitino/catalog/glue/GlueTypeConverter.java@@ -75,7 +75,9 @@ public class GlueTypeConverter implements DataTypeConverter<String, String> {public Type toGravitino(String glueType) {Preconditions.checkArgument(StringUtils.isNotBlank(glueType), "Glue column type must not be blank");- String lower = glueType.trim().toLowerCase(ROOT);+ // Keywords are matched in lower case, but struct field names keep their original case.+ String trimmed = glueType.trim();+ String lower = trimmed.toLowerCase(ROOT);switch (lower) {case BOOLEAN:@@ -92,7 +94,11 @@ public class GlueTypeConverter implements DataTypeConverter<String, String> {case FLOAT:return Types.FloatType.get();case DOUBLE:+ case DOUBLE_PRECISION:return Types.DoubleType.get();+ case DECIMAL:+ // Hive reads a decimal without precision and scale as decimal(10,0).+ return Types.DecimalType.of(10, 0);case STRING:return Types.StringType.get();case DATE:@@ -134,9 +140,9 @@ public class GlueTypeConverter implements DataTypeConverter<String, String> {}// name<body> types: array<T>, map<K,V>, struct<...>, uniontype<...>- m = ANGLE_TYPE_PATTERN.matcher(lower);+ m = ANGLE_TYPE_PATTERN.matcher(trimmed);if (m.matches()) {- String typeName = m.group(1);+ String typeName = m.group(1).toLowerCase(ROOT);String body = m.group(2).trim();switch (typeName) {case ARRAY:@@ -184,6 +190,12 @@ public class GlueTypeConverter implements DataTypeConverter<String, String> {@Overridepublic String fromGravitino(Type type) {+ if (type instanceof Type.IntegralType && !((Type.IntegralType) type).signed()) {+ throw new IllegalArgumentException(+ String.format(+ "Unsigned type %s is not supported by Glue; Glue/Hive has signed integers only",+ type.simpleString()));+ }if (type instanceof Types.BooleanType) return BOOLEAN;if (type instanceof Types.ByteType) return TINYINT;if (type instanceof Types.ShortType) return SMALLINT;@@ -200,7 +212,7 @@ public class GlueTypeConverter implements DataTypeConverter<String, String> {if (tsType.hasTimeZone()) {throw new IllegalArgumentException("Unsupported Gravitino type for Glue: "- + type+ + type.simpleString()+ ". Glue/Hive does not support TIMESTAMP WITH TIME ZONE.");}return TIMESTAMP;@@ -229,7 +241,10 @@ public class GlueTypeConverter implements DataTypeConverter<String, String> {if (type instanceof Types.StructType) {String fields =Arrays.stream(((Types.StructType) type).fields())- .map(f -> String.format("%s:%s", f.name(), fromGravitino(f.type())))+ .map(+ f ->+ String.format(+ "%s:%s", checkStructFieldName(f.name()), fromGravitino(f.type()))).collect(Collectors.joining(","));return String.format("%s<%s>", STRUCT, fields);}@@ -243,7 +258,20 @@ public class GlueTypeConverter implements DataTypeConverter<String, String> {if (type instanceof Types.ExternalType) {return ((Types.ExternalType) type).catalogString();}- throw new IllegalArgumentException("Unsupported Gravitino type for Glue: " + type);+ throw new IllegalArgumentException(+ "Unsupported Gravitino type for Glue: " + type.simpleString());+ }++ private static String checkStructFieldName(String name) {+ // Glue type strings have no quoting, so these characters would change how the type parses.+ Preconditions.checkArgument(+ StringUtils.isNotBlank(name)+ && name.equals(name.trim())+ && !StringUtils.containsAny(name, ":,<>()"),+ "Struct field name '%s' is not supported by Glue: it must not be blank, start or end with"+ + " whitespace, or contain ':', ',', '<', '>', '(' or ')'",+ name);+ return name;}/**diff --git a/catalogs/catalog-glue/src/test/java/org/apache/gravitino/catalog/glue/TestGlueCatalogCapability.java b/catalogs/catalog-glue/src/test/java/org/apache/gravitino/catalog/glue/TestGlueCatalogCapability.javaindex 9581a89e2a..265081b23b 100644--- a/catalogs/catalog-glue/src/test/java/org/apache/gravitino/catalog/glue/TestGlueCatalogCapability.java+++ b/catalogs/catalog-glue/src/test/java/org/apache/gravitino/catalog/glue/TestGlueCatalogCapability.java@@ -68,7 +68,7 @@ class TestGlueCatalogCapability {@Testvoid testCaseSensitiveOnColumnIsSupported() {- // Column name case folding is not documented in Glue Column API — treated as supported.+ // Iceberg keeps the case of column names; Hive-format names are folded by the catalog itself.CapabilityResult result = capability.caseSensitiveOnName(Capability.Scope.COLUMN);assertTrue(result.supported());}diff --git a/catalogs/catalog-glue/src/test/java/org/apache/gravitino/catalog/glue/TestGlueCatalogSchemaOperations.java b/catalogs/catalog-glue/src/test/java/org/apache/gravitino/catalog/glue/TestGlueCatalogSchemaOperations.javaindex d1eb719ee6..fb2ee6966d 100644--- a/catalogs/catalog-glue/src/test/java/org/apache/gravitino/catalog/glue/TestGlueCatalogSchemaOperations.java+++ b/catalogs/catalog-glue/src/test/java/org/apache/gravitino/catalog/glue/TestGlueCatalogSchemaOperations.java@@ -32,6 +32,7 @@ import java.time.Instant;import java.util.Collections;import java.util.List;import java.util.Map;+import java.util.concurrent.atomic.AtomicReference;import org.apache.commons.lang3.StringUtils;import org.apache.gravitino.NameIdentifier;import org.apache.gravitino.Namespace;@@ -52,6 +53,8 @@ import software.amazon.awssdk.services.glue.GlueClient;import software.amazon.awssdk.services.glue.model.AlreadyExistsException;import software.amazon.awssdk.services.glue.model.CreateDatabaseRequest;import software.amazon.awssdk.services.glue.model.Database;+import software.amazon.awssdk.services.glue.model.DatabaseIdentifier;+import software.amazon.awssdk.services.glue.model.DatabaseInput;import software.amazon.awssdk.services.glue.model.DeleteDatabaseRequest;import software.amazon.awssdk.services.glue.model.EntityNotFoundException;import software.amazon.awssdk.services.glue.model.GetDatabaseRequest;@@ -358,10 +361,7 @@ class TestGlueCatalogSchemaOperations {.parameters(Map.of("existing", "val")).createTime(Instant.now()).build();- when(mockClient.getDatabase(any(GetDatabaseRequest.class)))- .thenReturn(GetDatabaseResponse.builder().database(db).build());- when(mockClient.updateDatabase(any(UpdateDatabaseRequest.class)))- .thenReturn(UpdateDatabaseResponse.builder().build());+ useFakeGlueDatabase(db);ArgumentCaptor<UpdateDatabaseRequest> captor =ArgumentCaptor.forClass(UpdateDatabaseRequest.class);@@ -497,6 +497,112 @@ class TestGlueCatalogSchemaOperations {assertEquals("123456789012", captor.getValue().catalogId());}+ @Test+ void testLoadSchemaReportsLocationUri() {+ useFakeGlueDatabase(+ Database.builder()+ .name("mydb")+ .locationUri("s3://bucket/native_db")+ .parameters(Map.of("location", "s3://bucket/stale"))+ .build());++ GlueSchema schema = ops.loadSchema(NameIdentifier.of("metalake", "catalog", "mydb"));++ assertEquals("s3://bucket/native_db", schema.properties().get(GlueConstants.LOCATION));+ }++ @Test+ void testCreateSchemaStoresLocationOnlyAsLocationUri() {+ ArgumentCaptor<CreateDatabaseRequest> captor =+ ArgumentCaptor.forClass(CreateDatabaseRequest.class);++ GlueSchema created =+ ops.createSchema(+ NameIdentifier.of("metalake", "catalog", "mydb"),+ null,+ Map.of(GlueConstants.LOCATION, "s3://bucket/mydb", "k", "v"));+ assertEquals("s3://bucket/mydb", created.properties().get(GlueConstants.LOCATION));++ verify(mockClient).createDatabase(captor.capture());+ DatabaseInput input = captor.getValue().databaseInput();+ assertEquals("s3://bucket/mydb", input.locationUri());+ assertFalse(input.parameters().containsKey(GlueConstants.LOCATION));+ assertEquals("v", input.parameters().get("k"));+ }++ @Test+ void testAlterSchemaKeepsLocationUriAndUnmodeledFields() {+ useFakeGlueDatabase(+ Database.builder()+ .name("mydb")+ .description("native")+ .locationUri("s3://bucket/native_db")+ .parameters(Map.of("k", "v"))+ .targetDatabase(DatabaseIdentifier.builder().databaseName("shared").build())+ .build());+ ArgumentCaptor<UpdateDatabaseRequest> captor =+ ArgumentCaptor.forClass(UpdateDatabaseRequest.class);++ GlueSchema result =+ ops.alterSchema(+ NameIdentifier.of("metalake", "catalog", "mydb"), SchemaChange.setProperty("k2", "v2"));++ verify(mockClient).updateDatabase(captor.capture());+ DatabaseInput input = captor.getValue().databaseInput();+ assertEquals("s3://bucket/native_db", input.locationUri());+ assertEquals("native", input.description());+ assertEquals("shared", input.targetDatabase().databaseName());+ assertEquals("s3://bucket/native_db", result.properties().get(GlueConstants.LOCATION));+ }++ @Test+ void testAlterSchemaReturnsSubmittedDefinitionWhenReadBackFails() {+ Database database =+ Database.builder().name("mydb").locationUri("s3://bucket/native_db").build();+ when(mockClient.getDatabase(any(GetDatabaseRequest.class)))+ .thenReturn(GetDatabaseResponse.builder().database(database).build())+ .thenThrow(ThrottlingException.builder().message("slow down").build());++ GlueSchema result =+ ops.alterSchema(+ NameIdentifier.of("metalake", "catalog", "mydb"), SchemaChange.setProperty("k", "v"));++ verify(mockClient).updateDatabase(any(UpdateDatabaseRequest.class));+ assertEquals("v", result.properties().get("k"));+ assertEquals("s3://bucket/native_db", result.properties().get(GlueConstants.LOCATION));+ }++ @Test+ void testAlterSchemaLocationChangesLocationUri() {+ NameIdentifier ident = NameIdentifier.of("metalake", "catalog", "mydb");+ useFakeGlueDatabase(Database.builder().name("mydb").locationUri("s3://bucket/old").build());++ ops.alterSchema(ident, SchemaChange.setProperty(GlueConstants.LOCATION, "s3://bucket/new"));+ assertEquals("s3://bucket/new", ops.loadSchema(ident).properties().get(GlueConstants.LOCATION));++ ops.alterSchema(ident, SchemaChange.removeProperty(GlueConstants.LOCATION));+ assertFalse(ops.loadSchema(ident).properties().containsKey(GlueConstants.LOCATION));+ }++ /** Makes the mock behave like Glue for one database: updates are visible to later reads. */+ private void useFakeGlueDatabase(Database initial) {+ AtomicReference<Database> stored = new AtomicReference<>(initial);+ when(mockClient.getDatabase(any(GetDatabaseRequest.class)))+ .thenAnswer(inv -> GetDatabaseResponse.builder().database(stored.get()).build());+ when(mockClient.updateDatabase(any(UpdateDatabaseRequest.class)))+ .thenAnswer(+ inv -> {+ DatabaseInput in = ((UpdateDatabaseRequest) inv.getArgument(0)).databaseInput();+ stored.set(+ stored.get().toBuilder()+ .description(in.description())+ .locationUri(in.locationUri())+ .parameters(in.parameters())+ .build());+ return UpdateDatabaseResponse.builder().build();+ });+ }+private static GlueException glueException(String code, String message) {return (GlueException)GlueException.builder()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 9c9a7a1b25..370907a411 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@@ -20,6 +20,7 @@ package org.apache.gravitino.catalog.glue;import static org.junit.jupiter.api.Assertions.assertEquals;import static org.junit.jupiter.api.Assertions.assertFalse;+import static org.junit.jupiter.api.Assertions.assertNull;import static org.junit.jupiter.api.Assertions.assertThrows;import static org.junit.jupiter.api.Assertions.assertTrue;import static org.mockito.ArgumentMatchers.any;@@ -33,26 +34,40 @@ import java.util.Collections;import java.util.List;import java.util.Map;import java.util.Set;+import java.util.concurrent.atomic.AtomicReference;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.OptimisticLockException;import org.apache.gravitino.exceptions.TableAlreadyExistsException;import org.apache.gravitino.rel.Column;import org.apache.gravitino.rel.TableChange;+import org.apache.gravitino.rel.expressions.FunctionExpression;+import org.apache.gravitino.rel.expressions.NamedReference;+import org.apache.gravitino.rel.expressions.distributions.Distribution;import org.apache.gravitino.rel.expressions.distributions.Distributions;+import org.apache.gravitino.rel.expressions.distributions.Strategy;+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.indexes.Index;import org.apache.gravitino.rel.indexes.Indexes;+import org.apache.gravitino.rel.types.Type;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.awscore.exception.AwsErrorDetails;import software.amazon.awssdk.services.glue.GlueClient;import software.amazon.awssdk.services.glue.model.AlreadyExistsException;+import software.amazon.awssdk.services.glue.model.ConcurrentModificationException;import software.amazon.awssdk.services.glue.model.CreateTableRequest;+import software.amazon.awssdk.services.glue.model.CreateTableResponse;import software.amazon.awssdk.services.glue.model.Database;import software.amazon.awssdk.services.glue.model.DeleteTableRequest;import software.amazon.awssdk.services.glue.model.EntityNotFoundException;@@ -62,8 +77,13 @@ import software.amazon.awssdk.services.glue.model.GetTableRequest;import software.amazon.awssdk.services.glue.model.GetTableResponse;import software.amazon.awssdk.services.glue.model.GetTablesRequest;import software.amazon.awssdk.services.glue.model.GetTablesResponse;+import software.amazon.awssdk.services.glue.model.Order;+import software.amazon.awssdk.services.glue.model.SerDeInfo;+import software.amazon.awssdk.services.glue.model.SkewedInfo;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.ThrottlingException;import software.amazon.awssdk.services.glue.model.UpdateTableRequest;import software.amazon.awssdk.services.glue.model.UpdateTableResponse;@@ -79,6 +99,49 @@ class TestGlueCatalogTableOperations {ops.glueClient = mockClient;ops.warehouseLocation = "s3://test-bucket/warehouse";stubDatabaseLocation(null);+ useFakeGlueTable(null);+ }++ /**+ * Makes the mock behave like Glue for one table: creates and updates are visible to later reads,+ * which the catalog uses to build its responses.+ */+ private void useFakeGlueTable(Table initial) {+ AtomicReference<Table> stored = new AtomicReference<>(initial);+ when(mockClient.getTable(any(GetTableRequest.class)))+ .thenAnswer(+ inv -> {+ if (stored.get() == null) {+ throw EntityNotFoundException.builder().message("not found").build();+ }+ return GetTableResponse.builder().table(stored.get()).build();+ });+ when(mockClient.createTable(any(CreateTableRequest.class)))+ .thenAnswer(+ inv -> {+ stored.set(toTable(((CreateTableRequest) inv.getArgument(0)).tableInput()));+ return CreateTableResponse.builder().build();+ });+ when(mockClient.updateTable(any(UpdateTableRequest.class)))+ .thenAnswer(+ inv -> {+ stored.set(toTable(((UpdateTableRequest) inv.getArgument(0)).tableInput()));+ return UpdateTableResponse.builder().build();+ });+ }++ private static Table toTable(TableInput in) {+ return Table.builder()+ .name(in.name())+ .description(in.description())+ .owner(in.owner())+ .retention(in.retention())+ .storageDescriptor(in.storageDescriptor())+ .partitionKeys(in.partitionKeys())+ .tableType(in.tableType())+ .parameters(in.parameters())+ .createTime(Instant.now())+ .build();}/** Stubs the database lookup used to resolve table locations. */@@ -566,10 +629,7 @@ class TestGlueCatalogTableOperations {.storageDescriptor(StorageDescriptor.builder().build()).createTime(Instant.now()).build();- when(mockClient.getTable(any(GetTableRequest.class)))- .thenReturn(GetTableResponse.builder().table(glueTable).build());- when(mockClient.updateTable(any(UpdateTableRequest.class)))- .thenReturn(UpdateTableResponse.builder().build());+ useFakeGlueTable(glueTable);GlueTable result = ops.alterTable(ident, TableChange.updateComment("new comment"));@@ -612,10 +672,7 @@ class TestGlueCatalogTableOperations {.storageDescriptor(StorageDescriptor.builder().build()).createTime(Instant.now()).build();- when(mockClient.getTable(any(GetTableRequest.class)))- .thenReturn(GetTableResponse.builder().table(glueTable).build());- when(mockClient.updateTable(any(UpdateTableRequest.class)))- .thenReturn(UpdateTableResponse.builder().build());+ useFakeGlueTable(glueTable);GlueTable result = ops.alterTable(ident, TableChange.setProperty("newKey", "newVal"));@@ -641,10 +698,7 @@ class TestGlueCatalogTableOperations {.build()).createTime(Instant.now()).build();- when(mockClient.getTable(any(GetTableRequest.class)))- .thenReturn(GetTableResponse.builder().table(glueTable).build());- when(mockClient.updateTable(any(UpdateTableRequest.class)))- .thenReturn(UpdateTableResponse.builder().build());+ useFakeGlueTable(glueTable);GlueTable result =ops.alterTable(@@ -786,4 +840,742 @@ class TestGlueCatalogTableOperations {.parameters(Map.of("presto_view", "true")).build();}++ // -------------------------------------------------------------------------+ // Hive-format create validation+ // -------------------------------------------------------------------------++ private static final NameIdentifier HIVE_IDENT =+ NameIdentifier.of("metalake", "catalog", "mydb", "hive_tbl");++ private static Column col(String name, Type type) {+ return GlueColumn.builder().withName(name).withType(type).withNullable(true).build();+ }++ private GlueTable createHive(+ Column[] columns,+ Map<String, String> props,+ Transform[] partitions,+ Distribution distribution,+ SortOrder[] sortOrders) {+ return ops.createTable(+ HIVE_IDENT,+ columns,+ null,+ props,+ partitions,+ distribution,+ sortOrders,+ Indexes.EMPTY_INDEXES);+ }++ private void assertCreateRefused(+ String expectedText,+ Column[] columns,+ Map<String, String> props,+ Transform[] partitions,+ Distribution distribution,+ SortOrder[] sortOrders) {+ IllegalArgumentException e =+ assertThrows(+ IllegalArgumentException.class,+ () -> createHive(columns, props, partitions, distribution, sortOrders));+ assertTrue(e.getMessage().contains(expectedText), e.getMessage());+ verify(mockClient, never()).createTable(any(CreateTableRequest.class));+ }++ private static final Column[] ABC = {+ col("a", Types.StringType.get()),+ col("b", Types.IntegerType.get()),+ col("c", Types.DateType.get())+ };++ @Test+ void testCreateRefusesPartitionColumnsThatAreNotTrailing() {+ assertCreateRefused(+ "must be the last columns",+ ABC,+ Collections.emptyMap(),+ new Transform[] {Transforms.identity("a")},+ Distributions.NONE,+ SortOrders.NONE);+ assertCreateRefused(+ "must be the last columns",+ ABC,+ Collections.emptyMap(),+ new Transform[] {Transforms.identity("c"), Transforms.identity("b")},+ Distributions.NONE,+ SortOrders.NONE);+ }++ @Test+ void testCreateStoresTrailingPartitionColumns() {+ GlueTable created =+ createHive(+ ABC,+ Collections.emptyMap(),+ new Transform[] {Transforms.identity("b"), Transforms.identity("c")},+ Distributions.NONE,+ SortOrders.NONE);++ ArgumentCaptor<CreateTableRequest> captor = ArgumentCaptor.forClass(CreateTableRequest.class);+ verify(mockClient).createTable(captor.capture());+ TableInput input = captor.getValue().tableInput();+ assertEquals(List.of("b", "c"), input.partitionKeys().stream().map(c -> c.name()).toList());+ assertEquals(2, created.partitioning().length);+ }++ @Test+ void testCreateRefusesComplexPartitionColumn() {+ Column[] columns = {+ col("id", Types.LongType.get()),+ col("m", Types.MapType.valueNullable(Types.StringType.get(), Types.IntegerType.get()))+ };+ assertCreateRefused(+ "primitive type",+ columns,+ Collections.emptyMap(),+ new Transform[] {Transforms.identity("m")},+ Distributions.NONE,+ SortOrders.NONE);+ }++ @Test+ void testCreateRefusesDuplicateAndAutoIncrementColumns() {+ assertCreateRefused(+ "Duplicate column name",+ new Column[] {col("abc", Types.IntegerType.get()), col("Abc", Types.StringType.get())},+ Collections.emptyMap(),+ Transforms.EMPTY_TRANSFORM,+ Distributions.NONE,+ SortOrders.NONE);+ Column autoInc =+ GlueColumn.builder()+ .withName("id")+ .withType(Types.LongType.get())+ .withNullable(true)+ .withAutoIncrement(true)+ .build();+ assertCreateRefused(+ "auto-increment",+ new Column[] {autoInc},+ Collections.emptyMap(),+ Transforms.EMPTY_TRANSFORM,+ Distributions.NONE,+ SortOrders.NONE);+ }++ @Test+ void testCreateRefusesUnsupportedDistributionAndSortOrder() {+ assertCreateRefused(+ "hash distribution",+ ABC,+ Collections.emptyMap(),+ Transforms.EMPTY_TRANSFORM,+ Distributions.of(Strategy.RANGE, 4, NamedReference.field("a")),+ SortOrders.NONE);+ assertCreateRefused(+ "at least 1",+ ABC,+ Collections.emptyMap(),+ Transforms.EMPTY_TRANSFORM,+ Distributions.hash(0, NamedReference.field("a")),+ SortOrders.NONE);+ assertCreateRefused(+ "plain columns",+ ABC,+ Collections.emptyMap(),+ Transforms.EMPTY_TRANSFORM,+ Distributions.hash(4, FunctionExpression.of("abs", NamedReference.field("b"))),+ SortOrders.NONE);+ assertCreateRefused(+ "nulls_first",+ ABC,+ Collections.emptyMap(),+ Transforms.EMPTY_TRANSFORM,+ Distributions.NONE,+ new SortOrder[] {+ SortOrders.of(+ NamedReference.field("a"), SortDirection.DESCENDING, NullOrdering.NULLS_FIRST)+ });+ }++ @Test+ void testCreateDefaultsToTextStorage() {+ createHive(+ ABC,+ Collections.emptyMap(),+ Transforms.EMPTY_TRANSFORM,+ Distributions.NONE,+ SortOrders.NONE);++ ArgumentCaptor<CreateTableRequest> captor = ArgumentCaptor.forClass(CreateTableRequest.class);+ verify(mockClient).createTable(captor.capture());+ StorageDescriptor sd = captor.getValue().tableInput().storageDescriptor();+ assertEquals(HiveStorageConstants.TEXT_INPUT_FORMAT_CLASS, sd.inputFormat());+ assertEquals(HiveStorageConstants.IGNORE_KEY_OUTPUT_FORMAT_CLASS, sd.outputFormat());+ assertEquals(+ HiveStorageConstants.LAZY_SIMPLE_SERDE_CLASS, sd.serdeInfo().serializationLibrary());+ }++ @Test+ void testCreateRefusesConflictingOrPartialStorageClasses() {+ assertCreateRefused(+ "conflicts",+ ABC,+ Map.of(+ GlueConstants.FORMAT,+ "csv",+ GlueConstants.INPUT_FORMAT_CLASS,+ HiveStorageConstants.ORC_INPUT_FORMAT_CLASS),+ Transforms.EMPTY_TRANSFORM,+ Distributions.NONE,+ SortOrders.NONE);+ assertCreateRefused(+ "Set all of",+ ABC,+ Map.of(GlueConstants.INPUT_FORMAT_CLASS, HiveStorageConstants.ORC_INPUT_FORMAT_CLASS),+ Transforms.EMPTY_TRANSFORM,+ Distributions.NONE,+ SortOrders.NONE);+ assertCreateRefused(+ "Unsupported table format",+ ABC,+ Map.of(+ GlueConstants.FORMAT,+ "garbage",+ GlueConstants.INPUT_FORMAT_CLASS,+ "a",+ GlueConstants.OUTPUT_FORMAT,+ "b",+ GlueConstants.SERDE_LIB,+ "c"),+ Transforms.EMPTY_TRANSFORM,+ Distributions.NONE,+ SortOrders.NONE);+ }++ @Test+ void testCreateTreatsBlankLocationAsAbsentAndReturnsStoredTable() {+ GlueTable created =+ createHive(+ ABC,+ Map.of(GlueConstants.LOCATION, " "),+ Transforms.EMPTY_TRANSFORM,+ Distributions.NONE,+ SortOrders.NONE);++ assertEquals(+ "s3://test-bucket/warehouse/mydb/hive_tbl",+ created.properties().get(GlueConstants.LOCATION));+ assertEquals(+ HiveStorageConstants.TEXT_INPUT_FORMAT_CLASS,+ created.properties().get(GlueConstants.INPUT_FORMAT_CLASS));+ }++ @Test+ void testCreateUnsupportedTypeNamesColumn() {+ assertCreateRefused(+ "Column f",+ new Column[] {col("f", Types.FixedType.of(16))},+ Collections.emptyMap(),+ Transforms.EMPTY_TRANSFORM,+ Distributions.NONE,+ SortOrders.NONE);+ }++ @Test+ void testLoadRefusesTableWithDuplicateColumns() {+ useFakeGlueTable(+ Table.builder()+ .name("dup")+ .storageDescriptor(+ StorageDescriptor.builder()+ .columns(glueCol("id", "int"), glueCol("id", "string"))+ .build())+ .build());++ IllegalArgumentException e =+ assertThrows(+ IllegalArgumentException.class,+ () -> ops.loadTable(NameIdentifier.of("metalake", "catalog", "mydb", "dup")));+ assertTrue(e.getMessage().contains("more than one column named id"), e.getMessage());+ }++ // -------------------------------------------------------------------------+ // Hive-format alter+ // -------------------------------------------------------------------------++ private static final NameIdentifier ALTER_IDENT =+ NameIdentifier.of("metalake", "catalog", "mydb", "native");++ private static software.amazon.awssdk.services.glue.model.Column glueCol(+ String name, String type) {+ return software.amazon.awssdk.services.glue.model.Column.builder()+ .name(name)+ .type(type)+ .build();+ }++ /** A table as a crawler or another engine leaves it, with fields Gravitino does not model. */+ private static Table nativeTable() {+ return Table.builder()+ .name("native")+ .owner("crawler")+ .retention(7)+ .tableType("MANAGED_TABLE")+ .versionId("42")+ .parameters(Map.of("classification", "csv"))+ .partitionKeys(glueCol("dt", "string"))+ .storageDescriptor(+ StorageDescriptor.builder()+ .columns(+ glueCol("id", "int").toBuilder().parameters(Map.of("stat", "1")).build(),+ glueCol("s", "struct<Outer:int>"),+ glueCol("k", "string"))+ .location("s3://bucket/native")+ .inputFormat(HiveStorageConstants.TEXT_INPUT_FORMAT_CLASS)+ .outputFormat(HiveStorageConstants.IGNORE_KEY_OUTPUT_FORMAT_CLASS)+ .serdeInfo(+ SerDeInfo.builder()+ .serializationLibrary(HiveStorageConstants.LAZY_SIMPLE_SERDE_CLASS)+ .build())+ .compressed(true)+ .storedAsSubDirectories(true)+ .numberOfBuckets(4)+ .bucketColumns("k")+ .sortColumns(Order.builder().column("k").sortOrder(1).build())+ .parameters(Map.of("recordCount", "10"))+ .skewedInfo(SkewedInfo.builder().skewedColumnNames("k").build())+ .build())+ .build();+ }++ @Test+ void testCreateHiveTableRefusesIcebergTableType() {+ assertCreateRefused(+ "is not allowed on a Hive-format table",+ ABC,+ Map.of(GlueConstants.TABLE_TYPE_PARAM, "ICEBERG"),+ new Transform[0],+ Distributions.NONE,+ SortOrders.NONE);+ }++ @Test+ void testCreateReturnsSubmittedDefinitionWhenReadBackFails() {+ when(mockClient.createTable(any(CreateTableRequest.class)))+ .thenReturn(CreateTableResponse.builder().build());+ when(mockClient.getTable(any(GetTableRequest.class)))+ .thenThrow(+ ThrottlingException.builder()+ .awsErrorDetails(+ AwsErrorDetails.builder()+ .errorCode("ThrottlingException")+ .errorMessage("Rate exceeded")+ .build())+ .build());++ GlueTable table =+ createHive(ABC, Map.of(), new Transform[0], Distributions.NONE, SortOrders.NONE);++ assertEquals("hive_tbl", table.name());+ assertEquals(3, table.columns().length);+ assertEquals(+ HiveStorageConstants.TEXT_INPUT_FORMAT_CLASS,+ table.properties().get(GlueConstants.INPUT_FORMAT_CLASS));+ }++ @Test+ void testCreateTreatsBlankStorageClassesAsUnset() {+ useFakeGlueTable(null);+ GlueTable table =+ createHive(+ ABC,+ Map.of(+ GlueConstants.INPUT_FORMAT_CLASS, " ",+ GlueConstants.OUTPUT_FORMAT, "",+ GlueConstants.SERDE_LIB, " "),+ new Transform[0],+ Distributions.NONE,+ SortOrders.NONE);+ assertEquals(+ HiveStorageConstants.TEXT_INPUT_FORMAT_CLASS,+ table.properties().get(GlueConstants.INPUT_FORMAT_CLASS));+ }++ @Test+ void testCreateRefusesMismatchedBuiltInFormatClasses() {+ assertCreateRefused(+ "belong to different storage formats",+ ABC,+ Map.of(+ GlueConstants.INPUT_FORMAT_CLASS, HiveStorageConstants.ORC_INPUT_FORMAT_CLASS,+ GlueConstants.OUTPUT_FORMAT, HiveStorageConstants.PARQUET_OUTPUT_FORMAT_CLASS,+ GlueConstants.SERDE_LIB, HiveStorageConstants.LAZY_SIMPLE_SERDE_CLASS),+ new Transform[0],+ Distributions.NONE,+ SortOrders.NONE);++ // A custom SerDe over text files is a common combination.+ useFakeGlueTable(null);+ GlueTable table =+ createHive(+ ABC,+ Map.of(+ GlueConstants.INPUT_FORMAT_CLASS, HiveStorageConstants.TEXT_INPUT_FORMAT_CLASS,+ GlueConstants.OUTPUT_FORMAT, HiveStorageConstants.IGNORE_KEY_OUTPUT_FORMAT_CLASS,+ GlueConstants.SERDE_LIB, "org.openx.data.jsonserde.JsonSerDe"),+ new Transform[0],+ Distributions.NONE,+ SortOrders.NONE);+ assertEquals(+ "org.openx.data.jsonserde.JsonSerDe", table.properties().get(GlueConstants.SERDE_LIB));+ }++ @Test+ void testAlterRenamesSkewedColumns() {+ UpdateTableRequest req = alterAndCapture(TableChange.renameColumn(new String[] {"k"}, "k2"));+ assertEquals(+ List.of("k2"), req.tableInput().storageDescriptor().skewedInfo().skewedColumnNames());+ }++ @Test+ void testAlterRefusesDeletingSkewedColumn() {+ Table table = nativeTable();+ useFakeGlueTable(+ table.toBuilder()+ .storageDescriptor(+ table.storageDescriptor().toBuilder()+ .skewedInfo(SkewedInfo.builder().skewedColumnNames("id").build())+ .build())+ .build());+ IllegalArgumentException e =+ assertThrows(+ IllegalArgumentException.class,+ () ->+ ops.alterTable(ALTER_IDENT, TableChange.deleteColumn(new String[] {"id"}, false)));+ assertTrue(e.getMessage().contains("skewed"), e.getMessage());+ }++ @Test+ void testAlterRemovingStoragePropertyRemovesParameterOfSameName() {+ Table table = nativeTable();+ useFakeGlueTable(+ table.toBuilder()+ .parameters(Map.of("classification", "csv", GlueConstants.SERDE_NAME, "shadow"))+ .storageDescriptor(+ table.storageDescriptor().toBuilder()+ .serdeInfo(table.storageDescriptor().serdeInfo().toBuilder().name("s").build())+ .build())+ .build());+ ops.alterTable(ALTER_IDENT, TableChange.removeProperty(GlueConstants.SERDE_NAME));++ ArgumentCaptor<UpdateTableRequest> captor = ArgumentCaptor.forClass(UpdateTableRequest.class);+ verify(mockClient).updateTable(captor.capture());+ TableInput in = captor.getValue().tableInput();+ assertFalse(in.parameters().containsKey(GlueConstants.SERDE_NAME));+ assertNull(in.storageDescriptor().serdeInfo().name());+ }++ @Test+ void testAlterRefusesChangingTableFormat() {+ useFakeGlueTable(nativeTable());+ for (TableChange change :+ new TableChange[] {+ TableChange.setProperty(GlueConstants.TABLE_FORMAT, "iceberg"),+ TableChange.setProperty(GlueConstants.TABLE_TYPE_PARAM, "ICEBERG"),+ TableChange.removeProperty(GlueConstants.TABLE_FORMAT)+ }) {+ assertThrows(IllegalArgumentException.class, () -> ops.alterTable(ALTER_IDENT, change));+ }+ verify(mockClient, never()).updateTable(any(UpdateTableRequest.class));+ }++ private UpdateTableRequest alterAndCapture(TableChange... changes) {+ useFakeGlueTable(nativeTable());+ ops.alterTable(ALTER_IDENT, changes);+ ArgumentCaptor<UpdateTableRequest> captor = ArgumentCaptor.forClass(UpdateTableRequest.class);+ verify(mockClient).updateTable(captor.capture());+ return captor.getValue();+ }++ @Test+ void testAlterKeepsFieldsGravitinoDoesNotModel() {+ UpdateTableRequest req = alterAndCapture(TableChange.updateComment("new"));++ assertEquals("42", req.versionId());+ TableInput in = req.tableInput();+ assertEquals("new", in.description());+ assertEquals("crawler", in.owner());+ assertEquals(7, in.retention());+ assertEquals("MANAGED_TABLE", in.tableType());+ StorageDescriptor sd = in.storageDescriptor();+ assertEquals(Map.of("stat", "1"), sd.columns().get(0).parameters());+ assertEquals("struct<Outer:int>", sd.columns().get(1).type());+ assertTrue(sd.compressed());+ assertTrue(sd.storedAsSubDirectories());+ assertEquals(4, sd.numberOfBuckets());+ assertEquals(Map.of("recordCount", "10"), sd.parameters());+ assertEquals(List.of("k"), sd.skewedInfo().skewedColumnNames());+ }++ @Test+ void testAlterChangesLocationAndSerdeProperties() {+ UpdateTableRequest req =+ alterAndCapture(+ TableChange.setProperty(GlueConstants.LOCATION, "s3://bucket/moved"),+ TableChange.setProperty(GlueConstants.SERDE_PARAMETER_PREFIX + "field.delim", ","),+ TableChange.setProperty(GlueConstants.SERDE_NAME, "my_serde"));++ StorageDescriptor sd = req.tableInput().storageDescriptor();+ assertEquals("s3://bucket/moved", sd.location());+ assertEquals(",", sd.serdeInfo().parameters().get("field.delim"));+ assertEquals("my_serde", sd.serdeInfo().name());+ assertEquals(+ HiveStorageConstants.LAZY_SIMPLE_SERDE_CLASS, sd.serdeInfo().serializationLibrary());+ assertFalse(req.tableInput().parameters().containsKey(GlueConstants.LOCATION));+ }++ @Test+ void testAlterRefusesChangingStorageFormat() {+ useFakeGlueTable(nativeTable());+ assertThrows(+ IllegalArgumentException.class,+ () -> ops.alterTable(ALTER_IDENT, TableChange.setProperty(GlueConstants.FORMAT, "orc")));+ verify(mockClient, never()).updateTable(any(UpdateTableRequest.class));+ }++ @Test+ void testAlterTableWithoutStorageDescriptorKeepsIt() {+ useFakeGlueTable(Table.builder().name("native").partitionKeys(glueCol("dt", "string")).build());++ ops.alterTable(ALTER_IDENT, TableChange.updateComment("c"));++ ArgumentCaptor<UpdateTableRequest> captor = ArgumentCaptor.forClass(UpdateTableRequest.class);+ verify(mockClient).updateTable(captor.capture());+ assertNull(captor.getValue().tableInput().storageDescriptor());+ }++ @Test+ void testAlterRefusesNestedAndMissingColumns() {+ useFakeGlueTable(nativeTable());+ assertThrows(+ IllegalArgumentException.class,+ () ->+ ops.alterTable(+ ALTER_IDENT,+ TableChange.updateColumnType(new String[] {"s", "Outer"}, Types.LongType.get())));+ assertThrows(+ IllegalArgumentException.class,+ () -> ops.alterTable(ALTER_IDENT, TableChange.deleteColumn(new String[] {"nope"}, false)));+ assertThrows(+ IllegalArgumentException.class,+ () -> ops.alterTable(ALTER_IDENT, TableChange.renameColumn(new String[] {"nope"}, "x")));++ // Deleting a missing column with ifExists is a no-op and writes nothing.+ ops.alterTable(ALTER_IDENT, TableChange.deleteColumn(new String[] {"nope"}, true));+ verify(mockClient, never()).updateTable(any(UpdateTableRequest.class));+ }++ @Test+ void testCreateHiveTableFoldsColumnNames() {+ useFakeGlueTable(null);+ Column[] columns = {col("UserId", Types.LongType.get()), col("Region", Types.StringType.get())};+ createHive(+ columns,+ Collections.emptyMap(),+ new Transform[] {Transforms.identity("Region")},+ Distributions.of(Strategy.HASH, 4, NamedReference.field("UserId")),+ new SortOrder[] {SortOrders.of(NamedReference.field("UserId"), SortDirection.ASCENDING)});++ ArgumentCaptor<CreateTableRequest> captor = ArgumentCaptor.forClass(CreateTableRequest.class);+ verify(mockClient).createTable(captor.capture());+ TableInput input = captor.getValue().tableInput();+ assertEquals("userid", input.storageDescriptor().columns().get(0).name());+ assertEquals("region", input.partitionKeys().get(0).name());+ assertEquals(List.of("userid"), input.storageDescriptor().bucketColumns());+ assertEquals("userid", input.storageDescriptor().sortColumns().get(0).column());+ }++ @Test+ void testAlterFoldsNewHiveColumnNames() {+ UpdateTableRequest req =+ alterAndCapture(+ TableChange.renameColumn(new String[] {"k"}, "KeyCol"),+ TableChange.addColumn(new String[] {"NewCol"}, Types.StringType.get()));++ StorageDescriptor sd = req.tableInput().storageDescriptor();+ assertEquals(+ List.of("id", "s", "keycol", "newcol"), sd.columns().stream().map(c -> c.name()).toList());+ assertEquals(List.of("keycol"), sd.bucketColumns());+ assertEquals("keycol", sd.sortColumns().get(0).column());+ }++ @Test+ void testAlterReturnsSubmittedDefinitionWhenReadBackFails() {+ when(mockClient.getTable(any(GetTableRequest.class)))+ .thenReturn(GetTableResponse.builder().table(nativeTable()).build())+ .thenThrow(ThrottlingException.builder().message("slow down").build());++ GlueTable table = ops.alterTable(ALTER_IDENT, TableChange.setProperty("k1", "v1"));++ verify(mockClient).updateTable(any(UpdateTableRequest.class));+ assertEquals("v1", table.properties().get("k1"));+ assertEquals("id", table.columns()[0].name());+ }++ @Test+ void testSetStoragePropertyRemovesTableParameterOfSameName() {+ useFakeGlueTable(+ nativeTable().toBuilder().parameters(Map.of(GlueConstants.SERDE_NAME, "old")).build());++ ops.alterTable(ALTER_IDENT, TableChange.setProperty(GlueConstants.SERDE_NAME, "new"));++ ArgumentCaptor<UpdateTableRequest> captor = ArgumentCaptor.forClass(UpdateTableRequest.class);+ verify(mockClient).updateTable(captor.capture());+ TableInput input = captor.getValue().tableInput();+ assertEquals("new", input.storageDescriptor().serdeInfo().name());+ assertFalse(input.parameters().containsKey(GlueConstants.SERDE_NAME));+ }++ @Test+ void testCreateRefusesSerDeOfAnotherBuiltInFormat() {+ assertCreateRefused(+ "belong to different storage formats",+ ABC,+ Map.of(+ GlueConstants.INPUT_FORMAT_CLASS, HiveStorageConstants.ORC_INPUT_FORMAT_CLASS,+ GlueConstants.OUTPUT_FORMAT, HiveStorageConstants.ORC_OUTPUT_FORMAT_CLASS,+ GlueConstants.SERDE_LIB, HiveStorageConstants.PARQUET_SERDE_CLASS),+ new Transform[0],+ Distributions.NONE,+ SortOrders.NONE);+ assertCreateRefused(+ "belong to different storage formats",+ ABC,+ Map.of(+ GlueConstants.INPUT_FORMAT_CLASS, HiveStorageConstants.TEXT_INPUT_FORMAT_CLASS,+ GlueConstants.OUTPUT_FORMAT, HiveStorageConstants.IGNORE_KEY_OUTPUT_FORMAT_CLASS,+ GlueConstants.SERDE_LIB, HiveStorageConstants.ORC_SERDE_CLASS),+ new Transform[0],+ Distributions.NONE,+ SortOrders.NONE);++ // A custom SerDe is taken as given, even over a format with its own SerDe.+ useFakeGlueTable(null);+ createHive(+ ABC,+ Map.of(+ GlueConstants.INPUT_FORMAT_CLASS, HiveStorageConstants.ORC_INPUT_FORMAT_CLASS,+ GlueConstants.OUTPUT_FORMAT, HiveStorageConstants.ORC_OUTPUT_FORMAT_CLASS,+ GlueConstants.SERDE_LIB, "com.example.CustomSerDe"),+ new Transform[0],+ Distributions.NONE,+ SortOrders.NONE);+ verify(mockClient).createTable(any(CreateTableRequest.class));+ }++ @Test+ void testAlterMatchesColumnNamesWithoutCase() {+ UpdateTableRequest req =+ alterAndCapture(TableChange.updateColumnComment(new String[] {"ID"}, "the id"));+ assertEquals("the id", req.tableInput().storageDescriptor().columns().get(0).comment());+ }++ @Test+ void testAlterAddColumnHonorsPosition() {+ UpdateTableRequest req =+ alterAndCapture(+ TableChange.addColumn(+ new String[] {"first_col"},+ Types.StringType.get(),+ null,+ TableChange.ColumnPosition.first()),+ TableChange.addColumn(+ new String[] {"after_id"},+ Types.StringType.get(),+ null,+ TableChange.ColumnPosition.after("id")));++ assertEquals(+ List.of("first_col", "id", "after_id", "s", "k"),+ req.tableInput().storageDescriptor().columns().stream().map(c -> c.name()).toList());+ }++ @Test+ void testAlterRefusesBadAddColumns() {+ useFakeGlueTable(nativeTable());+ assertThrows(+ IllegalArgumentException.class,+ () ->+ ops.alterTable(+ ALTER_IDENT,+ TableChange.addColumn(+ new String[] {"x"},+ Types.StringType.get(),+ null,+ TableChange.ColumnPosition.after("nope"))));+ assertThrows(+ IllegalArgumentException.class,+ () ->+ ops.alterTable(+ ALTER_IDENT,+ TableChange.addColumn(+ new String[] {"x"},+ Types.LongType.get(),+ null,+ TableChange.ColumnPosition.defaultPos(),+ true,+ true)));+ assertThrows(+ IllegalArgumentException.class,+ () ->+ ops.alterTable(+ ALTER_IDENT, TableChange.addColumn(new String[] {"ID"}, Types.StringType.get())));+ verify(mockClient, never()).updateTable(any(UpdateTableRequest.class));+ }++ @Test+ void testAlterUpdatesColumnPosition() {+ UpdateTableRequest req =+ alterAndCapture(+ TableChange.updateColumnPosition(+ new String[] {"k"}, TableChange.ColumnPosition.first()));+ assertEquals(+ List.of("k", "id", "s"),+ req.tableInput().storageDescriptor().columns().stream().map(c -> c.name()).toList());+ }++ @Test+ void testAlterRenameBucketColumnUpdatesBucketAndSortColumns() {+ UpdateTableRequest req = alterAndCapture(TableChange.renameColumn(new String[] {"k"}, "k2"));+ StorageDescriptor sd = req.tableInput().storageDescriptor();+ assertEquals(List.of("k2"), sd.bucketColumns());+ assertEquals("k2", sd.sortColumns().get(0).column());+ }++ @Test+ void testAlterRefusesDeletingBucketColumn() {+ useFakeGlueTable(nativeTable());+ IllegalArgumentException e =+ assertThrows(+ IllegalArgumentException.class,+ () -> ops.alterTable(ALTER_IDENT, TableChange.deleteColumn(new String[] {"k"}, false)));+ assertTrue(e.getMessage().contains("Cannot delete column k"), e.getMessage());+ }++ @Test+ void testAlterConcurrentModificationIsConflict() {+ useFakeGlueTable(nativeTable());+ when(mockClient.updateTable(any(UpdateTableRequest.class)))+ .thenThrow(+ ConcurrentModificationException.builder()+ .message("Update table failed due to concurrent modifications")+ .build());++ assertThrows(+ OptimisticLockException.class,+ () -> ops.alterTable(ALTER_IDENT, TableChange.setProperty("k", "v")));+ }}diff --git a/catalogs/catalog-glue/src/test/java/org/apache/gravitino/catalog/glue/TestGlueIcebergTableHelper.java b/catalogs/catalog-glue/src/test/java/org/apache/gravitino/catalog/glue/TestGlueIcebergTableHelper.javaindex 3daef01cce..d2c2d744bc 100644--- a/catalogs/catalog-glue/src/test/java/org/apache/gravitino/catalog/glue/TestGlueIcebergTableHelper.java+++ b/catalogs/catalog-glue/src/test/java/org/apache/gravitino/catalog/glue/TestGlueIcebergTableHelper.java@@ -30,10 +30,13 @@ import static org.mockito.Mockito.when;import java.io.IOException;import java.util.HashMap;+import java.util.List;import java.util.Map;+import java.util.stream.Collectors;import org.apache.gravitino.catalog.lakehouse.iceberg.IcebergConstants;import org.apache.gravitino.meta.AuditInfo;import org.apache.gravitino.rel.Column;+import org.apache.gravitino.rel.TableChange;import org.apache.gravitino.rel.types.Types;import org.apache.iceberg.PartitionSpec;import org.apache.iceberg.Schema;@@ -42,7 +45,9 @@ import org.apache.iceberg.Table;import org.apache.iceberg.aws.AwsClientProperties;import org.apache.iceberg.aws.glue.GlueCatalog;import org.apache.iceberg.catalog.Catalog;+import org.apache.iceberg.catalog.Namespace;import org.apache.iceberg.catalog.TableIdentifier;+import org.apache.iceberg.inmemory.InMemoryCatalog;import org.apache.iceberg.types.Types.BooleanType;import org.apache.iceberg.types.Types.DateType;import org.apache.iceberg.types.Types.DecimalType;@@ -350,4 +355,40 @@ class TestGlueIcebergTableHelper {assertEquals("2500", icebergProps.get("http-client.apache.connection-timeout-ms"));assertEquals("2500", icebergProps.get("http-client.apache.socket-timeout-ms"));}++ @Test+ void testAlterTableKeepsTheCaseOfColumnNames() throws IOException {+ try (InMemoryCatalog catalog = new InMemoryCatalog()) {+ catalog.initialize("test", new HashMap<>());+ catalog.createNamespace(Namespace.of("db"));+ catalog.createTable(+ TableIdentifier.of("db", "events"),+ new Schema(+ NestedField.optional(1, "UserId", LongType.get()),+ NestedField.optional(2, "EventTime", TimestampType.withoutZone())));++ GlueIcebergTableHelper.alterTable(+ catalog,+ "db",+ "events",+ TableChange.deleteColumn(new String[] {"UserId"}, false),+ TableChange.renameColumn(new String[] {"EventTime"}, "eventAt"),+ TableChange.addColumn(new String[] {"newCol"}, Types.StringType.get()));++ Schema schema = catalog.loadTable(TableIdentifier.of("db", "events")).schema();+ assertEquals(+ List.of("eventAt", "newCol"),+ schema.columns().stream().map(NestedField::name).collect(Collectors.toList()));++ // Column names match exactly, so a name in another case is not found.+ assertThrows(+ IllegalArgumentException.class,+ () ->+ GlueIcebergTableHelper.alterTable(+ catalog,+ "db",+ "events",+ TableChange.deleteColumn(new String[] {"eventat"}, false)));+ }+ }}diff --git a/catalogs/catalog-glue/src/test/java/org/apache/gravitino/catalog/glue/TestGluePartitionOperations.java b/catalogs/catalog-glue/src/test/java/org/apache/gravitino/catalog/glue/TestGluePartitionOperations.javaindex 3d6eca2169..772a2caaf0 100644--- a/catalogs/catalog-glue/src/test/java/org/apache/gravitino/catalog/glue/TestGluePartitionOperations.java+++ b/catalogs/catalog-glue/src/test/java/org/apache/gravitino/catalog/glue/TestGluePartitionOperations.java@@ -18,6 +18,7 @@*/package org.apache.gravitino.catalog.glue;+import static org.junit.jupiter.api.Assertions.assertArrayEquals;import static org.junit.jupiter.api.Assertions.assertEquals;import static org.junit.jupiter.api.Assertions.assertFalse;import static org.junit.jupiter.api.Assertions.assertThrows;@@ -29,7 +30,9 @@ import static org.mockito.Mockito.verify;import static org.mockito.Mockito.when;import java.util.List;+import java.util.Map;import org.apache.commons.lang3.StringUtils;+import org.apache.gravitino.catalog.hive.HiveStorageConstants;import org.apache.gravitino.exceptions.ForbiddenException;import org.apache.gravitino.exceptions.NoSuchPartitionException;import org.apache.gravitino.exceptions.PartitionAlreadyExistsException;@@ -50,7 +53,12 @@ import software.amazon.awssdk.services.glue.model.GetPartitionRequest;import software.amazon.awssdk.services.glue.model.GetPartitionResponse;import software.amazon.awssdk.services.glue.model.GetPartitionsRequest;import software.amazon.awssdk.services.glue.model.GetPartitionsResponse;+import software.amazon.awssdk.services.glue.model.GetTableRequest;+import software.amazon.awssdk.services.glue.model.GetTableResponse;import software.amazon.awssdk.services.glue.model.InvalidInputException;+import software.amazon.awssdk.services.glue.model.PartitionInput;+import software.amazon.awssdk.services.glue.model.SerDeInfo;+import software.amazon.awssdk.services.glue.model.StorageDescriptor;class TestGluePartitionOperations {@@ -62,6 +70,36 @@ class TestGluePartitionOperations {mockClient = mock(GlueClient.class);ops =new GlueTableOperations(mockClient, null, "mydb", "mytable", new String[] {"dt", "region"});+ // The table a new partition copies its storage descriptor from.+ when(mockClient.getTable(any(GetTableRequest.class)))+ .thenReturn(+ GetTableResponse.builder()+ .table(+ software.amazon.awssdk.services.glue.model.Table.builder()+ .name("mytable")+ .storageDescriptor(+ StorageDescriptor.builder()+ .location("s3://bucket/mydb/mytable/")+ .inputFormat(HiveStorageConstants.TEXT_INPUT_FORMAT_CLASS)+ .outputFormat(HiveStorageConstants.IGNORE_KEY_OUTPUT_FORMAT_CLASS)+ .serdeInfo(+ SerDeInfo.builder()+ .serializationLibrary(+ HiveStorageConstants.LAZY_SIMPLE_SERDE_CLASS)+ .build())+ .build())+ .build())+ .build());+ // Glue returns the partition that was added.+ when(mockClient.getPartition(any(GetPartitionRequest.class)))+ .thenAnswer(+ inv ->+ GetPartitionResponse.builder()+ .partition(+ software.amazon.awssdk.services.glue.model.Partition.builder()+ .values(((GetPartitionRequest) inv.getArgument(0)).partitionValues())+ .build())+ .build());}// -------------------------------------------------------------------------@@ -143,6 +181,42 @@ class TestGluePartitionOperations {assertEquals("dt=2024-01-01/region=us", result.name());}+ @Test+ void testPartitionWithEmptyValueIsAddressableByItsListedName() {+ software.amazon.awssdk.services.glue.model.Partition gluePartition =+ software.amazon.awssdk.services.glue.model.Partition.builder()+ .values("2024-01-01", "")+ .build();+ when(mockClient.getPartitions(any(GetPartitionsRequest.class)))+ .thenReturn(GetPartitionsResponse.builder().partitions(gluePartition).build());+ when(mockClient.getPartition(any(GetPartitionRequest.class)))+ .thenReturn(GetPartitionResponse.builder().partition(gluePartition).build());++ String name = ops.listPartitionNames()[0];+ assertEquals("dt=2024-01-01/region=", name);++ ops.getPartition(name);+ ArgumentCaptor<GetPartitionRequest> captor = ArgumentCaptor.forClass(GetPartitionRequest.class);+ verify(mockClient).getPartition(captor.capture());+ assertEquals(List.of("2024-01-01", ""), captor.getValue().partitionValues());+ }++ @Test+ void testPartitionNameUsesLowerCaseKeys() {+ GlueTableOperations upperCaseOps =+ new GlueTableOperations(mockClient, null, "mydb", "mytable", new String[] {"DT"});+ when(mockClient.getPartitions(any(GetPartitionsRequest.class)))+ .thenReturn(+ GetPartitionsResponse.builder()+ .partitions(+ software.amazon.awssdk.services.glue.model.Partition.builder()+ .values("2024-01-01")+ .build())+ .build());++ assertEquals("dt=2024-01-01", upperCaseOps.listPartitionNames()[0]);+ }+@Testvoid testGetPartitionNotFound() {when(mockClient.getPartition(any(GetPartitionRequest.class)))@@ -230,7 +304,7 @@ class TestGluePartitionOperations {private static IdentityPartition partitionWithRegion(String region) {return Partitions.identity(- "p",+ null,new String[][] {{"dt"}, {"region"}},new org.apache.gravitino.rel.expressions.literals.Literal[] {Literals.stringLiteral("2024-01-01"), Literals.stringLiteral(region)@@ -315,4 +389,153 @@ class TestGluePartitionOperations {verify(mockClient).deletePartition(captor.capture());assertEquals("123456789012", captor.getValue().catalogId());}++ private static IdentityPartition partition(String name, String[][] fieldNames, String... values) {+ org.apache.gravitino.rel.expressions.literals.Literal<?>[] literals =+ new org.apache.gravitino.rel.expressions.literals.Literal<?>[values.length];+ for (int i = 0; i < values.length; i++) {+ literals[i] = Literals.stringLiteral(values[i]);+ }+ return Partitions.identity(name, fieldNames, literals, java.util.Collections.emptyMap());+ }++ private PartitionInput addAndCapture(IdentityPartition partition) {+ ops.addPartition(partition);+ ArgumentCaptor<CreatePartitionRequest> captor =+ ArgumentCaptor.forClass(CreatePartitionRequest.class);+ verify(mockClient).createPartition(captor.capture());+ return captor.getValue().partitionInput();+ }++ @Test+ void testPartitionValueWithSlashIsEscapedAndAddressable() {+ PartitionInput input =+ addAndCapture(partition(null, new String[][] {{"dt"}, {"region"}}, "2025/12/31", "us"));+ assertEquals(List.of("2025/12/31", "us"), input.values());++ Partition added = ops.getPartition("dt=2025%2F12%2F31/region=us");+ assertEquals("dt=2025%2F12%2F31/region=us", added.name());++ ArgumentCaptor<GetPartitionRequest> getCaptor =+ ArgumentCaptor.forClass(GetPartitionRequest.class);+ verify(mockClient, org.mockito.Mockito.atLeastOnce()).getPartition(getCaptor.capture());+ assertEquals(List.of("2025/12/31", "us"), getCaptor.getValue().partitionValues());+ }++ @Test+ void testAddPartitionAcceptsUnescapedName() {+ PartitionInput input =+ addAndCapture(+ partition(+ "dt=2025/12/31/region=us",+ new String[][] {{"dt"}, {"region"}},+ "2025/12/31",+ "us"));+ assertEquals(List.of("2025/12/31", "us"), input.values());+ }++ @Test+ void testEscapeRoundTrip() {+ String value = "a/b=c%d:e#f";+ assertEquals(+ value, GlueTableOperations.unescapePathName(GlueTableOperations.escapePathName(value)));+ assertEquals("100%", GlueTableOperations.unescapePathName("100%"));+ assertEquals("%+1", GlueTableOperations.unescapePathName("%+1"));+ }++ @Test+ void testAddPartitionPlacesValuesByFieldName() {+ PartitionInput input =+ addAndCapture(partition(null, new String[][] {{"region"}, {"dt"}}, "us", "2024-01-01"));+ assertEquals(List.of("2024-01-01", "us"), input.values());+ }++ @Test+ void testAddPartitionRefusesUnknownFieldOrMismatchedName() {+ assertThrows(+ IllegalArgumentException.class,+ () -> ops.addPartition(partition(null, new String[][] {{"zz"}, {"yy"}}, "a", "b")));+ IllegalArgumentException e =+ assertThrows(+ IllegalArgumentException.class,+ () ->+ ops.addPartition(+ partition(+ "dt=q/region=9", new String[][] {{"dt"}, {"region"}}, "2024-01-01", "us")));+ assertTrue(e.getMessage().contains("does not match"), e.getMessage());+ verify(mockClient, never()).createPartition(any(CreatePartitionRequest.class));+ }++ @Test+ void testAddPartitionCopiesTableStorageDescriptor() {+ PartitionInput input =+ addAndCapture(partition(null, new String[][] {{"dt"}, {"region"}}, "2024-01-01", "us"));+ StorageDescriptor sd = input.storageDescriptor();+ assertEquals("s3://bucket/mydb/mytable/dt=2024-01-01/region=us", sd.location());+ assertEquals(HiveStorageConstants.TEXT_INPUT_FORMAT_CLASS, sd.inputFormat());+ assertEquals(+ HiveStorageConstants.LAZY_SIMPLE_SERDE_CLASS, sd.serdeInfo().serializationLibrary());+ }++ @Test+ void testAddPartitionRefusesTableWithoutLocation() {+ when(mockClient.getTable(any(GetTableRequest.class)))+ .thenReturn(+ GetTableResponse.builder()+ .table(+ software.amazon.awssdk.services.glue.model.Table.builder()+ .name("mytable")+ .build())+ .build());++ IllegalArgumentException e =+ assertThrows(+ IllegalArgumentException.class,+ () ->+ ops.addPartition(+ partition(null, new String[][] {{"dt"}, {"region"}}, "2024-01-01", "us")));+ assertTrue(e.getMessage().contains("no storage location"), e.getMessage());+ }++ @Test+ void testAddPartitionNameIgnoresCaseOfColumnNames() {+ PartitionInput input =+ addAndCapture(+ partition(+ "DT=2024-01-01/Region=us",+ new String[][] {{"dt"}, {"region"}},+ "2024-01-01",+ "us"));+ assertEquals(List.of("2024-01-01", "us"), input.values());++ assertThrows(+ IllegalArgumentException.class,+ () ->+ ops.addPartition(+ partition(+ "dt=2024-01-01/region=US",+ new String[][] {{"dt"}, {"region"}},+ "2024-01-01",+ "us")));+ }++ @Test+ void testAddPartitionReturnsTheRequestedValuesWithoutReadingBack() {+ IdentityPartition partition =+ Partitions.identity(+ null,+ new String[][] {{"region"}, {"dt"}},+ new org.apache.gravitino.rel.expressions.literals.Literal<?>[] {+ Literals.stringLiteral("us"), Literals.dateLiteral(java.time.LocalDate.of(2024, 1, 1))+ },+ Map.of("k", "v"));++ IdentityPartition result = (IdentityPartition) ops.addPartition(partition);++ assertEquals("dt=2024-01-01/region=us", result.name());+ assertArrayEquals(new String[][] {{"dt"}, {"region"}}, result.fieldNames());+ assertEquals(Literals.dateLiteral(java.time.LocalDate.of(2024, 1, 1)), result.values()[0]);+ assertEquals(Map.of("k", "v"), result.properties());+ verify(mockClient, never()).getPartition(any(GetPartitionRequest.class));+ }}diff --git a/catalogs/catalog-glue/src/test/java/org/apache/gravitino/catalog/glue/TestGlueTablePropertiesMetadata.java b/catalogs/catalog-glue/src/test/java/org/apache/gravitino/catalog/glue/TestGlueTablePropertiesMetadata.javaindex 89322b5519..0b622a5996 100644--- a/catalogs/catalog-glue/src/test/java/org/apache/gravitino/catalog/glue/TestGlueTablePropertiesMetadata.java+++ b/catalogs/catalog-glue/src/test/java/org/apache/gravitino/catalog/glue/TestGlueTablePropertiesMetadata.java@@ -21,6 +21,7 @@ package org.apache.gravitino.catalog.glue;import static org.apache.gravitino.catalog.glue.GlueConstants.METADATA_LOCATION;import static org.apache.gravitino.catalog.glue.GlueConstants.TABLE_FORMAT;import static org.junit.jupiter.api.Assertions.assertFalse;+import static org.junit.jupiter.api.Assertions.assertTrue;import org.junit.jupiter.api.BeforeEach;import org.junit.jupiter.api.Test;@@ -44,6 +45,11 @@ class TestGlueTablePropertiesMetadata {assertFalse(metadata.isHiddenProperty(TABLE_FORMAT));}+ @Test+ void testTableFormatIsImmutable() {+ assertTrue(metadata.isImmutableProperty(TABLE_FORMAT));+ }+@Testvoid testMetadataLocationIsOptional() {assertFalse(metadata.isRequiredProperty(METADATA_LOCATION));diff --git a/catalogs/catalog-glue/src/test/java/org/apache/gravitino/catalog/glue/TestGlueTypeConverter.java b/catalogs/catalog-glue/src/test/java/org/apache/gravitino/catalog/glue/TestGlueTypeConverter.javaindex 5dcd3aa5e6..c3dbe2e50f 100644--- a/catalogs/catalog-glue/src/test/java/org/apache/gravitino/catalog/glue/TestGlueTypeConverter.java+++ b/catalogs/catalog-glue/src/test/java/org/apache/gravitino/catalog/glue/TestGlueTypeConverter.java@@ -19,8 +19,10 @@package org.apache.gravitino.catalog.glue;import static org.junit.jupiter.api.Assertions.assertEquals;+import static org.junit.jupiter.api.Assertions.assertFalse;import static org.junit.jupiter.api.Assertions.assertInstanceOf;import static org.junit.jupiter.api.Assertions.assertThrows;+import static org.junit.jupiter.api.Assertions.assertTrue;import org.apache.gravitino.rel.types.Type;import org.apache.gravitino.rel.types.Types;@@ -233,4 +235,62 @@ class TestGlueTypeConverter {assertEquals(gravitinoType, CONVERTER.toGravitino(glueType));assertEquals(glueType, CONVERTER.fromGravitino(gravitinoType));}++ @Test+ void testStructFieldNamesKeepTheirCase() {+ String glueType = "struct<Outer:struct<InNer:int>,lowx:string>";+ Types.StructType struct = (Types.StructType) CONVERTER.toGravitino(glueType);++ assertEquals("Outer", struct.fields()[0].name());+ assertEquals("InNer", ((Types.StructType) struct.fields()[0].type()).fields()[0].name());+ assertEquals(glueType, CONVERTER.fromGravitino(struct));+ }++ @Test+ void testStructFieldNameThatBreaksTypeStringIsRefused() {+ for (String name : new String[] {"a:b", "x,y", "a<b", " ", "a(", "b)", " a", "a "}) {+ Types.StructType struct =+ Types.StructType.of(Types.StructType.Field.nullableField(name, Types.IntegerType.get()));+ IllegalArgumentException e =+ assertThrows(IllegalArgumentException.class, () -> CONVERTER.fromGravitino(struct));+ assertTrue(e.getMessage().contains("Struct field name"), e.getMessage());+ }+ }++ @Test+ void testBareDecimalAndDoublePrecision() {+ assertEquals(Types.DecimalType.of(10, 0), CONVERTER.toGravitino("decimal"));+ assertEquals(Types.DecimalType.of(10, 0), CONVERTER.toGravitino("DECIMAL"));+ assertEquals(+ Types.ListType.nullable(Types.DecimalType.of(10, 0)),+ CONVERTER.toGravitino("array<DECIMAL>"));+ assertEquals(Types.DoubleType.get(), CONVERTER.toGravitino("double precision"));+ assertEquals(+ Types.MapType.valueNullable(Types.StringType.get(), Types.DoubleType.get()),+ CONVERTER.toGravitino("map<string,DOUBLE PRECISION>"));+ }++ @Test+ void testUnsignedIntegersAreRefused() {+ for (Type type :+ new Type[] {+ Types.ByteType.unsigned(),+ Types.ShortType.unsigned(),+ Types.IntegerType.unsigned(),+ Types.LongType.unsigned()+ }) {+ IllegalArgumentException e =+ assertThrows(IllegalArgumentException.class, () -> CONVERTER.fromGravitino(type));+ assertTrue(e.getMessage().contains(type.simpleString()), e.getMessage());+ }+ }++ @Test+ void testUnsupportedTypeMessageUsesTypeSyntax() {+ IllegalArgumentException e =+ assertThrows(+ IllegalArgumentException.class, () -> CONVERTER.fromGravitino(Types.FixedType.of(16)));+ assertTrue(e.getMessage().contains("fixed(16)"), e.getMessage());+ assertFalse(e.getMessage().contains("@"), e.getMessage());+ }}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 29f5e6bdb7..820b5a0455 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@@ -64,7 +64,11 @@ import org.junit.jupiter.api.BeforeAll;import org.junit.jupiter.api.Test;import org.junit.jupiter.api.TestInstance;import software.amazon.awssdk.services.glue.GlueClient;+import software.amazon.awssdk.services.glue.model.CreateDatabaseRequest;import software.amazon.awssdk.services.glue.model.CreateTableRequest;+import software.amazon.awssdk.services.glue.model.DatabaseInput;+import software.amazon.awssdk.services.glue.model.GetDatabaseRequest;+import software.amazon.awssdk.services.glue.model.GetPartitionRequest;import software.amazon.awssdk.services.glue.model.GetTableRequest;import software.amazon.awssdk.services.glue.model.StorageDescriptor;import software.amazon.awssdk.services.glue.model.TableInput;@@ -499,6 +503,101 @@ abstract class AbstractGlueCatalogIT {// Partition tests// -------------------------------------------------------------------------+ @Test+ void testAlterNativeTableKeepsFieldsGravitinoDoesNotModel() {+ String schema = newSchema();+ ops.createSchema(schemaIdent(schema), null, Collections.emptyMap());+ glueClient()+ .createTable(+ CreateTableRequest.builder()+ .databaseName(schema)+ .tableInput(+ TableInput.builder()+ .name("native_tbl")+ .owner("crawler")+ .tableType("EXTERNAL_TABLE")+ .parameters(Map.of("classification", "csv"))+ .storageDescriptor(+ StorageDescriptor.builder()+ .columns(+ software.amazon.awssdk.services.glue.model.Column.builder()+ .name("s")+ .type("struct<Outer:int>")+ .parameters(Map.of("stat", "1"))+ .build())+ .location("s3://gravitino-test-bucket/" + schema + "/native_tbl")+ .parameters(Map.of("recordCount", "10"))+ .build())+ .build())+ .build());++ ops.alterTable(tableIdent(schema, "native_tbl"), TableChange.updateComment("altered"));++ software.amazon.awssdk.services.glue.model.Table stored =+ glueClient()+ .getTable(GetTableRequest.builder().databaseName(schema).name("native_tbl").build())+ .table();+ assertEquals("altered", stored.description());+ assertEquals("crawler", stored.owner());+ assertEquals("csv", stored.parameters().get("classification"));+ assertEquals("10", stored.storageDescriptor().parameters().get("recordCount"));+ assertEquals("struct<Outer:int>", stored.storageDescriptor().columns().get(0).type());+ assertEquals("1", stored.storageDescriptor().columns().get(0).parameters().get("stat"));+ }++ @Test+ void testAlterSchemaKeepsNativeLocationUri() {+ String schema = newSchema();+ String location = "s3://gravitino-test-bucket/" + schema;+ glueClient()+ .createDatabase(+ CreateDatabaseRequest.builder()+ .databaseInput(DatabaseInput.builder().name(schema).locationUri(location).build())+ .build());++ ops.alterSchema(schemaIdent(schema), SchemaChange.setProperty("k", "v"));++ assertEquals(+ location,+ glueClient()+ .getDatabase(GetDatabaseRequest.builder().name(schema).build())+ .database()+ .locationUri());+ assertEquals(+ location, ops.loadSchema(schemaIdent(schema)).properties().get(GlueConstants.LOCATION));+ }++ @Test+ void testAddPartitionIsEscapedAndReadable() {+ String schema = newSchema();+ ops.createSchema(schemaIdent(schema), null, Collections.emptyMap());+ SupportsPartitions sp = createPartitionedTable(schema, "ptbl");++ Partition added = sp.addPartition(identityPartition("2025/12/31"));++ assertEquals("dt=2025%2F12%2F31", added.name());+ assertTrue(Arrays.asList(sp.listPartitionNames()).contains("dt=2025%2F12%2F31"));+ assertEquals("dt=2025%2F12%2F31", sp.getPartition("dt=2025%2F12%2F31").name());++ software.amazon.awssdk.services.glue.model.Partition stored =+ glueClient()+ .getPartition(+ GetPartitionRequest.builder()+ .databaseName(schema)+ .tableName("ptbl")+ .partitionValues("2025/12/31")+ .build())+ .partition();+ assertEquals(+ "s3://gravitino-test-bucket/" + schema + "/ptbl/dt=2025%2F12%2F31",+ stored.storageDescriptor().location());+ assertEquals(+ HiveStorageConstants.LAZY_SIMPLE_SERDE_CLASS,+ stored.storageDescriptor().serdeInfo().serializationLibrary());++ assertTrue(sp.dropPartition("dt=2025%2F12%2F31"));+ }+@Testvoid testAddPartition() {String schema = newSchema();diff --git a/clients/client-python/gravitino/api/policy/policy_content.py b/clients/client-python/gravitino/api/policy/policy_content.pyindex 467a5d9574..267f6c731d 100644--- a/clients/client-python/gravitino/api/policy/policy_content.py+++ b/clients/client-python/gravitino/api/policy/policy_content.py@@ -1,3 +1,4 @@+# pylint: disable=too-many-lines# 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@@ -15,8 +16,6 @@# specific language governing permissions and limitations# under the License.-# pylint: disable=too-many-lines-from __future__ import annotationsimport rediff --git a/core/src/main/java/org/apache/gravitino/catalog/TableOperationDispatcher.java b/core/src/main/java/org/apache/gravitino/catalog/TableOperationDispatcher.javaindex b63df43356..0a4e49e96e 100644--- a/core/src/main/java/org/apache/gravitino/catalog/TableOperationDispatcher.java+++ b/core/src/main/java/org/apache/gravitino/catalog/TableOperationDispatcher.java@@ -400,8 +400,10 @@ public class TableOperationDispatcher extends OperationDispatcher implements TabupdateColumnsIfNecessary(alteredTable,tableEntity,- alignNameChangesWithStoredColumns(- catalogResult.columnNameChanges, tableEntity.columns()));+ alignNameChangesWithCatalogColumns(+ alignNameChangesWithStoredColumns(+ catalogResult.columnNameChanges, tableEntity.columns()),+ alteredTable.columns()));return TableEntity.builder().withId(tableEntity.id())@@ -776,9 +778,7 @@ public class TableOperationDispatcher extends OperationDispatcher implements Tab.withCreateTime(Instant.now()).build();List<ColumnEntity> columnEntityList =- IntStream.range(0, columns.length)- .mapToObj(i -> ColumnEntity.toColumnEntity(columns[i], i, idGenerator.nextId(), audit))- .collect(Collectors.toList());+ toColumnEntities(withCatalogColumnNames(columns, table.columns()), audit);TableEntity tableEntity =TableEntity.builder()@@ -813,6 +813,39 @@ public class TableOperationDispatcher extends OperationDispatcher implements Tab.withHiddenProperties(catalogResult.hiddenProperties);}+ /**+ * Returns the requested columns under the names the catalog reports for them. A catalog may store+ * a name in another case than requested, and the stored entity has to carry the name the catalog+ * reports on later loads. A column whose name differs by more than case keeps the requested name.+ *+ * @param columns the columns of the create request+ * @param catalogColumns the columns the catalog reports for the created table+ * @return the columns to store+ */+ @VisibleForTesting+ static Column[] withCatalogColumnNames(Column[] columns, Column[] catalogColumns) {+ if (columns.length != catalogColumns.length) {+ return columns;+ }++ Column[] named = columns.clone();+ for (int i = 0; i < columns.length; i++) {+ Column column = columns[i];+ String catalogName = catalogColumns[i].name();+ if (!catalogName.equals(column.name()) && catalogName.equalsIgnoreCase(column.name())) {+ named[i] =+ Column.of(+ catalogName,+ column.dataType(),+ column.comment(),+ column.nullable(),+ column.autoIncrement(),+ column.defaultValue());+ }+ }+ return named;+ }+private TableCatalogResult snapshotTable(CatalogManager.CatalogWrapper catalog, Table table, boolean managed) throws Exception {Table snapshot = catalog.detachConnectorResult(table);@@ -1038,6 +1071,47 @@ public class TableOperationDispatcher extends OperationDispatcher implements Tabreturn aligned;}+ /**+ * Points column renames at the names the catalog reports.+ *+ * <p>A catalog may store a name in another case than requested, such as Glue for Hive-format+ * tables. A rename target the catalog does not report is mapped to the catalog column it matches+ * when exactly one unclaimed column does, so the rename keeps the column id instead of being+ * stored as a drop plus an add.+ *+ * @param nameChanges the renames and drops keyed by the stored column names+ * @param catalogColumns the columns the catalog reports, or {@code null} if it reports none+ * @return the renames and drops with targets the catalog reports+ */+ @VisibleForTesting+ static Map<String, String> alignNameChangesWithCatalogColumns(+ Map<String, String> nameChanges, @Nullable Column[] catalogColumns) {+ if (nameChanges.isEmpty() || catalogColumns == null) {+ return nameChanges;+ }++ Set<String> catalogNames =+ Arrays.stream(catalogColumns).map(Column::name).collect(Collectors.toSet());+ Set<String> claimed = new HashSet<>(nameChanges.values());+ Map<String, String> aligned = new HashMap<>();+ for (Map.Entry<String, String> change : nameChanges.entrySet()) {+ String target = change.getValue();+ if (target != null && !catalogNames.contains(target)) {+ List<String> matches =+ catalogNames.stream()+ .filter(target::equalsIgnoreCase)+ .filter(name -> !claimed.contains(name))+ .collect(Collectors.toList());+ if (matches.size() == 1) {+ target = matches.get(0);+ claimed.add(target);+ }+ }+ aligned.put(change.getKey(), target);+ }+ return aligned;+ }+/** Returns the original name of the pre-existing column currently called {@code name}. */@Nullableprivate static String originalColumnNamed(diff --git a/core/src/test/java/org/apache/gravitino/catalog/TestTableOperationDispatcher.java b/core/src/test/java/org/apache/gravitino/catalog/TestTableOperationDispatcher.javaindex d153edf8f9..eca298fd11 100644--- a/core/src/test/java/org/apache/gravitino/catalog/TestTableOperationDispatcher.java+++ b/core/src/test/java/org/apache/gravitino/catalog/TestTableOperationDispatcher.java@@ -2059,6 +2059,68 @@ public class TestTableOperationDispatcher extends TestOperationDispatcher {TableOperationDispatcher.alignNameChangesWithStoredColumns(exactAndAmbiguous, ambiguous));}+ @Test+ public void testAlignNameChangesWithCatalogColumns() {+ Column[] folded = {catalogColumn("customerid"), catalogColumn("cust"), catalogColumn("amount")};++ // A rename target that differs in case from a catalog column is mapped to it.+ Map<String, String> changes = new HashMap<>();+ changes.put("cust_id", "CustomerId");+ changes.put("cust2", "CUST");+ changes.put("amount2", "amount");+ changes.put("dropped", null);+ Map<String, String> expected = new HashMap<>();+ expected.put("cust_id", "customerid");+ expected.put("cust2", "cust");+ expected.put("amount2", "amount");+ expected.put("dropped", null);+ Assertions.assertEquals(+ expected, TableOperationDispatcher.alignNameChangesWithCatalogColumns(changes, folded));++ // A column is not taken from a rename that names it exactly, and several matches are ambiguous.+ Map<String, String> claimed = ImmutableMap.of("a", "x", "b", "X");+ Assertions.assertEquals(+ claimed,+ TableOperationDispatcher.alignNameChangesWithCatalogColumns(+ claimed, new Column[] {catalogColumn("x")}));+ Map<String, String> ambiguous = ImmutableMap.of("a", "Xy");+ Assertions.assertEquals(+ ambiguous,+ TableOperationDispatcher.alignNameChangesWithCatalogColumns(+ ambiguous, new Column[] {catalogColumn("xy"), catalogColumn("XY")}));++ // A catalog that reports no columns leaves the changes as they are.+ Assertions.assertEquals(+ ambiguous, TableOperationDispatcher.alignNameChangesWithCatalogColumns(ambiguous, null));+ }++ @Test+ public void testWithCatalogColumnNames() {+ Column requested = Column.of("UserId", Types.LongType.get(), "the user", false, false, null);+ Column other = catalogColumn("Other");++ Column[] named =+ TableOperationDispatcher.withCatalogColumnNames(+ new Column[] {requested, other},+ new Column[] {catalogColumn("userid"), catalogColumn("different")});+ Assertions.assertEquals("userid", named[0].name());+ Assertions.assertEquals(Types.LongType.get(), named[0].dataType());+ Assertions.assertEquals("the user", named[0].comment());+ Assertions.assertFalse(named[0].nullable());+ Assertions.assertEquals("Other", named[1].name());++ // Columns that do not line up with the request keep the requested names.+ Column[] mismatched = {requested};+ Assertions.assertArrayEquals(+ mismatched,+ TableOperationDispatcher.withCatalogColumnNames(+ mismatched, new Column[] {catalogColumn("userid"), catalogColumn("extra")}));+ }++ private static Column catalogColumn(String name) {+ return Column.of(name, Types.IntegerType.get());+ }+private static ColumnEntity storedColumn(String name) {return ColumnEntity.builder().withId(RandomIdGenerator.INSTANCE.nextId())diff --git a/docs/aws-glue-catalog.md b/docs/aws-glue-catalog.mdindex 2cce47a845..8f13dce87b 100644--- a/docs/aws-glue-catalog.md+++ b/docs/aws-glue-catalog.md@@ -18,7 +18,11 @@ Apache Gravitino uses [AWS Glue Data Catalog](https://aws.amazon.com/glue/) as a* Gravitino uses the AWS SDK v2 to communicate with Glue.:::note-The Glue catalog is case-insensitive for schema and table names. AWS Glue folds database and table names to lowercase on storage.+The Glue catalog is case-insensitive for schema and table names, which AWS Glue stores in lowercase. Column names of Hive-format tables are stored in lowercase as well. Iceberg tables keep the case of their column names in the Iceberg metadata, while the copy of the columns in Glue is lowercase, so some engines may not read mixed-case Iceberg columns.+:::++:::caution+Each Glue Data Catalog (one AWS account, region and `aws-glue-catalog-id`) must be managed by only one Gravitino catalog, in the same way that two Hive catalogs must not share one Hive Metastore. Two Gravitino catalogs pointing to the same Glue Data Catalog are not supported.:::## Catalog@@ -35,19 +39,19 @@ The Glue catalog supports creating, updating, and deleting databases and tablesBesides the [common catalog properties](./gravitino-server-config.md#catalog-properties-configuration), the Glue catalog has the following properties:-| Property Name | Description | Default Value | Required | Immutable |-|----------------------------------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|---------------|----------|-----------|-| `aws-region` | AWS region for the Glue Data Catalog, as a known AWS region identifier in lower case (e.g. `us-east-1`). | (none) | Yes | Yes |-| `aws-glue-catalog-id` | The 12-digit AWS account ID that owns the Glue catalog. When omitted, defaults to the caller's AWS account ID. | (none) | No | Yes |-| `aws-access-key-id` | AWS access key ID for static credential authentication. When omitted, the default credential chain is used. Temporary keys (prefix `ASIA`) are not supported, because they need a session token. | (none) | No | No |-| `aws-secret-access-key` | AWS secret access key paired with `aws-access-key-id`. When omitted, the default credential chain is used. | (none) | No | No |-| `aws-glue-endpoint` | Custom Glue endpoint URL for VPC endpoints or LocalStack testing (e.g. `http://localhost:4566`). Must be an `http` or `https` URL. | (none) | No | No |-| `aws-glue-api-call-timeout-ms` | Upper bound in milliseconds for one Glue API call made by the catalog, including all retries. The AWS clients used for Iceberg tables only take `aws-glue-api-call-attempt-timeout-ms`. | `30000` | No | No |-| `aws-glue-api-call-attempt-timeout-ms` | Upper bound in milliseconds for a single attempt of a Glue API call. Also used as the connection and socket timeout of the AWS clients (Glue and S3) used for Iceberg tables. | `10000` | No | No |-| `aws-glue-max-attempts` | Maximum number of attempts of a Glue API call made by the catalog, including the first one. Retries apply to throttling and transient failures. The AWS clients used for Iceberg tables keep the AWS SDK default. | `4` | No | No |-| `warehouse` | Base storage path used as the warehouse when no explicit `location` is specified at table creation time and the Glue database declares no `LocationUri` (e.g. `s3://my-bucket/warehouse`). Table location is then derived as `warehouse/database/table`. Must be a URI with a scheme. Iceberg tables need an `s3://`, `s3a://` or `s3n://` location. | (none) | Yes | No |-| `default-table-format` | Default format for tables created via Gravitino's `createTable()` API. Accepted values: `iceberg`, `hive`. | `hive` | No | No |-| `table-format-filter` | Comma-separated list of table formats exposed by the catalog. Accepted values: `all`, `hive`, `iceberg`, `delta`, `parquet`. Tables of other formats are absent from list, load, alter and drop, and cannot be created through the catalog. | `all` | No | No |+| Property Name | Description | Default Value | Required | Immutable |+|----------------------------------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|---------------|----------|-----------|+| `aws-region` | AWS region for the Glue Data Catalog, as a known AWS region identifier in lower case (e.g. `us-east-1`). | (none) | Yes | Yes |+| `aws-glue-catalog-id` | The 12-digit AWS account ID that owns the Glue catalog. When omitted, defaults to the caller's AWS account ID. | (none) | No | Yes |+| `aws-access-key-id` | AWS access key ID for static credential authentication. When omitted, the default credential chain is used. Temporary keys (prefix `ASIA`) are not supported, because they need a session token. | (none) | No | No |+| `aws-secret-access-key` | AWS secret access key paired with `aws-access-key-id`. When omitted, the default credential chain is used. | (none) | No | No |+| `aws-glue-endpoint` | Custom Glue endpoint URL for VPC endpoints or LocalStack testing (e.g. `http://localhost:4566`). Must be an `http` or `https` URL. | (none) | No | No |+| `aws-glue-api-call-timeout-ms` | Upper bound in milliseconds for one Glue API call made by the catalog, including all retries. The AWS clients used for Iceberg tables only take `aws-glue-api-call-attempt-timeout-ms`. | `30000` | No | No |+| `aws-glue-api-call-attempt-timeout-ms` | Upper bound in milliseconds for a single attempt of a Glue API call. Also used as the connection and socket timeout of the AWS clients (Glue and S3) used for Iceberg tables. | `10000` | No | No |+| `aws-glue-max-attempts` | Maximum number of attempts of a Glue API call made by the catalog, including the first one. Retries apply to throttling and transient failures. The AWS clients used for Iceberg tables keep the AWS SDK default. | `4` | No | No |+| `warehouse` | Base storage path used as the warehouse when no explicit `location` is specified at table creation time and the Glue database declares no `LocationUri` (e.g. `s3://my-bucket/warehouse`). Table location is then derived as `warehouse/database/table`. Must be a URI with a scheme. Iceberg tables need an `s3://`, `s3a://` or `s3n://` location. | (none) | Yes | No |+| `default-table-format` | Default format for tables created via Gravitino's `createTable()` API. Accepted values: `iceberg`, `hive`. | `hive` | No | No |+| `table-format-filter` | Comma-separated list of table formats exposed by the catalog. Accepted values: `all`, `hive`, `iceberg`, `delta`, `parquet`. A table's format is its `table-format` property; a table without it is `iceberg` when it has `table_type=ICEBERG`, and `hive` otherwise, including Delta tables registered by other engines. Tables of other formats are absent from list, load, alter and drop, and cannot be created through the catalog. | `all` | No | No |:::note**Authentication priority**: Static credentials (`aws-access-key-id` + `aws-secret-access-key`) take precedence over the default credential chain (environment variables, instance profile, container credentials).@@ -101,6 +105,7 @@ The supported partitioning strategies depend on the table format::::cautionThe `fieldName` specified in the partitioning attribute must be the name of a column defined in the table.+For Hive-format tables, the partition columns must be the last columns of the table, in partitioning order, and must have a primitive type.:::### Table Sort Orders and Distributions@@ -110,6 +115,7 @@ Although Gravitino supports several distribution strategies, AWS Glue inherently:::cautionThe `fieldName` specified in the `distribution` and `sortOrders` attribute must be the name of a column defined in the table.+Only plain column references are supported, the number of buckets must be at least 1, and a sort order must use the default null ordering of its direction (`nulls_first` for ascending, `nulls_last` for descending), because Glue stores only the sort direction.:::### Table Column Types@@ -126,7 +132,9 @@ The following table lists the data types mapped from the Glue catalog to Graviti| `bigint` | `long` || `float` | `float` || `double` | `double` |+| `double precision` | `double` || `decimal` | `decimal` |+| `decimal` (no args) | `decimal(10,0)` || `string` | `string` || `char` | `char` || `varchar` | `varchar` |@@ -144,6 +152,10 @@ The following table lists the data types mapped from the Glue catalog to GravitiData types not listed above map to Gravitino **[External Type](./tables-and-views.md#external-type)**, which represents an unresolvable data type from the Glue catalog.:::+:::caution+Unsigned integer types are not supported, because Glue and Hive have signed integers only. Struct field names must not contain `:`, `,`, `<` or `>`, because Glue type strings cannot quote them.+:::+### Table PropertiesThe following table lists predefined properties for Glue tables. Additional key-value properties pass through to the underlying Glue database.@@ -154,18 +166,18 @@ The following table lists predefined properties for Glue tables. Additional key-**Immutable**: Fields that cannot be modified once set.:::-| Property Name | Description | Default Value | Required | Reserved | Immutable |-|---------------------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|--------------------------------------------------------------|----------|----------|-----------|-| `location` | The location for table storage, such as `s3://bucket/prefix/test_table`. When not specified, it is derived from the `LocationUri` of the Glue database as `database-location/table`, falling back to `warehouse/database/table` when the database declares no location. | (derived from database location or warehouse) | No | No | No |-| `format` | The table file format (`parquet`, `orc`, `textfile`, etc.). When set, `input-format`, `output-format`, and `serde-lib` are derived automatically. Used primarily when creating Hive-format tables via Trino. | (none) | No | No | Yes |-| `input-format` | The input format class for the table, such as `org.apache.hadoop.hive.ql.io.orc.OrcInputFormat`. | `org.apache.hadoop.mapred.TextInputFormat` | No | No | Yes |-| `output-format` | The output format class for the table, such as `org.apache.hadoop.hive.ql.io.orc.OrcOutputFormat`. | `org.apache.hadoop.hive.ql.io.HiveIgnoreKeyTextOutputFormat` | No | No | Yes |-| `serde-lib` | The serde library class for the table, such as `org.apache.hadoop.hive.ql.io.orc.OrcSerde`. | `org.apache.hadoop.hive.serde2.lazy.LazySimpleSerDe` | No | No | Yes |-| `serde-name` | The name of the serde. | (none) | No | No | No |-| `serde.parameter.` | The prefix of the serde parameter, such as `"serde.parameter.orc.create.index" = "true"`, indicating ORC serde lib to create row indexes. | (none) | No | No | No |-| `table-format` | Table format stored in Glue `Table.parameters()`. Use `ICEBERG` to create an Iceberg table. Common values: `ICEBERG`, `HIVE`. | (none) | No | No | No |-| `metadata_location` | Iceberg table metadata file location stored in Glue `Table.parameters()`. When set during `createTable()`, registers an existing Iceberg table rather than creating a new one. | (none) | No | No | No |-| `comment` | Used to store a table comment. | (none) | No | Yes | No |+| Property Name | Description | Default Value | Required | Reserved | Immutable |+|---------------------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|--------------------------------------------------------------|----------|----------|-----------|+| `location` | The location for table storage, such as `s3://bucket/prefix/test_table`. When not specified, it is derived from the `LocationUri` of the Glue database as `database-location/table`, falling back to `warehouse/database/table` when the database declares no location. | (derived from database location or warehouse) | No | No | No |+| `format` | The table file format (`parquet`, `orc`, `textfile`, etc.). When set, `input-format`, `output-format`, and `serde-lib` are derived automatically, and any of them that is also set must match. Without `format`, set all three classes or none; with none, the table is a text table. | (none) | No | No | Yes |+| `input-format` | The input format class for the table, such as `org.apache.hadoop.hive.ql.io.orc.OrcInputFormat`. | `org.apache.hadoop.mapred.TextInputFormat` | No | No | Yes |+| `output-format` | The output format class for the table, such as `org.apache.hadoop.hive.ql.io.orc.OrcOutputFormat`. | `org.apache.hadoop.hive.ql.io.HiveIgnoreKeyTextOutputFormat` | No | No | Yes |+| `serde-lib` | The serde library class for the table, such as `org.apache.hadoop.hive.ql.io.orc.OrcSerde`. | `org.apache.hadoop.hive.serde2.lazy.LazySimpleSerDe` | No | No | Yes |+| `serde-name` | The name of the serde. | (none) | No | No | No |+| `serde.parameter.` | The prefix of the serde parameter, such as `"serde.parameter.orc.create.index" = "true"`, indicating ORC serde lib to create row indexes. | (none) | No | No | No |+| `table-format` | Table format stored in Glue `Table.parameters()`. Use `ICEBERG` to create an Iceberg table. Common values: `ICEBERG`, `HIVE`. | (none) | No | No | Yes |+| `metadata_location` | Iceberg table metadata file location stored in Glue `Table.parameters()`. When set during `createTable()`, registers an existing Iceberg table rather than creating a new one. | (none) | No | No | No |+| `comment` | Used to store a table comment. | (none) | No | Yes | No |:::noteAll entries in the Glue `Table.parameters()` pass through Gravitino's API layer intact. This passthrough ensures `table_type=ICEBERG`, `metadata_location=s3://...`, `spark.sql.sources.provider=delta`, and any other format indicators survive Gravitino's metadata proxy layer.@@ -201,6 +213,10 @@ Iceberg-format table rename is supported.| `Change Column Position` | `Update the position of a column` || `Change Column Comment` | `Update the column comment` |+:::note+For Hive-format tables, changes to nested struct fields are not supported; change the whole column instead. Partition columns only support comment changes. Bucket and sort columns can be renamed but not deleted.+:::+##### Alter partitionThe Glue catalog supports partition operations via `SupportsPartitions` for Hive-format identity-partitioned tables:@@ -214,6 +230,8 @@ The Glue catalog supports partition operations via `SupportsPartitions` for HiveOnly `IdentityPartition` is supported because the Glue partition model is Hive-style key=value.:::+Partition names escape special characters in values as Hive does, for example `/` becomes `%2F`. A new partition takes its columns, formats and SerDe from the table, and its location is the table location followed by the partition name.+## Iceberg TablesThe Glue catalog supports creating and managing Iceberg-format tables through the Apache Iceberg SDK's `GlueCatalog`. When an Iceberg table is created, Gravitino writes the `metadata.json` file to S3 and registers the table in Glue with the correct `metadata_location` parameter, making it usable by Trino (Lakehouse connector), Spark, and other Iceberg-native query engines.