World's most powerful open data catalog for building a high-performance, geo-distributed and federated metadata lake.
Java ai-catalogdata-catalogdatalakefederated-querylakehousemetadatametalakemodel-catalogopendatacatalogskycomputingstratosphere
[#14564] fix(catalog-glue): Fix Iceberg table handling (#14565)
Yuhuibfa88fcbb41f
diff --git a/catalogs/catalog-common/src/main/java/org/apache/gravitino/catalog/glue/GlueConstants.java b/catalogs/catalog-common/src/main/java/org/apache/gravitino/catalog/glue/GlueConstants.javaindex a1a3ea62e7..f940f97b22 100644--- a/catalogs/catalog-common/src/main/java/org/apache/gravitino/catalog/glue/GlueConstants.java+++ b/catalogs/catalog-common/src/main/java/org/apache/gravitino/catalog/glue/GlueConstants.java@@ -53,8 +53,7 @@ public final class GlueConstants {/*** Upper bound in milliseconds for one Glue API call made by the catalog, including all retries- * (optional). The AWS clients used for Iceberg tables only take the attempt timeout. Defaults to- * {@link #DEFAULT_AWS_GLUE_API_CALL_TIMEOUT_MS}.+ * (optional). Defaults to {@link #DEFAULT_AWS_GLUE_API_CALL_TIMEOUT_MS}.*/public static final String AWS_GLUE_API_CALL_TIMEOUT_MS = "aws-glue-api-call-timeout-ms";@@ -63,8 +62,8 @@ public final class GlueConstants {/*** Upper bound in milliseconds for a single attempt of a Glue API call (optional). Also used as- * the HTTP connection and socket timeout of the AWS clients (Glue and S3) used for Iceberg- * tables. Defaults to {@link #DEFAULT_AWS_GLUE_API_CALL_ATTEMPT_TIMEOUT_MS}.+ * the HTTP connection and socket timeout of the S3 client used for Iceberg tables. Defaults to+ * {@link #DEFAULT_AWS_GLUE_API_CALL_ATTEMPT_TIMEOUT_MS}.*/public static final String AWS_GLUE_API_CALL_ATTEMPT_TIMEOUT_MS ="aws-glue-api-call-attempt-timeout-ms";@@ -74,8 +73,8 @@ public final class GlueConstants {/*** Maximum number of attempts of a Glue API call made by the catalog, including the first one- * (optional). Retries apply to throttling and transient failures. The AWS clients used for- * Iceberg tables keep the AWS SDK default. Defaults to {@link #DEFAULT_AWS_GLUE_MAX_ATTEMPTS}.+ * (optional). Retries apply to throttling and transient failures. Defaults to {@link+ * #DEFAULT_AWS_GLUE_MAX_ATTEMPTS}.*/public static final String AWS_GLUE_MAX_ATTEMPTS = "aws-glue-max-attempts";@@ -114,15 +113,18 @@ public final class GlueConstants {// -------------------------------------------------------------------------/**- * Glue table format parameter key stored in {@code Table.parameters()}. Common values: {@code- * ICEBERG}, {@code HIVE}, {@code DELTA}, {@code PARQUET} (uppercase, as stored by Glue). Used- * internally to determine the table format when reading Glue tables.+ * Table property that chooses the format of a table at create: {@code HIVE} or {@code ICEBERG}.+ * It is not stored; a loaded table reports it from its {@link #TABLE_TYPE_PARAM} parameter, and+ * it cannot be changed.*/public static final String TABLE_FORMAT = "table-format";- /** Table-format value indicating an Iceberg table stored in Glue {@code Table.parameters()}. */+ /** Value of {@link #TABLE_FORMAT} for an Iceberg table. */public static final String TABLE_FORMAT_ICEBERG = "ICEBERG";+ /** Value of {@link #TABLE_FORMAT} for a Hive-format table. */+ public static final String TABLE_FORMAT_HIVE = "HIVE";+/*** Table file format (lowercase, e.g. "parquet", "orc", "textfile") used when creating Hive-format* tables via Trino. Maps to input-format/output-format/serde-lib.@@ -132,6 +134,13 @@ public final class GlueConstants {/** Iceberg table metadata location stored in Glue {@code Table.parameters()}. */public static final String METADATA_LOCATION = "metadata_location";+ /**+ * Key of the {@code Table.parameters()} entry, set to {@code true}, that marks an Iceberg table+ * registered through Gravitino from an existing metadata file. Such a table shares its files with+ * the table it was registered from, so Gravitino changes only its Glue parameters.+ */+ public static final String REGISTERED_ICEBERG_TABLE_PARAM = "gravitino.iceberg.registered";+/*** Key of the {@code table_type} entry in {@code Table.parameters()} that identifies the table* format (e.g., {@code "ICEBERG"}).diff --git a/catalogs/catalog-glue/build.gradle.kts b/catalogs/catalog-glue/build.gradle.ktsindex 0e9a9c2ace..825cae2793 100644--- a/catalogs/catalog-glue/build.gradle.kts+++ b/catalogs/catalog-glue/build.gradle.kts@@ -29,6 +29,7 @@ dependencies {compileOnly(project(":common"))compileOnly(project(":core"))+ compileOnly(libs.aws.dynamodb)compileOnly(libs.lombok)implementation(project(":catalogs:catalog-common")) {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 bed6d8eff4..abdaa86d05 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@@ -106,6 +106,17 @@ public class GlueCatalogOperations implements CatalogOperations, SupportsSchemasprivate static final Logger LOG = LoggerFactory.getLogger(GlueCatalogOperations.class);+ /**+ * Properties that identify the format of an Iceberg table, its metadata file and whether it was+ * registered; an alter cannot change them.+ */+ private static final Set<String> ICEBERG_RESERVED_KEYS =+ ImmutableSet.of(+ GlueConstants.TABLE_TYPE_PARAM,+ GlueConstants.TABLE_FORMAT,+ GlueConstants.METADATA_LOCATION,+ GlueConstants.REGISTERED_ICEBERG_TABLE_PARAM);+/** Table property keys that map to StorageDescriptor fields, not to Table.parameters(). */private static final Set<String> SD_TABLE_PROPERTY_KEYS =ImmutableSet.of(@@ -436,14 +447,20 @@ public class GlueCatalogOperations implements CatalogOperations, SupportsSchemasGlueTable 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- // Table to obtain the accurate partition spec and sort order.+ // The Iceberg metadata is the only source of the columns, partitioning and sort order of an+ // Iceberg table; the Glue columns are a Hive-style copy. A table whose metadata cannot be+ // read is reported as an error rather than with the Glue copy.if (GlueIcebergTableHelper.isIcebergTable(rawGlueTable)) {try {GlueIcebergTableHelper.loadTable(icebergGlueCatalog, dbName, ident.name(), table);- } catch (Exception e) {- LOG.warn("Failed to load Iceberg metadata for table {}.{}", dbName, ident.name(), e);+ } catch (RuntimeException e) {+ String metadataLocation = rawGlueTable.parameters().get(GlueConstants.METADATA_LOCATION);+ throw GlueExceptionConverter.toIcebergException(+ e,+ metadataLocation == null+ ? "Iceberg metadata of table " + ident.name()+ : String.format(+ "Iceberg metadata %s of table %s", metadataLocation, ident.name()));}}@@ -472,14 +489,28 @@ public class GlueCatalogOperations implements CatalogOperations, SupportsSchemasString dbName = schemaName(ident.namespace());Map<String, String> props = properties != null ? properties : Collections.emptyMap();- String tableFormat = props.getOrDefault(GlueConstants.TABLE_FORMAT, defaultTableFormat);- boolean isIceberg = GlueConstants.ICEBERG_TABLE_TYPE_VALUE.equalsIgnoreCase(tableFormat);- String normalizedFormat =- isIceberg- ? GlueConstants.ICEBERG_TABLE_TYPE_VALUE.toLowerCase(Locale.ROOT)- : props- .getOrDefault(GlueConstants.TABLE_FORMAT, GlueConstants.DEFAULT_TABLE_FORMAT_VALUE)- .toLowerCase(Locale.ROOT);+ String tableFormat =+ props.getOrDefault(+ GlueConstants.TABLE_FORMAT,+ defaultTableFormat != null+ ? defaultTableFormat+ : GlueConstants.DEFAULT_TABLE_FORMAT_VALUE);+ Preconditions.checkArgument(+ GlueConstants.TABLE_FORMAT_HIVE.equalsIgnoreCase(tableFormat)+ || GlueConstants.TABLE_FORMAT_ICEBERG.equalsIgnoreCase(tableFormat),+ "Unsupported value '%s' of '%s': use %s or %s",+ tableFormat,+ GlueConstants.TABLE_FORMAT,+ GlueConstants.TABLE_FORMAT_HIVE,+ GlueConstants.TABLE_FORMAT_ICEBERG);+ boolean isIceberg = GlueConstants.TABLE_FORMAT_ICEBERG.equalsIgnoreCase(tableFormat);+ String normalizedFormat = tableFormat.toLowerCase(Locale.ROOT);+ // table-format only chooses how the table is created; the format of a stored table is its+ // table_type, so table-format is not stored.+ if (props.containsKey(GlueConstants.TABLE_FORMAT)) {+ props = new HashMap<>(props);+ props.remove(GlueConstants.TABLE_FORMAT);+ }// A table of an excluded format would be created but stay invisible through this catalog.Preconditions.checkArgument(isFormatVisible(normalizedFormat),@@ -508,38 +539,33 @@ public class GlueCatalogOperations implements CatalogOperations, SupportsSchemasvalidateHiveSortOrders(sortOrders);}- // For Iceberg tables, stamp table_type=ICEBERG into the Glue parameters so that- // isIcebergTable() detection works consistently for future alterTable/listTable calls.- Map<String, String> finalProps = props;- if (isIceberg) {- finalProps = new HashMap<>(props);- finalProps.put(GlueConstants.TABLE_TYPE_PARAM, GlueConstants.ICEBERG_TABLE_TYPE_VALUE);- // Resolve location from warehouse if not explicitly provided.- if (!finalProps.containsKey(GlueConstants.LOCATION)) {- finalProps.put(GlueConstants.LOCATION, resolveTableLocation(null, dbName, ident.name()));- }+ if (isIceberg && props.containsKey(GlueConstants.METADATA_LOCATION)) {+ return registerIcebergTable(+ ident, dbName, comment, columns, props, partitions, distribution, sortOrders);}if (isIceberg) {- boolean registerMode = props.containsKey(GlueConstants.METADATA_LOCATION);- if (!registerMode) {- // Use Iceberg SDK to create the table (writes metadata.json to S3 and registers in Glue).- try {- GlueIcebergTableHelper.createTable(- icebergGlueCatalog,- dbName,- ident.name(),- columns,- comment,- finalProps,- partitions,- sortOrders);- } catch (RuntimeException e) {- throw GlueExceptionConverter.toIcebergException(e, "table " + ident.name());- }- LOG.info("Created Iceberg table {}.{} via Iceberg SDK", dbName, ident.name());- return loadTable(ident);+ Map<String, String> icebergProps = new HashMap<>(props);+ // Resolve location from warehouse if not explicitly provided.+ if (!icebergProps.containsKey(GlueConstants.LOCATION)) {+ icebergProps.put(GlueConstants.LOCATION, resolveTableLocation(null, dbName, ident.name()));+ }+ // Use Iceberg SDK to create the table (writes metadata.json to S3 and registers in Glue).+ try {+ GlueIcebergTableHelper.createTable(+ icebergGlueCatalog,+ dbName,+ ident.name(),+ columns,+ comment,+ icebergProps,+ partitions,+ sortOrders);+ } catch (RuntimeException e) {+ throw GlueExceptionConverter.toIcebergException(e, "table " + ident.name());}+ LOG.info("Created Iceberg table {}.{} via Iceberg SDK", dbName, ident.name());+ return loadTable(ident);}TableInput input =@@ -547,18 +573,17 @@ public class GlueCatalogOperations implements CatalogOperations, SupportsSchemasdbName,ident.name(),comment,- isIceberg ? columns : toLowerCaseColumns(columns),- finalProps,+ toLowerCaseColumns(columns),+ props,partitions,distribution,- sortOrders,- isIceberg);+ sortOrders);CreateTableRequest.Builder req =CreateTableRequest.builder().databaseName(dbName).tableInput(input);executeCreateTable(dbName, ident, req);- LOG.info("Created {} table {}.{}", isIceberg ? "Iceberg" : "Glue", dbName, ident.name());+ LOG.info("Created Glue table {}.{}", dbName, ident.name());return loadAfterWrite(ident, dbName, input);}@@ -738,20 +763,11 @@ public class GlueCatalogOperations implements CatalogOperations, SupportsSchemas}TableInput input =- TableInput.builder()- .name(raw.name())+ tableInputFrom(raw).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(@@ -933,17 +949,15 @@ public class GlueCatalogOperations implements CatalogOperations, SupportsSchemasprivate GlueTable alterIcebergTable(NameIdentifier ident, String dbName, Table rawGlueTable, TableChange... changes) {- // Register-mode: has METADATA_LOCATION but was not created via the Gravitino Iceberg SDK- // (i.e., TABLE_TYPE_PARAM is absent). Fall back to the native Glue SDK update path.- boolean hasMetadataLocation =- rawGlueTable.hasParameters()- && rawGlueTable.parameters().containsKey(GlueConstants.METADATA_LOCATION);- boolean isSdkManaged =- rawGlueTable.hasParameters()- && GlueConstants.ICEBERG_TABLE_TYPE_VALUE.equalsIgnoreCase(- rawGlueTable.parameters().get(GlueConstants.TABLE_TYPE_PARAM));- if (hasMetadataLocation && !isSdkManaged) {- return alterRegisterModeIcebergTable(ident, dbName, rawGlueTable, changes);+ for (TableChange change : changes) {+ if (change instanceof TableChange.SetProperty) {+ checkIcebergTableParameterKey(((TableChange.SetProperty) change).getProperty());+ } else if (change instanceof TableChange.RemoveProperty) {+ checkIcebergTableParameterKey(((TableChange.RemoveProperty) change).getProperty());+ }+ }+ if (isRegisteredIcebergTable(rawGlueTable)) {+ return alterRegisteredIcebergTable(ident, dbName, rawGlueTable, changes);}TableIdentifier finalId;try {@@ -964,37 +978,218 @@ public class GlueCatalogOperations implements CatalogOperations, SupportsSchemasreturn loadTable(finalIdent);}- private GlueTable alterRegisterModeIcebergTable(+ /**+ * Registers an existing Iceberg table from its metadata file. Iceberg reads the file before the+ * Glue table is created, and takes the Glue columns and location from it. The Glue table is then+ * marked as registered, so that later changes through Gravitino touch only its Glue parameters+ * and never write into the files it shares with the table it was registered from.+ */+ private GlueTable registerIcebergTable(+ NameIdentifier ident,+ String dbName,+ String comment,+ Column[] columns,+ Map<String, String> props,+ Transform[] partitions,+ Distribution distribution,+ SortOrder[] sortOrders) {+ String metadataLocation = props.get(GlueConstants.METADATA_LOCATION);+ Preconditions.checkArgument(+ StringUtils.isNotBlank(metadataLocation),+ "Property %s cannot be blank",+ GlueConstants.METADATA_LOCATION);+ Preconditions.checkArgument(+ !props.containsKey(GlueConstants.LOCATION),+ "A registered Iceberg table takes its location from %s; do not set %s",+ GlueConstants.METADATA_LOCATION,+ GlueConstants.LOCATION);+ Preconditions.checkArgument(+ (partitions == null || partitions.length == 0)+ && (sortOrders == null || sortOrders.length == 0)+ && (distribution == null || distribution.strategy() == Strategy.NONE),+ "A registered Iceberg table takes its partitioning and sort order from %s; do not set"+ + " them",+ GlueConstants.METADATA_LOCATION);++ TableIdentifier tableId = TableIdentifier.of(dbName, ident.name());+ org.apache.iceberg.Table registered;+ try {+ registered = icebergGlueCatalog.registerTable(tableId, metadataLocation);+ } catch (RuntimeException e) {+ throw GlueExceptionConverter.toIcebergException(+ e, String.format("registering table %s from %s", ident.name(), metadataLocation));+ }++ // Iceberg writes only its own Glue parameters during registration, so the marker takes a second+ // update. A process stopped between the two leaves an unmarked table, which has to be marked by+ // hand.+ try {+ checkRegisteredColumns(columns, registered.schema(), metadataLocation);+ checkRegisteredProperties(props, registered.properties(), metadataLocation);+ Table raw = getRawTable(dbName, ident.name());+ Map<String, String> params = new HashMap<>(raw.parameters());+ props.forEach(params::putIfAbsent);+ params.put(GlueConstants.REGISTERED_ICEBERG_TABLE_PARAM, "true");+ TableInput input =+ tableInputFrom(raw)+ .description(comment != null ? comment : raw.description())+ .parameters(params)+ .build();+ executeUpdateTable(+ ident,+ UpdateTableRequest.builder()+ .databaseName(dbName)+ .tableInput(input)+ .versionId(raw.versionId()));+ } catch (RuntimeException e) {+ // Without the marker the table would be altered as its own, so do not leave it behind.+ // Dropping the Glue entry keeps the metadata and data files.+ try {+ icebergGlueCatalog.dropTable(tableId, false);+ } catch (RuntimeException dropFailure) {+ e.addSuppressed(dropFailure);+ }+ throw e;+ }+ LOG.info("Registered Iceberg table {}.{} from {}", dbName, ident.name(), metadataLocation);+ return loadTable(ident);+ }++ /** Request columns of a registration are optional, and must match the metadata file if given. */+ private static void checkRegisteredColumns(+ Column[] columns, org.apache.iceberg.Schema schema, String metadataLocation) {+ if (columns == null || columns.length == 0) {+ return;+ }+ List<String> requested =+ Arrays.stream(columns)+ .map(c -> c.name().toLowerCase(Locale.ROOT))+ .collect(Collectors.toList());+ List<String> stored =+ schema.columns().stream()+ .map(f -> f.name().toLowerCase(Locale.ROOT))+ .collect(Collectors.toList());+ Preconditions.checkArgument(+ requested.equals(stored),+ "Columns %s differ from the columns %s in %s; pass an empty column list to take them from"+ + " the metadata file",+ requested,+ stored,+ metadataLocation);+ }++ /**+ * A load reports the properties of the metadata file, so a request cannot give them new values.+ */+ private static void checkRegisteredProperties(+ Map<String, String> props, Map<String, String> metadataProps, String metadataLocation) {+ props.forEach(+ (key, value) ->+ Preconditions.checkArgument(+ !metadataProps.containsKey(key) || metadataProps.get(key).equals(value),+ "Property %s is set to '%s' in %s and cannot be given another value",+ key,+ metadataProps.get(key),+ metadataLocation));+ }++ /**+ * Alters an Iceberg table registered through Gravitino. Only its Glue parameters change; the+ * metadata file and the data files belong to the table it was registered from. Properties of the+ * metadata file cannot be changed: Iceberg engines read them from the file, and so does a load.+ */+ private GlueTable alterRegisteredIcebergTable(NameIdentifier ident, String dbName, Table rawGlueTable, TableChange... changes) {Map<String, String> newParams = new HashMap<>(rawGlueTable.parameters());+ Set<String> changedProperties = new HashSet<>();for (TableChange change : changes) {if (change instanceof TableChange.SetProperty) {TableChange.SetProperty sp = (TableChange.SetProperty) change;+ checkIcebergTableParameterKey(sp.getProperty());newParams.put(sp.getProperty(), sp.getValue());+ changedProperties.add(sp.getProperty());} else if (change instanceof TableChange.RemoveProperty) {- newParams.remove(((TableChange.RemoveProperty) change).getProperty());+ String property = ((TableChange.RemoveProperty) change).getProperty();+ checkIcebergTableParameterKey(property);+ newParams.remove(property);+ changedProperties.add(property);} else {throw new IllegalArgumentException(- "Unsupported change for register-mode Iceberg table: "- + change.getClass().getSimpleName());+ String.format(+ "Iceberg table %s was registered from an existing metadata file, so only its"+ + " properties can be changed; %s is not supported",+ ident.name(), change.getClass().getSimpleName()));}}- TableInput input =- TableInput.builder()- .name(rawGlueTable.name())- .description(rawGlueTable.description())- .tableType(rawGlueTable.tableType())- .parameters(newParams)- .storageDescriptor(rawGlueTable.storageDescriptor())- .build();+ Map<String, String> metadataProps;+ try {+ metadataProps =+ icebergGlueCatalog.loadTable(TableIdentifier.of(dbName, ident.name())).properties();+ } catch (RuntimeException e) {+ throw GlueExceptionConverter.toIcebergException(e, "altering table " + ident.name());+ }+ for (String property : changedProperties) {+ Preconditions.checkArgument(+ !metadataProps.containsKey(property),+ "Property %s of registered Iceberg table %s comes from its metadata file and cannot be"+ + " changed",+ property,+ ident.name());+ }- executeUpdateTable(ident, UpdateTableRequest.builder().databaseName(dbName).tableInput(input));- LOG.info(- "Altered register-mode Iceberg table {}.{} properties via Glue SDK", dbName, ident.name());+ TableInput input = tableInputFrom(rawGlueTable).parameters(newParams).build();+ executeUpdateTable(+ ident,+ UpdateTableRequest.builder()+ .databaseName(dbName)+ .tableInput(input)+ .versionId(rawGlueTable.versionId()));+ LOG.info("Altered registered Iceberg table {}.{} properties", dbName, ident.name());return loadTable(ident);}+ private static void checkIcebergTableParameterKey(String property) {+ Preconditions.checkArgument(+ !ICEBERG_RESERVED_KEYS.contains(property),+ "Property %s of an Iceberg table cannot be changed",+ property);+ }++ private static boolean isRegisteredIcebergTable(Table table) {+ return table.hasParameters()+ && "true"+ .equalsIgnoreCase(table.parameters().get(GlueConstants.REGISTERED_ICEBERG_TABLE_PARAM));+ }++ /** Starts a Glue table definition from the table as Glue holds it, so no field is lost. */+ private static TableInput.Builder tableInputFrom(Table raw) {+ return TableInput.builder()+ .name(raw.name())+ .description(raw.description())+ .owner(raw.owner())+ .lastAccessTime(raw.lastAccessTime())+ .lastAnalyzedTime(raw.lastAnalyzedTime())+ .retention(raw.retention())+ .storageDescriptor(raw.storageDescriptor())+ .partitionKeys(raw.partitionKeys())+ .viewOriginalText(raw.viewOriginalText())+ .viewExpandedText(raw.viewExpandedText())+ .tableType(raw.tableType())+ .parameters(raw.parameters())+ .targetTable(raw.targetTable());+ }++ private Table getRawTable(String dbName, String tableName) {+ GetTableRequest.Builder req = GetTableRequest.builder().databaseName(dbName).name(tableName);+ applyCatalogId(catalogId, req::catalogId);+ try {+ return callGlue(() -> glueClient.getTable(req.build()), "table " + tableName).table();+ } catch (GlueException e) {+ throw GlueExceptionConverter.toTableException(e, "table " + tableName);+ }+ }+@Overridepublic boolean dropTable(NameIdentifier ident) {String dbName = schemaName(ident.namespace());@@ -1031,6 +1226,47 @@ public class GlueCatalogOperations implements CatalogOperations, SupportsSchemas}}+ /**+ * Drops an Iceberg table and deletes the data and metadata files its metadata references. Hive+ * tables in Glue are external, and registered Iceberg tables share their files with the table+ * they were registered from, so neither can be purged.+ */+ @Override+ public boolean purgeTable(NameIdentifier ident) throws UnsupportedOperationException {+ String dbName = schemaName(ident.namespace());+ Table existing;+ try {+ existing = getRawTable(dbName, ident.name());+ } catch (NoSuchTableException e) {+ return false;+ }+ rejectIfView(existing, ident, dbName);+ if (!matchesFormatFilter(existing)) {+ return false;+ }+ if (!GlueIcebergTableHelper.isIcebergTable(existing)) {+ throw new UnsupportedOperationException(+ String.format(+ "Cannot purge table %s: Glue Hive-format tables are external, so only drop is"+ + " supported and the files stay in place",+ ident.name()));+ }+ if (isRegisteredIcebergTable(existing)) {+ throw new UnsupportedOperationException(+ String.format(+ "Cannot purge table %s: it was registered from an existing metadata file and shares"+ + " its files with that table; drop it instead",+ ident.name()));+ }+ try {+ boolean purged = icebergGlueCatalog.dropTable(TableIdentifier.of(dbName, ident.name()), true);+ LOG.info("Purged Iceberg table {}.{}", dbName, ident.name());+ return purged;+ } catch (RuntimeException e) {+ throw GlueExceptionConverter.toIcebergException(e, "purging table " + ident.name());+ }+ }+private static String schemaName(Namespace namespace) {String[] levels = namespace.levels();Preconditions.checkArgument(@@ -1078,11 +1314,6 @@ public class GlueCatalogOperations implements CatalogOperations, SupportsSchemas.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<>();@@ -1195,17 +1426,17 @@ public class GlueCatalogOperations implements CatalogOperations, SupportsSchemas// NOTE: parameter type is the Glue SDK Table, not GlueTable (our domain class).// The Glue SDK's Column model is also referenced by FQN throughout this class because its// simple name conflicts with the imported org.apache.gravitino.rel.Column.+ /**+ * A table is an Iceberg table when its native {@code table_type} parameter says so, and a+ * Hive-format table otherwise, the same classification every other operation uses.+ */private boolean matchesFormatFilter(Table table) {if (tableFormatFilter == null) return true;- String fmt = table.hasParameters() ? table.parameters().get(GlueConstants.TABLE_FORMAT) : null;- // Fall back to checking native Glue table_type for tables created without the Gravitino- // table-format property (e.g. created via default-table-format config or external tooling).- if (fmt == null && GlueIcebergTableHelper.isIcebergTable(table)) {- fmt = GlueConstants.ICEBERG_TABLE_TYPE_VALUE;- }- String normalized =- fmt != null ? fmt.toLowerCase(Locale.ROOT) : GlueConstants.DEFAULT_TABLE_FORMAT_VALUE;- return isFormatVisible(normalized);+ String format =+ GlueIcebergTableHelper.isIcebergTable(table)+ ? GlueConstants.TABLE_FORMAT_ICEBERG+ : GlueConstants.TABLE_FORMAT_HIVE;+ return isFormatVisible(format.toLowerCase(Locale.ROOT));}private boolean isFormatVisible(String normalizedFormat) {@@ -1255,8 +1486,7 @@ public class GlueCatalogOperations implements CatalogOperations, SupportsSchemasMap<String, String> properties,Transform[] partitions,Distribution distribution,- SortOrder[] sortOrders,- boolean isIceberg) {+ SortOrder[] sortOrders) {int partCount = partitions.length;Preconditions.checkArgument(@@ -1293,18 +1523,16 @@ public class GlueCatalogOperations implements CatalogOperations, SupportsSchemasString 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();- }+ 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 =@@ -1322,7 +1550,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))+ .map(column -> column.toLowerCase(Locale.ROOT)).collect(Collectors.toList());}@@ -1331,9 +1559,8 @@ public class GlueCatalogOperations implements CatalogOperations, SupportsSchemasfor (SortOrder so : sortOrders) {if (so.expression() instanceof NamedReference.FieldReference) {String colName =- storedColumnName(- String.join(".", ((NamedReference.FieldReference) so.expression()).fieldName()),- isIceberg);+ String.join(".", ((NamedReference.FieldReference) so.expression()).fieldName())+ .toLowerCase(Locale.ROOT);int order = so.direction() == SortDirection.ASCENDING ? 1 : 0;glueSortCols.add(Order.builder().column(colName).sortOrder(order).build());}@@ -1352,20 +1579,14 @@ public class GlueCatalogOperations implements CatalogOperations, SupportsSchemas.sortColumns(glueSortCols).build();- TableInput.Builder builder =- TableInput.builder()- .name(name)- .description(comment)- .tableType(GlueConstants.EXTERNAL_TABLE_TYPE)- .parameters(tableParams)- .storageDescriptor(sd);-- // AWS Glue rejects partitionKeys for Iceberg-format tables.- if (!isIceberg) {- builder.partitionKeys(gluePartCols);- }-- return builder.build();+ return TableInput.builder()+ .name(name)+ .description(comment)+ .tableType(GlueConstants.EXTERNAL_TABLE_TYPE)+ .parameters(tableParams)+ .storageDescriptor(sd)+ .partitionKeys(gluePartCols)+ .build();}private software.amazon.awssdk.services.glue.model.Column toGlueColumn(Column col) {diff --git a/catalogs/catalog-glue/src/main/java/org/apache/gravitino/catalog/glue/GlueCatalogPropertiesMetadata.java b/catalogs/catalog-glue/src/main/java/org/apache/gravitino/catalog/glue/GlueCatalogPropertiesMetadata.javaindex cc964daa32..bfe85eb93a 100644--- a/catalogs/catalog-glue/src/main/java/org/apache/gravitino/catalog/glue/GlueCatalogPropertiesMetadata.java+++ b/catalogs/catalog-glue/src/main/java/org/apache/gravitino/catalog/glue/GlueCatalogPropertiesMetadata.java@@ -105,13 +105,16 @@ public class GlueCatalogPropertiesMetadata extends BaseCatalogPropertiesMetadatapositiveLongEntry(AWS_GLUE_API_CALL_TIMEOUT_MS,"Upper bound in milliseconds for one Glue API call made by the catalog,"- + " including retries. Not applied to Iceberg table I/O.",+ + " including retries. Also applied to the Glue calls of Iceberg tables, but"+ + " not to S3 I/O.",DEFAULT_AWS_GLUE_API_CALL_TIMEOUT_MS)).put(AWS_GLUE_API_CALL_ATTEMPT_TIMEOUT_MS,positiveLongEntry(AWS_GLUE_API_CALL_ATTEMPT_TIMEOUT_MS,- "Upper bound in milliseconds for a single attempt of a Glue API call.",+ "Upper bound in milliseconds for a single attempt of a Glue API call. Also used"+ + " as the connection and socket timeout of the S3 client used for Iceberg"+ + " tables.",DEFAULT_AWS_GLUE_API_CALL_ATTEMPT_TIMEOUT_MS)).put(AWS_GLUE_MAX_ATTEMPTS,@@ -119,7 +122,8 @@ public class GlueCatalogPropertiesMetadata extends BaseCatalogPropertiesMetadata.withName(AWS_GLUE_MAX_ATTEMPTS).withDescription("Maximum number of attempts of a Glue API call made by the catalog,"- + " including the first one. Not applied to Iceberg table I/O.")+ + " including the first one. Also applied to the Glue calls of Iceberg"+ + " tables, but not to S3 I/O.").withJavaType(Integer.class).withDefaultValue(DEFAULT_AWS_GLUE_MAX_ATTEMPTS).withDecoder(diff --git a/catalogs/catalog-glue/src/main/java/org/apache/gravitino/catalog/glue/GlueClientProvider.java b/catalogs/catalog-glue/src/main/java/org/apache/gravitino/catalog/glue/GlueClientProvider.javaindex b25e6b14c8..5eb60e43a6 100644--- a/catalogs/catalog-glue/src/main/java/org/apache/gravitino/catalog/glue/GlueClientProvider.java+++ b/catalogs/catalog-glue/src/main/java/org/apache/gravitino/catalog/glue/GlueClientProvider.java@@ -66,6 +66,17 @@ public final class GlueClientProvider {* credentials*/public static GlueClient buildClient(Map<String, String> config) {+ return buildClient(config, true);+ }++ /**+ * Builds a {@link GlueClient} from the given catalog configuration map.+ *+ * @param config Catalog configuration properties.+ * @param checkCredentials whether to check up front that credentials can be resolved+ * @return A configured and ready-to-use {@link GlueClient}.+ */+ static GlueClient buildClient(Map<String, String> config, boolean checkCredentials) {validateConfig(config);String region = config.get(GlueConstants.AWS_REGION);GlueClientBuilder builder = GlueClient.builder().region(Region.of(region));@@ -84,7 +95,9 @@ public final class GlueClientProvider {hasAwsStaticCredentials(accessKey, secretKey)? StaticCredentialsProvider.create(AwsBasicCredentials.create(accessKey, secretKey)): DefaultCredentialsProvider.builder().build();- validateCredentials(credentialsProvider);+ if (checkCredentials) {+ validateCredentials(credentialsProvider);+ }builder.credentialsProvider(credentialsProvider);// Bound every call so an endpoint that does not answer cannot hold a request thread for thediff --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 203e0b1db2..a62c4131f3 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@@ -36,6 +36,7 @@ import org.apache.iceberg.exceptions.CommitFailedException;import org.apache.iceberg.exceptions.CommitStateUnknownException;import org.apache.iceberg.exceptions.NoSuchNamespaceException;import software.amazon.awssdk.awscore.exception.AwsErrorDetails;+import software.amazon.awssdk.awscore.exception.AwsServiceException;import software.amazon.awssdk.core.exception.ApiCallAttemptTimeoutException;import software.amazon.awssdk.core.exception.ApiCallTimeoutException;import software.amazon.awssdk.core.exception.SdkClientException;@@ -50,6 +51,7 @@ import software.amazon.awssdk.services.glue.model.GlueException;import software.amazon.awssdk.services.glue.model.InvalidInputException;import software.amazon.awssdk.services.glue.model.ThrottlingException;import software.amazon.awssdk.services.glue.model.ValidationException;+import software.amazon.awssdk.services.s3.model.S3Exception;/** Converts AWS Glue SDK exceptions to Gravitino exceptions. */final class GlueExceptionConverter {@@ -341,10 +343,11 @@ final class GlueExceptionConverter {* and S3 errors either as its own exception types or wrapped around the AWS SDK exception, so the* cause chain is walked from the outside in and the first recognized type decides the result:* Iceberg not-found, already-exists, validation and forbidden errors map to the matching- * Gravitino types, a commit conflict maps to {@link OptimisticLockException}, and AWS SDK causes- * go through {@link #toGenericException}. A commit whose state is unknown is reported as such,- * because the change may have been applied. {@link GravitinoRuntimeException}, {@link- * IllegalArgumentException} and {@link UnsupportedOperationException} are returned as is.+ * Gravitino types, a commit conflict maps to {@link OptimisticLockException}, S3 failures map by+ * their HTTP status, and other AWS SDK causes go through {@link #toGenericException}. A commit+ * whose state is unknown is reported as such, because the change may have been applied. {@link+ * GravitinoRuntimeException}, {@link IllegalArgumentException} and {@link+ * UnsupportedOperationException} are returned as is.** @param e the failure raised by an Iceberg catalog call* @param context description of the operation context for error messages@@ -413,6 +416,23 @@ final class GlueExceptionConverter {// Not wrapped by Iceberg; it may be the table or its database.return new NotFoundException(e, "%s: %s", context, describe(t));}+ if (t instanceof S3Exception) {+ return toS3Exception((S3Exception) t, context, e);+ }+ if (t instanceof SdkClientException) {+ // The failing client may be the Glue or the S3 client of the Iceberg catalog.+ SdkClientException clientException = (SdkClientException) t;+ if (isCredentialFailure(clientException)) {+ return toCredentialException(clientException, context);+ }+ return new ConnectionFailedException(+ e,+ "Failed to reach AWS (Glue or S3) for %s: %s",+ context,+ StringUtils.defaultIfBlank(+ ExceptionMessages.usefulMessage(clientException),+ clientException.getClass().getSimpleName()));+ }if (t instanceof SdkException) {return toGenericException((SdkException) t, context, null);}@@ -420,6 +440,39 @@ final class GlueExceptionConverter {return new RuntimeException(context + ": " + describe(e), e);}+ /**+ * Converts an S3 failure met while reading or writing Iceberg metadata or data files. The status+ * decides the result, since S3 reports most failures under a few generic error codes.+ */+ private static RuntimeException toS3Exception(+ S3Exception s3Exception, String context, RuntimeException e) {+ String detail = awsErrorDetail(s3Exception);+ int status = s3Exception.statusCode();+ if (status == 403) {+ return new ForbiddenException(e, "S3 denied access for %s: %s", context, detail);+ }+ if (status == 404) {+ return new NotFoundException(e, "S3 object or bucket not found for %s: %s", context, detail);+ }+ if (status == 503 || s3Exception.isThrottlingException()) {+ return new ServiceUnavailableException(+ e, "S3 throttled the request for %s; the request can be retried: %s", context, detail);+ }+ if (status == 301) {+ return new IllegalArgumentException(+ String.format(+ "S3 redirected the request for %s; the bucket is likely in a different region than"+ + " '%s': %s",+ context, GlueConstants.AWS_REGION, detail),+ e);+ }+ if (status >= 400 && status < 500) {+ return new IllegalArgumentException(+ String.format("S3 rejected the request for %s: %s", context, detail), e);+ }+ return new RuntimeException(String.format("S3 error: %s: %s", context, detail), e);+ }+private static String regionMismatchMessage(GlueException e, @Nullable GlueClient client) {GlueServiceClientConfiguration conf =client == null ? null : client.serviceClientConfiguration();@@ -458,19 +511,19 @@ final class GlueExceptionConverter {}/**- * Renders the AWS-side detail of a Glue exception. AWS names the failing action and the resource- * there, which is what the caller needs to act on; the error code is prefixed so the failure can- * be classified at a glance. Long messages, which quote the offending request value, are- * shortened in the middle so the violated constraint at the end stays visible.+ * Renders the AWS-side detail of a Glue or S3 exception. AWS names the failing action and the+ * resource there, which is what the caller needs to act on; the error code is prefixed so the+ * failure can be classified at a glance. Long messages, which quote the offending request value,+ * are shortened in the middle so the violated constraint at the end stays visible.*- * @param e the Glue exception to describe+ * @param e the AWS service exception to describe* @return the AWS error code and message, or a best-effort description when they are unavailable*/- private static String awsErrorDetail(GlueException e) {+ private static String awsErrorDetail(AwsServiceException e) {return StringUtils.abbreviateMiddle(rawAwsErrorDetail(e), " ... ", MAX_AWS_MESSAGE_LENGTH);}- private static String rawAwsErrorDetail(GlueException e) {+ private static String rawAwsErrorDetail(AwsServiceException e) {AwsErrorDetails details = e.awsErrorDetails();if (details != null) {String code = details.errorCode();diff --git a/catalogs/catalog-glue/src/main/java/org/apache/gravitino/catalog/glue/GlueIcebergAwsClientFactory.java b/catalogs/catalog-glue/src/main/java/org/apache/gravitino/catalog/glue/GlueIcebergAwsClientFactory.javanew file mode 100644index 0000000000..bbd20eba14--- /dev/null+++ b/catalogs/catalog-glue/src/main/java/org/apache/gravitino/catalog/glue/GlueIcebergAwsClientFactory.java@@ -0,0 +1,89 @@+/*+ * Licensed to the Apache Software Foundation (ASF) under one+ * or more contributor license agreements. See the NOTICE file+ * distributed with this work for additional information+ * regarding copyright ownership. The ASF licenses this file+ * to you under the Apache License, Version 2.0 (the+ * "License"); you may not use this file except in compliance+ * with the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing,+ * software distributed under the License is distributed on an+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY+ * KIND, either express or implied. See the License for the+ * specific language governing permissions and limitations+ * under the License.+ */+package org.apache.gravitino.catalog.glue;++import java.util.HashMap;+import java.util.Map;+import org.apache.iceberg.aws.AwsClientFactories;+import org.apache.iceberg.aws.AwsClientFactory;+import org.apache.iceberg.aws.AwsProperties;+import org.apache.iceberg.util.PropertyUtil;+import software.amazon.awssdk.services.dynamodb.DynamoDbClient;+import software.amazon.awssdk.services.glue.GlueClient;+import software.amazon.awssdk.services.kms.KmsClient;+import software.amazon.awssdk.services.s3.S3AsyncClient;+import software.amazon.awssdk.services.s3.S3Client;++/**+ * AWS client factory of the Iceberg Glue catalog used for Iceberg tables. The Glue client is built+ * the same way as the catalog's own Glue client, so the call timeout, attempt timeout and maximum+ * attempts of the catalog also apply to Iceberg tables. The other clients come from the Iceberg+ * default factory.+ *+ * <p>The catalog properties the Glue client needs are passed under {@link #GLUE_CONFIG_PREFIX}.+ */+public class GlueIcebergAwsClientFactory implements AwsClientFactory {++ /** Prefix of the Iceberg catalog properties that carry the Gravitino Glue catalog properties. */+ static final String GLUE_CONFIG_PREFIX = "gravitino.glue.";++ private static final long serialVersionUID = 1L;++ private HashMap<String, String> glueConfig;++ private AwsClientFactory delegate;++ /** Creates a factory; Iceberg calls {@link #initialize(Map)} before using it. */+ public GlueIcebergAwsClientFactory() {}++ @Override+ public void initialize(Map<String, String> properties) {+ this.glueConfig =+ new HashMap<>(PropertyUtil.propertiesWithPrefix(properties, GLUE_CONFIG_PREFIX));+ Map<String, String> delegateProperties = new HashMap<>(properties);+ delegateProperties.remove(AwsProperties.CLIENT_FACTORY);+ this.delegate = AwsClientFactories.from(delegateProperties);+ }++ @Override+ public GlueClient glue() {+ // The catalog's own Glue client has already checked that credentials can be resolved.+ return GlueClientProvider.buildClient(glueConfig, false);+ }++ @Override+ public S3Client s3() {+ return delegate.s3();+ }++ @Override+ public S3AsyncClient s3Async() {+ return delegate.s3Async();+ }++ @Override+ public KmsClient kms() {+ return delegate.kms();+ }++ @Override+ public DynamoDbClient dynamo() {+ return delegate.dynamo();+ }+}diff --git a/catalogs/catalog-glue/src/main/java/org/apache/gravitino/catalog/glue/GlueIcebergTableHelper.java b/catalogs/catalog-glue/src/main/java/org/apache/gravitino/catalog/glue/GlueIcebergTableHelper.javaindex 17deff4297..46e990fdad 100644--- a/catalogs/catalog-glue/src/main/java/org/apache/gravitino/catalog/glue/GlueIcebergTableHelper.java+++ b/catalogs/catalog-glue/src/main/java/org/apache/gravitino/catalog/glue/GlueIcebergTableHelper.java@@ -28,10 +28,13 @@ import static org.apache.gravitino.rel.types.Types.ExternalType;import static org.apache.gravitino.rel.types.Types.FixedCharType;import static org.apache.gravitino.rel.types.Types.FixedType;import static org.apache.gravitino.rel.types.Types.FloatType;+import static org.apache.gravitino.rel.types.Types.GeographyType;+import static org.apache.gravitino.rel.types.Types.GeometryType;import static org.apache.gravitino.rel.types.Types.IntegerType;import static org.apache.gravitino.rel.types.Types.ListType;import static org.apache.gravitino.rel.types.Types.LongType;import static org.apache.gravitino.rel.types.Types.MapType;+import static org.apache.gravitino.rel.types.Types.NullType;import static org.apache.gravitino.rel.types.Types.ShortType;import static org.apache.gravitino.rel.types.Types.StringType;import static org.apache.gravitino.rel.types.Types.StructType;@@ -39,6 +42,7 @@ import static org.apache.gravitino.rel.types.Types.TimeType;import static org.apache.gravitino.rel.types.Types.TimestampType;import static org.apache.gravitino.rel.types.Types.UUIDType;import static org.apache.gravitino.rel.types.Types.VarCharType;+import static org.apache.gravitino.rel.types.Types.VariantType;import com.google.common.annotations.VisibleForTesting;import com.google.common.base.Preconditions;@@ -46,12 +50,14 @@ import com.google.common.collect.ImmutableSet;import java.net.URI;import java.net.URISyntaxException;import java.util.ArrayList;+import java.util.Arrays;import java.util.HashMap;import java.util.List;import java.util.Locale;import java.util.Map;+import java.util.Objects;import java.util.Set;-import java.util.regex.Pattern;+import java.util.stream.Collectors;import javax.annotation.Nullable;import org.apache.commons.lang3.StringUtils;import org.apache.gravitino.catalog.lakehouse.iceberg.IcebergConstants;@@ -74,8 +80,10 @@ import org.apache.iceberg.NullOrder;import org.apache.iceberg.PartitionSpec;import org.apache.iceberg.Schema;import org.apache.iceberg.Table;+import org.apache.iceberg.Transaction;import org.apache.iceberg.UpdateProperties;import org.apache.iceberg.UpdateSchema;+import org.apache.iceberg.aws.AwsProperties;import org.apache.iceberg.aws.glue.GlueCatalog;import org.apache.iceberg.catalog.Catalog;import org.apache.iceberg.catalog.TableIdentifier;@@ -83,6 +91,9 @@ import org.apache.iceberg.exceptions.AlreadyExistsException;import org.apache.iceberg.exceptions.ValidationException;import org.apache.iceberg.expressions.Expressions;import org.apache.iceberg.expressions.UnboundTerm;+import org.apache.iceberg.transforms.PartitionSpecVisitor;+import org.apache.iceberg.transforms.SortOrderVisitor;+import org.apache.iceberg.types.EdgeAlgorithm;import org.apache.iceberg.types.Types;import org.slf4j.Logger;import org.slf4j.LoggerFactory;@@ -104,6 +115,10 @@ final class GlueIcebergTableHelper {private static final String DOT = ".";+ private static final int MICROSECOND_PRECISION = 6;++ private static final int NANOSECOND_PRECISION = 9;+private static final Set<String> S3_SCHEMES = ImmutableSet.of("s3", "s3a", "s3n");// Iceberg GlueCatalog properties (not defined in IcebergConstants).@@ -122,6 +137,25 @@ final class GlueIcebergTableHelper {private static final String CLIENT_CREDENTIALS_PROVIDER_SECRET_ACCESS_KEY ="client.credentials-provider.secret-access-key";+ /** Catalog properties the Glue client of the Iceberg catalog is built from. */+ private static final Set<String> GLUE_CLIENT_CONFIG_KEYS =+ ImmutableSet.of(+ GlueConstants.AWS_REGION,+ GlueConstants.AWS_ACCESS_KEY_ID,+ GlueConstants.AWS_SECRET_ACCESS_KEY,+ GlueConstants.AWS_GLUE_ENDPOINT,+ GlueConstants.AWS_GLUE_API_CALL_TIMEOUT_MS,+ GlueConstants.AWS_GLUE_API_CALL_ATTEMPT_TIMEOUT_MS,+ GlueConstants.AWS_GLUE_MAX_ATTEMPTS);++ /** Table properties that Glue holds about the table, which Iceberg properties cannot shadow. */+ private static final Set<String> GLUE_OWNED_PROPS =+ ImmutableSet.of(+ GlueConstants.TABLE_TYPE_PARAM,+ GlueConstants.TABLE_FORMAT,+ GlueConstants.METADATA_LOCATION,+ GlueConstants.REGISTERED_ICEBERG_TABLE_PARAM);+private static final Set<String> EXCLUDED_TABLE_PROPS =Set.of(GlueConstants.LOCATION,@@ -130,9 +164,6 @@ final class GlueIcebergTableHelper {GlueConstants.OUTPUT_FORMAT,GlueConstants.SERDE_LIB);- // Iceberg 1.10+ uses "bucket[n]" / "truncate[w]" format for Transform.toString().- private static final Pattern TRANSFORM_PARAM_PATTERN = Pattern.compile(".*\\[(\\d+)\\]");-private GlueIcebergTableHelper() {}/**@@ -219,8 +250,18 @@ final class GlueIcebergTableHelper {icebergProps.put(GLUE_ENDPOINT, endpoint);}- // The Iceberg AWS clients take no total call timeout, so bound each connection and read by- // the per-attempt timeout of the catalog's own Glue client.+ // The Glue client is built like the catalog's own, with its call timeout and retries.+ icebergProps.put(AwsProperties.CLIENT_FACTORY, GlueIcebergAwsClientFactory.class.getName());+ GLUE_CLIENT_CONFIG_KEYS.forEach(+ key -> {+ String value = config.get(key);+ if (value != null) {+ icebergProps.put(GlueIcebergAwsClientFactory.GLUE_CONFIG_PREFIX + key, value);+ }+ });++ // The Iceberg S3 client takes no total call timeout, so bound each connection and read by the+ // per-attempt timeout of the Glue client.String attemptTimeoutMs = String.valueOf(GlueClientProvider.apiCallAttemptTimeoutMs(config));icebergProps.put(HTTP_CLIENT_TYPE, "apache");icebergProps.put(HTTP_CLIENT_APACHE_CONNECTION_TIMEOUT_MS, attemptTimeoutMs);@@ -246,9 +287,17 @@ final class GlueIcebergTableHelper {}// Merge Iceberg table properties (stored in metadata.json) into the Gravitino properties.- // Iceberg properties take precedence over Glue parameters for overlapping keys.+ // Iceberg properties take precedence over Glue parameters for overlapping keys, except for the+ // ones Glue holds about the table itself, such as its format and metadata file.Map<String, String> mergedProps = new HashMap<>(table.properties());- mergedProps.putAll(icebergTable.properties());+ icebergTable+ .properties()+ .forEach(+ (key, value) -> {+ if (!GLUE_OWNED_PROPS.contains(key)) {+ mergedProps.put(key, value);+ }+ });table.setProperties(mergedProps);// Overwrite Glue's Hive-style column types with the accurate types from the Iceberg schema.@@ -279,12 +328,13 @@ final class GlueIcebergTableHelper {/*** Converts an Iceberg type to the equivalent Gravitino type.*- * <p>TIME and TIMESTAMP types are always returned with microsecond (6) precision, matching- * Iceberg's internal representation.+ * <p>TIME and TIMESTAMP types are returned with microsecond (6) precision and the nanosecond+ * timestamp types with precision 9, as the Iceberg catalog reports them.*/// TODO: the Iceberg-to-Gravitino conversions in this class (type mapping, partition spec,- // sort order, etc.) duplicate logic in catalog-lakehouse-iceberg. Consider extracting them- // to a shared layer (e.g. catalog-common) so both catalogs can reuse the code.+ // sort order, etc.) duplicate logic in catalog-lakehouse-iceberg and must give the same results.+ // Consider extracting them to a shared layer (e.g. catalog-common) so both catalogs can reuse+ // the code.// The parameter uses FQN because org.apache.iceberg.types.Type and// org.apache.gravitino.rel.types.Type share the same simple name.static Type fromIcebergType(org.apache.iceberg.types.Type icebergType) {@@ -308,12 +358,28 @@ final class GlueIcebergTableHelper {case DATE:return DateType.get();case TIME:- return TimeType.of(6);+ return TimeType.of(MICROSECOND_PRECISION);case TIMESTAMP:Types.TimestampType ts = (Types.TimestampType) icebergType;return ts.shouldAdjustToUTC()- ? TimestampType.withTimeZone(6)- : TimestampType.withoutTimeZone(6);+ ? TimestampType.withTimeZone(MICROSECOND_PRECISION)+ : TimestampType.withoutTimeZone(MICROSECOND_PRECISION);+ case TIMESTAMP_NANO:+ Types.TimestampNanoType tsNano = (Types.TimestampNanoType) icebergType;+ return tsNano.shouldAdjustToUTC()+ ? TimestampType.withTimeZone(NANOSECOND_PRECISION)+ : TimestampType.withoutTimeZone(NANOSECOND_PRECISION);+ case VARIANT:+ return VariantType.get();+ case UNKNOWN:+ // Iceberg v3 unknown is the null-only placeholder type.+ return NullType.get();+ case GEOMETRY:+ return GeometryType.of(((Types.GeometryType) icebergType).crs());+ case GEOGRAPHY:+ Types.GeographyType geography = (Types.GeographyType) icebergType;+ // EdgeAlgorithm.toString() is the lower-case spec name, which GeographyType requires.+ return GeographyType.of(geography.crs(), geography.algorithm().toString());case DECIMAL:Types.DecimalType decimal = (Types.DecimalType) icebergType;return DecimalType.of(decimal.precision(), decimal.scale());@@ -401,11 +467,6 @@ final class GlueIcebergTableHelper {tableProps.put("write.format.default", format.toLowerCase(Locale.ROOT));}- String tableFormat = properties.get(GlueConstants.TABLE_FORMAT);- if (tableFormat != null) {- tableProps.put(GlueConstants.TABLE_FORMAT, tableFormat);- }-TableIdentifier tableId = TableIdentifier.of(dbName, tableName);LOG.info("Creating Iceberg table {} at location {} via Iceberg SDK", tableId, location);@@ -433,9 +494,9 @@ final class GlueIcebergTableHelper {* TableChange.SetProperty}, and {@link TableChange.RemoveProperty}. A rename is an exclusive* operation and cannot be combined with other changes.*- * <p><b>Note:</b> Schema changes and property changes are committed in two separate transactions.- * If the schema commit succeeds but the property commit fails, the table is left in a partially- * altered state. This is a known limitation of the current Iceberg SDK integration.+ * <p>Schema and property changes are committed in one Iceberg transaction. Column changes that+ * Iceberg cannot apply, such as auto-increment or default values, are refused before anything is+ * staged.** @param icebergCatalog the Iceberg Glue catalog* @param dbName the Glue database name@@ -460,12 +521,11 @@ final class GlueIcebergTableHelper {}}- Table table = icebergCatalog.loadTable(TableIdentifier.of(dbName, tableName));-boolean hasSchemaChange = false;boolean hasPropChange = false;for (TableChange change : changes) {if (change instanceof TableChange.ColumnChange) {+ checkColumnChange((TableChange.ColumnChange) change);hasSchemaChange = true;} else if (change instanceof TableChange.SetProperty|| change instanceof TableChange.RemoveProperty) {@@ -476,17 +536,25 @@ final class GlueIcebergTableHelper {}}+ Table table = icebergCatalog.loadTable(TableIdentifier.of(dbName, tableName));+ // Schema and property changes are staged in one transaction, so a request is applied as a+ // whole or not at all.+ Transaction transaction = table.newTransaction();+if (hasSchemaChange) {- UpdateSchema update = table.updateSchema();+ UpdateSchema update = transaction.updateSchema();for (TableChange change : changes) {if (change instanceof TableChange.AddColumn) {TableChange.AddColumn add = (TableChange.AddColumn) change;- Preconditions.checkArgument(- add.fieldName().length == 1, "Nested column additions are not supported");- update.addColumn(add.fieldName()[0], toIcebergType(add.getDataType()), add.getComment());+ String name = add.fieldName()[0];+ update.addColumn(name, toIcebergType(add.getDataType()), add.getComment());if (!add.isNullable()) {- update.requireColumn(add.fieldName()[0]);+ update.requireColumn(name);}+ moveColumn(update, name, add.getPosition());+ } else if (change instanceof TableChange.UpdateColumnPosition) {+ TableChange.UpdateColumnPosition move = (TableChange.UpdateColumnPosition) change;+ moveColumn(update, move.fieldName()[0], move.getPosition());} else if (change instanceof TableChange.DeleteColumn) {TableChange.DeleteColumn del = (TableChange.DeleteColumn) change;Preconditions.checkArgument(@@ -533,11 +601,10 @@ final class GlueIcebergTableHelper {}}update.commit();- LOG.info("Altered Iceberg table {}.{} schema via Iceberg SDK", dbName, tableName);}if (hasPropChange) {- UpdateProperties update = table.updateProperties();+ UpdateProperties update = transaction.updateProperties();for (TableChange change : changes) {if (change instanceof TableChange.SetProperty) {TableChange.SetProperty sp = (TableChange.SetProperty) change;@@ -548,11 +615,62 @@ final class GlueIcebergTableHelper {}}update.commit();- LOG.info("Altered Iceberg table {}.{} properties via Iceberg SDK", dbName, tableName);}++ transaction.commitTransaction();+ LOG.info("Altered Iceberg table {}.{} via Iceberg SDK", dbName, tableName);return TableIdentifier.of(dbName, tableName);}+ /**+ * Refuses column changes that Iceberg cannot apply through this catalog, before anything is+ * staged, so that no change of a request is skipped without an error.+ */+ private static void checkColumnChange(TableChange.ColumnChange change) {+ String[] fieldName = change.fieldName();+ Preconditions.checkArgument(+ fieldName != null && fieldName.length > 0, "Column change field name cannot be empty");+ String name = String.join(DOT, fieldName);+ Preconditions.checkArgument(+ fieldName.length == 1,+ "Iceberg tables in Glue do not support changes to nested field %s",+ name);+ if (change instanceof TableChange.AddColumn) {+ TableChange.AddColumn add = (TableChange.AddColumn) change;+ Preconditions.checkArgument(+ !add.isAutoIncrement(), "Iceberg does not support auto-increment columns: %s", name);+ Preconditions.checkArgument(+ add.getDefaultValue() == null+ || Column.DEFAULT_VALUE_NOT_SET.equals(add.getDefaultValue()),+ "Iceberg tables in Glue do not support column default values: %s",+ name);+ return;+ }+ Preconditions.checkArgument(+ change instanceof TableChange.UpdateColumnPosition+ || change instanceof TableChange.DeleteColumn+ || change instanceof TableChange.RenameColumn+ || change instanceof TableChange.UpdateColumnType+ || change instanceof TableChange.UpdateColumnComment+ || change instanceof TableChange.UpdateColumnNullability,+ "Iceberg tables in Glue do not support %s on column %s",+ change.getClass().getSimpleName(),+ name);+ }++ /**+ * Moves a column to the requested position. The default position applies only to added columns,+ * which Iceberg already places at the end.+ */+ private static void moveColumn(+ UpdateSchema update, String name, TableChange.ColumnPosition position) {+ if (position instanceof TableChange.First) {+ update.moveFirst(name);+ } else if (position instanceof TableChange.After) {+ update.moveAfter(name, ((TableChange.After) position).getColumn());+ }+ }+// ---------------------------------------------------------------------------// Partition / sort conversion (Iceberg -> Gravitino)// ---------------------------------------------------------------------------@@ -560,90 +678,181 @@ final class GlueIcebergTableHelper {/*** Converts an Iceberg {@link org.apache.iceberg.PartitionSpec} to Gravitino {@link Transform}s.*- * <p>Supports identity, year, month, day, hour, bucket, and truncate transforms.+ * <p>Fields with the {@code void} transform, which Iceberg v1 tables keep for dropped partition+ * fields, no longer partition data and are left out. A transform Gravitino has no type for is+ * reported by its Iceberg name.*/static Transform[] convertPartitionSpec(PartitionSpec spec, Schema schema) {+ PartitionSpecVisitor<Transform> visitor =+ new PartitionSpecVisitor<Transform>() {+ @Override+ public Transform identity(int fieldId, String sourceName, int sourceId) {+ return Transforms.identity(columnName(schema, sourceId));+ }++ @Override+ public Transform bucket(int fieldId, String sourceName, int sourceId, int numBuckets) {+ return Transforms.bucket(numBuckets, new String[] {columnName(schema, sourceId)});+ }++ @Override+ public Transform truncate(int fieldId, String sourceName, int sourceId, int width) {+ return Transforms.truncate(width, columnName(schema, sourceId));+ }++ @Override+ public Transform year(int fieldId, String sourceName, int sourceId) {+ return Transforms.year(columnName(schema, sourceId));+ }++ @Override+ public Transform month(int fieldId, String sourceName, int sourceId) {+ return Transforms.month(columnName(schema, sourceId));+ }++ @Override+ public Transform day(int fieldId, String sourceName, int sourceId) {+ return Transforms.day(columnName(schema, sourceId));+ }++ @Override+ public Transform hour(int fieldId, String sourceName, int sourceId) {+ return Transforms.hour(columnName(schema, sourceId));+ }++ @Override+ public Transform alwaysNull(int fieldId, String sourceName, int sourceId) {+ return null;+ }++ @Override+ public Transform unknown(int fieldId, String sourceName, int sourceId, String transform) {+ return Transforms.apply(+ transform, new Expression[] {NamedReference.field(columnName(schema, sourceId))});+ }+ };return spec.fields().stream()- .map(- field -> {- String colName = resolveColumnName(schema, field.sourceId());- String transformStr = field.transform().toString().toLowerCase(Locale.ROOT);- if (transformStr.startsWith("identity")) {- return Transforms.identity(colName);- } else if (transformStr.startsWith("year")) {- return Transforms.year(colName);- } else if (transformStr.startsWith("month")) {- return Transforms.month(colName);- } else if (transformStr.startsWith("day")) {- return Transforms.day(colName);- } else if (transformStr.startsWith("hour")) {- return Transforms.hour(colName);- } else if (transformStr.startsWith("bucket")) {- int numBuckets = extractTransformParam(field.transform().toString());- return Transforms.bucket(numBuckets, new String[] {colName});- } else if (transformStr.startsWith("truncate")) {- int width = extractTransformParam(field.transform().toString());- return Transforms.truncate(width, new String[] {colName});- } else {- throw new IllegalArgumentException(- "Unsupported partition transform: " + transformStr);- }- })+ .map(field -> PartitionSpecVisitor.visit(schema, field, visitor))+ .filter(Objects::nonNull).toArray(Transform[]::new);}- /** Converts an Iceberg {@link org.apache.iceberg.SortOrder} to Gravitino {@link SortOrder}s. */+ /**+ * Converts an Iceberg {@link org.apache.iceberg.SortOrder} to Gravitino {@link SortOrder}s. A+ * transform Gravitino has no function for is reported by its Iceberg name.+ */static SortOrder[] convertIcebergSortOrder(org.apache.iceberg.SortOrder iceSortOrder, Schema schema) {if (iceSortOrder == null || iceSortOrder.fields().isEmpty()) {return new SortOrder[0];}- return iceSortOrder.fields().stream()- .map(- field -> {- String colName = resolveColumnName(schema, field.sourceId());- SortDirection direction =- field.direction() == org.apache.iceberg.SortDirection.ASC- ? SortDirection.ASCENDING- : SortDirection.DESCENDING;- NullOrdering nullOrdering =- field.nullOrder() == org.apache.iceberg.NullOrder.NULLS_FIRST- ? NullOrdering.NULLS_FIRST- : NullOrdering.NULLS_LAST;-- org.apache.iceberg.transforms.Transform<?, ?> transform = field.transform();- String transformStr = transform.toString().toLowerCase(Locale.ROOT);- if (transformStr.startsWith("identity")) {- return SortOrders.of(NamedReference.field(colName), direction, nullOrdering);- }+ SortOrderVisitor<SortOrder> visitor =+ new SortOrderVisitor<SortOrder>() {+ @Override+ public SortOrder field(+ String sourceName,+ int sourceId,+ org.apache.iceberg.SortDirection direction,+ NullOrder nullOrder) {+ return sortOrder(column(sourceId), direction, nullOrder);+ }- Expression expr;- if (transformStr.startsWith("year")) {- expr = FunctionExpression.of("year", NamedReference.field(colName));- } else if (transformStr.startsWith("month")) {- expr = FunctionExpression.of("month", NamedReference.field(colName));- } else if (transformStr.startsWith("day")) {- expr = FunctionExpression.of("day", NamedReference.field(colName));- } else if (transformStr.startsWith("hour")) {- expr = FunctionExpression.of("hour", NamedReference.field(colName));- } else if (transformStr.startsWith("bucket")) {- int numBuckets = extractTransformParam(transformStr);- expr =- FunctionExpression.of(- "bucket",- Literals.integerLiteral(numBuckets),- NamedReference.field(colName));- } else if (transformStr.startsWith("truncate")) {- int width = extractTransformParam(transformStr);- expr =- FunctionExpression.of(- "truncate", Literals.integerLiteral(width), NamedReference.field(colName));- } else {- expr = NamedReference.field(colName);- }- return SortOrders.of(expr, direction, nullOrdering);- })- .toArray(SortOrder[]::new);+ @Override+ public SortOrder bucket(+ String sourceName,+ int sourceId,+ int numBuckets,+ org.apache.iceberg.SortDirection direction,+ NullOrder nullOrder) {+ return sortOrder(+ FunctionExpression.of(+ "bucket", Literals.integerLiteral(numBuckets), column(sourceId)),+ direction,+ nullOrder);+ }++ @Override+ public SortOrder truncate(+ String sourceName,+ int sourceId,+ int width,+ org.apache.iceberg.SortDirection direction,+ NullOrder nullOrder) {+ return sortOrder(+ FunctionExpression.of("truncate", Literals.integerLiteral(width), column(sourceId)),+ direction,+ nullOrder);+ }++ @Override+ public SortOrder year(+ String sourceName,+ int sourceId,+ org.apache.iceberg.SortDirection direction,+ NullOrder nullOrder) {+ return function("year", sourceId, direction, nullOrder);+ }++ @Override+ public SortOrder month(+ String sourceName,+ int sourceId,+ org.apache.iceberg.SortDirection direction,+ NullOrder nullOrder) {+ return function("month", sourceId, direction, nullOrder);+ }++ @Override+ public SortOrder day(+ String sourceName,+ int sourceId,+ org.apache.iceberg.SortDirection direction,+ NullOrder nullOrder) {+ return function("day", sourceId, direction, nullOrder);+ }++ @Override+ public SortOrder hour(+ String sourceName,+ int sourceId,+ org.apache.iceberg.SortDirection direction,+ NullOrder nullOrder) {+ return function("hour", sourceId, direction, nullOrder);+ }++ @Override+ public SortOrder unknown(+ String sourceName,+ int sourceId,+ String transform,+ org.apache.iceberg.SortDirection direction,+ NullOrder nullOrder) {+ return function(transform, sourceId, direction, nullOrder);+ }++ private SortOrder function(+ String name,+ int sourceId,+ org.apache.iceberg.SortDirection direction,+ NullOrder nullOrder) {+ return sortOrder(FunctionExpression.of(name, column(sourceId)), direction, nullOrder);+ }++ private NamedReference column(int sourceId) {+ return NamedReference.field(columnName(schema, sourceId));+ }+ };+ return SortOrderVisitor.visit(iceSortOrder, visitor).toArray(new SortOrder[0]);+ }++ private static SortOrder sortOrder(+ Expression expression, org.apache.iceberg.SortDirection direction, NullOrder nullOrder) {+ return SortOrders.of(+ expression,+ direction == org.apache.iceberg.SortDirection.ASC+ ? SortDirection.ASCENDING+ : SortDirection.DESCENDING,+ nullOrder == NullOrder.NULLS_FIRST ? NullOrdering.NULLS_FIRST : NullOrdering.NULLS_LAST);}// ---------------------------------------------------------------------------@@ -708,7 +917,18 @@ final class GlueIcebergTableHelper {if (type instanceof BooleanType) {return Types.BooleanType.get();}- if (type instanceof ByteType || type instanceof ShortType || type instanceof IntegerType) {+ if (type instanceof Type.IntegralType && !((Type.IntegralType) type).signed()) {+ throw new IllegalArgumentException(+ String.format(+ "Unsigned type %s is not supported by Iceberg; use a signed type",+ type.simpleString()));+ }+ if (type instanceof ByteType || type instanceof ShortType) {+ throw new IllegalArgumentException(+ String.format(+ "Type %s is not supported by Iceberg; use integer instead", type.simpleString()));+ }+ if (type instanceof IntegerType) {return Types.IntegerType.get();}if (type instanceof LongType) {@@ -730,7 +950,7 @@ final class GlueIcebergTableHelper {}if (type instanceof TimeType) {TimeType timeType = (TimeType) type;- if (!timeType.hasPrecisionSet() || timeType.precision() == 6) {+ if (!timeType.hasPrecisionSet() || timeType.precision() == MICROSECOND_PRECISION) {return Types.TimeType.get();}throw new IllegalArgumentException(@@ -739,150 +959,233 @@ final class GlueIcebergTableHelper {}if (type instanceof TimestampType) {TimestampType tsType = (TimestampType) type;- if (!tsType.hasPrecisionSet() || tsType.precision() == 6) {+ if (!tsType.hasPrecisionSet() || tsType.precision() == MICROSECOND_PRECISION) {return tsType.hasTimeZone()? Types.TimestampType.withZone(): Types.TimestampType.withoutZone();}+ // Nanosecond timestamps need Iceberg format version 3, which Iceberg checks at create.+ if (tsType.precision() == NANOSECOND_PRECISION) {+ return tsType.hasTimeZone()+ ? Types.TimestampNanoType.withZone()+ : Types.TimestampNanoType.withoutZone();+ }throw new IllegalArgumentException(- "Iceberg only supports microsecond precision (6) for timestamp type, got: "+ "Iceberg only supports microsecond (6) or nanosecond (9) precision for timestamp type,"+ + " got: "+ tsType.precision());}if (type instanceof DecimalType) {DecimalType dt = (DecimalType) type;return Types.DecimalType.of(dt.precision(), dt.scale());}- if (type instanceof BinaryType || type instanceof FixedType) {+ if (type instanceof BinaryType) {return Types.BinaryType.get();}+ if (type instanceof FixedType) {+ return Types.FixedType.ofLength(((FixedType) type).length());+ }if (type instanceof UUIDType) {return Types.UUIDType.get();}- throw new UnsupportedOperationException("Unsupported type for Iceberg: " + type.simpleString());+ if (type instanceof VariantType) {+ return Types.VariantType.get();+ }+ if (type instanceof GeometryType) {+ return Types.GeometryType.of(((GeometryType) type).crs());+ }+ if (type instanceof GeographyType) {+ GeographyType geography = (GeographyType) type;+ return Types.GeographyType.of(geography.crs(), EdgeAlgorithm.fromName(geography.algorithm()));+ }+ if (type instanceof NullType) {+ return Types.UnknownType.get();+ }+ throw new IllegalArgumentException(+ String.format("Type %s is not supported by Iceberg tables", type.simpleString()));}// ---------------------------------------------------------------------------// Partition / sort conversion (Gravitino -> Iceberg)// ---------------------------------------------------------------------------- private static PartitionSpec toPartitionSpec(Schema schema, Transform[] partitions) {+ @VisibleForTesting+ static PartitionSpec toPartitionSpec(Schema schema, @Nullable Transform[] partitions) {if (partitions == null || partitions.length == 0) {return PartitionSpec.unpartitioned();}PartitionSpec.Builder builder = PartitionSpec.builderFor(schema);for (Transform transform : partitions) {Preconditions.checkArgument(transform != null, "Partition transform cannot be null");- if (transform instanceof Transforms.IdentityTransform) {- String colName = String.join(DOT, ((Transforms.IdentityTransform) transform).fieldName());- builder.identity(colName);- } else if (transform instanceof Transforms.BucketTransform) {- Transforms.BucketTransform bucket = (Transforms.BucketTransform) transform;- String[][] fieldNames = bucket.fieldNames();- Preconditions.checkArgument(- fieldNames.length == 1,- "Iceberg partition does not support multi-field bucket: %s",- transform);- builder.bucket(String.join(DOT, fieldNames[0]), bucket.numBuckets());- } else if (transform instanceof Transforms.TruncateTransform) {- Transforms.TruncateTransform truncate = (Transforms.TruncateTransform) transform;- builder.truncate(String.join(DOT, truncate.fieldName()), truncate.width());- } else if (transform instanceof Transforms.YearTransform) {- builder.year(String.join(DOT, ((Transforms.YearTransform) transform).fieldName()));- } else if (transform instanceof Transforms.MonthTransform) {- builder.month(String.join(DOT, ((Transforms.MonthTransform) transform).fieldName()));- } else if (transform instanceof Transforms.DayTransform) {- builder.day(String.join(DOT, ((Transforms.DayTransform) transform).fieldName()));- } else if (transform instanceof Transforms.HourTransform) {- builder.hour(String.join(DOT, ((Transforms.HourTransform) transform).fieldName()));- } else {- throw new UnsupportedOperationException("Transform is not supported: " + transform.name());+ // Iceberg checks the source type only when the spec is built, so each field is first built+ // alone to name the field that does not fit.+ try {+ addPartitionField(PartitionSpec.builderFor(schema), transform).build();+ addPartitionField(builder, transform);+ } catch (ValidationException | IllegalArgumentException e) {+ throw new IllegalArgumentException(+ String.format("Invalid partition %s: %s", describe(transform), e.getMessage()), e);}}- return builder.build();+ try {+ return builder.build();+ } catch (ValidationException | IllegalArgumentException e) {+ throw new IllegalArgumentException(+ String.format("Invalid partitioning %s: %s", describe(partitions), e.getMessage()), e);+ }+ }++ private static PartitionSpec.Builder addPartitionField(+ PartitionSpec.Builder builder, Transform transform) {+ if (transform instanceof Transforms.IdentityTransform) {+ return builder.identity(+ String.join(DOT, ((Transforms.IdentityTransform) transform).fieldName()));+ } else if (transform instanceof Transforms.BucketTransform) {+ Transforms.BucketTransform bucket = (Transforms.BucketTransform) transform;+ String[][] fieldNames = bucket.fieldNames();+ Preconditions.checkArgument(+ fieldNames.length == 1, "Iceberg buckets take exactly one column");+ return builder.bucket(String.join(DOT, fieldNames[0]), bucket.numBuckets());+ } else if (transform instanceof Transforms.TruncateTransform) {+ Transforms.TruncateTransform truncate = (Transforms.TruncateTransform) transform;+ return builder.truncate(String.join(DOT, truncate.fieldName()), truncate.width());+ } else if (transform instanceof Transforms.YearTransform) {+ return builder.year(String.join(DOT, ((Transforms.YearTransform) transform).fieldName()));+ } else if (transform instanceof Transforms.MonthTransform) {+ return builder.month(String.join(DOT, ((Transforms.MonthTransform) transform).fieldName()));+ } else if (transform instanceof Transforms.DayTransform) {+ return builder.day(String.join(DOT, ((Transforms.DayTransform) transform).fieldName()));+ } else if (transform instanceof Transforms.HourTransform) {+ return builder.hour(String.join(DOT, ((Transforms.HourTransform) transform).fieldName()));+ }+ throw new IllegalArgumentException(+ "Iceberg supports identity, bucket, truncate, year, month, day and hour partitions");}- private static org.apache.iceberg.SortOrder toSortOrder(Schema schema, SortOrder[] sortOrders) {+ @VisibleForTesting+ static org.apache.iceberg.SortOrder toSortOrder(Schema schema, @Nullable SortOrder[] sortOrders) {if (sortOrders == null || sortOrders.length == 0) {return org.apache.iceberg.SortOrder.unsorted();}org.apache.iceberg.SortOrder.Builder builder = org.apache.iceberg.SortOrder.builderFor(schema);for (SortOrder sortOrder : sortOrders) {- if (sortOrder.expression() instanceof NamedReference.FieldReference) {- String fieldName =- String.join(DOT, ((NamedReference.FieldReference) sortOrder.expression()).fieldName());- builder.sortBy(- fieldName,- toIcebergDirection(sortOrder.direction()),- toIcebergNullOrder(sortOrder.nullOrdering()));- } else if (sortOrder.expression() instanceof FunctionExpression) {- FunctionExpression func = (FunctionExpression) sortOrder.expression();- UnboundTerm<Object> term = toIcebergSortTerm(func);- builder.sortBy(- term,- toIcebergDirection(sortOrder.direction()),- toIcebergNullOrder(sortOrder.nullOrdering()));- } else {- throw new UnsupportedOperationException(- "Sort expression is not supported: " + sortOrder.expression());+ Preconditions.checkArgument(sortOrder != null, "Sort order cannot be null");+ // The term is bound to the schema when the order is built, so each term is first built+ // alone to name the term that does not fit.+ try {+ addSortField(org.apache.iceberg.SortOrder.builderFor(schema), sortOrder).build();+ addSortField(builder, sortOrder);+ } catch (ValidationException | IllegalArgumentException e) {+ throw new IllegalArgumentException(+ String.format(+ "Invalid sort order %s: %s", describe(sortOrder.expression()), e.getMessage()),+ e);}}return builder.build();}+ private static org.apache.iceberg.SortOrder.Builder addSortField(+ org.apache.iceberg.SortOrder.Builder builder, SortOrder sortOrder) {+ Expression expression = sortOrder.expression();+ org.apache.iceberg.SortDirection direction = toIcebergDirection(sortOrder.direction());+ NullOrder nullOrder = toIcebergNullOrder(sortOrder.nullOrdering());+ if (expression instanceof NamedReference.FieldReference) {+ String fieldName = String.join(DOT, ((NamedReference.FieldReference) expression).fieldName());+ return builder.sortBy(fieldName, direction, nullOrder);+ } else if (expression instanceof FunctionExpression) {+ return builder.sortBy(+ toIcebergSortTerm((FunctionExpression) expression), direction, nullOrder);+ }+ throw new IllegalArgumentException(+ "Iceberg sorts by a column or by a bucket, truncate, year, month, day or hour of a column");+ }+private static UnboundTerm<Object> toIcebergSortTerm(FunctionExpression func) {String name = func.functionName().toLowerCase(Locale.ROOT);switch (name) {case "bucket":Preconditions.checkArgument(- func.arguments().length == 2, "Bucket sort must have 2 arguments");+ func.arguments().length == 2, "bucket takes a bucket count and a column");int numBuckets = getIntLiteral(func.arguments()[0]);String bucketField = getFieldName(func.arguments()[1]);return Expressions.bucket(bucketField, numBuckets);case "truncate":Preconditions.checkArgument(- func.arguments().length == 2, "Truncate sort must have 2 arguments");+ func.arguments().length == 2, "truncate takes a width and a column");int width = getIntLiteral(func.arguments()[0]);String truncateField = getFieldName(func.arguments()[1]);return Expressions.truncate(truncateField, width);case "year":- return Expressions.year(getSingleField(func.arguments()));+ return Expressions.year(getSingleField(func));case "month":- return Expressions.month(getSingleField(func.arguments()));+ return Expressions.month(getSingleField(func));case "day":- return Expressions.day(getSingleField(func.arguments()));+ return Expressions.day(getSingleField(func));case "hour":- return Expressions.hour(getSingleField(func.arguments()));+ return Expressions.hour(getSingleField(func));default:- throw new UnsupportedOperationException(- "Sort function not supported: " + func.functionName());+ throw new IllegalArgumentException(+ "Iceberg sorts by a column or by a bucket, truncate, year, month, day or hour of a"+ + " column");}}- private static String getSingleField(Expression[] args) {- Preconditions.checkArgument(args.length == 1, "Sort function must have 1 argument");- return getFieldName(args[0]);+ private static String getSingleField(FunctionExpression func) {+ Preconditions.checkArgument(+ func.arguments().length == 1, "%s takes one column", func.functionName());+ return getFieldName(func.arguments()[0]);}private static String getFieldName(Expression expr) {Preconditions.checkArgument(- expr instanceof NamedReference.FieldReference,- "Expected field reference, got: %s",- expr.getClass().getSimpleName());+ expr instanceof NamedReference.FieldReference, "expected a column, got %s", describe(expr));return String.join(DOT, ((NamedReference.FieldReference) expr).fieldName());}private static int getIntLiteral(Expression expr) {Preconditions.checkArgument(- expr instanceof Literal, "Expected literal, got: %s", expr.getClass().getSimpleName());+ expr instanceof Literal, "expected an integer, got %s", describe(expr));Object value = ((Literal<?>) expr).value();try {return Integer.parseInt(String.valueOf(value));} catch (NumberFormatException e) {- throw new IllegalArgumentException(- "Expected integer literal, got: " + value + " in expression: " + expr, e);+ throw new IllegalArgumentException("expected an integer, got " + value, e);}}+ /** Renders partition transforms the way a user writes them, such as {@code bucket(4, id)}. */+ private static String describe(Transform[] transforms) {+ return Arrays.stream(transforms)+ .map(t -> t == null ? "null" : describe(t))+ .collect(Collectors.joining(", ", "[", "]"));+ }++ private static String describe(Transform transform) {+ return transform.name()+ + Arrays.stream(transform.arguments())+ .map(GlueIcebergTableHelper::describe)+ .collect(Collectors.joining(", ", "(", ")"));+ }++ /** Renders a column reference, literal or function the way a user writes it. */+ private static String describe(Expression expr) {+ if (expr instanceof NamedReference.FieldReference) {+ return String.join(DOT, ((NamedReference.FieldReference) expr).fieldName());+ }+ if (expr instanceof Literal) {+ return String.valueOf(((Literal<?>) expr).value());+ }+ if (expr instanceof FunctionExpression) {+ FunctionExpression func = (FunctionExpression) expr;+ return func.functionName()+ + Arrays.stream(func.arguments())+ .map(GlueIcebergTableHelper::describe)+ .collect(Collectors.joining(", ", "(", ")"));+ }+ return expr.getClass().getSimpleName();+ }+private static org.apache.iceberg.SortDirection toIcebergDirection(SortDirection direction) {return direction == SortDirection.ASCENDING? org.apache.iceberg.SortDirection.ASC@@ -897,7 +1200,7 @@ final class GlueIcebergTableHelper {* Returns the column name for the given Iceberg field ID, throwing if the field is not found in* the schema.*/- private static String resolveColumnName(Schema schema, int sourceId) {+ private static String columnName(Schema schema, int sourceId) {String colName = schema.findColumnName(sourceId);Preconditions.checkState(colName != null,@@ -905,24 +1208,4 @@ final class GlueIcebergTableHelper {sourceId);return colName;}-- /**- * Extracts an integer parameter from an Iceberg transform string (e.g. "bucket[16]" or- * "truncate[8]").- *- * <p>Iceberg does not expose transform parameters through a typed API, so string parsing is used.- */- private static int extractTransformParam(String transformStr) {- String param = TRANSFORM_PARAM_PATTERN.matcher(transformStr).replaceAll("$1");- if (param.equals(transformStr)) {- throw new IllegalArgumentException(- "Cannot extract numeric parameter from transform: " + transformStr);- }- try {- return Integer.parseInt(param);- } catch (NumberFormatException e) {- throw new IllegalArgumentException(- "Invalid numeric parameter in transform: " + transformStr, e);- }- }}diff --git a/catalogs/catalog-glue/src/main/java/org/apache/gravitino/catalog/glue/GlueTable.java b/catalogs/catalog-glue/src/main/java/org/apache/gravitino/catalog/glue/GlueTable.javaindex 77f44cddb1..937f71b728 100644--- a/catalogs/catalog-glue/src/main/java/org/apache/gravitino/catalog/glue/GlueTable.java+++ b/catalogs/catalog-glue/src/main/java/org/apache/gravitino/catalog/glue/GlueTable.java@@ -70,6 +70,9 @@ public class GlueTable extends BaseTable {/** Database (schema) this table belongs to. */private String dbName;+ /** Whether the Glue table is an Iceberg table, as its {@code table_type} parameter says. */+ private boolean icebergTable;+private GlueTable() {}/**@@ -96,8 +99,21 @@ public class GlueTable extends BaseTable {return new GlueTableOperations(glueClient, catalogId, dbName, name, partColNames);}+ /**+ * Returns the Glue partition operations of a Hive-format table. Iceberg tables keep their+ * partitions in Iceberg manifests, not in Glue, so they have none.+ *+ * @throws UnsupportedOperationException for an Iceberg-format table+ */@Overridepublic SupportsPartitions supportPartitions() throws UnsupportedOperationException {+ if (icebergTable) {+ throw new UnsupportedOperationException(+ String.format(+ "Partition operations are not supported for Iceberg-format table %s; its"+ + " partitions are kept in Iceberg metadata, not in Glue",+ name));+ }return (SupportsPartitions) ops();}@@ -175,6 +191,12 @@ public class GlueTable extends BaseTable {if (glueTable.hasParameters()) {properties.putAll(glueTable.parameters());}+ // The format of a table is told by its native table_type parameter; table-format only chooses+ // the format at create, so it is reported from table_type and never taken from storage.+ boolean iceberg = GlueIcebergTableHelper.isIcebergTable(glueTable);+ properties.put(+ GlueConstants.TABLE_FORMAT,+ iceberg ? GlueConstants.TABLE_FORMAT_ICEBERG : GlueConstants.TABLE_FORMAT_HIVE);if (sd != null) {putIfNotBlank(properties, LOCATION, sd.location());@@ -198,16 +220,19 @@ public class GlueTable extends BaseTable {.withLastModifiedTime(glueTable.updateTime()).build();- return GlueTable.builder()- .withName(glueTable.name())- .withComment(glueTable.description())- .withColumns(columns.toArray(new Column[0]))- .withProperties(properties)- .withPartitioning(partitioning)- .withDistribution(distribution)- .withSortOrders(sortOrders)- .withAuditInfo(auditInfo)- .build();+ GlueTable table =+ GlueTable.builder()+ .withName(glueTable.name())+ .withComment(glueTable.description())+ .withColumns(columns.toArray(new Column[0]))+ .withProperties(properties)+ .withPartitioning(partitioning)+ .withDistribution(distribution)+ .withSortOrders(sortOrders)+ .withAuditInfo(auditInfo)+ .build();+ table.icebergTable = iceberg;+ return table;}private static void putIfNotBlank(Map<String, String> map, String key, String value) {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 81f562a108..23fe3f4f05 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@@ -55,7 +55,8 @@ public class GlueTablePropertiesMetadata extends BasePropertiesMetadata {ImmutableList.of(stringImmutablePropertyEntry(TABLE_FORMAT,- "Table format stored in Table.parameters(). Common values: ICEBERG, HIVE.",+ "Table format chosen at create: HIVE or ICEBERG. A loaded table reports it from"+ + " its table_type parameter.",false,null,false,diff --git a/catalogs/catalog-glue/src/test/java/org/apache/gravitino/catalog/glue/TestAwsGlueTableConversion.java b/catalogs/catalog-glue/src/test/java/org/apache/gravitino/catalog/glue/TestAwsGlueTableConversion.javaindex 5c8c609a3e..428cd7c86d 100644--- a/catalogs/catalog-glue/src/test/java/org/apache/gravitino/catalog/glue/TestAwsGlueTableConversion.java+++ b/catalogs/catalog-glue/src/test/java/org/apache/gravitino/catalog/glue/TestAwsGlueTableConversion.java@@ -139,7 +139,7 @@ class TestAwsGlueTableConversion extends GlueTableTestBase {.storageDescriptor(StorageDescriptor.builder().build()).parameters(Map.of(- GlueConstants.TABLE_FORMAT, "ICEBERG",+ GlueConstants.TABLE_TYPE_PARAM, "ICEBERG",GlueConstants.METADATA_LOCATION, "s3://bucket/path/metadata/v1.metadata.json")).build();diff --git a/catalogs/catalog-glue/src/test/java/org/apache/gravitino/catalog/glue/TestGlueCatalogOperationsForIceberg.java b/catalogs/catalog-glue/src/test/java/org/apache/gravitino/catalog/glue/TestGlueCatalogOperationsForIceberg.javaindex a188025933..255593ed65 100644--- a/catalogs/catalog-glue/src/test/java/org/apache/gravitino/catalog/glue/TestGlueCatalogOperationsForIceberg.java+++ b/catalogs/catalog-glue/src/test/java/org/apache/gravitino/catalog/glue/TestGlueCatalogOperationsForIceberg.java@@ -19,6 +19,7 @@package org.apache.gravitino.catalog.glue;import static org.apache.gravitino.catalog.glue.GlueConstants.ICEBERG_TABLE_TYPE_VALUE;+import static org.apache.gravitino.catalog.glue.GlueConstants.METADATA_LOCATION;import static org.apache.gravitino.catalog.glue.GlueConstants.TABLE_TYPE_PARAM;import static org.junit.jupiter.api.Assertions.assertEquals;import static org.junit.jupiter.api.Assertions.assertFalse;@@ -34,15 +35,19 @@ import java.util.Map;import java.util.Set;import org.apache.gravitino.NameIdentifier;import org.apache.gravitino.exceptions.ForbiddenException;+import org.apache.gravitino.exceptions.NotFoundException;import org.apache.gravitino.exceptions.TableAlreadyExistsException;-import org.apache.gravitino.rel.SupportsPartitions;+import org.apache.gravitino.rel.Column;import org.apache.gravitino.rel.TableChange;import org.apache.gravitino.rel.expressions.distributions.Distributions;import org.apache.gravitino.rel.expressions.transforms.Transform;import org.apache.gravitino.rel.indexes.Indexes;import org.apache.gravitino.rel.types.Types;+import org.apache.iceberg.PartitionSpec;import org.apache.iceberg.Schema;+import org.apache.iceberg.SortOrder;import org.apache.iceberg.Table;+import org.apache.iceberg.Transaction;import org.apache.iceberg.catalog.Catalog;import org.apache.iceberg.catalog.TableIdentifier;import org.junit.jupiter.api.BeforeEach;@@ -52,15 +57,16 @@ import org.mockito.Mockito;import software.amazon.awssdk.awscore.exception.AwsErrorDetails;import software.amazon.awssdk.services.glue.GlueClient;import software.amazon.awssdk.services.glue.model.Database;+import software.amazon.awssdk.services.glue.model.DeleteTableRequest;import software.amazon.awssdk.services.glue.model.GetDatabaseRequest;import software.amazon.awssdk.services.glue.model.GetDatabaseResponse;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.GlueException;import software.amazon.awssdk.services.glue.model.StorageDescriptor;import software.amazon.awssdk.services.glue.model.UpdateTableRequest;+import software.amazon.awssdk.services.s3.model.S3Exception;class TestGlueCatalogOperationsForIceberg {@@ -145,6 +151,7 @@ class TestGlueCatalogOperationsForIceberg {.thenReturn(mockBuilder);when(mockClient.getTable(any(GetTableRequest.class))).thenReturn(GetTableResponse.builder().table(created).build());+ stubIcebergTable();NameIdentifier ident = NameIdentifier.of("cat", "ns", DB, TABLE);GlueColumn[] cols = {@@ -181,10 +188,11 @@ class TestGlueCatalogOperationsForIceberg {when(mockClient.getTable(any(GetTableRequest.class))).thenReturn(GetTableResponse.builder().table(rawTable).build());- Table mockTable = mock(Table.class);+ Table mockTable = stubIcebergTable();+ Transaction mockTransaction = mock(Transaction.class);org.apache.iceberg.UpdateSchema mockUpdateSchema = mock(org.apache.iceberg.UpdateSchema.class);- when(mockIcebergCatalog.loadTable(any(TableIdentifier.class))).thenReturn(mockTable);- when(mockTable.updateSchema()).thenReturn(mockUpdateSchema);+ when(mockTable.newTransaction()).thenReturn(mockTransaction);+ when(mockTransaction.updateSchema()).thenReturn(mockUpdateSchema);NameIdentifier ident = NameIdentifier.of("cat", "ns", DB, TABLE);ops.alterTable(@@ -194,6 +202,7 @@ class TestGlueCatalogOperationsForIceberg {verify(mockUpdateSchema).addColumn("score", org.apache.iceberg.types.Types.DoubleType.get(), (String) null);verify(mockUpdateSchema).commit();+ verify(mockTransaction).commitTransaction();}@Test@@ -222,30 +231,335 @@ class TestGlueCatalogOperationsForIceberg {}@Test- void testLoadTableWithIcebergMetadataLoadFailure() {+ void testLoadTableFailsWhenIcebergMetadataFileIsMissing() {+ String metadataLocation = LOCATION + "/metadata/00001.metadata.json";+ stubGlueTable(+ Map.of(TABLE_TYPE_PARAM, ICEBERG_TABLE_TYPE_VALUE, METADATA_LOCATION, metadataLocation));+ when(mockIcebergCatalog.loadTable(any(TableIdentifier.class)))+ .thenThrow(+ new org.apache.iceberg.exceptions.NotFoundException(+ "Location does not exist: %s", metadataLocation));++ NotFoundException e =+ assertThrows(+ NotFoundException.class,+ () -> ops.loadTable(NameIdentifier.of("cat", "ns", DB, TABLE)));+ assertTrue(e.getMessage().contains(metadataLocation), e.getMessage());+ }++ @Test+ void testDropTableDoesNotNeedIcebergMetadata() {+ stubGlueTable(+ Map.of(+ TABLE_TYPE_PARAM,+ ICEBERG_TABLE_TYPE_VALUE,+ METADATA_LOCATION,+ LOCATION + "/metadata/00001.metadata.json"));+ when(mockIcebergCatalog.loadTable(any(TableIdentifier.class)))+ .thenThrow(new org.apache.iceberg.exceptions.NotFoundException("Location does not exist"));++ assertTrue(ops.dropTable(NameIdentifier.of("cat", "ns", DB, TABLE)));++ verify(mockClient).deleteTable(any(DeleteTableRequest.class));+ verify(mockIcebergCatalog, never()).loadTable(any(TableIdentifier.class));+ }++ @Test+ void testLoadTableFailsWhenS3DeniesIcebergMetadata() {+ stubGlueTable(Map.of(TABLE_TYPE_PARAM, ICEBERG_TABLE_TYPE_VALUE));+ when(mockIcebergCatalog.loadTable(any(TableIdentifier.class)))+ .thenThrow(+ S3Exception.builder()+ .statusCode(403)+ .awsErrorDetails(+ AwsErrorDetails.builder()+ .errorCode("AccessDenied")+ .errorMessage("Access Denied")+ .build())+ .build());++ ForbiddenException e =+ assertThrows(+ ForbiddenException.class,+ () -> ops.loadTable(NameIdentifier.of("cat", "ns", DB, TABLE)));+ assertTrue(e.getMessage().contains("S3 denied access"), e.getMessage());+ assertTrue(e.getMessage().contains("Iceberg metadata of table " + TABLE), e.getMessage());+ assertFalse(e.getMessage().contains("Glue error"), e.getMessage());+ }++ @Test+ void testPartitionOperationsRefusedForIcebergTable() {+ stubGlueTable(Map.of(TABLE_TYPE_PARAM, ICEBERG_TABLE_TYPE_VALUE));+ stubIcebergTable();++ GlueTable table = ops.loadTable(NameIdentifier.of("cat", "ns", DB, TABLE));++ assertThrows(UnsupportedOperationException.class, table::supportPartitions);+ verify(mockClient, never()).getPartitions(any(GetPartitionsRequest.class));+ }++ @Test+ void testRegisterIcebergTableUsesMetadataFileAndMarksTable() {+ String metadataLocation = LOCATION + "/metadata/00001.metadata.json";+ Table registered = mockIcebergTable();+ when(mockIcebergCatalog.registerTable(TableIdentifier.of(DB, TABLE), metadataLocation))+ .thenReturn(registered);+ when(mockIcebergCatalog.loadTable(any(TableIdentifier.class))).thenReturn(registered);+ stubGlueTable(+ Map.of(TABLE_TYPE_PARAM, ICEBERG_TABLE_TYPE_VALUE, METADATA_LOCATION, metadataLocation));++ ops.createTable(+ NameIdentifier.of("cat", "ns", DB, TABLE),+ icebergColumns(),+ "registered",+ Map.of(+ GlueConstants.TABLE_FORMAT, "iceberg", METADATA_LOCATION, metadataLocation, "k", "v"),+ new Transform[0],+ Distributions.NONE,+ null,+ Indexes.EMPTY_INDEXES);++ ArgumentCaptor<UpdateTableRequest> captor = ArgumentCaptor.forClass(UpdateTableRequest.class);+ verify(mockClient).updateTable(captor.capture());+ Map<String, String> params = captor.getValue().tableInput().parameters();+ assertEquals("true", params.get(GlueConstants.REGISTERED_ICEBERG_TABLE_PARAM));+ assertEquals("v", params.get("k"));+ assertEquals(metadataLocation, params.get(METADATA_LOCATION));+ assertEquals("registered", captor.getValue().tableInput().description());+ verify(mockIcebergCatalog, never()).buildTable(any(TableIdentifier.class), any(Schema.class));+ }++ @Test+ void testRegisterIcebergTableRefusesDifferentColumnsAndDropsGlueEntry() {+ String metadataLocation = LOCATION + "/metadata/00001.metadata.json";+ Table registered = mockIcebergTable();+ when(mockIcebergCatalog.registerTable(TableIdentifier.of(DB, TABLE), metadataLocation))+ .thenReturn(registered);+ GlueColumn[] cols = {+ GlueColumn.builder().withName("bogus").withType(Types.DateType.get()).build()+ };++ IllegalArgumentException e =+ assertThrows(+ IllegalArgumentException.class,+ () ->+ ops.createTable(+ NameIdentifier.of("cat", "ns", DB, TABLE),+ cols,+ null,+ Map.of(+ GlueConstants.TABLE_FORMAT, "iceberg", METADATA_LOCATION, metadataLocation),+ new Transform[0],+ Distributions.NONE,+ null,+ Indexes.EMPTY_INDEXES));+ assertTrue(e.getMessage().contains("bogus"), e.getMessage());+ verify(mockIcebergCatalog).dropTable(TableIdentifier.of(DB, TABLE), false);+ verify(mockClient, never()).updateTable(any(UpdateTableRequest.class));+ }++ @Test+ void testRegisterIcebergTableRefusesLocation() {+ assertThrows(+ IllegalArgumentException.class,+ () ->+ ops.createTable(+ NameIdentifier.of("cat", "ns", DB, TABLE),+ icebergColumns(),+ null,+ Map.of(+ GlueConstants.TABLE_FORMAT,+ "iceberg",+ METADATA_LOCATION,+ LOCATION + "/metadata/00001.metadata.json",+ GlueConstants.LOCATION,+ LOCATION),+ new Transform[0],+ Distributions.NONE,+ null,+ Indexes.EMPTY_INDEXES));+ verify(mockIcebergCatalog, never()).registerTable(any(TableIdentifier.class), any());+ }++ @Test+ void testAlterRegisteredIcebergTableChangesOnlyGlueParameters() {+ stubGlueTable(registeredParams());+ stubIcebergTable();++ ops.alterTable(NameIdentifier.of("cat", "ns", DB, TABLE), TableChange.setProperty("k1", "v1"));++ ArgumentCaptor<UpdateTableRequest> captor = ArgumentCaptor.forClass(UpdateTableRequest.class);+ verify(mockClient).updateTable(captor.capture());+ assertEquals("v1", captor.getValue().tableInput().parameters().get("k1"));+ assertEquals("3", captor.getValue().versionId());+ verify(mockIcebergCatalog, never()).renameTable(any(), any());+ verify(mockIcebergCatalog, Mockito.times(2)).loadTable(any(TableIdentifier.class));+ }++ @Test+ void testAlterRegisteredIcebergTableRefusesMetadataProperties() {+ stubGlueTable(registeredParams());+ Table table = stubIcebergTable();+ when(table.properties()).thenReturn(Map.of("write.format.default", "parquet"));+ NameIdentifier ident = NameIdentifier.of("cat", "ns", DB, TABLE);++ IllegalArgumentException set =+ assertThrows(+ IllegalArgumentException.class,+ () -> ops.alterTable(ident, TableChange.setProperty("write.format.default", "orc")));+ assertTrue(set.getMessage().contains("write.format.default"), set.getMessage());+ assertThrows(+ IllegalArgumentException.class,+ () -> ops.alterTable(ident, TableChange.removeProperty("write.format.default")));++ verify(mockClient, never()).updateTable(any(UpdateTableRequest.class));+ verify(table, never()).newTransaction();+ }++ @Test+ void testRegisterIcebergTableRefusesPropertyThatDiffersFromMetadata() {+ String metadataLocation = LOCATION + "/metadata/00001.metadata.json";+ Table registered = mockIcebergTable();+ when(registered.properties()).thenReturn(Map.of("write.format.default", "parquet"));+ when(mockIcebergCatalog.registerTable(TableIdentifier.of(DB, TABLE), metadataLocation))+ .thenReturn(registered);++ IllegalArgumentException e =+ assertThrows(+ IllegalArgumentException.class,+ () ->+ ops.createTable(+ NameIdentifier.of("cat", "ns", DB, TABLE),+ new Column[0],+ null,+ Map.of(+ GlueConstants.TABLE_FORMAT,+ "iceberg",+ METADATA_LOCATION,+ metadataLocation,+ "write.format.default",+ "orc"),+ new Transform[0],+ Distributions.NONE,+ null,+ Indexes.EMPTY_INDEXES));+ assertTrue(e.getMessage().contains("write.format.default"), e.getMessage());+ verify(mockIcebergCatalog).dropTable(TableIdentifier.of(DB, TABLE), false);+ verify(mockClient, never()).updateTable(any(UpdateTableRequest.class));+ }++ @Test+ void testAlterRegisteredIcebergTableRefusesColumnAndReservedChanges() {+ stubGlueTable(registeredParams());+ NameIdentifier ident = NameIdentifier.of("cat", "ns", DB, TABLE);++ assertThrows(+ IllegalArgumentException.class,+ () ->+ ops.alterTable(+ ident, TableChange.addColumn(new String[] {"c"}, Types.IntegerType.get())));+ assertThrows(+ IllegalArgumentException.class,+ () -> ops.alterTable(ident, TableChange.setProperty(METADATA_LOCATION, "s3://b/x.json")));+ assertThrows(+ IllegalArgumentException.class,+ () ->+ ops.alterTable(+ ident, TableChange.removeProperty(GlueConstants.REGISTERED_ICEBERG_TABLE_PARAM)));+ verify(mockClient, never()).updateTable(any(UpdateTableRequest.class));+ }++ @Test+ void testPurgeIcebergTableDeletesFiles() {+ stubGlueTable(Map.of(TABLE_TYPE_PARAM, ICEBERG_TABLE_TYPE_VALUE));+ when(mockIcebergCatalog.dropTable(TableIdentifier.of(DB, TABLE), true)).thenReturn(true);++ assertTrue(ops.purgeTable(NameIdentifier.of("cat", "ns", DB, TABLE)));+ verify(mockIcebergCatalog).dropTable(TableIdentifier.of(DB, TABLE), true);+ }++ @Test+ void testPurgeRefusedForHiveAndRegisteredTables() {+ NameIdentifier ident = NameIdentifier.of("cat", "ns", DB, TABLE);+ stubGlueTable(Map.of("table_type", "HIVE"));+ assertThrows(UnsupportedOperationException.class, () -> ops.purgeTable(ident));++ stubGlueTable(registeredParams());+ assertThrows(UnsupportedOperationException.class, () -> ops.purgeTable(ident));+ verify(mockIcebergCatalog, never()).dropTable(any(TableIdentifier.class), Mockito.anyBoolean());+ }++ @Test+ void testIcebergPropertiesCannotShadowGlueFormat() {+ stubGlueTable(Map.of(TABLE_TYPE_PARAM, ICEBERG_TABLE_TYPE_VALUE));+ Table icebergTable = mockIcebergTable();+ when(icebergTable.properties())+ .thenReturn(Map.of(TABLE_TYPE_PARAM, "HIVE", GlueConstants.TABLE_FORMAT, "HIVE", "k", "v"));+ when(mockIcebergCatalog.loadTable(any(TableIdentifier.class))).thenReturn(icebergTable);++ GlueTable table = ops.loadTable(NameIdentifier.of("cat", "ns", DB, TABLE));++ assertEquals(ICEBERG_TABLE_TYPE_VALUE, table.properties().get(TABLE_TYPE_PARAM));+ assertEquals("ICEBERG", table.properties().get(GlueConstants.TABLE_FORMAT));+ assertEquals("v", table.properties().get("k"));+ assertThrows(UnsupportedOperationException.class, table::supportPartitions);+ }++ @Test+ void testIcebergAlterRefusesFormatProperties() {+ stubGlueTable(Map.of(TABLE_TYPE_PARAM, ICEBERG_TABLE_TYPE_VALUE));+ NameIdentifier ident = NameIdentifier.of("cat", "ns", DB, TABLE);+ for (TableChange change :+ new TableChange[] {+ TableChange.setProperty(TABLE_TYPE_PARAM, "HIVE"),+ TableChange.setProperty(GlueConstants.TABLE_FORMAT, "HIVE"),+ TableChange.removeProperty(METADATA_LOCATION)+ }) {+ assertThrows(IllegalArgumentException.class, () -> ops.alterTable(ident, change));+ }+ verify(mockIcebergCatalog, never()).loadTable(any(TableIdentifier.class));+ }++ private static Map<String, String> registeredParams() {+ return Map.of(+ TABLE_TYPE_PARAM,+ ICEBERG_TABLE_TYPE_VALUE,+ METADATA_LOCATION,+ LOCATION + "/metadata/00001.metadata.json",+ GlueConstants.REGISTERED_ICEBERG_TABLE_PARAM,+ "true");+ }++ private void stubGlueTable(Map<String, String> params) {software.amazon.awssdk.services.glue.model.Table rawTable =software.amazon.awssdk.services.glue.model.Table.builder().name(TABLE)- .parameters(Map.of(TABLE_TYPE_PARAM, ICEBERG_TABLE_TYPE_VALUE))+ .versionId("3")+ .parameters(params).storageDescriptor(StorageDescriptor.builder().build()).build();-when(mockClient.getTable(any(GetTableRequest.class))).thenReturn(GetTableResponse.builder().table(rawTable).build());- when(mockIcebergCatalog.loadTable(any(TableIdentifier.class)))- .thenThrow(new RuntimeException("metadata file is missing"));- when(mockClient.getPartitions(any(GetPartitionsRequest.class)))- .thenReturn(GetPartitionsResponse.builder().build());+ }- GlueTable result = ops.loadTable(NameIdentifier.of("cat", "ns", DB, TABLE));- SupportsPartitions partitions = result.supportPartitions();+ /** Makes every Iceberg table load return a one-column, unpartitioned table. */+ private Table stubIcebergTable() {+ Table table = mockIcebergTable();+ when(mockIcebergCatalog.loadTable(any(TableIdentifier.class))).thenReturn(table);+ return table;+ }- assertEquals(0, partitions.listPartitionNames().length);- ArgumentCaptor<GetPartitionsRequest> captor =- ArgumentCaptor.forClass(GetPartitionsRequest.class);- verify(mockClient).getPartitions(captor.capture());- assertEquals(DB, captor.getValue().databaseName());- assertEquals(TABLE, captor.getValue().tableName());+ private static Table mockIcebergTable() {+ Schema schema =+ new Schema(+ org.apache.iceberg.types.Types.NestedField.required(+ 1, "id", org.apache.iceberg.types.Types.LongType.get()));+ Table table = mock(Table.class);+ when(table.schema()).thenReturn(schema);+ when(table.spec()).thenReturn(PartitionSpec.unpartitioned());+ when(table.sortOrder()).thenReturn(SortOrder.unsorted());+ when(table.properties()).thenReturn(Map.of());+ return table;}@Test@@ -353,10 +667,7 @@ class TestGlueCatalogOperationsForIceberg {when(mockClient.getTable(any(GetTableRequest.class))).thenReturn(GetTableResponse.builder().table(rawTable).build()).thenReturn(GetTableResponse.builder().table(renamedTable).build());- when(mockIcebergCatalog.loadTable(TableIdentifier.of(DB, newName)))- .thenThrow(new RuntimeException("no iceberg metadata"));- when(mockClient.getPartitions(any(GetPartitionsRequest.class)))- .thenReturn(GetPartitionsResponse.builder().build());+ stubIcebergTable();NameIdentifier ident = NameIdentifier.of("cat", "ns", DB, TABLE);GlueTable result = ops.alterTable(ident, TableChange.rename(newName));@@ -384,6 +695,7 @@ class TestGlueCatalogOperationsForIceberg {.thenReturn(mockBuilder);when(mockClient.getTable(any(GetTableRequest.class))).thenReturn(GetTableResponse.builder().table(created).build());+ stubIcebergTable();ops.defaultTableFormat = "iceberg";NameIdentifier ident = NameIdentifier.of("cat", "ns", DB, TABLE);@@ -427,10 +739,7 @@ class TestGlueCatalogOperationsForIceberg {when(mockClient.getTable(any(GetTableRequest.class))).thenReturn(GetTableResponse.builder().table(rawTable).build()).thenReturn(GetTableResponse.builder().table(renamedTable).build());- when(mockIcebergCatalog.loadTable(TableIdentifier.of(DB, newName)))- .thenThrow(new RuntimeException("no iceberg metadata"));- when(mockClient.getPartitions(any(GetPartitionsRequest.class)))- .thenReturn(GetPartitionsResponse.builder().build());+ stubIcebergTable();NameIdentifier ident = NameIdentifier.of("cat", "ns", DB, TABLE);GlueTable result = ops.alterTable(ident, TableChange.rename(newName));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 370907a411..2acf42697b 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@@ -190,7 +190,7 @@ class TestGlueCatalogTableOperations {Table icebergTable =Table.builder().name("ice_tbl")- .parameters(Map.of(GlueConstants.TABLE_FORMAT, "ICEBERG"))+ .parameters(Map.of(GlueConstants.TABLE_TYPE_PARAM, "ICEBERG")).build();Table hiveTable = Table.builder().name("hive_tbl").parameters(Collections.emptyMap()).build();@@ -252,18 +252,55 @@ class TestGlueCatalogTableOperations {@Testvoid testFormatFilterKeepsVisibleFormatUsable() {- ops.tableFormatFilter = Set.of("iceberg");- NameIdentifier ident = NameIdentifier.of("metalake", "catalog", "mydb", "ice_tbl");- Table icebergTable =+ ops.tableFormatFilter = Set.of("hive");+ NameIdentifier ident = NameIdentifier.of("metalake", "catalog", "mydb", "hive_tbl");+ // table-format is not stored: a Glue parameter left by an older version does not change the+ // format, which comes from table_type.+ Table hiveTable =Table.builder()- .name("ice_tbl")+ .name("hive_tbl").parameters(Map.of(GlueConstants.TABLE_FORMAT, "ICEBERG")).storageDescriptor(StorageDescriptor.builder().build()).build();when(mockClient.getTable(any(GetTableRequest.class)))- .thenReturn(GetTableResponse.builder().table(icebergTable).build());+ .thenReturn(GetTableResponse.builder().table(hiveTable).build());++ GlueTable loaded = ops.loadTable(ident);+ assertEquals("hive_tbl", loaded.name());+ assertEquals("HIVE", loaded.properties().get(GlueConstants.TABLE_FORMAT));+ }- assertEquals("ice_tbl", ops.loadTable(ident).name());+ @Test+ void testCreateRefusesUnknownTableFormatAndDoesNotStoreIt() {+ assertThrows(+ IllegalArgumentException.class,+ () ->+ ops.createTable(+ NameIdentifier.of("metalake", "catalog", "mydb", "t"),+ new Column[] {+ GlueColumn.builder().withName("id").withType(Types.LongType.get()).build()+ },+ null,+ Map.of(GlueConstants.TABLE_FORMAT, "delta"),+ Transforms.EMPTY_TRANSFORM,+ Distributions.NONE,+ SortOrders.NONE,+ Indexes.EMPTY_INDEXES));++ useFakeGlueTable(null);+ ops.createTable(+ NameIdentifier.of("metalake", "catalog", "mydb", "t"),+ new Column[] {GlueColumn.builder().withName("id").withType(Types.LongType.get()).build()},+ null,+ Map.of(GlueConstants.TABLE_FORMAT, "hive"),+ Transforms.EMPTY_TRANSFORM,+ Distributions.NONE,+ SortOrders.NONE,+ Indexes.EMPTY_INDEXES);+ ArgumentCaptor<CreateTableRequest> captor = ArgumentCaptor.forClass(CreateTableRequest.class);+ verify(mockClient).createTable(captor.capture());+ assertFalse(+ captor.getValue().tableInput().parameters().containsKey(GlueConstants.TABLE_FORMAT));}@Testdiff --git a/catalogs/catalog-glue/src/test/java/org/apache/gravitino/catalog/glue/TestGlueExceptionConverter.java b/catalogs/catalog-glue/src/test/java/org/apache/gravitino/catalog/glue/TestGlueExceptionConverter.javaindex dd47890432..b9b0d11259 100644--- a/catalogs/catalog-glue/src/test/java/org/apache/gravitino/catalog/glue/TestGlueExceptionConverter.java+++ b/catalogs/catalog-glue/src/test/java/org/apache/gravitino/catalog/glue/TestGlueExceptionConverter.java@@ -44,6 +44,7 @@ import software.amazon.awssdk.services.glue.model.EntityNotFoundException;import software.amazon.awssdk.services.glue.model.GlueException;import software.amazon.awssdk.services.glue.model.InvalidInputException;import software.amazon.awssdk.services.glue.model.ThrottlingException;+import software.amazon.awssdk.services.s3.model.S3Exception;/** Tests for {@link GlueExceptionConverter}. */public class TestGlueExceptionConverter {@@ -502,4 +503,53 @@ public class TestGlueExceptionConverter {assertTrue(message.contains(GlueConstants.AWS_REGION), message);assertFalse(message.contains("rejected the configured credentials"), message);}++ @Test+ void testIcebergS3FailuresMapByStatus() {+ assertInstanceOf(+ NotFoundException.class,+ GlueExceptionConverter.toIcebergException(s3Exception(404, "NoSuchBucket"), "table t"));+ assertInstanceOf(+ ServiceUnavailableException.class,+ GlueExceptionConverter.toIcebergException(s3Exception(503, "SlowDown"), "table t"));+ assertInstanceOf(+ IllegalArgumentException.class,+ GlueExceptionConverter.toIcebergException(+ s3Exception(301, "PermanentRedirect"), "table t"));+ RuntimeException other =+ GlueExceptionConverter.toIcebergException(s3Exception(500, "InternalError"), "table t");+ assertTrue(other.getMessage().startsWith("S3 error"), other.getMessage());+ assertTrue(other.getMessage().contains("[InternalError]"), other.getMessage());+ }++ @Test+ void testIcebergS3RedirectPointsAtBucketRegion() {+ RuntimeException converted =+ GlueExceptionConverter.toIcebergException(s3Exception(301, "PermanentRedirect"), "table t");+ assertInstanceOf(IllegalArgumentException.class, converted);+ assertTrue(converted.getMessage().contains("different region"), converted.getMessage());+ assertTrue(converted.getMessage().contains("table t"), converted.getMessage());+ }++ @Test+ void testIcebergClientFailureDoesNotBlameGlue() {+ RuntimeException converted =+ GlueExceptionConverter.toIcebergException(+ new RuntimeException(+ "wrapped",+ SdkClientException.create("Unable to execute HTTP request: Read timed out")),+ "Iceberg metadata of table t");+ assertInstanceOf(ConnectionFailedException.class, converted);+ assertTrue(converted.getMessage().contains("AWS (Glue or S3)"), converted.getMessage());+ }++ private static RuntimeException s3Exception(int status, String code) {+ return new RuntimeException(+ "wrapped",+ S3Exception.builder()+ .statusCode(status)+ .awsErrorDetails(+ AwsErrorDetails.builder().errorCode(code).errorMessage("message").build())+ .build());+ }}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 d2c2d744bc..7bca5ef101 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@@ -37,7 +37,14 @@ 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.expressions.FunctionExpression;+import org.apache.gravitino.rel.expressions.NamedReference;+import org.apache.gravitino.rel.expressions.literals.Literals;+import org.apache.gravitino.rel.expressions.sorts.SortOrders;+import org.apache.gravitino.rel.expressions.transforms.Transform;+import org.apache.gravitino.rel.expressions.transforms.Transforms;import org.apache.gravitino.rel.types.Types;+import org.apache.iceberg.HasTableOperations;import org.apache.iceberg.PartitionSpec;import org.apache.iceberg.Schema;import org.apache.iceberg.SortOrder;@@ -391,4 +398,247 @@ class TestGlueIcebergTableHelper {TableChange.deleteColumn(new String[] {"eventat"}, false)));}}++ @Test+ void testFromIcebergTypeV3Types() {+ assertEquals(+ Types.TimestampType.withTimeZone(9),+ fromIcebergType(org.apache.iceberg.types.Types.TimestampNanoType.withZone()));+ assertEquals(+ Types.TimestampType.withoutTimeZone(9),+ fromIcebergType(org.apache.iceberg.types.Types.TimestampNanoType.withoutZone()));+ assertEquals(+ Types.VariantType.get(), fromIcebergType(org.apache.iceberg.types.Types.VariantType.get()));+ assertEquals(+ Types.NullType.get(), fromIcebergType(org.apache.iceberg.types.Types.UnknownType.get()));+ assertEquals(+ Types.GeometryType.of("srid:3857"),+ fromIcebergType(org.apache.iceberg.types.Types.GeometryType.of("srid:3857")));+ assertEquals(+ Types.GeographyType.of("srid:4269", "karney"),+ fromIcebergType(+ org.apache.iceberg.types.Types.GeographyType.of(+ "srid:4269", org.apache.iceberg.types.EdgeAlgorithm.KARNEY)));+ }++ @Test+ void testToIcebergSchemaMatchesIcebergCatalogTypes() {+ Schema schema =+ GlueIcebergTableHelper.toIcebergSchema(+ new Column[] {+ column("f", Types.FixedType.of(16)),+ column("ts_ns", Types.TimestampType.withoutTimeZone(9)),+ column("v", Types.VariantType.get()),+ column("g", Types.GeometryType.of("srid:3857"))+ });+ assertEquals(FixedType.ofLength(16), schema.findType("f"));+ assertEquals(+ org.apache.iceberg.types.Types.TimestampNanoType.withoutZone(), schema.findType("ts_ns"));+ assertEquals(org.apache.iceberg.types.Types.VariantType.get(), schema.findType("v"));+ assertEquals(org.apache.iceberg.types.Types.GeometryType.of("srid:3857"), schema.findType("g"));+ }++ @Test+ void testToIcebergSchemaRefusesTypesIcebergCannotStore() {+ for (org.apache.gravitino.rel.types.Type type :+ new org.apache.gravitino.rel.types.Type[] {+ Types.ByteType.get(), Types.ShortType.get(), Types.IntegerType.unsigned()+ }) {+ IllegalArgumentException e =+ assertThrows(+ IllegalArgumentException.class,+ () -> GlueIcebergTableHelper.toIcebergSchema(new Column[] {column("c", type)}));+ assertTrue(e.getMessage().contains(type.simpleString()), e.getMessage());+ }+ }++ @Test+ void testInvalidPartitionIsRefusedWithTheRequestedTransform() {+ Schema schema = partitionTestSchema();+ IllegalArgumentException year =+ assertThrows(+ IllegalArgumentException.class,+ () ->+ GlueIcebergTableHelper.toPartitionSpec(+ schema, new Transform[] {Transforms.year("name")}));+ assertTrue(year.getMessage().contains("year(name)"), year.getMessage());++ IllegalArgumentException bucket =+ assertThrows(+ IllegalArgumentException.class,+ () ->+ GlueIcebergTableHelper.toPartitionSpec(+ schema,+ new Transform[] {+ Transforms.bucket(4, new String[] {"id"}, new String[] {"name"})+ }));+ assertTrue(bucket.getMessage().contains("bucket(4, id, name)"), bucket.getMessage());+ assertFalse(bucket.getMessage().contains("@"), bucket.getMessage());+ }++ @Test+ void testInvalidSortOrderIsRefusedWithTheRequestedTerm() {+ Schema schema = partitionTestSchema();+ IllegalArgumentException year =+ assertThrows(+ IllegalArgumentException.class,+ () ->+ GlueIcebergTableHelper.toSortOrder(+ schema,+ new org.apache.gravitino.rel.expressions.sorts.SortOrder[] {+ SortOrders.ascending(+ FunctionExpression.of("year", NamedReference.field("name")))+ }));+ assertTrue(year.getMessage().contains("year(name)"), year.getMessage());++ IllegalArgumentException literal =+ assertThrows(+ IllegalArgumentException.class,+ () ->+ GlueIcebergTableHelper.toSortOrder(+ schema,+ new org.apache.gravitino.rel.expressions.sorts.SortOrder[] {+ SortOrders.ascending(Literals.integerLiteral(1))+ }));+ assertFalse(literal.getMessage().contains("LiteralImpl"), literal.getMessage());+ }++ @Test+ void testConvertPartitionSpecSkipsVoidFields() throws IOException {+ try (InMemoryCatalog catalog = newCatalog()) {+ Table table =+ catalog+ .buildTable(TableIdentifier.of("db", "t"), partitionTestSchema())+ .withPartitionSpec(+ PartitionSpec.builderFor(partitionTestSchema())+ .identity("name")+ .identity("id")+ .build())+ .withProperty("format-version", "1")+ .create();+ table.updateSpec().removeField("name").commit();+ table.refresh();++ Transform[] transforms =+ GlueIcebergTableHelper.convertPartitionSpec(table.spec(), table.schema());+ assertEquals(1, transforms.length);+ assertEquals(Transforms.identity("id"), transforms[0]);+ }+ }++ @Test+ void testAlterTableAppliesColumnPositions() throws IOException {+ try (InMemoryCatalog catalog = newCatalog()) {+ catalog.createTable(TableIdentifier.of("db", "t"), partitionTestSchema());++ GlueIcebergTableHelper.alterTable(+ catalog,+ "db",+ "t",+ TableChange.addColumn(+ new String[] {"first_col"},+ Types.IntegerType.get(),+ null,+ TableChange.ColumnPosition.first()),+ TableChange.updateColumnPosition(+ new String[] {"id"}, TableChange.ColumnPosition.after("name")));++ List<String> names =+ catalog.loadTable(TableIdentifier.of("db", "t")).schema().columns().stream()+ .map(NestedField::name)+ .collect(Collectors.toList());+ assertEquals(List.of("first_col", "name", "id"), names);+ }+ }++ @Test+ void testDefaultPositionLeavesAddedColumnLast() throws IOException {+ assertColumnsAfterAlter(+ List.of("name", "id", "added"),+ TableChange.addColumn(new String[] {"added"}, Types.IntegerType.get()),+ TableChange.updateColumnPosition(+ new String[] {"id"}, TableChange.ColumnPosition.after("name")));+ }++ @Test+ void testDefaultPositionLeavesReaddedColumnLast() throws IOException {+ assertColumnsAfterAlter(+ List.of("name", "added", "id"),+ TableChange.deleteColumn(new String[] {"id"}, false),+ TableChange.addColumn(new String[] {"added"}, Types.IntegerType.get()),+ TableChange.addColumn(new String[] {"id"}, Types.LongType.get()));+ }++ @Test+ void testExistingColumnCannotMoveToDefaultPosition() {+ assertThrows(+ IllegalArgumentException.class,+ () ->+ TableChange.updateColumnPosition(+ new String[] {"id"}, TableChange.ColumnPosition.defaultPos()));+ }++ @Test+ void testAlterTableIsAppliedAsAWhole() throws IOException {+ try (InMemoryCatalog catalog = newCatalog()) {+ Table table = catalog.createTable(TableIdentifier.of("db", "t"), partitionTestSchema());+ String before = ((HasTableOperations) table).operations().current().metadataFileLocation();++ // Iceberg refuses to downgrade a v2 table to v1 when the property change is staged.+ assertThrows(+ IllegalArgumentException.class,+ () ->+ GlueIcebergTableHelper.alterTable(+ catalog,+ "db",+ "t",+ TableChange.addColumn(new String[] {"partial"}, Types.StringType.get()),+ TableChange.setProperty("format-version", "1")));+ Table reloaded = catalog.loadTable(TableIdentifier.of("db", "t"));+ assertEquals(+ before, ((HasTableOperations) reloaded).operations().current().metadataFileLocation());+ assertEquals(2, reloaded.schema().columns().size());++ assertThrows(+ IllegalArgumentException.class,+ () ->+ GlueIcebergTableHelper.alterTable(+ catalog,+ "db",+ "t",+ TableChange.updateColumnAutoIncrement(new String[] {"id"}, true)));+ }+ }++ private static void assertColumnsAfterAlter(List<String> expected, TableChange... changes)+ throws IOException {+ try (InMemoryCatalog catalog = newCatalog()) {+ catalog.createTable(TableIdentifier.of("db", "t"), partitionTestSchema());++ GlueIcebergTableHelper.alterTable(catalog, "db", "t", changes);++ List<String> names =+ catalog.loadTable(TableIdentifier.of("db", "t")).schema().columns().stream()+ .map(NestedField::name)+ .collect(Collectors.toList());+ assertEquals(expected, names);+ }+ }++ private static InMemoryCatalog newCatalog() {+ InMemoryCatalog catalog = new InMemoryCatalog();+ catalog.initialize("test", new HashMap<>());+ catalog.createNamespace(Namespace.of("db"));+ return catalog;+ }++ private static Schema partitionTestSchema() {+ return new Schema(+ NestedField.optional(1, "id", LongType.get()),+ NestedField.optional(2, "name", StringType.get()));+ }++ private static Column column(String name, org.apache.gravitino.rel.types.Type type) {+ return GlueColumn.builder().withName(name).withType(type).withNullable(true).build();+ }}diff --git a/catalogs/catalog-glue/src/test/java/org/apache/gravitino/catalog/glue/TestGlueTableConversion.java b/catalogs/catalog-glue/src/test/java/org/apache/gravitino/catalog/glue/TestGlueTableConversion.javaindex bf61faa98c..3f20de58f5 100644--- a/catalogs/catalog-glue/src/test/java/org/apache/gravitino/catalog/glue/TestGlueTableConversion.java+++ b/catalogs/catalog-glue/src/test/java/org/apache/gravitino/catalog/glue/TestGlueTableConversion.java@@ -72,7 +72,7 @@ class TestGlueTableConversion extends GlueTableTestBase {.storageDescriptor(StorageDescriptor.builder().build()).parameters(Map.of(- GlueConstants.TABLE_FORMAT, "ICEBERG",+ GlueConstants.TABLE_TYPE_PARAM, "ICEBERG",GlueConstants.METADATA_LOCATION, "s3://bucket/path/metadata/v1.metadata.json")).createTime(Instant.now()).updateTime(Instant.now())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 820b5a0455..ccc5a90921 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@@ -195,6 +195,29 @@ abstract class AbstractGlueCatalogIT {return rawGlueClient;}+ /**+ * Creates the Glue entry of an Iceberg table directly through the Glue API, as another engine+ * would. Its metadata file does not exist, so the table can be listed and dropped but not loaded.+ */+ private void createExternalIcebergTable(String schema, String name) {+ glueClient()+ .createTable(+ CreateTableRequest.builder()+ .databaseName(schema)+ .tableInput(+ TableInput.builder()+ .name(name)+ .tableType(GlueConstants.EXTERNAL_TABLE_TYPE)+ .parameters(+ Map.of(+ GlueConstants.TABLE_TYPE_PARAM,+ GlueConstants.ICEBERG_TABLE_TYPE_VALUE,+ GlueConstants.METADATA_LOCATION,+ "s3://bucket/path/metadata/v1.metadata.json"))+ .build())+ .build());+ }+/** Creates a Presto/Athena style view directly through the Glue API. */private void createGlueView(String schema, String name) {glueClient()@@ -474,29 +497,27 @@ abstract class AbstractGlueCatalogIT {// -------------------------------------------------------------------------@Test- void testCreateIcebergTable() {+ void testRegisterIcebergTableWithBlankMetadataLocationIsRefused() {String schema = newSchema();ops.createSchema(schemaIdent(schema), null, Collections.emptyMap());Map<String, String> props = new HashMap<>();props.put(GlueConstants.TABLE_FORMAT, "ICEBERG");- props.put(GlueConstants.METADATA_LOCATION, "s3://bucket/path/metadata/v1.metadata.json");- ops.createTable(- tableIdent(schema, "iceberg_tbl"),- new Column[0],- null,- props,- new Transform[0],- Distributions.NONE,- new SortOrder[0],- new Index[0]);-- Table loaded = ops.loadTable(tableIdent(schema, "iceberg_tbl"));- assertEquals("ICEBERG", loaded.properties().get(GlueConstants.TABLE_FORMAT));- assertEquals(- "s3://bucket/path/metadata/v1.metadata.json",- loaded.properties().get(GlueConstants.METADATA_LOCATION));- assertEquals(0, loaded.columns().length);+ props.put(GlueConstants.METADATA_LOCATION, " ");+ assertThrows(+ IllegalArgumentException.class,+ () ->+ ops.createTable(+ tableIdent(schema, "iceberg_tbl"),+ new Column[0],+ null,+ props,+ new Transform[0],+ Distributions.NONE,+ new SortOrder[0],+ new Index[0]));+ assertThrows(+ NoSuchTableException.class, () -> ops.loadTable(tableIdent(schema, "iceberg_tbl")));}// -------------------------------------------------------------------------@@ -828,18 +849,7 @@ abstract class AbstractGlueCatalogIT {String schema = newSchema();ops.createSchema(schemaIdent(schema), null, Collections.emptyMap());- Map<String, String> props = new HashMap<>();- props.put(GlueConstants.TABLE_FORMAT, "ICEBERG");- props.put(GlueConstants.METADATA_LOCATION, "s3://bucket/path/metadata/v1.metadata.json");- ops.createTable(- tableIdent(schema, "iceberg_drop"),- new Column[0],- null,- props,- new Transform[0],- Distributions.NONE,- new SortOrder[0],- new Index[0]);+ createExternalIcebergTable(schema, "iceberg_drop");assertTrue(ops.dropTable(tableIdent(schema, "iceberg_drop")));assertFalse(ops.dropTable(tableIdent(schema, "iceberg_drop")));@@ -852,18 +862,7 @@ abstract class AbstractGlueCatalogIT {createHiveTable(schema, "hive_mixed");- Map<String, String> icebergProps = new HashMap<>();- icebergProps.put(GlueConstants.TABLE_FORMAT, "ICEBERG");- icebergProps.put(GlueConstants.METADATA_LOCATION, "s3://bucket/path/metadata/v1.metadata.json");- ops.createTable(- tableIdent(schema, "iceberg_mixed"),- new Column[0],- null,- icebergProps,- new Transform[0],- Distributions.NONE,- new SortOrder[0],- new Index[0]);+ createExternalIcebergTable(schema, "iceberg_mixed");List<String> names =Arrays.stream(ops.listTables(tableNs(schema)))diff --git a/catalogs/catalog-glue/src/test/java/org/apache/gravitino/catalog/glue/integration/test/AwsGlueCatalogIT.java b/catalogs/catalog-glue/src/test/java/org/apache/gravitino/catalog/glue/integration/test/AwsGlueCatalogIT.javaindex eb1437e3a4..0430f7b248 100644--- a/catalogs/catalog-glue/src/test/java/org/apache/gravitino/catalog/glue/integration/test/AwsGlueCatalogIT.java+++ b/catalogs/catalog-glue/src/test/java/org/apache/gravitino/catalog/glue/integration/test/AwsGlueCatalogIT.java@@ -20,14 +20,18 @@ package org.apache.gravitino.catalog.glue.integration.test;import static org.junit.jupiter.api.Assertions.assertEquals;import static org.junit.jupiter.api.Assertions.assertFalse;+import static org.junit.jupiter.api.Assertions.assertThrows;import static org.junit.jupiter.api.Assertions.assertTrue;import com.google.common.base.Preconditions;+import java.net.URI;import java.util.Collections;import java.util.HashMap;import java.util.Map;import org.apache.gravitino.NameIdentifier;import org.apache.gravitino.catalog.glue.GlueConstants;+import org.apache.gravitino.exceptions.NoSuchTableException;+import org.apache.gravitino.exceptions.NotFoundException;import org.apache.gravitino.rel.Column;import org.apache.gravitino.rel.Table;import org.apache.gravitino.rel.TableChange;@@ -42,6 +46,10 @@ import org.junit.jupiter.api.TestInstance;import org.junit.jupiter.api.condition.EnabledIfEnvironmentVariable;import org.slf4j.Logger;import org.slf4j.LoggerFactory;+import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;+import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider;+import software.amazon.awssdk.regions.Region;+import software.amazon.awssdk.services.s3.S3Client;/*** Runs {@link AbstractGlueCatalogIT} scenarios against a real AWS Glue endpoint.@@ -184,4 +192,176 @@ class AwsGlueCatalogIT extends AbstractGlueCatalogIT {ops.dropSchema(NameIdentifier.of("ml", "cat", schema), false);}}++ @Test+ void testRegisteredIcebergTableTakesMetadataAndOnlyChangesGlue() {+ String bucket = System.getenv("AWS_S3_TEST_BUCKET");+ String schema = "glue_it_" + System.nanoTime();+ NameIdentifier src = NameIdentifier.of("ml", "cat", schema, "ice_src");+ NameIdentifier reg = NameIdentifier.of("ml", "cat", schema, "ice_reg");+ NameIdentifier missing = NameIdentifier.of("ml", "cat", schema, "ice_missing");+ String location = "s3://" + bucket + "/" + schema + "/ice_src";+ ops.createSchema(NameIdentifier.of("ml", "cat", schema), null, Collections.emptyMap());+ try {+ createIcebergTable(src, location);+ String metadataLocation =+ ops.loadTable(src).properties().get(GlueConstants.METADATA_LOCATION);++ Map<String, String> props = new HashMap<>();+ props.put(GlueConstants.TABLE_FORMAT, "ICEBERG");+ props.put(GlueConstants.METADATA_LOCATION, metadataLocation);+ Table registered =+ ops.createTable(+ reg,+ new Column[0],+ null,+ props,+ new Transform[0],+ Distributions.NONE,+ new SortOrder[0],+ new Index[0]);+ assertEquals(1, registered.columns().length);+ assertEquals("id", registered.columns()[0].name());+ assertEquals(location, registered.properties().get(GlueConstants.LOCATION));+ assertEquals(+ "true", registered.properties().get(GlueConstants.REGISTERED_ICEBERG_TABLE_PARAM));++ assertThrows(+ IllegalArgumentException.class,+ () ->+ ops.alterTable(+ reg, TableChange.addColumn(new String[] {"c"}, Types.IntegerType.get())));+ ops.alterTable(reg, TableChange.setProperty("k1", "v1"));+ Table altered = ops.loadTable(reg);+ assertEquals("v1", altered.properties().get("k1"));+ assertEquals(metadataLocation, altered.properties().get(GlueConstants.METADATA_LOCATION));+ assertEquals(+ metadataLocation, ops.loadTable(src).properties().get(GlueConstants.METADATA_LOCATION));+ assertThrows(UnsupportedOperationException.class, () -> ops.purgeTable(reg));++ props.put(+ GlueConstants.METADATA_LOCATION, location + "/metadata/00099-missing.metadata.json");+ assertThrows(+ NotFoundException.class,+ () ->+ ops.createTable(+ missing,+ new Column[0],+ null,+ props,+ new Transform[0],+ Distributions.NONE,+ new SortOrder[0],+ new Index[0]));+ assertThrows(NoSuchTableException.class, () -> ops.loadTable(missing));+ } finally {+ ops.dropTable(reg);+ ops.purgeTable(src);+ ops.dropSchema(NameIdentifier.of("ml", "cat", schema), true);+ }+ }++ @Test+ void testIcebergTableWithMissingMetadataFileFailsToLoad() {+ String bucket = System.getenv("AWS_S3_TEST_BUCKET");+ String schema = "glue_it_" + System.nanoTime();+ NameIdentifier ident = NameIdentifier.of("ml", "cat", schema, "ice_lost");+ ops.createSchema(NameIdentifier.of("ml", "cat", schema), null, Collections.emptyMap());+ try (S3Client s3 = s3Client()) {+ createIcebergTable(ident, "s3://" + bucket + "/" + schema + "/ice_lost");+ Table loaded = ops.loadTable(ident);+ assertThrows(UnsupportedOperationException.class, loaded::supportPartitions);++ String metadataLocation = loaded.properties().get(GlueConstants.METADATA_LOCATION);+ URI uri = URI.create(metadataLocation);+ s3.deleteObject(b -> b.bucket(uri.getHost()).key(uri.getPath().substring(1)));++ NotFoundException e = assertThrows(NotFoundException.class, () -> ops.loadTable(ident));+ assertTrue(e.getMessage().contains(metadataLocation), e.getMessage());+ assertTrue(ops.dropTable(ident));+ } finally {+ ops.dropTable(ident);+ ops.dropSchema(NameIdentifier.of("ml", "cat", schema), true);+ }+ }++ @Test+ void testPurgeIcebergTableDeletesItsFiles() {+ String bucket = System.getenv("AWS_S3_TEST_BUCKET");+ String schema = "glue_it_" + System.nanoTime();+ NameIdentifier ident = NameIdentifier.of("ml", "cat", schema, "ice_purge");+ String prefix = schema + "/ice_purge/";+ ops.createSchema(NameIdentifier.of("ml", "cat", schema), null, Collections.emptyMap());+ try (S3Client s3 = s3Client()) {+ createIcebergTable(ident, "s3://" + bucket + "/" + prefix);+ ops.alterTable(ident, TableChange.setProperty("k1", "v1"));+ assertTrue(s3.listObjectsV2(b -> b.bucket(bucket).prefix(prefix)).keyCount() > 0);++ assertTrue(ops.purgeTable(ident));+ assertThrows(NoSuchTableException.class, () -> ops.loadTable(ident));+ assertEquals(0, s3.listObjectsV2(b -> b.bucket(bucket).prefix(prefix)).keyCount());+ } finally {+ ops.dropSchema(NameIdentifier.of("ml", "cat", schema), true);+ }+ }++ @Test+ void testIcebergAlterIsAppliedAsAWhole() {+ String bucket = System.getenv("AWS_S3_TEST_BUCKET");+ String schema = "glue_it_" + System.nanoTime();+ NameIdentifier ident = NameIdentifier.of("ml", "cat", schema, "ice_atomic");+ ops.createSchema(NameIdentifier.of("ml", "cat", schema), null, Collections.emptyMap());+ try {+ createIcebergTable(ident, "s3://" + bucket + "/" + schema + "/ice_atomic");+ String before = ops.loadTable(ident).properties().get(GlueConstants.METADATA_LOCATION);++ assertThrows(+ IllegalArgumentException.class,+ () ->+ ops.alterTable(+ ident,+ TableChange.addColumn(new String[] {"partial"}, Types.StringType.get()),+ TableChange.setProperty("format-version", "1")));+ Table unchanged = ops.loadTable(ident);+ assertEquals(before, unchanged.properties().get(GlueConstants.METADATA_LOCATION));+ assertEquals(1, unchanged.columns().length);++ ops.alterTable(+ ident,+ TableChange.addColumn(+ new String[] {"first_col"},+ Types.IntegerType.get(),+ null,+ TableChange.ColumnPosition.first()));+ assertEquals("first_col", ops.loadTable(ident).columns()[0].name());+ } finally {+ ops.purgeTable(ident);+ ops.dropSchema(NameIdentifier.of("ml", "cat", schema), true);+ }+ }++ private void createIcebergTable(NameIdentifier ident, String location) {+ Map<String, String> props = new HashMap<>();+ props.put(GlueConstants.TABLE_FORMAT, "ICEBERG");+ props.put(GlueConstants.LOCATION, location);+ ops.createTable(+ ident,+ new Column[] {Column.of("id", Types.LongType.get(), null)},+ null,+ props,+ new Transform[0],+ Distributions.NONE,+ new SortOrder[0],+ new Index[0]);+ }++ private static S3Client s3Client() {+ return S3Client.builder()+ .region(Region.of(System.getenv().getOrDefault("AWS_DEFAULT_REGION", "us-east-1")))+ .credentialsProvider(+ StaticCredentialsProvider.create(+ AwsBasicCredentials.create(+ System.getenv("AWS_ACCESS_KEY_ID"), System.getenv("AWS_SECRET_ACCESS_KEY"))))+ .build();+ }}diff --git a/docs/aws-glue-catalog.md b/docs/aws-glue-catalog.mdindex 49cd8ce2d1..232444f5b9 100644--- a/docs/aws-glue-catalog.md+++ b/docs/aws-glue-catalog.md@@ -39,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`. 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 |+| 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. Also applied to the Glue calls of Iceberg tables, but not to S3 I/O. | `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 S3 client 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. Also applied to the Glue calls of Iceberg tables, but not to S3 I/O. | `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 is `iceberg` when it has `table_type=ICEBERG`, and `hive` otherwise, including Delta tables registered by other engines, so `delta` and `parquet` match no table. 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).@@ -175,8 +175,8 @@ The following table lists predefined properties for Glue tables. Additional key-| `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 |+| `table-format` | Format the table is created in: `HIVE` or `ICEBERG`. It is not stored; a loaded table reports `ICEBERG` when it has `table_type=ICEBERG`, and `HIVE` otherwise. | (catalog `default-table-format`) | 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; see [Register an Existing Iceberg Table](#register-an-existing-iceberg-table). | (none) | No | No | No || `comment` | Used to store a table comment. | (none) | No | Yes | No |:::note@@ -244,59 +244,80 @@ The `warehouse` catalog property is required, but it is used only as a fallback### Register an Existing Iceberg Table-To register an Iceberg table that already exists in S3, set `metadata_location` to the path of the existing `metadata.json` file during `createTable()`. In this mode, Gravitino registers the table in Glue without creating new metadata.+To register an Iceberg table that already exists in S3, set `metadata_location` to the path of the existing `metadata.json` file during `createTable()`. Gravitino reads the metadata file before it creates the Glue table, and refuses the request if the file does not exist or is not Iceberg table metadata. No new metadata file is written.++The columns, location, partitioning and sort order of a registered table come from the metadata file. Send `"columns": []` to take the columns from the metadata file; if columns are given, their names must match it. Do not set `location`, partitioning or sort order. A property in the request cannot give a property of the metadata file another value.++A registered table shares its metadata and data files with the table it was registered from, so Gravitino marks it with the Glue parameter `gravitino.iceberg.registered=true` and changes only its Glue parameters afterwards: property changes are stored in Glue, and column, partition and other schema changes are refused. Properties of the metadata file cannot be set or removed, because Iceberg engines read them from that file. A registered table cannot be purged.++A table registered by an earlier Gravitino version, or by a registration that stopped before the parameter was written, has no marker. Gravitino treats it as the owner of its metadata, so an alter through Gravitino writes new metadata files and forks the history it shares with the source table. Gravitino cannot detect such tables, and the parameter cannot be set through Gravitino; to protect one, add the parameter to the table directly in AWS Glue.### Iceberg Column TypesIceberg tables use the Iceberg type system, which differs from Hive types. The following table lists the Gravitino types supported for Iceberg tables and how they map to Iceberg types:-| Gravitino Data Type | Iceberg Data Type | Notes |-|--------------------------|-----------------------|-----------------------------------------------------|-| `boolean` | `boolean` | |-| `byte` | `int` | Widened to 32-bit integer |-| `short` | `int` | Widened to 32-bit integer |-| `integer` | `int` | |-| `long` | `long` | |-| `float` | `float` | |-| `double` | `double` | |-| `decimal(p, s)` | `decimal(p, s)` | |-| `string` | `string` | |-| `varchar` | `string` | Iceberg has no variable-length char types |-| `char` | `string` | Iceberg has no variable-length char types |-| `date` | `date` | |-| `time(6)` | `time` | Only microsecond precision (6) is supported |-| `timestamp(6)` | `timestamp` | Only microsecond precision (6) is supported |-| `timestamptz(6)` | `timestamptz` | Only microsecond precision (6) is supported |-| `binary` | `binary` | |-| `fixed(n)` | `binary` | Mapped to variable-length binary |-| `uuid` | `uuid` | |-| `list` | `list` | |-| `map` | `map` | |-| `struct` | `struct` | |+| Gravitino Data Type | Iceberg Data Type | Notes |+|-----------------------------|-----------------------------|---------------------------------------------|+| `boolean` | `boolean` | |+| `integer` | `int` | |+| `long` | `long` | |+| `float` | `float` | |+| `double` | `double` | |+| `decimal(p, s)` | `decimal(p, s)` | |+| `string` | `string` | |+| `varchar` | `string` | Iceberg has no variable-length char types |+| `char` | `string` | Iceberg has no variable-length char types |+| `date` | `date` | |+| `time(6)` | `time` | Only microsecond precision (6) is supported |+| `timestamp(6)` | `timestamp` | |+| `timestamptz(6)` | `timestamptz` | |+| `timestamp(9)` | `timestamp_ns` | Needs format version 3 |+| `timestamptz(9)` | `timestamptz_ns` | Needs format version 3 |+| `binary` | `binary` | |+| `fixed(n)` | `fixed(n)` | |+| `uuid` | `uuid` | |+| `variant` | `variant` | Needs format version 3 |+| `geometry(crs)` | `geometry(crs)` | Needs format version 3 |+| `geography(crs, algorithm)` | `geography(crs, algorithm)` | Needs format version 3 |+| `null` | `unknown` | Needs format version 3 |+| `list` | `list` | |+| `map` | `map` | |+| `struct` | `struct` | |++:::caution+`byte`, `short` and unsigned types are not supported for Iceberg tables; use `integer` or `long`.+:::### Iceberg Table Alter OperationsFor Iceberg tables, the following alter operations are supported:-| Operation | Gravitino Table Update Request |-|---------------------------------|-----------------------------------|-| Add column | `Add a column` |-| Delete column | `Delete a column` |-| Rename column | `Rename a column` |-| Update column type | `Update the type of a column` |-| Update column comment | `Update the column comment` |-| Update column nullability | `Update column nullability` |-| Set table property | `Set a table property` |-| Remove table property | `Remove a table property` |+| Operation | Gravitino Table Update Request |+|---------------------------|-----------------------------------|+| Add column | `Add a column` |+| Delete column | `Delete a column` |+| Rename column | `Rename a column` |+| Update column type | `Update the type of a column` |+| Update column position | `Update the position of a column` |+| Update column comment | `Update the column comment` |+| Update column nullability | `Update column nullability` |+| Set table property | `Set a table property` |+| Remove table property | `Remove a table property` |-:::caution-Schema changes and property changes are committed in two separate Iceberg transactions. If the schema commit succeeds but the property commit fails, the table is left in a partially altered state.-:::+Schema and property changes of one request are committed in one Iceberg transaction, so they are applied together or not at all. A request that reports an error may still have been applied, for example when the commit state is unknown or the reload after the commit fails, so check the table before retrying. Property changes of a registered table are stored in Glue and do not use an Iceberg transaction.:::caution-Nested column operations (add, delete, rename, type update) are not supported for Iceberg tables via this catalog.+Nested column operations, auto-increment and column default values are not supported for Iceberg tables via this catalog.:::+### Drop and Purge Iceberg Tables++Dropping an Iceberg table removes only its Glue entry; the metadata and data files stay in S3. Purging an Iceberg table also deletes the data and metadata files its metadata references. Hive-format tables and registered Iceberg tables cannot be purged.++### Iceberg Table Partitions++Iceberg tables keep their partitions in Iceberg metadata, not in Glue, so partition operations are not supported for them. The partitioning of an Iceberg table is reported by the table itself; fields with the `void` transform, which Iceberg v1 tables keep for dropped partition fields, are left out.+## Security### AWS IAM Permissions