Skip to content

World's most powerful open data catalog for building a high-performance, geo-distributed and federated metadata lake.

[#357] feat(catalog-lakehouse-iceberg): Add Iceberg table operations support in Graviton (#400)

Clearvive086bd01a52d0
diff --git a/catalogs/catalog-lakehouse-iceberg/src/main/java/com/datastrato/graviton/catalog/lakehouse/iceberg/IcebergCatalogOperations.java b/catalogs/catalog-lakehouse-iceberg/src/main/java/com/datastrato/graviton/catalog/lakehouse/iceberg/IcebergCatalogOperations.java
index f8cb2fdc36..6c2bfdd0be 100644
--- a/catalogs/catalog-lakehouse-iceberg/src/main/java/com/datastrato/graviton/catalog/lakehouse/iceberg/IcebergCatalogOperations.java
+++ b/catalogs/catalog-lakehouse-iceberg/src/main/java/com/datastrato/graviton/catalog/lakehouse/iceberg/IcebergCatalogOperations.java
@@ -32,14 +32,24 @@ import com.google.common.base.Preconditions;
import com.google.common.collect.Maps;
import java.time.Instant;
import java.util.ArrayList;
+import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
+import java.util.stream.Collectors;
+import org.apache.commons.lang3.ArrayUtils;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.iceberg.catalog.TableIdentifier;
+import org.apache.iceberg.exceptions.AlreadyExistsException;
import org.apache.iceberg.exceptions.NamespaceNotEmptyException;
import org.apache.iceberg.exceptions.NoSuchNamespaceException;
+import org.apache.iceberg.rest.requests.RenameTableRequest;
import org.apache.iceberg.rest.requests.UpdateNamespacePropertiesRequest;
import org.apache.iceberg.rest.responses.GetNamespaceResponse;
+import org.apache.iceberg.rest.responses.ListTablesResponse;
+import org.apache.iceberg.rest.responses.LoadTableResponse;
+import org.apache.iceberg.rest.responses.UpdateNamespacePropertiesResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -54,6 +64,8 @@ public class IcebergCatalogOperations implements CatalogOperations, SupportsSche
private final CatalogEntity entity;
+ private IcebergTableOpsHelper icebergTableOpsHelper;
+
/**
* Constructs a new instance of IcebergCatalogOperations.
*
@@ -74,6 +86,7 @@ public class IcebergCatalogOperations implements CatalogOperations, SupportsSche
IcebergConfig icebergConfig = new IcebergConfig();
icebergConfig.loadFromMap(conf, k -> true);
this.icebergTableOps = new IcebergTableOps(icebergConfig);
+ this.icebergTableOpsHelper = icebergTableOps.createIcebergTableOpsHelper();
}
/** Closes the Iceberg catalog and releases the associated client pool. */
@@ -140,8 +153,7 @@ public class IcebergCatalogOperations implements CatalogOperations, SupportsSche
return createdSchema;
} catch (org.apache.iceberg.exceptions.AlreadyExistsException e) {
throw new SchemaAlreadyExistsException(
- String.format("Iceberg schema (database) '%s' already exists in Iceberg", ident.name()),
- e);
+ String.format("Iceberg schema (database) '%s' already exists", ident.name()), e);
} catch (NoSuchNamespaceException e) {
throw new NoSuchSchemaException(
String.format(
@@ -174,6 +186,7 @@ public class IcebergCatalogOperations implements CatalogOperations, SupportsSche
.map(map -> map.get(IcebergSchema.ICEBERG_COMMENT_FIELD_NAME))
.orElse(""))
.withProperties(response.properties())
+ .withAuditInfo(AuditInfo.EMPTY)
.build();
LOG.info("Loaded Iceberg schema (database) {} from Iceberg ", ident.name());
return icebergSchema;
@@ -235,17 +248,22 @@ public class IcebergCatalogOperations implements CatalogOperations, SupportsSche
new IcebergSchema.Builder()
.withName(ident.name())
.withComment(comment)
+ .withAuditInfo(AuditInfo.EMPTY)
.withProperties(resultProperties)
.build();
UpdateNamespacePropertiesRequest updateNamespacePropertiesRequest =
UpdateNamespacePropertiesRequest.builder().updateAll(updates).removeAll(removals).build();
- icebergTableOps.updateNamespaceProperties(
- IcebergTableOpsHelper.getIcebergNamespace(ident), updateNamespacePropertiesRequest);
- LOG.info("Altered Iceberg schema (database) {} in Iceberg", ident.name());
+ UpdateNamespacePropertiesResponse updateNamespacePropertiesResponse =
+ icebergTableOps.updateNamespaceProperties(
+ IcebergTableOpsHelper.getIcebergNamespace(ident), updateNamespacePropertiesRequest);
+ LOG.info(
+ "Altered Iceberg schema (database) {}. UpdateResponse:\n{}",
+ ident.name(),
+ updateNamespacePropertiesResponse);
return icebergSchema;
} catch (NoSuchNamespaceException e) {
throw new NoSuchSchemaException(
- String.format("Iceberg schema (database) %s does not exist in Iceberg", ident.name()), e);
+ String.format("Iceberg schema (database) %s does not exist", ident.name()), e);
} catch (Exception e) {
throw new RuntimeException(e);
}
@@ -272,7 +290,7 @@ public class IcebergCatalogOperations implements CatalogOperations, SupportsSche
"Iceberg schema (database) %s is not empty. One or more tables exist.", ident.name()),
e);
} catch (NoSuchNamespaceException e) {
- LOG.warn("Iceberg schema (database) {} does not exist in Iceberg", ident.name());
+ LOG.warn("Iceberg schema (database) {} does not exist", ident.name());
return false;
} catch (Exception e) {
throw new RuntimeException(e);
@@ -288,8 +306,19 @@ public class IcebergCatalogOperations implements CatalogOperations, SupportsSche
*/
@Override
public NameIdentifier[] listTables(Namespace namespace) throws NoSuchSchemaException {
- // TODO supported method.
- throw new UnsupportedOperationException();
+ try {
+ ListTablesResponse listTablesResponse =
+ icebergTableOps.listTable(IcebergTableOpsHelper.getIcebergNamespace(namespace.levels()));
+ return listTablesResponse.identifiers().stream()
+ .map(
+ tableIdentifier ->
+ NameIdentifier.of(
+ ArrayUtils.add(tableIdentifier.namespace().levels(), tableIdentifier.name())))
+ .toArray(NameIdentifier[]::new);
+ } catch (NoSuchNamespaceException e) {
+ throw new NoSuchSchemaException(
+ "Schema (database) does not exist " + namespace + " in Iceberg");
+ }
}
/**
@@ -301,13 +330,19 @@ public class IcebergCatalogOperations implements CatalogOperations, SupportsSche
*/
@Override
public Table loadTable(NameIdentifier tableIdent) throws NoSuchTableException {
- // TODO supported method.
- throw new UnsupportedOperationException();
- }
+ try {
- @Override
- public boolean tableExists(NameIdentifier ident) {
- return TableCatalog.super.tableExists(ident);
+ LoadTableResponse tableResponse =
+ icebergTableOps.loadTable(IcebergTableOpsHelper.buildIcebergTableIdentifier(tableIdent));
+ IcebergTable icebergTable =
+ IcebergTable.fromIcebergTable(tableResponse.tableMetadata(), tableIdent.name());
+
+ LOG.info("Loaded Iceberg table {}", tableIdent.name());
+ return icebergTable;
+ } catch (org.apache.iceberg.exceptions.NoSuchTableException e) {
+ throw new NoSuchTableException(
+ String.format("Iceberg table does not exist: %s", tableIdent.name()), e);
+ }
}
/**
@@ -322,8 +357,66 @@ public class IcebergCatalogOperations implements CatalogOperations, SupportsSche
@Override
public Table alterTable(NameIdentifier tableIdent, TableChange... changes)
throws NoSuchTableException, IllegalArgumentException {
- // TODO supported method.
- throw new UnsupportedOperationException();
+ Optional<TableChange> renameTableOptional =
+ Arrays.stream(changes)
+ .filter(tableChange -> tableChange instanceof TableChange.RenameTable)
+ .reduce((a, b) -> b);
+ if (renameTableOptional.isPresent()) {
+ String otherChange =
+ Arrays.stream(changes)
+ .filter(tableChange -> !(tableChange instanceof TableChange.RenameTable))
+ .map(String::valueOf)
+ .collect(Collectors.joining("\n"));
+ Preconditions.checkArgument(
+ StringUtils.isEmpty(otherChange),
+ String.format(
+ "The operation to change the table name cannot be performed together with other operations."
+ + "The list of operations that you cannot perform includes: \n %s",
+ otherChange));
+ return renameTable(tableIdent, (TableChange.RenameTable) renameTableOptional.get());
+ }
+ return internalUpdateTable(tableIdent, changes);
+ }
+
+ private Table internalUpdateTable(NameIdentifier tableIdent, TableChange... changes)
+ throws NoSuchTableException, IllegalArgumentException {
+ try {
+ IcebergTableOpsHelper.IcebergTableChange icebergTableChange =
+ icebergTableOpsHelper.buildIcebergTableChanges(tableIdent, changes);
+ LoadTableResponse loadTableResponse = icebergTableOps.updateTable(icebergTableChange);
+ loadTableResponse.validate();
+ return IcebergTable.fromIcebergTable(loadTableResponse.tableMetadata(), tableIdent.name());
+ } catch (org.apache.iceberg.exceptions.NoSuchTableException e) {
+ throw new NoSuchTableException(
+ String.format("Iceberg table does not exist: %s", tableIdent.name()), e);
+ }
+ }
+
+ /**
+ * Perform name change operations on the Iceberg.
+ *
+ * @param tableIdent tableIdent of this table.
+ * @param renameTable Table Change to modify the table name.
+ * @return Returns the table for Iceberg.
+ * @throws NoSuchTableException
+ * @throws IllegalArgumentException
+ */
+ private Table renameTable(NameIdentifier tableIdent, TableChange.RenameTable renameTable)
+ throws NoSuchTableException, IllegalArgumentException {
+ try {
+ RenameTableRequest renameTableRequest =
+ RenameTableRequest.builder()
+ .withSource(IcebergTableOpsHelper.buildIcebergTableIdentifier(tableIdent))
+ .withDestination(
+ IcebergTableOpsHelper.buildIcebergTableIdentifier(
+ tableIdent.namespace(), renameTable.getNewName()))
+ .build();
+ icebergTableOps.renameTable(renameTableRequest);
+ return loadTable(NameIdentifier.of(tableIdent.namespace(), renameTable.getNewName()));
+ } catch (org.apache.iceberg.exceptions.NoSuchTableException e) {
+ throw new NoSuchTableException(
+ String.format("Iceberg table does not exist: %s", tableIdent.name()), e);
+ }
}
/**
@@ -334,8 +427,15 @@ public class IcebergCatalogOperations implements CatalogOperations, SupportsSche
*/
@Override
public boolean dropTable(NameIdentifier tableIdent) {
- // TODO supported method.
- throw new UnsupportedOperationException();
+ try {
+ icebergTableOps.dropTable(
+ TableIdentifier.of(ArrayUtils.add(tableIdent.namespace().levels(), tableIdent.name())));
+ LOG.info("Dropped Iceberg table {}", tableIdent.name());
+ return true;
+ } catch (org.apache.iceberg.exceptions.NoSuchTableException e) {
+ LOG.warn("Iceberg table {} does not exist", tableIdent.name());
+ return false;
+ }
}
/**
@@ -346,7 +446,7 @@ public class IcebergCatalogOperations implements CatalogOperations, SupportsSche
* @param comment The comment for the new table.
* @param properties The properties for the new table.
* @param partitions The partitioning for the new table.
- * @return The newly created HiveTable instance.
+ * @return The newly created IcebergTable instance.
* @throws NoSuchSchemaException If the schema for the table does not exist.
* @throws TableAlreadyExistsException If the table with the same name already exists.
*/
@@ -360,7 +460,39 @@ public class IcebergCatalogOperations implements CatalogOperations, SupportsSche
Distribution distribution,
SortOrder[] sortOrders)
throws NoSuchSchemaException, TableAlreadyExistsException {
- throw new UnsupportedOperationException();
+ try {
+ NameIdentifier schemaIdent = NameIdentifier.of(tableIdent.namespace().levels());
+ if (!schemaExists(schemaIdent)) {
+ LOG.warn("Iceberg schema (database) does not exist: {}", schemaIdent);
+ throw new NoSuchSchemaException("Iceberg Schema (database) does not exist " + schemaIdent);
+ }
+
+ IcebergTable createdTable =
+ new IcebergTable.Builder()
+ .withName(tableIdent.name())
+ .withColumns(columns)
+ .withComment(comment)
+ .withPartitions(partitions)
+ .withSortOrders(sortOrders)
+ .withProperties(properties)
+ .withAuditInfo(
+ new AuditInfo.Builder()
+ .withCreator(currentUser())
+ .withCreateTime(Instant.now())
+ .build())
+ .build();
+
+ LoadTableResponse loadTableResponse =
+ icebergTableOps.createTable(
+ IcebergTableOpsHelper.getIcebergNamespace(tableIdent.namespace().levels()),
+ createdTable.toCreateTableRequest());
+ loadTableResponse.validate();
+
+ LOG.info("Created Iceberg table {}", tableIdent.name());
+ return createdTable;
+ } catch (AlreadyExistsException e) {
+ throw new TableAlreadyExistsException("Table already exists: " + tableIdent.name(), e);
+ }
}
/**
@@ -372,8 +504,15 @@ public class IcebergCatalogOperations implements CatalogOperations, SupportsSche
*/
@Override
public boolean purgeTable(NameIdentifier tableIdent) throws UnsupportedOperationException {
- // TODO supported method.
- throw new UnsupportedOperationException();
+ try {
+ icebergTableOps.purgeTable(
+ TableIdentifier.of(ArrayUtils.add(tableIdent.namespace().levels(), tableIdent.name())));
+ LOG.info("Purge Iceberg table {}", tableIdent.name());
+ return true;
+ } catch (org.apache.iceberg.exceptions.NoSuchTableException e) {
+ LOG.warn("Iceberg table {} does not exist", tableIdent.name());
+ return false;
+ }
}
// TODO. We should figure out a better way to get the current user from servlet container.
diff --git a/catalogs/catalog-lakehouse-iceberg/src/main/java/com/datastrato/graviton/catalog/lakehouse/iceberg/IcebergColumn.java b/catalogs/catalog-lakehouse-iceberg/src/main/java/com/datastrato/graviton/catalog/lakehouse/iceberg/IcebergColumn.java
new file mode 100644
index 0000000000..202cf555fb
--- /dev/null
+++ b/catalogs/catalog-lakehouse-iceberg/src/main/java/com/datastrato/graviton/catalog/lakehouse/iceberg/IcebergColumn.java
@@ -0,0 +1,61 @@
+/*
+ * Copyright 2023 Datastrato.
+ * This software is licensed under the Apache License version 2.
+ */
+package com.datastrato.graviton.catalog.lakehouse.iceberg;
+
+import com.datastrato.graviton.catalog.rel.BaseColumn;
+
+/** Represents a column in the Iceberg column. */
+public class IcebergColumn extends BaseColumn {
+
+ private int id;
+
+ private boolean optional;
+
+ private IcebergColumn() {}
+
+ public int getId() {
+ return id;
+ }
+
+ public boolean isOptional() {
+ return optional;
+ }
+
+ /** A builder class for constructing IcebergColumn instances. */
+ public static class Builder extends BaseColumnBuilder<Builder, IcebergColumn> {
+
+ /** The ID of this field. */
+ private int id;
+
+ /** Can the corresponding value of this field be null. */
+ private boolean optional;
+
+ public Builder withId(int id) {
+ this.id = id;
+ return this;
+ }
+
+ public Builder withOptional(boolean optional) {
+ this.optional = optional;
+ return this;
+ }
+
+ /**
+ * Internal method to build a IcebergColumn instance using the provided values.
+ *
+ * @return A new IcebergColumn instance with the configured values.
+ */
+ @Override
+ protected IcebergColumn internalBuild() {
+ IcebergColumn icebergColumn = new IcebergColumn();
+ icebergColumn.id = id;
+ icebergColumn.name = name;
+ icebergColumn.comment = comment;
+ icebergColumn.dataType = dataType;
+ icebergColumn.optional = optional;
+ return icebergColumn;
+ }
+ }
+}
diff --git a/catalogs/catalog-lakehouse-iceberg/src/main/java/com/datastrato/graviton/catalog/lakehouse/iceberg/IcebergSchema.java b/catalogs/catalog-lakehouse-iceberg/src/main/java/com/datastrato/graviton/catalog/lakehouse/iceberg/IcebergSchema.java
index 94856bf41f..84e8cf8831 100644
--- a/catalogs/catalog-lakehouse-iceberg/src/main/java/com/datastrato/graviton/catalog/lakehouse/iceberg/IcebergSchema.java
+++ b/catalogs/catalog-lakehouse-iceberg/src/main/java/com/datastrato/graviton/catalog/lakehouse/iceberg/IcebergSchema.java
@@ -12,7 +12,7 @@ import org.apache.commons.collections4.MapUtils;
import org.apache.iceberg.catalog.Namespace;
import org.apache.iceberg.rest.requests.CreateNamespaceRequest;
-/** Represents an Iceberg Schema (Database) entity in the Iceberg Metastore catalog. */
+/** Represents an Iceberg Schema (Database) entity in the Iceberg schema. */
@ToString
public class IcebergSchema extends BaseSchema {
diff --git a/catalogs/catalog-lakehouse-iceberg/src/main/java/com/datastrato/graviton/catalog/lakehouse/iceberg/IcebergTable.java b/catalogs/catalog-lakehouse-iceberg/src/main/java/com/datastrato/graviton/catalog/lakehouse/iceberg/IcebergTable.java
new file mode 100644
index 0000000000..c9d6ba57d2
--- /dev/null
+++ b/catalogs/catalog-lakehouse-iceberg/src/main/java/com/datastrato/graviton/catalog/lakehouse/iceberg/IcebergTable.java
@@ -0,0 +1,128 @@
+/*
+ * Copyright 2023 Datastrato.
+ * This software is licensed under the Apache License version 2.
+ */
+package com.datastrato.graviton.catalog.lakehouse.iceberg;
+
+import com.datastrato.graviton.catalog.lakehouse.iceberg.converter.ConvertUtil;
+import com.datastrato.graviton.catalog.lakehouse.iceberg.converter.FromIcebergPartitionSpec;
+import com.datastrato.graviton.catalog.lakehouse.iceberg.converter.FromIcebergSortOrder;
+import com.datastrato.graviton.catalog.lakehouse.iceberg.converter.ToIcebergPartitionSpec;
+import com.datastrato.graviton.catalog.lakehouse.iceberg.converter.ToIcebergSortOrder;
+import com.datastrato.graviton.catalog.lakehouse.iceberg.ops.IcebergTableOpsHelper;
+import com.datastrato.graviton.catalog.rel.BaseTable;
+import com.datastrato.graviton.meta.AuditInfo;
+import com.google.common.collect.Maps;
+import java.util.Map;
+import lombok.Getter;
+import lombok.ToString;
+import org.apache.iceberg.Schema;
+import org.apache.iceberg.TableMetadata;
+import org.apache.iceberg.rest.requests.CreateTableRequest;
+
+/** Represents an Iceberg Table entity in the Iceberg table. */
+@ToString
+@Getter
+public class IcebergTable extends BaseTable {
+
+ /**
+ * A reserved property to specify the location of the table. The files of the table should be
+ * under this location.
+ */
+ public static final String PROP_LOCATION = "location";
+
+ /** A reserved property to specify the provider of the table. */
+ public static final String PROP_PROVIDER = "provider";
+
+ /** The default provider of the table. */
+ public static final String DEFAULT_ICEBERG_PROVIDER = "iceberg";
+
+ public static final String ICEBERG_COMMENT_FIELD_NAME = "comment";
+
+ private String location;
+
+ private IcebergTable() {}
+
+ public CreateTableRequest toCreateTableRequest() {
+ Schema schema = ConvertUtil.toIcebergSchema(this);
+
+ Map<String, String> resultProperties =
+ Maps.newHashMap(IcebergTableOpsHelper.removeReservedProperties(properties));
+ CreateTableRequest.Builder builder =
+ CreateTableRequest.builder()
+ .withName(name)
+ .withLocation(location)
+ .withSchema(schema)
+ .setProperties(resultProperties)
+ .withPartitionSpec(ToIcebergPartitionSpec.toPartitionSpec(schema, partitions))
+ .withWriteOrder(ToIcebergSortOrder.toSortOrder(schema, sortOrders));
+ return builder.build();
+ }
+
+ /**
+ * Creates a new IcebergTable instance from a Table and a Builder.
+ *
+ * @param table The inner Table representing the IcebergTable.
+ * @param tableName The name of Table.
+ * @return A new IcebergTable instance.
+ */
+ public static IcebergTable fromIcebergTable(TableMetadata table, String tableName) {
+ Map<String, String> properties = table.properties();
+
+ Schema schema = table.schema();
+ IcebergColumn[] icebergColumns =
+ schema.columns().stream().map(ConvertUtil::fromNestedField).toArray(IcebergColumn[]::new);
+ return new IcebergTable.Builder()
+ .withComment(table.property(IcebergSchema.ICEBERG_COMMENT_FIELD_NAME, ""))
+ .withLocation(table.location())
+ .withProperties(properties)
+ .withColumns(icebergColumns)
+ .withName(tableName)
+ .withAuditInfo(AuditInfo.EMPTY)
+ .withPartitions(FromIcebergPartitionSpec.fromPartitionSpec(table.spec(), schema))
+ .withSortOrders(FromIcebergSortOrder.fromSortOrder(table.sortOrder()))
+ .build();
+ }
+
+ /** A builder class for constructing IcebergTable instances. */
+ public static class Builder extends BaseTableBuilder<Builder, IcebergTable> {
+
+ private String location;
+
+ public Builder withLocation(String location) {
+ this.location = location;
+ return this;
+ }
+
+ /**
+ * Internal method to build an IcebergTable instance using the provided values.
+ *
+ * @return A new IcebergTable instance with the configured values.
+ */
+ @Override
+ protected IcebergTable internalBuild() {
+ IcebergTable icebergTable = new IcebergTable();
+ icebergTable.name = name;
+ icebergTable.comment = comment;
+ icebergTable.properties =
+ properties != null ? Maps.newHashMap(properties) : Maps.newHashMap();
+ icebergTable.auditInfo = auditInfo;
+ icebergTable.columns = columns;
+ if (null != location) {
+ icebergTable.location = location;
+ } else {
+ icebergTable.location = icebergTable.properties.get(PROP_LOCATION);
+ }
+ icebergTable.partitions = partitions;
+ icebergTable.sortOrders = sortOrders;
+ if (null != comment) {
+ icebergTable.properties.putIfAbsent(ICEBERG_COMMENT_FIELD_NAME, comment);
+ }
+ String provider = icebergTable.properties.get(PROP_PROVIDER);
+ if (provider != null && !DEFAULT_ICEBERG_PROVIDER.equalsIgnoreCase(provider)) {
+ throw new IllegalArgumentException("Unsupported format in USING: " + provider);
+ }
+ return icebergTable;
+ }
+ }
+}
diff --git a/catalogs/catalog-lakehouse-iceberg/src/main/java/com/datastrato/graviton/catalog/lakehouse/iceberg/converter/ConvertUtil.java b/catalogs/catalog-lakehouse-iceberg/src/main/java/com/datastrato/graviton/catalog/lakehouse/iceberg/converter/ConvertUtil.java
new file mode 100644
index 0000000000..d20d1255c2
--- /dev/null
+++ b/catalogs/catalog-lakehouse-iceberg/src/main/java/com/datastrato/graviton/catalog/lakehouse/iceberg/converter/ConvertUtil.java
@@ -0,0 +1,62 @@
+/*
+ * Copyright 2023 Datastrato.
+ * This software is licensed under the Apache License version 2.
+ */
+package com.datastrato.graviton.catalog.lakehouse.iceberg.converter;
+
+import com.datastrato.graviton.catalog.lakehouse.iceberg.IcebergColumn;
+import com.datastrato.graviton.catalog.lakehouse.iceberg.IcebergTable;
+import org.apache.iceberg.Schema;
+import org.apache.iceberg.types.Type;
+import org.apache.iceberg.types.TypeUtil;
+import org.apache.iceberg.types.Types;
+
+public class ConvertUtil {
+
+ /**
+ * Convert the Iceberg Table to the corresponding schema information in the Iceberg.
+ *
+ * @param icebergTable Iceberg table.
+ * @return iceberg schema.
+ */
+ public static Schema toIcebergSchema(IcebergTable icebergTable) {
+ Type converted = ToIcebergTypeVisitor.visit(icebergTable, new ToIcebergType(icebergTable));
+ return new Schema(converted.asNestedType().asStructType().fields());
+ }
+
+ /**
+ * Convert the Graviton type to the Iceberg type.
+ *
+ * @param gravitonType
+ * @return Iceberg type.
+ */
+ public static Type toIcebergType(io.substrait.type.Type gravitonType) {
+ return ToIcebergTypeVisitor.visit(gravitonType, new ToIcebergType());
+ }
+
+ /**
+ * Convert the nested type of Iceberg to the type of graviton.
+ *
+ * @param type Iceberg type of field.
+ * @return
+ */
+ public static io.substrait.type.Type formIcebergType(Type type) {
+ return TypeUtil.visit(type, new FromIcebergType());
+ }
+
+ /**
+ * Convert the nested field of Iceberg to the Iceberg column.
+ *
+ * @param nestedField Iceberg nested field.
+ * @return
+ */
+ public static IcebergColumn fromNestedField(Types.NestedField nestedField) {
+ return new IcebergColumn.Builder()
+ .withId(nestedField.fieldId())
+ .withName(nestedField.name())
+ .withOptional(nestedField.isOptional())
+ .withComment(nestedField.doc())
+ .withType(ConvertUtil.formIcebergType(nestedField.type()))
+ .build();
+ }
+}
diff --git a/catalogs/catalog-lakehouse-iceberg/src/main/java/com/datastrato/graviton/catalog/lakehouse/iceberg/converter/FromIcebergPartitionSpec.java b/catalogs/catalog-lakehouse-iceberg/src/main/java/com/datastrato/graviton/catalog/lakehouse/iceberg/converter/FromIcebergPartitionSpec.java
new file mode 100644
index 0000000000..0deffba1cc
--- /dev/null
+++ b/catalogs/catalog-lakehouse-iceberg/src/main/java/com/datastrato/graviton/catalog/lakehouse/iceberg/converter/FromIcebergPartitionSpec.java
@@ -0,0 +1,106 @@
+/*
+ * Copyright 2023 Datastrato.
+ * This software is licensed under the Apache License version 2.
+ */
+package com.datastrato.graviton.catalog.lakehouse.iceberg.converter;
+
+import static io.substrait.expression.ExpressionCreator.i32;
+
+import com.datastrato.graviton.rel.transforms.Transform;
+import com.datastrato.graviton.rel.transforms.Transforms;
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.Lists;
+import java.util.List;
+import java.util.Map;
+import org.apache.iceberg.PartitionField;
+import org.apache.iceberg.PartitionSpec;
+import org.apache.iceberg.Schema;
+import org.apache.iceberg.transforms.PartitionSpecVisitor;
+
+/**
+ * Convert IcebergTransform to GravitonTransform.
+ *
+ * <p>Referred from
+ * core/src/main/java/org/apache/iceberg/spark/Spark3Util/SpecTransformToSparkTransform.java
+ */
+public class FromIcebergPartitionSpec implements PartitionSpecVisitor<Transform> {
+
+ private final Map<Integer, String> idToName;
+
+ public FromIcebergPartitionSpec(Map<Integer, String> idToName) {
+ this.idToName = idToName;
+ }
+
+ @Override
+ public Transform identity(String sourceName, int sourceId) {
+ return Transforms.identity(new String[] {idToName.get(sourceId)});
+ }
+
+ @Override
+ public Transform bucket(String sourceName, int sourceId, int numBuckets) {
+ Transforms.LiteralReference bucketNum = Transforms.literal(i32(false, numBuckets));
+ Transforms.NamedReference field = Transforms.field(new String[] {idToName.get(sourceId)});
+ // bucket(fieldName, bucketNum)
+ return Transforms.function("bucket", new Transform[] {field, bucketNum});
+ }
+
+ @Override
+ public Transform truncate(String sourceName, int sourceId, int width) {
+ Transforms.LiteralReference bucketNum = Transforms.literal(i32(false, width));
+ Transforms.NamedReference field = Transforms.field(new String[] {idToName.get(sourceId)});
+ return Transforms.function("truncate", new Transform[] {field, bucketNum});
+ }
+
+ @Override
+ public Transform year(String sourceName, int sourceId) {
+ return Transforms.year(new String[] {idToName.get(sourceId)});
+ }
+
+ @Override
+ public Transform month(String sourceName, int sourceId) {
+ return Transforms.month(new String[] {idToName.get(sourceId)});
+ }
+
+ @Override
+ public Transform day(String sourceName, int sourceId) {
+ return Transforms.day(new String[] {idToName.get(sourceId)});
+ }
+
+ @Override
+ public Transform hour(String sourceName, int sourceId) {
+ return Transforms.hour(new String[] {idToName.get(sourceId)});
+ }
+
+ @Override
+ public Transform alwaysNull(int fieldId, String sourceName, int sourceId) {
+ // do nothing for alwaysNull, it doesn't need to be converted to a transform
+ return null;
+ }
+
+ @Override
+ public Transform unknown(int fieldId, String sourceName, int sourceId, String transform) {
+ throw new UnsupportedOperationException("Unsupported Transform conversion type.");
+ }
+
+ /**
+ * Transform assembled into graviton.
+ *
+ * @param partitionSpec
+ * @param schema
+ * @return
+ */
+ @VisibleForTesting
+ public static Transform[] fromPartitionSpec(PartitionSpec partitionSpec, Schema schema) {
+ FromIcebergPartitionSpec visitor = new FromIcebergPartitionSpec(schema.idToName());
+ List<Transform> transforms = Lists.newArrayList();
+ List<PartitionField> fields = partitionSpec.fields();
+
+ for (PartitionField field : fields) {
+ Transform transform = PartitionSpecVisitor.visit(schema, field, visitor);
+ if (transform != null) {
+ transforms.add(transform);
+ }
+ }
+ return transforms.toArray(new Transform[0]);
+ }
+}
diff --git a/catalogs/catalog-lakehouse-iceberg/src/main/java/com/datastrato/graviton/catalog/lakehouse/iceberg/converter/FromIcebergSortOrder.java b/catalogs/catalog-lakehouse-iceberg/src/main/java/com/datastrato/graviton/catalog/lakehouse/iceberg/converter/FromIcebergSortOrder.java
new file mode 100644
index 0000000000..7171342daf
--- /dev/null
+++ b/catalogs/catalog-lakehouse-iceberg/src/main/java/com/datastrato/graviton/catalog/lakehouse/iceberg/converter/FromIcebergSortOrder.java
@@ -0,0 +1,100 @@
+/*
+ * Copyright 2023 Datastrato.
+ * This software is licensed under the Apache License version 2.
+ */
+package com.datastrato.graviton.catalog.lakehouse.iceberg.converter;
+
+import com.datastrato.graviton.rel.SortOrder;
+import com.datastrato.graviton.rel.transforms.Transforms;
+import com.google.common.annotations.VisibleForTesting;
+import java.util.List;
+import java.util.Map;
+import org.apache.iceberg.NullOrder;
+import org.apache.iceberg.Schema;
+import org.apache.iceberg.SortDirection;
+import org.apache.iceberg.transforms.SortOrderVisitor;
+
+/**
+ * Implement iceberg sort order converter to graviton sort order.
+ *
+ * <p>Referred from core/src/main/java/org/apache/iceberg/spark/SortOrderToSpark.java
+ */
+public class FromIcebergSortOrder implements SortOrderVisitor<SortOrder> {
+
+ private final Map<Integer, String> idToName;
+
+ public FromIcebergSortOrder(Schema schema) {
+ this.idToName = schema.idToName();
+ }
+
+ @Override
+ public SortOrder field(String sourceName, int id, SortDirection direction, NullOrder nullOrder) {
+ return fieldSortOrder(id, direction, nullOrder);
+ }
+
+ @Override
+ public SortOrder bucket(
+ String sourceName, int id, int width, SortDirection direction, NullOrder nullOrder) {
+ return functionSortOrder("bucket", id, direction, nullOrder);
+ }
+
+ @Override
+ public SortOrder truncate(
+ String sourceName, int id, int width, SortDirection direction, NullOrder nullOrder) {
+ return functionSortOrder("truncate", id, direction, nullOrder);
+ }
+
+ @Override
+ public SortOrder year(String sourceName, int id, SortDirection direction, NullOrder nullOrder) {
+ return functionSortOrder(Transforms.NAME_OF_YEAR, id, direction, nullOrder);
+ }
+
+ @Override
+ public SortOrder month(String sourceName, int id, SortDirection direction, NullOrder nullOrder) {
+ return functionSortOrder(Transforms.NAME_OF_MONTH, id, direction, nullOrder);
+ }
+
+ @Override
+ public SortOrder day(String sourceName, int id, SortDirection direction, NullOrder nullOrder) {
+ return functionSortOrder(Transforms.NAME_OF_DAY, id, direction, nullOrder);
+ }
+
+ @Override
+ public SortOrder hour(String sourceName, int id, SortDirection direction, NullOrder nullOrder) {
+ return functionSortOrder(Transforms.NAME_OF_HOUR, id, direction, nullOrder);
+ }
+
+ private SortOrder fieldSortOrder(int id, SortDirection direction, NullOrder nullOrder) {
+ return SortOrder.fieldSortOrder(
+ new String[] {idToName.get(id)}, toGraviton(direction), toGraviton(nullOrder));
+ }
+
+ private SortOrder functionSortOrder(
+ String name, int id, SortDirection direction, NullOrder nullOrder) {
+ return SortOrder.functionSortOrder(
+ name, new String[] {idToName.get(id)}, toGraviton(direction), toGraviton(nullOrder));
+ }
+
+ private SortOrder.Direction toGraviton(SortDirection direction) {
+ return direction == SortDirection.ASC ? SortOrder.Direction.ASC : SortOrder.Direction.DESC;
+ }
+
+ private SortOrder.NullOrdering toGraviton(NullOrder nullOrder) {
+ return nullOrder == NullOrder.NULLS_FIRST
+ ? SortOrder.NullOrdering.FIRST
+ : SortOrder.NullOrdering.LAST;
+ }
+
+ /**
+ * Convert Iceberg order to Graviton.
+ *
+ * @param sortOrder
+ * @return Graviton sort order
+ */
+ @VisibleForTesting
+ public static SortOrder[] fromSortOrder(org.apache.iceberg.SortOrder sortOrder) {
+ FromIcebergSortOrder visitor = new FromIcebergSortOrder(sortOrder.schema());
+ List<SortOrder> ordering = SortOrderVisitor.visit(sortOrder, visitor);
+ return ordering.toArray(new SortOrder[0]);
+ }
+}
diff --git a/catalogs/catalog-lakehouse-iceberg/src/main/java/com/datastrato/graviton/catalog/lakehouse/iceberg/converter/FromIcebergType.java b/catalogs/catalog-lakehouse-iceberg/src/main/java/com/datastrato/graviton/catalog/lakehouse/iceberg/converter/FromIcebergType.java
new file mode 100644
index 0000000000..ecad1d0e7c
--- /dev/null
+++ b/catalogs/catalog-lakehouse-iceberg/src/main/java/com/datastrato/graviton/catalog/lakehouse/iceberg/converter/FromIcebergType.java
@@ -0,0 +1,97 @@
+/*
+ * Copyright 2023 Datastrato.
+ * This software is licensed under the Apache License version 2.
+ */
+package com.datastrato.graviton.catalog.lakehouse.iceberg.converter;
+
+import io.substrait.type.Type;
+import io.substrait.type.TypeCreator;
+import java.util.List;
+import org.apache.iceberg.Schema;
+import org.apache.iceberg.types.TypeUtil;
+import org.apache.iceberg.types.Types;
+
+/**
+ * Implement a type converter to convert types in Iceberg.
+ *
+ * <p>Referred from core/src/main/java/org/apache/iceberg/spark/TypeToSparkType.java
+ */
+public class FromIcebergType extends TypeUtil.SchemaVisitor<Type> {
+
+ public FromIcebergType() {}
+
+ @Override
+ public Type schema(Schema schema, Type structType) {
+ throw new UnsupportedOperationException("Data conversion of schema type is not supported");
+ }
+
+ @Override
+ public Type struct(Types.StructType struct, List<Type> fieldResults) {
+ throw new UnsupportedOperationException("Data conversion of struct type is not supported");
+ }
+
+ @Override
+ public Type field(Types.NestedField field, Type fieldResult) {
+ return fieldResult;
+ }
+
+ @Override
+ public Type list(Types.ListType list, Type elementResult) {
+ if (list.isElementOptional()) {
+ return TypeCreator.NULLABLE.list(elementResult);
+ } else {
+ return TypeCreator.REQUIRED.list(elementResult);
+ }
+ }
+
+ @Override
+ public Type map(Types.MapType map, Type keyResult, Type valueResult) {
+ if (map.isValueOptional()) {
+ return TypeCreator.NULLABLE.map(keyResult, valueResult);
+ } else {
+ return TypeCreator.REQUIRED.map(keyResult, valueResult);
+ }
+ }
+
+ @Override
+ public Type primitive(org.apache.iceberg.types.Type.PrimitiveType primitive) {
+ switch (primitive.typeId()) {
+ case BOOLEAN:
+ return TypeCreator.NULLABLE.BOOLEAN;
+ case INTEGER:
+ return TypeCreator.NULLABLE.I32;
+ case LONG:
+ return TypeCreator.NULLABLE.I64;
+ case FLOAT:
+ return TypeCreator.NULLABLE.FP32;
+ case DOUBLE:
+ return TypeCreator.NULLABLE.FP64;
+ case DATE:
+ return TypeCreator.NULLABLE.DATE;
+ case TIME:
+ return TypeCreator.NULLABLE.TIME;
+ case TIMESTAMP:
+ Types.TimestampType ts = (Types.TimestampType) primitive;
+ if (ts.shouldAdjustToUTC()) {
+ return TypeCreator.NULLABLE.TIMESTAMP_TZ;
+ } else {
+ return TypeCreator.NULLABLE.TIMESTAMP;
+ }
+ case STRING:
+ return TypeCreator.NULLABLE.STRING;
+ case UUID:
+ return TypeCreator.NULLABLE.UUID;
+ case FIXED:
+ Types.FixedType fixedType = (Types.FixedType) primitive;
+ return TypeCreator.NULLABLE.fixedChar(fixedType.length());
+ case BINARY:
+ return TypeCreator.NULLABLE.BINARY;
+ case DECIMAL:
+ Types.DecimalType decimal = (Types.DecimalType) primitive;
+ return TypeCreator.NULLABLE.decimal(decimal.precision(), decimal.scale());
+ default:
+ throw new UnsupportedOperationException(
+ "Cannot convert unknown type to Graviton: " + primitive);
+ }
+ }
+}
diff --git a/catalogs/catalog-lakehouse-iceberg/src/main/java/com/datastrato/graviton/catalog/lakehouse/iceberg/converter/ToIcebergPartitionSpec.java b/catalogs/catalog-lakehouse-iceberg/src/main/java/com/datastrato/graviton/catalog/lakehouse/iceberg/converter/ToIcebergPartitionSpec.java
new file mode 100644
index 0000000000..0ed71cdb1a
--- /dev/null
+++ b/catalogs/catalog-lakehouse-iceberg/src/main/java/com/datastrato/graviton/catalog/lakehouse/iceberg/converter/ToIcebergPartitionSpec.java
@@ -0,0 +1,131 @@
+/*
+ * Copyright 2023 Datastrato.
+ * This software is licensed under the Apache License version 2.
+ */
+package com.datastrato.graviton.catalog.lakehouse.iceberg.converter;
+
+import com.datastrato.graviton.catalog.lakehouse.iceberg.IcebergTable;
+import com.datastrato.graviton.rel.transforms.Transform;
+import com.datastrato.graviton.rel.transforms.Transforms;
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.base.Preconditions;
+import io.substrait.expression.ImmutableExpression;
+import java.util.Arrays;
+import java.util.Locale;
+import java.util.stream.Collectors;
+import org.apache.iceberg.PartitionSpec;
+import org.apache.iceberg.Schema;
+
+/** Convert Graviton Transforms to Iceberg PartitionSpec. */
+public class ToIcebergPartitionSpec {
+
+ private static final String DOT = ".";
+
+ /**
+ * Convert iceberg table to iceberg partition spec through graviton.
+ *
+ * @param icebergTable the iceberg table.
+ * @return
+ */
+ @VisibleForTesting
+ public static PartitionSpec toPartitionSpec(IcebergTable icebergTable) {
+ Schema schema = ConvertUtil.toIcebergSchema(icebergTable);
+ return ToIcebergPartitionSpec.toPartitionSpec(schema, icebergTable.partitioning());
+ }
+
+ /**
+ * Converts graviton transforms into a {@link PartitionSpec}.
+ *
+ * @param schema the table schema
+ * @param partitioning Graviton Transforms
+ * @return a PartitionSpec
+ */
+ @VisibleForTesting
+ public static PartitionSpec toPartitionSpec(Schema schema, Transform[] partitioning) {
+ if (partitioning == null || partitioning.length == 0) {
+ return PartitionSpec.unpartitioned();
+ }
+ PartitionSpec.Builder builder = PartitionSpec.builderFor(schema);
+ for (Transform transform : partitioning) {
+ if (transform instanceof Transforms.NamedReference) {
+ String[] fieldName = ((Transforms.NamedReference) transform).value();
+ Preconditions.checkArgument(
+ fieldName.length == 1, "Iceberg partition does not support nested field", transform);
+ String colName = String.join(DOT, fieldName);
+ builder.identity(colName);
+ } else if (transform instanceof Transforms.FunctionTrans) {
+ Preconditions.checkArgument(
+ transform.arguments().length == 1,
+ "Iceberg partition does not support nested field",
+ transform);
+ String colName =
+ Arrays.stream(transform.arguments())
+ .map(t -> ((Transforms.NamedReference) t).value()[0])
+ .collect(Collectors.joining(DOT));
+ switch (transform.name().toLowerCase(Locale.ROOT)) {
+ // TODO minghuang add support for other transforms.
+ case "identity":
+ builder.identity(colName);
+ break;
+ case "bucket":
+ builder.bucket(colName, findWidth(transform));
+ break;
+ case Transforms.NAME_OF_YEAR:
+ builder.year(colName);
+ break;
+ case Transforms.NAME_OF_MONTH:
+ builder.month(colName);
+ break;
+ case Transforms.NAME_OF_DAY:
+ builder.day(colName);
+ break;
+ case Transforms.NAME_OF_HOUR:
+ builder.hour(colName);
+ break;
+ case "truncate":
+ builder.truncate(colName, findWidth(transform));
+ break;
+ default:
+ throw new UnsupportedOperationException(
+ "Transform is not supported: " + transform.name());
+ }
+ } else {
+ throw new UnsupportedOperationException("Transform is not supported: " + transform.name());
+ }
+ }
+ return builder.build();
+ }
+
+ private static int findWidth(Transform transform) {
+ Preconditions.checkArgument(
+ transform.arguments().length == 1, "Transform with multiple arguments is not supported");
+ Transform expr = transform.arguments()[0];
+ if (expr instanceof Transforms.LiteralReference) {
+ Transforms.LiteralReference literalReference = (Transforms.LiteralReference) expr;
+ if (literalReference.value() instanceof ImmutableExpression.I8Literal) {
+ int val =
+ ((ImmutableExpression.I8Literal) ((Transforms.LiteralReference) expr).value()).value();
+ checkTransformArgument(val > 0, transform);
+ return val;
+ } else if (literalReference.value() instanceof ImmutableExpression.I16Literal) {
+ int val = ((ImmutableExpression.I16Literal) literalReference.value()).value();
+ checkTransformArgument(val > 0, transform);
+ return val;
+ } else if (literalReference.value() instanceof ImmutableExpression.I32Literal) {
+ int val = ((ImmutableExpression.I32Literal) literalReference.value()).value();
+ checkTransformArgument(val > 0, transform);
+ return val;
+
+ } else if (literalReference.value() instanceof ImmutableExpression.I64Literal) {
+ long val = ((ImmutableExpression.I64Literal) literalReference.value()).value();
+ checkTransformArgument(val > 0 && val < Integer.MAX_VALUE, transform);
+ return Math.toIntExact(val);
+ }
+ }
+ throw new IllegalArgumentException("Cannot find width for transform: " + transform.name());
+ }
+
+ private static void checkTransformArgument(boolean val, Transform transform) {
+ Preconditions.checkArgument(val, "Unsupported width for transform: %s", transform.name());
+ }
+}
diff --git a/catalogs/catalog-lakehouse-iceberg/src/main/java/com/datastrato/graviton/catalog/lakehouse/iceberg/converter/ToIcebergSortOrder.java b/catalogs/catalog-lakehouse-iceberg/src/main/java/com/datastrato/graviton/catalog/lakehouse/iceberg/converter/ToIcebergSortOrder.java
new file mode 100644
index 0000000000..eb5e6fda66
--- /dev/null
+++ b/catalogs/catalog-lakehouse-iceberg/src/main/java/com/datastrato/graviton/catalog/lakehouse/iceberg/converter/ToIcebergSortOrder.java
@@ -0,0 +1,108 @@
+/*
+ * Copyright 2023 Datastrato.
+ * This software is licensed under the Apache License version 2.
+ */
+package com.datastrato.graviton.catalog.lakehouse.iceberg.converter;
+
+import com.datastrato.graviton.rel.SortOrder;
+import com.datastrato.graviton.rel.transforms.Transform;
+import com.datastrato.graviton.rel.transforms.Transforms;
+import com.google.common.base.Preconditions;
+import io.substrait.expression.Expression;
+import java.util.Arrays;
+import java.util.Locale;
+import java.util.stream.Collectors;
+import org.apache.commons.lang3.ArrayUtils;
+import org.apache.iceberg.NullOrder;
+import org.apache.iceberg.Schema;
+import org.apache.iceberg.SortDirection;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.expressions.UnboundTerm;
+
+/** Implement iceberg sort order converter to graviton sort order. */
+public class ToIcebergSortOrder {
+
+ private static final String DOT = ".";
+
+ /**
+ * Convert Graviton order to Iceberg.
+ *
+ * @param schema Iceberg schema.
+ * @param sortOrders Graviton sort order.
+ * @return Iceberg sort order.
+ */
+ public static org.apache.iceberg.SortOrder toSortOrder(Schema schema, SortOrder[] sortOrders) {
+ if (ArrayUtils.isEmpty(sortOrders)) {
+ return null;
+ }
+ org.apache.iceberg.SortOrder.Builder sortOrderBuilder =
+ org.apache.iceberg.SortOrder.builderFor(schema);
+ for (SortOrder sortOrder : sortOrders) {
+ Transform transform = sortOrder.getTransform();
+ if (transform instanceof Transforms.NamedReference) {
+ String fieldName = String.join(DOT, ((Transforms.NamedReference) transform).value());
+ sortOrderBuilder.sortBy(
+ fieldName, toIceberg(sortOrder.getDirection()), toIceberg(sortOrder.getNullOrdering()));
+ } else if (transform instanceof Transforms.FunctionTrans) {
+ Preconditions.checkArgument(
+ transform.arguments().length == 1,
+ "Iceberg sort order does not support nested field",
+ transform);
+ String colName =
+ Arrays.stream(transform.arguments())
+ .map(t -> ((Transforms.NamedReference) t).value()[0])
+ .collect(Collectors.joining(DOT));
+ UnboundTerm<Object> expression;
+ switch (transform.name().toLowerCase(Locale.ROOT)) {
+ // TODO minghuang - add more functions implementation.
+ case "bucket":
+ int numBuckets =
+ ((Expression.I32Literal)
+ ((Transforms.LiteralReference) transform.arguments()[0]).value())
+ .value();
+ expression = Expressions.bucket(colName, numBuckets);
+ break;
+ case "truncate":
+ int width =
+ ((Expression.I32Literal)
+ ((Transforms.LiteralReference) transform.arguments()[0]).value())
+ .value();
+ expression = Expressions.truncate(colName, width);
+ break;
+ case Transforms.NAME_OF_YEAR:
+ expression = Expressions.year(colName);
+ break;
+ case Transforms.NAME_OF_MONTH:
+ expression = Expressions.month(colName);
+ break;
+ case Transforms.NAME_OF_DAY:
+ expression = Expressions.day(colName);
+ break;
+ case Transforms.NAME_OF_HOUR:
+ expression = Expressions.hour(colName);
+ break;
+ default:
+ throw new UnsupportedOperationException(
+ "Transform is not supported: " + transform.name());
+ }
+ sortOrderBuilder.sortBy(
+ expression,
+ toIceberg(sortOrder.getDirection()),
+ toIceberg(sortOrder.getNullOrdering()));
+ } else {
+ throw new UnsupportedOperationException("Transform is not supported: " + transform.name());
+ }
+ }
+ return sortOrderBuilder.build();
+ }
+
+ private static NullOrder toIceberg(SortOrder.NullOrdering nullOrdering) {
+ return nullOrdering == SortOrder.NullOrdering.FIRST
+ ? NullOrder.NULLS_FIRST
+ : NullOrder.NULLS_LAST;
+ }
+
+ private static SortDirection toIceberg(SortOrder.Direction direction) {
+ return direction == SortOrder.Direction.ASC ? SortDirection.ASC : SortDirection.DESC;
+ }
+}
diff --git a/catalogs/catalog-lakehouse-iceberg/src/main/java/com/datastrato/graviton/catalog/lakehouse/iceberg/converter/ToIcebergType.java b/catalogs/catalog-lakehouse-iceberg/src/main/java/com/datastrato/graviton/catalog/lakehouse/iceberg/converter/ToIcebergType.java
new file mode 100644
index 0000000000..6d0a9443d8
--- /dev/null
+++ b/catalogs/catalog-lakehouse-iceberg/src/main/java/com/datastrato/graviton/catalog/lakehouse/iceberg/converter/ToIcebergType.java
@@ -0,0 +1,124 @@
+/*
+ * Copyright 2023 Datastrato.
+ * This software is licensed under the Apache License version 2.
+ */
+package com.datastrato.graviton.catalog.lakehouse.iceberg.converter;
+
+import com.datastrato.graviton.catalog.lakehouse.iceberg.IcebergColumn;
+import com.datastrato.graviton.catalog.lakehouse.iceberg.IcebergTable;
+import com.google.common.collect.Lists;
+import java.util.Arrays;
+import java.util.List;
+import java.util.stream.Collectors;
+import org.apache.iceberg.types.Type;
+import org.apache.iceberg.types.Types;
+
+/**
+ * Convert Graviton types to iceberg types.
+ *
+ * <p>Referred from core/src/main/java/org/apache/iceberg/spark/SparkTypeToType.java
+ */
+public class ToIcebergType extends ToIcebergTypeVisitor<Type> {
+ private final IcebergTable root;
+ private int nextId = 0;
+
+ public ToIcebergType() {
+ this.root = null;
+ }
+
+ public ToIcebergType(IcebergTable root) {
+ this.root = root;
+ // the root struct's fields use the first ids
+ this.nextId = root.columns().length;
+ }
+
+ private int getNextId() {
+ return nextId++;
+ }
+
+ @Override
+ public Type struct(IcebergTable struct, List<Type> types) {
+ List<IcebergColumn> fields =
+ Arrays.stream(struct.columns())
+ .map(column -> (IcebergColumn) column)
+ .collect(Collectors.toList());
+ List<Types.NestedField> newFields = Lists.newArrayListWithExpectedSize(fields.size());
+ boolean isRoot = root == struct;
+
+ for (int i = 0; i < fields.size(); i += 1) {
+ IcebergColumn field = fields.get(i);
+ Type type = types.get(i);
+
+ // for new conversions, use ordinals for ids in the root struct
+ int id = isRoot ? i : getNextId();
+ if (field.isOptional()) {
+ newFields.add(Types.NestedField.optional(id, field.name(), type, field.comment()));
+ } else {
+ newFields.add(Types.NestedField.required(id, field.name(), type, field.comment()));
+ }
+ }
+ return Types.StructType.of(newFields);
+ }
+
+ @Override
+ public Type field(IcebergColumn field, Type typeResult) {
+ return typeResult;
+ }
+
+ @Override
+ public Type array(io.substrait.type.Type.ListType array, Type elementType) {
+ if (array.nullable()) {
+ return Types.ListType.ofOptional(getNextId(), elementType);
+ } else {
+ return Types.ListType.ofRequired(getNextId(), elementType);
+ }
+ }
+
+ @Override
+ public Type map(io.substrait.type.Type.Map map, Type keyType, Type valueType) {
+ if (map.nullable()) {
+ return Types.MapType.ofOptional(getNextId(), getNextId(), keyType, valueType);
+ } else {
+ return Types.MapType.ofRequired(getNextId(), getNextId(), keyType, valueType);
+ }
+ }
+
+ @Override
+ public Type atomic(io.substrait.type.Type primitive) {
+ if (primitive instanceof io.substrait.type.Type.Bool) {
+ return Types.BooleanType.get();
+ } else if (primitive instanceof io.substrait.type.Type.I8
+ || primitive instanceof io.substrait.type.Type.I16
+ || primitive instanceof io.substrait.type.Type.I32) {
+ return Types.IntegerType.get();
+ } else if (primitive instanceof io.substrait.type.Type.I64) {
+ return Types.LongType.get();
+ } else if (primitive instanceof io.substrait.type.Type.FP32) {
+ return Types.FloatType.get();
+ } else if (primitive instanceof io.substrait.type.Type.FP64) {
+ return Types.DoubleType.get();
+ } else if (primitive instanceof io.substrait.type.Type.Str
+ || primitive instanceof io.substrait.type.Type.VarChar) {
+ return Types.StringType.get();
+ } else if (primitive instanceof io.substrait.type.Type.Date) {
+ return Types.DateType.get();
+ } else if (primitive instanceof io.substrait.type.Type.Time) {
+ return Types.TimeType.get();
+ } else if (primitive instanceof io.substrait.type.Type.TimestampTZ) {
+ return Types.TimestampType.withZone();
+ } else if (primitive instanceof io.substrait.type.Type.Timestamp) {
+ return Types.TimestampType.withoutZone();
+ } else if (primitive instanceof io.substrait.type.Type.Decimal) {
+ return Types.DecimalType.of(
+ ((io.substrait.type.Type.Decimal) primitive).precision(),
+ ((io.substrait.type.Type.Decimal) primitive).scale());
+ } else if (primitive instanceof io.substrait.type.Type.FixedChar) {
+ return Types.FixedType.ofLength(((io.substrait.type.Type.FixedChar) primitive).length());
+ } else if (primitive instanceof io.substrait.type.Type.Binary) {
+ return Types.BinaryType.get();
+ } else if (primitive instanceof io.substrait.type.Type.UUID) {
+ return Types.UUIDType.get();
+ }
+ throw new UnsupportedOperationException("Not a supported type: " + primitive.toString());
+ }
+}
diff --git a/catalogs/catalog-lakehouse-iceberg/src/main/java/com/datastrato/graviton/catalog/lakehouse/iceberg/converter/ToIcebergTypeVisitor.java b/catalogs/catalog-lakehouse-iceberg/src/main/java/com/datastrato/graviton/catalog/lakehouse/iceberg/converter/ToIcebergTypeVisitor.java
new file mode 100644
index 0000000000..47d10296b2
--- /dev/null
+++ b/catalogs/catalog-lakehouse-iceberg/src/main/java/com/datastrato/graviton/catalog/lakehouse/iceberg/converter/ToIcebergTypeVisitor.java
@@ -0,0 +1,78 @@
+/*
+ * Copyright 2023 Datastrato.
+ * This software is licensed under the Apache License version 2.
+ */
+package com.datastrato.graviton.catalog.lakehouse.iceberg.converter;
+
+import com.datastrato.graviton.catalog.lakehouse.iceberg.IcebergColumn;
+import com.datastrato.graviton.catalog.lakehouse.iceberg.IcebergTable;
+import com.datastrato.graviton.rel.Column;
+import com.google.common.collect.Lists;
+import io.substrait.type.Type;
+import java.util.List;
+
+/**
+ * Type converter belonging to graviton.
+ *
+ * <p>Referred from core/src/main/java/org/apache/iceberg/spark/SparkTypeVisitor.java
+ */
+public class ToIcebergTypeVisitor<T> {
+
+ /**
+ * Traverse the graviton table and convert the fields into iceberg fields.
+ *
+ * @param table iceberg table.
+ * @param visitor
+ * @param <T>
+ * @return
+ */
+ public static <T> T visit(IcebergTable table, ToIcebergTypeVisitor<T> visitor) {
+ Column[] columns = table.columns();
+ List<T> fieldResults = Lists.newArrayListWithExpectedSize(columns.length);
+
+ for (Column field : columns) {
+ fieldResults.add(visitor.field((IcebergColumn) field, visit(field.dataType(), visitor)));
+ }
+ return visitor.struct(table, fieldResults);
+ }
+
+ /**
+ * Convert the type mapping of graviton to Iceberg.
+ *
+ * @param type TODO Abstract a data type in a graviton.
+ * @param visitor
+ * @return
+ * @param <T>
+ */
+ public static <T> T visit(Type type, ToIcebergTypeVisitor<T> visitor) {
+ if (type instanceof Type.Map) {
+ Type.Map map = (Type.Map) type;
+ return visitor.map(map, visit(map.key(), visitor), visit(map.value(), visitor));
+ } else if (type instanceof Type.ListType) {
+ Type.ListType list = (Type.ListType) type;
+ return visitor.array(list, visit(list.elementType(), visitor));
+ } else {
+ return visitor.atomic(type);
+ }
+ }
+
+ public T struct(IcebergTable struct, List<T> fieldResults) {
+ throw new UnsupportedOperationException();
+ }
+
+ public T field(IcebergColumn field, T typeResult) {
+ throw new UnsupportedOperationException();
+ }
+
+ public T array(Type.ListType array, T elementResult) {
+ throw new UnsupportedOperationException();
+ }
+
+ public T map(Type.Map map, T keyResult, T valueResult) {
+ throw new UnsupportedOperationException();
+ }
+
+ public T atomic(Type primitive) {
+ throw new UnsupportedOperationException();
+ }
+}
diff --git a/catalogs/catalog-lakehouse-iceberg/src/main/java/com/datastrato/graviton/catalog/lakehouse/iceberg/ops/IcebergTableOpsHelper.java b/catalogs/catalog-lakehouse-iceberg/src/main/java/com/datastrato/graviton/catalog/lakehouse/iceberg/ops/IcebergTableOpsHelper.java
index a18d3df448..53d9178ba5 100644
--- a/catalogs/catalog-lakehouse-iceberg/src/main/java/com/datastrato/graviton/catalog/lakehouse/iceberg/ops/IcebergTableOpsHelper.java
+++ b/catalogs/catalog-lakehouse-iceberg/src/main/java/com/datastrato/graviton/catalog/lakehouse/iceberg/ops/IcebergTableOpsHelper.java
@@ -6,6 +6,7 @@
package com.datastrato.graviton.catalog.lakehouse.iceberg.ops;
import com.datastrato.graviton.NameIdentifier;
+import com.datastrato.graviton.catalog.lakehouse.iceberg.converter.ConvertUtil;
import com.datastrato.graviton.rel.TableChange;
import com.datastrato.graviton.rel.TableChange.AddColumn;
import com.datastrato.graviton.rel.TableChange.After;
@@ -25,13 +26,11 @@ import com.google.common.base.Joiner;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Lists;
-import io.substrait.type.Type;
-import io.substrait.type.Type.Binary;
-import io.substrait.type.Type.I32;
-import io.substrait.type.Type.I64;
import java.util.Arrays;
import java.util.List;
+import java.util.Map;
import java.util.Set;
+import java.util.stream.Collectors;
import javax.ws.rs.NotSupportedException;
import lombok.Getter;
import lombok.Setter;
@@ -45,10 +44,7 @@ import org.apache.iceberg.catalog.Catalog;
import org.apache.iceberg.catalog.Namespace;
import org.apache.iceberg.catalog.TableIdentifier;
import org.apache.iceberg.types.Type.PrimitiveType;
-import org.apache.iceberg.types.Types.IntegerType;
-import org.apache.iceberg.types.Types.LongType;
import org.apache.iceberg.types.Types.NestedField;
-import org.apache.iceberg.types.Types.StringType;
import org.apache.iceberg.types.Types.StructType;
public class IcebergTableOpsHelper {
@@ -81,18 +77,6 @@ public class IcebergTableOpsHelper {
}
}
- // todo, just for pass the updateTable test, @yunqing will provide a new implement
- private static org.apache.iceberg.types.Type convertType(Type gravitonType) {
- if (gravitonType instanceof I32) {
- return IntegerType.get();
- } else if (gravitonType instanceof I64) {
- return LongType.get();
- } else if (gravitonType instanceof Binary) {
- return StringType.get();
- }
- return StringType.get();
- }
-
private void doDeleteColumn(
UpdateSchema icebergUpdateSchema, DeleteColumn deleteColumn, Schema icebergTableSchema) {
NestedField deleteField = icebergTableSchema.findField(DOT.join(deleteColumn.fieldNames()));
@@ -149,7 +133,8 @@ public class IcebergTableOpsHelper {
private void doUpdateColumnType(
UpdateSchema icebergUpdateSchema, UpdateColumnType updateColumnType) {
- org.apache.iceberg.types.Type type = convertType(updateColumnType.getNewDataType());
+ org.apache.iceberg.types.Type type =
+ ConvertUtil.toIcebergType(updateColumnType.getNewDataType());
Preconditions.checkArgument(
type.isPrimitiveType(),
"Cannot update %s, not a primitive type: %s",
@@ -196,7 +181,7 @@ public class IcebergTableOpsHelper {
icebergUpdateSchema.addColumn(
getParentName(addColumn.fieldNames()),
getLeafName(addColumn.fieldNames()),
- convertType(addColumn.getDataType()),
+ ConvertUtil.toIcebergType(addColumn.getDataType()),
addColumn.getComment());
ColumnPosition position = getAddColumnPosition(parentStruct, addColumn.getPosition());
@@ -296,6 +281,12 @@ public class IcebergTableOpsHelper {
return icebergTableChange;
}
+ public static Map<String, String> removeReservedProperties(Map<String, String> createProperties) {
+ return createProperties.entrySet().stream()
+ .filter(entry -> !IcebergReservedProperties.contains(entry.getKey()))
+ .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
+ }
+
public static Namespace getIcebergNamespace(NameIdentifier ident) {
return getIcebergNamespace(ArrayUtils.add(ident.namespace().levels(), ident.name()));
}
@@ -304,6 +295,16 @@ public class IcebergTableOpsHelper {
return Namespace.of(level);
}
+ public static TableIdentifier buildIcebergTableIdentifier(
+ com.datastrato.graviton.Namespace namespace, String name) {
+ return TableIdentifier.of(ArrayUtils.add(namespace.levels(), name));
+ }
+
+ public static TableIdentifier buildIcebergTableIdentifier(NameIdentifier nameIdentifier) {
+ return TableIdentifier.of(
+ ArrayUtils.add(nameIdentifier.namespace().levels(), nameIdentifier.name()));
+ }
+
@VisibleForTesting
static String getParentName(String[] fields) {
if (fields.length > 1) {
diff --git a/catalogs/catalog-lakehouse-iceberg/src/main/java/com/datastrato/graviton/catalog/lakehouse/iceberg/utils/IcebergCatalogUtil.java b/catalogs/catalog-lakehouse-iceberg/src/main/java/com/datastrato/graviton/catalog/lakehouse/iceberg/utils/IcebergCatalogUtil.java
index c3c90451ad..d93230b9af 100644
--- a/catalogs/catalog-lakehouse-iceberg/src/main/java/com/datastrato/graviton/catalog/lakehouse/iceberg/utils/IcebergCatalogUtil.java
+++ b/catalogs/catalog-lakehouse-iceberg/src/main/java/com/datastrato/graviton/catalog/lakehouse/iceberg/utils/IcebergCatalogUtil.java
@@ -21,7 +21,7 @@ import org.slf4j.LoggerFactory;
public class IcebergCatalogUtil {
- private static Logger LOG = LoggerFactory.getLogger(IcebergCatalogUtil.class);
+ private static final Logger LOG = LoggerFactory.getLogger(IcebergCatalogUtil.class);
private static InMemoryCatalog loadMemoryCatalog(Map<String, String> properties) {
InMemoryCatalog memoryCatalog = new InMemoryCatalog();
diff --git a/catalogs/catalog-lakehouse-iceberg/src/test/java/com/datastrato/graviton/catalog/lakehouse/iceberg/IcebergCatalogTest.java b/catalogs/catalog-lakehouse-iceberg/src/test/java/com/datastrato/graviton/catalog/lakehouse/iceberg/TestIcebergCatalog.java
similarity index 98%
rename from catalogs/catalog-lakehouse-iceberg/src/test/java/com/datastrato/graviton/catalog/lakehouse/iceberg/IcebergCatalogTest.java
rename to catalogs/catalog-lakehouse-iceberg/src/test/java/com/datastrato/graviton/catalog/lakehouse/iceberg/TestIcebergCatalog.java
index 6b23079ed6..26463ae679 100644
--- a/catalogs/catalog-lakehouse-iceberg/src/test/java/com/datastrato/graviton/catalog/lakehouse/iceberg/IcebergCatalogTest.java
+++ b/catalogs/catalog-lakehouse-iceberg/src/test/java/com/datastrato/graviton/catalog/lakehouse/iceberg/TestIcebergCatalog.java
@@ -16,7 +16,7 @@ import org.apache.iceberg.rest.responses.ListNamespacesResponse;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
-public class IcebergCatalogTest {
+public class TestIcebergCatalog {
@Test
public void testListDatabases() {
AuditInfo auditInfo =
diff --git a/catalogs/catalog-lakehouse-iceberg/src/test/java/com/datastrato/graviton/catalog/lakehouse/iceberg/IcebergSchemaTest.java b/catalogs/catalog-lakehouse-iceberg/src/test/java/com/datastrato/graviton/catalog/lakehouse/iceberg/TestIcebergSchema.java
similarity index 98%
rename from catalogs/catalog-lakehouse-iceberg/src/test/java/com/datastrato/graviton/catalog/lakehouse/iceberg/IcebergSchemaTest.java
rename to catalogs/catalog-lakehouse-iceberg/src/test/java/com/datastrato/graviton/catalog/lakehouse/iceberg/TestIcebergSchema.java
index 75b4b6d377..43b7e4c7ce 100644
--- a/catalogs/catalog-lakehouse-iceberg/src/test/java/com/datastrato/graviton/catalog/lakehouse/iceberg/IcebergSchemaTest.java
+++ b/catalogs/catalog-lakehouse-iceberg/src/test/java/com/datastrato/graviton/catalog/lakehouse/iceberg/TestIcebergSchema.java
@@ -18,7 +18,7 @@ import java.util.Map;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
-public class IcebergSchemaTest {
+public class TestIcebergSchema {
private static final String META_LAKE_NAME = "metalake";
@@ -53,7 +53,7 @@ public class IcebergSchemaTest {
() -> {
icebergCatalog.asSchemas().createSchema(ident, COMMENT_VALUE, properties);
});
- Assertions.assertTrue(exception.getMessage().contains("already exists in Iceberg"));
+ Assertions.assertTrue(exception.getMessage().contains("already exists"));
}
@Test
diff --git a/catalogs/catalog-lakehouse-iceberg/src/test/java/com/datastrato/graviton/catalog/lakehouse/iceberg/TestIcebergTable.java b/catalogs/catalog-lakehouse-iceberg/src/test/java/com/datastrato/graviton/catalog/lakehouse/iceberg/TestIcebergTable.java
new file mode 100644
index 0000000000..603503984b
--- /dev/null
+++ b/catalogs/catalog-lakehouse-iceberg/src/test/java/com/datastrato/graviton/catalog/lakehouse/iceberg/TestIcebergTable.java
@@ -0,0 +1,479 @@
+/*
+ * Copyright 2023 Datastrato.
+ * This software is licensed under the Apache License version 2.
+ */
+package com.datastrato.graviton.catalog.lakehouse.iceberg;
+
+import static com.datastrato.graviton.rel.transforms.Transforms.day;
+import static com.datastrato.graviton.rel.transforms.Transforms.identity;
+
+import com.datastrato.graviton.NameIdentifier;
+import com.datastrato.graviton.Namespace;
+import com.datastrato.graviton.exceptions.NoSuchSchemaException;
+import com.datastrato.graviton.exceptions.TableAlreadyExistsException;
+import com.datastrato.graviton.meta.AuditInfo;
+import com.datastrato.graviton.meta.CatalogEntity;
+import com.datastrato.graviton.rel.Column;
+import com.datastrato.graviton.rel.Distribution;
+import com.datastrato.graviton.rel.Distribution.Strategy;
+import com.datastrato.graviton.rel.SortOrder;
+import com.datastrato.graviton.rel.SortOrder.Direction;
+import com.datastrato.graviton.rel.SortOrder.NullOrdering;
+import com.datastrato.graviton.rel.Table;
+import com.datastrato.graviton.rel.TableCatalog;
+import com.datastrato.graviton.rel.TableChange;
+import com.datastrato.graviton.rel.transforms.Transform;
+import com.datastrato.graviton.rel.transforms.Transforms;
+import com.google.common.collect.Maps;
+import io.substrait.type.TypeCreator;
+import java.io.IOException;
+import java.time.Instant;
+import java.util.Arrays;
+import java.util.Map;
+import java.util.UUID;
+import org.apache.commons.lang3.ArrayUtils;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.Test;
+
+public class TestIcebergTable {
+
+ private static final String META_LAKE_NAME = "metalake";
+
+ private static final String ICEBERG_CATALOG_NAME = "test_catalog";
+ private static final String ICEBERG_SCHEMA_NAME = "test_schema";
+ private static final String ICEBERG_COMMENT = "test_comment";
+ private static IcebergCatalog icebergCatalog;
+ private static IcebergSchema icebergSchema;
+ private static final NameIdentifier schemaIdent =
+ NameIdentifier.of(META_LAKE_NAME, ICEBERG_CATALOG_NAME, ICEBERG_SCHEMA_NAME);
+
+ @BeforeAll
+ private static void setup() {
+ initIcebergCatalog();
+ initIcebergSchema();
+ }
+
+ @AfterEach
+ private void resetSchema() {
+ TableCatalog tableCatalog = icebergCatalog.asTableCatalog();
+ NameIdentifier[] nameIdentifiers =
+ tableCatalog.listTables(
+ Namespace.of(ArrayUtils.add(schemaIdent.namespace().levels(), schemaIdent.name())));
+ if (ArrayUtils.isNotEmpty(nameIdentifiers)) {
+ Arrays.stream(nameIdentifiers).forEach(tableCatalog::dropTable);
+ }
+ icebergCatalog.asSchemas().dropSchema(schemaIdent, false);
+ initIcebergSchema();
+ }
+
+ private static void initIcebergSchema() {
+ Map<String, String> properties = Maps.newHashMap();
+ properties.put("key1", "val1");
+ properties.put("key2", "val2");
+
+ icebergSchema =
+ (IcebergSchema)
+ icebergCatalog.asSchemas().createSchema(schemaIdent, ICEBERG_COMMENT, properties);
+ }
+
+ private static void initIcebergCatalog() {
+ AuditInfo auditInfo =
+ new AuditInfo.Builder()
+ .withCreator("testIcebergUser")
+ .withCreateTime(Instant.now())
+ .build();
+
+ CatalogEntity entity =
+ new CatalogEntity.Builder()
+ .withId(1L)
+ .withName(ICEBERG_CATALOG_NAME)
+ .withNamespace(Namespace.of(META_LAKE_NAME))
+ .withType(IcebergCatalog.Type.RELATIONAL)
+ .withProvider("iceberg")
+ .withAuditInfo(auditInfo)
+ .build();
+
+ Map<String, String> conf = Maps.newHashMap();
+ icebergCatalog = new IcebergCatalog().withCatalogConf(conf).withCatalogEntity(entity);
+ }
+
+ private Distribution createDistribution() {
+ return Distribution.builder()
+ .withNumber(10)
+ .withTransforms(new Transform[] {Transforms.field(new String[] {"col_1"})})
+ .withStrategy(Strategy.EVEN)
+ .build();
+ }
+
+ private SortOrder[] createSortOrder() {
+ return new SortOrder[] {
+ SortOrder.builder()
+ .withNullOrdering(NullOrdering.FIRST)
+ .withDirection(Direction.DESC)
+ .withTransform(Transforms.field(new String[] {"col_2"}))
+ .build()
+ };
+ }
+
+ @Test
+ public void testCreateIcebergTable() throws IOException {
+ String icebergTableName = "test_iceberg_table";
+ NameIdentifier tableIdentifier =
+ NameIdentifier.of(
+ META_LAKE_NAME, icebergCatalog.name(), icebergSchema.name(), icebergTableName);
+ Map<String, String> properties = Maps.newHashMap();
+ properties.put("key1", "val1");
+ properties.put("key2", "val2");
+
+ IcebergColumn col1 =
+ new IcebergColumn.Builder()
+ .withName("col_1")
+ .withType(TypeCreator.NULLABLE.I8)
+ .withComment(ICEBERG_COMMENT)
+ .build();
+ IcebergColumn col2 =
+ new IcebergColumn.Builder()
+ .withName("col_2")
+ .withType(TypeCreator.NULLABLE.DATE)
+ .withComment(ICEBERG_COMMENT)
+ .build();
+ Column[] columns = new Column[] {col1, col2};
+
+ SortOrder[] sortOrders = createSortOrder();
+ Table table =
+ icebergCatalog
+ .asTableCatalog()
+ .createTable(
+ tableIdentifier,
+ columns,
+ ICEBERG_COMMENT,
+ properties,
+ new Transform[0],
+ null,
+ sortOrders);
+ Assertions.assertEquals(tableIdentifier.name(), table.name());
+ Assertions.assertEquals(ICEBERG_COMMENT, table.comment());
+ Assertions.assertEquals("val1", table.properties().get("key1"));
+ Assertions.assertEquals("val2", table.properties().get("key2"));
+
+ Table loadedTable = icebergCatalog.asTableCatalog().loadTable(tableIdentifier);
+
+ Assertions.assertEquals("val1", loadedTable.properties().get("key1"));
+ Assertions.assertEquals("val2", loadedTable.properties().get("key2"));
+
+ Assertions.assertTrue(icebergCatalog.asTableCatalog().tableExists(tableIdentifier));
+ NameIdentifier[] tableIdents =
+ icebergCatalog.asTableCatalog().listTables(tableIdentifier.namespace());
+ Assertions.assertTrue(Arrays.asList(tableIdents).contains(tableIdentifier));
+
+ Assertions.assertEquals(sortOrders.length, loadedTable.sortOrder().length);
+ for (int i = 0; i < loadedTable.sortOrder().length; i++) {
+ Assertions.assertEquals(
+ sortOrders[i].getDirection(), loadedTable.sortOrder()[i].getDirection());
+ Assertions.assertEquals(
+ sortOrders[i].getTransform(), loadedTable.sortOrder()[i].getTransform());
+ }
+ // Compare sort and order
+
+ // Test exception
+ Throwable exception =
+ Assertions.assertThrows(
+ TableAlreadyExistsException.class,
+ () ->
+ icebergCatalog
+ .asTableCatalog()
+ .createTable(
+ tableIdentifier,
+ columns,
+ ICEBERG_COMMENT,
+ properties,
+ new Transform[0],
+ null,
+ sortOrders));
+ Assertions.assertTrue(exception.getMessage().contains("Table already exists"));
+ }
+
+ @Test
+ public void testCreatePartitionedIcebergTable() {
+ NameIdentifier tableIdentifier =
+ NameIdentifier.of(
+ META_LAKE_NAME, icebergCatalog.name(), icebergSchema.name(), genRandomName());
+ Map<String, String> properties = Maps.newHashMap();
+ properties.put("key1", "val1");
+ properties.put("key2", "val2");
+
+ IcebergColumn col1 =
+ new IcebergColumn.Builder()
+ .withName("city")
+ .withType(TypeCreator.NULLABLE.I8)
+ .withComment(ICEBERG_COMMENT)
+ .build();
+ IcebergColumn col2 =
+ new IcebergColumn.Builder()
+ .withName("date")
+ .withType(TypeCreator.NULLABLE.DATE)
+ .withComment(ICEBERG_COMMENT)
+ .build();
+ Column[] columns = new Column[] {col1, col2};
+
+ Transform[] partitions = new Transform[] {day(new String[] {col2.name()})};
+
+ Table table =
+ icebergCatalog
+ .asTableCatalog()
+ .createTable(tableIdentifier, columns, ICEBERG_COMMENT, properties, partitions);
+ Assertions.assertEquals(tableIdentifier.name(), table.name());
+ Assertions.assertEquals(ICEBERG_COMMENT, table.comment());
+ Assertions.assertEquals("val1", table.properties().get("key1"));
+ Assertions.assertEquals("val2", table.properties().get("key2"));
+ Assertions.assertArrayEquals(partitions, table.partitioning());
+
+ Table loadedTable = icebergCatalog.asTableCatalog().loadTable(tableIdentifier);
+
+ Assertions.assertEquals("val1", loadedTable.properties().get("key1"));
+ Assertions.assertEquals("val2", loadedTable.properties().get("key2"));
+ Assertions.assertArrayEquals(partitions, loadedTable.partitioning());
+
+ Assertions.assertTrue(icebergCatalog.asTableCatalog().tableExists(tableIdentifier));
+ NameIdentifier[] tableIdents =
+ icebergCatalog.asTableCatalog().listTables(tableIdentifier.namespace());
+ Assertions.assertTrue(Arrays.asList(tableIdents).contains(tableIdentifier));
+
+ // Test exception
+ Throwable exception =
+ Assertions.assertThrows(
+ TableAlreadyExistsException.class,
+ () ->
+ icebergCatalog
+ .asTableCatalog()
+ .createTable(
+ tableIdentifier,
+ columns,
+ ICEBERG_COMMENT,
+ properties,
+ new Transform[] {day(new String[] {col2.name()})}));
+ Assertions.assertTrue(exception.getMessage().contains("Table already exists"));
+
+ exception =
+ Assertions.assertThrows(
+ RuntimeException.class,
+ () ->
+ icebergCatalog
+ .asTableCatalog()
+ .createTable(
+ NameIdentifier.of(
+ META_LAKE_NAME,
+ icebergCatalog.name(),
+ icebergSchema.name(),
+ genRandomName()),
+ columns,
+ ICEBERG_COMMENT,
+ properties,
+ new Transform[] {identity(new String[] {col1.name(), col2.name()})}));
+ Assertions.assertTrue(
+ exception.getMessage().contains("Iceberg partition does not support nested field"));
+
+ exception =
+ Assertions.assertThrows(
+ IllegalArgumentException.class,
+ () ->
+ icebergCatalog
+ .asTableCatalog()
+ .createTable(
+ NameIdentifier.of(
+ META_LAKE_NAME,
+ icebergCatalog.name(),
+ icebergSchema.name(),
+ genRandomName()),
+ columns,
+ ICEBERG_COMMENT,
+ properties,
+ new Transform[] {identity(new String[] {"not_exist_field"})}));
+ Assertions.assertTrue(
+ exception.getMessage().contains("Cannot find source column: not_exist_field"));
+ }
+
+ @Test
+ public void testDropIcebergTable() {
+ NameIdentifier tableIdentifier =
+ NameIdentifier.of(
+ META_LAKE_NAME, icebergCatalog.name(), icebergSchema.name(), genRandomName());
+ Map<String, String> properties = Maps.newHashMap();
+ properties.put("key1", "val1");
+ properties.put("key2", "val2");
+
+ IcebergColumn col1 =
+ new IcebergColumn.Builder()
+ .withName("col_1")
+ .withType(TypeCreator.NULLABLE.I8)
+ .withComment(ICEBERG_COMMENT)
+ .build();
+ IcebergColumn col2 =
+ new IcebergColumn.Builder()
+ .withName("col_2")
+ .withType(TypeCreator.NULLABLE.DATE)
+ .withComment(ICEBERG_COMMENT)
+ .build();
+ Column[] columns = new Column[] {col1, col2};
+
+ icebergCatalog
+ .asTableCatalog()
+ .createTable(
+ tableIdentifier,
+ columns,
+ ICEBERG_COMMENT,
+ properties,
+ new Transform[0],
+ Distribution.NONE,
+ new SortOrder[0]);
+
+ Assertions.assertTrue(icebergCatalog.asTableCatalog().tableExists(tableIdentifier));
+ icebergCatalog.asTableCatalog().dropTable(tableIdentifier);
+ Assertions.assertFalse(icebergCatalog.asTableCatalog().tableExists(tableIdentifier));
+ }
+
+ @Test
+ public void testListTableException() {
+ Namespace tableNs = Namespace.of("metalake", icebergCatalog.name(), "not_exist_db");
+ Throwable exception =
+ Assertions.assertThrows(
+ NoSuchSchemaException.class, () -> icebergCatalog.asTableCatalog().listTables(tableNs));
+ Assertions.assertTrue(exception.getMessage().contains("Schema (database) does not exist"));
+ }
+
+ @Test
+ public void testAlterIcebergTable() {
+ // create a table with random name
+ NameIdentifier tableIdentifier =
+ NameIdentifier.of(
+ META_LAKE_NAME, icebergCatalog.name(), icebergSchema.name(), genRandomName());
+ Map<String, String> properties = Maps.newHashMap();
+ properties.put("key1", "val1");
+ properties.put("key2", "val2");
+
+ IcebergColumn col1 =
+ new IcebergColumn.Builder()
+ .withName("col_1")
+ .withType(TypeCreator.NULLABLE.I8)
+ .withComment(ICEBERG_COMMENT)
+ .build();
+ IcebergColumn col2 =
+ new IcebergColumn.Builder()
+ .withName("col_2")
+ .withType(TypeCreator.NULLABLE.DATE)
+ .withComment(ICEBERG_COMMENT)
+ .build();
+ Column[] columns = new Column[] {col1, col2};
+
+ Distribution distribution = createDistribution();
+ SortOrder[] sortOrders = createSortOrder();
+
+ Table createdTable =
+ icebergCatalog
+ .asTableCatalog()
+ .createTable(
+ tableIdentifier,
+ columns,
+ ICEBERG_COMMENT,
+ properties,
+ new Transform[0],
+ distribution,
+ sortOrders);
+ Assertions.assertTrue(icebergCatalog.asTableCatalog().tableExists(tableIdentifier));
+
+ Throwable exception =
+ Assertions.assertThrows(
+ IllegalArgumentException.class,
+ () ->
+ icebergCatalog
+ .asTableCatalog()
+ .alterTable(
+ tableIdentifier,
+ TableChange.updateComment(ICEBERG_COMMENT + "_new"),
+ TableChange.rename("test_iceberg_table_new")));
+ Assertions.assertTrue(
+ exception.getMessage().contains("The operation to change the table name cannot"));
+
+ // test alter
+ icebergCatalog
+ .asTableCatalog()
+ .alterTable(
+ tableIdentifier,
+ TableChange.updateComment(ICEBERG_COMMENT + "_new"),
+ TableChange.removeProperty("key1"),
+ TableChange.setProperty("key2", "val2_new"),
+ // columns current format: [col_1:I8:comment, col_2:DATE:comment]
+ TableChange.addColumn(new String[] {"col_3"}, TypeCreator.NULLABLE.STRING),
+ // columns current format: [col_1:I8:comment, col_2:DATE:comment, col_3:STRING:null]
+ TableChange.renameColumn(new String[] {"col_2"}, "col_2_new"),
+ // columns current format: [col_1:I8:comment, col_2_new:DATE:comment, col_3:STRING:null]
+ TableChange.updateColumnComment(new String[] {"col_1"}, ICEBERG_COMMENT + "_new"),
+ // columns current format: [col_1:I8:comment_new, col_2_new:DATE:comment,
+ // col_3:STRING:null]
+ TableChange.updateColumnType(new String[] {"col_1"}, TypeCreator.NULLABLE.I32),
+ // columns current format: [col_1:I32:comment_new, col_2_new:DATE:comment,
+ // col_3:STRING:null]
+ TableChange.updateColumnPosition(
+ new String[] {"col_2"}, TableChange.ColumnPosition.first())
+ // columns current: [col_2_new:DATE:comment, col_1:I32:comment_new, col_3:STRING:null]
+ );
+
+ icebergCatalog
+ .asTableCatalog()
+ .alterTable(tableIdentifier, TableChange.rename("test_iceberg_table_new"));
+
+ Table alteredTable =
+ icebergCatalog
+ .asTableCatalog()
+ .loadTable(NameIdentifier.of(tableIdentifier.namespace(), "test_iceberg_table_new"));
+
+ Assertions.assertEquals(ICEBERG_COMMENT + "_new", alteredTable.comment());
+ Assertions.assertFalse(alteredTable.properties().containsKey("key1"));
+ Assertions.assertEquals(alteredTable.properties().get("key2"), "val2_new");
+
+ Assertions.assertEquals(sortOrders.length, alteredTable.sortOrder().length);
+
+ Column[] expected =
+ new Column[] {
+ new IcebergColumn.Builder()
+ .withName("col_2_new")
+ .withType(TypeCreator.NULLABLE.DATE)
+ .withComment(ICEBERG_COMMENT)
+ .build(),
+ new IcebergColumn.Builder()
+ .withName("col_1")
+ .withType(TypeCreator.NULLABLE.I32)
+ .withComment(ICEBERG_COMMENT + "_new")
+ .build(),
+ new IcebergColumn.Builder()
+ .withName("col_3")
+ .withType(TypeCreator.NULLABLE.STRING)
+ .withComment(null)
+ .build()
+ };
+ Assertions.assertArrayEquals(expected, alteredTable.columns());
+
+ // test delete column change
+ icebergCatalog
+ .asTableCatalog()
+ .alterTable(
+ NameIdentifier.of(tableIdentifier.namespace(), "test_iceberg_table_new"),
+ TableChange.deleteColumn(new String[] {"col_1"}, false));
+ Table alteredTable1 =
+ icebergCatalog
+ .asTableCatalog()
+ .loadTable(NameIdentifier.of(tableIdentifier.namespace(), "test_iceberg_table_new"));
+ expected =
+ Arrays.stream(expected).filter(c -> !"col_1".equals(c.name())).toArray(Column[]::new);
+ Assertions.assertArrayEquals(expected, alteredTable1.columns());
+
+ Assertions.assertNotNull(alteredTable.partitioning());
+ Assertions.assertArrayEquals(createdTable.partitioning(), alteredTable.partitioning());
+ }
+
+ protected static String genRandomName() {
+ return UUID.randomUUID().toString().replace("-", "");
+ }
+}
diff --git a/catalogs/catalog-lakehouse-iceberg/src/test/java/com/datastrato/graviton/catalog/lakehouse/iceberg/converter/TestBaseConvert.java b/catalogs/catalog-lakehouse-iceberg/src/test/java/com/datastrato/graviton/catalog/lakehouse/iceberg/converter/TestBaseConvert.java
new file mode 100644
index 0000000000..86f121c1b9
--- /dev/null
+++ b/catalogs/catalog-lakehouse-iceberg/src/test/java/com/datastrato/graviton/catalog/lakehouse/iceberg/converter/TestBaseConvert.java
@@ -0,0 +1,132 @@
+/*
+ * Copyright 2023 Datastrato.
+ * This software is licensed under the Apache License version 2.
+ */
+package com.datastrato.graviton.catalog.lakehouse.iceberg.converter;
+
+import com.datastrato.graviton.catalog.lakehouse.iceberg.IcebergColumn;
+import com.datastrato.graviton.rel.Column;
+import com.datastrato.graviton.rel.SortOrder;
+import com.google.common.collect.Lists;
+import io.substrait.type.Type;
+import io.substrait.type.TypeCreator;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.Map;
+import org.apache.commons.lang3.RandomUtils;
+import org.apache.iceberg.types.Types;
+
+/** Provide some basic usage methods and test classes for basic fields. */
+public class TestBaseConvert {
+
+ protected static final String TEST_COMMENT = "test_comment";
+ protected static final String TEST_NAME = "test";
+ protected static final String TEST_FIELD = "test";
+ protected static final String TEST_LOCATION = "location";
+
+ protected static final Map<String, Type> GRAVITON_TYPE = new HashMap<>();
+ protected static final Map<String, org.apache.iceberg.types.Type> ICEBERG_TYPE = new HashMap<>();
+
+ static {
+ GRAVITON_TYPE.put("BOOLEAN", TypeCreator.NULLABLE.BOOLEAN);
+ // Types not supported by iceberg
+ // GRAVITON_TYPE.put("I8", TypeCreator.NULLABLE.I8);
+ // GRAVITON_TYPE.put("I16", TypeCreator.NULLABLE.I16);
+ GRAVITON_TYPE.put("I32", TypeCreator.NULLABLE.I32);
+ GRAVITON_TYPE.put("I64", TypeCreator.NULLABLE.I64);
+ GRAVITON_TYPE.put("FP32", TypeCreator.NULLABLE.FP32);
+ GRAVITON_TYPE.put("FP64", TypeCreator.NULLABLE.FP64);
+ GRAVITON_TYPE.put("STRING", TypeCreator.NULLABLE.STRING);
+ GRAVITON_TYPE.put("BINARY", TypeCreator.NULLABLE.BINARY);
+ GRAVITON_TYPE.put("TIMESTAMP", TypeCreator.NULLABLE.TIMESTAMP);
+ GRAVITON_TYPE.put("TIMESTAMP_TZ", TypeCreator.NULLABLE.TIMESTAMP_TZ);
+ GRAVITON_TYPE.put("DATE", TypeCreator.NULLABLE.DATE);
+ GRAVITON_TYPE.put("TIME", TypeCreator.NULLABLE.TIME);
+ GRAVITON_TYPE.put("UUID", TypeCreator.NULLABLE.UUID);
+ // Types not supported by iceberg
+ // ICEBERG_TYPE.put("INTERVAL_DAY", TypeCreator.NULLABLE.INTERVAL_DAY);
+ // ICEBERG_TYPE.put("INTERVAL_YEAR", TypeCreator.NULLABLE.INTERVAL_YEAR);
+
+ ICEBERG_TYPE.put("BOOLEAN", org.apache.iceberg.types.Types.BooleanType.get());
+ ICEBERG_TYPE.put("I8", org.apache.iceberg.types.Types.IntegerType.get());
+ ICEBERG_TYPE.put("I16", org.apache.iceberg.types.Types.IntegerType.get());
+ ICEBERG_TYPE.put("I32", org.apache.iceberg.types.Types.IntegerType.get());
+ ICEBERG_TYPE.put("I64", org.apache.iceberg.types.Types.LongType.get());
+ ICEBERG_TYPE.put("FP32", org.apache.iceberg.types.Types.FloatType.get());
+ ICEBERG_TYPE.put("FP64", org.apache.iceberg.types.Types.DoubleType.get());
+ ICEBERG_TYPE.put("STRING", org.apache.iceberg.types.Types.StringType.get());
+ ICEBERG_TYPE.put("BINARY", org.apache.iceberg.types.Types.BinaryType.get());
+ ICEBERG_TYPE.put("TIMESTAMP", org.apache.iceberg.types.Types.TimestampType.withoutZone());
+ ICEBERG_TYPE.put("TIMESTAMP_TZ", org.apache.iceberg.types.Types.TimestampType.withZone());
+ ICEBERG_TYPE.put("DATE", org.apache.iceberg.types.Types.DateType.get());
+ ICEBERG_TYPE.put("TIME", org.apache.iceberg.types.Types.TimeType.get());
+ ICEBERG_TYPE.put("UUID", org.apache.iceberg.types.Types.UUIDType.get());
+ }
+
+ protected static Column[] createColumns(String... colNames) {
+ ArrayList<Column> results = Lists.newArrayList();
+ for (String colName : colNames) {
+ results.add(
+ new IcebergColumn.Builder()
+ .withName(colName)
+ .withType(getRandomGravitonType())
+ .withComment(TEST_COMMENT)
+ .build());
+ }
+ return results.toArray(new Column[0]);
+ }
+
+ protected static SortOrder[] createSortOrder(String... colNames) {
+ ArrayList<SortOrder> results = Lists.newArrayList();
+ for (String colName : colNames) {
+ results.add(
+ SortOrder.fieldSortOrder(
+ new String[] {colName},
+ RandomUtils.nextBoolean() ? SortOrder.Direction.DESC : SortOrder.Direction.ASC,
+ RandomUtils.nextBoolean()
+ ? SortOrder.NullOrdering.FIRST
+ : SortOrder.NullOrdering.LAST));
+ }
+ return results.toArray(new SortOrder[0]);
+ }
+
+ protected static SortOrder createFunctionSortOrder(String name, String colName) {
+ return SortOrder.functionSortOrder(
+ name,
+ new String[] {colName},
+ RandomUtils.nextBoolean() ? SortOrder.Direction.DESC : SortOrder.Direction.ASC,
+ RandomUtils.nextBoolean() ? SortOrder.NullOrdering.FIRST : SortOrder.NullOrdering.LAST);
+ }
+
+ protected static Types.NestedField createNestedField(
+ int id, String name, org.apache.iceberg.types.Type type) {
+ return Types.NestedField.optional(id, name, type, TEST_COMMENT);
+ }
+
+ protected static Types.NestedField[] createNestedField(String... colNames) {
+ ArrayList<Types.NestedField> results = Lists.newArrayList();
+ for (int i = 0; i < colNames.length; i++) {
+ results.add(
+ Types.NestedField.of(
+ i + 1, RandomUtils.nextBoolean(), colNames[i], getRandomIcebergType(), TEST_COMMENT));
+ }
+ return results.toArray(new Types.NestedField[0]);
+ }
+
+ private static Type getRandomGravitonType() {
+ Collection<Type> values = GRAVITON_TYPE.values();
+ return values.stream()
+ .skip(RandomUtils.nextInt(0, values.size()))
+ .findFirst()
+ .orElseThrow(() -> new RuntimeException("No type found"));
+ }
+
+ private static org.apache.iceberg.types.Type getRandomIcebergType() {
+ Collection<org.apache.iceberg.types.Type> values = ICEBERG_TYPE.values();
+ return values.stream()
+ .skip(RandomUtils.nextInt(0, values.size()))
+ .findFirst()
+ .orElseThrow(() -> new RuntimeException("No type found"));
+ }
+}
diff --git a/catalogs/catalog-lakehouse-iceberg/src/test/java/com/datastrato/graviton/catalog/lakehouse/iceberg/converter/TestConvertUtil.java b/catalogs/catalog-lakehouse-iceberg/src/test/java/com/datastrato/graviton/catalog/lakehouse/iceberg/converter/TestConvertUtil.java
new file mode 100644
index 0000000000..9aec6bb09f
--- /dev/null
+++ b/catalogs/catalog-lakehouse-iceberg/src/test/java/com/datastrato/graviton/catalog/lakehouse/iceberg/converter/TestConvertUtil.java
@@ -0,0 +1,268 @@
+/*
+ * Copyright 2023 Datastrato.
+ * This software is licensed under the Apache License version 2.
+ */
+package com.datastrato.graviton.catalog.lakehouse.iceberg.converter;
+
+import com.datastrato.graviton.catalog.lakehouse.iceberg.IcebergColumn;
+import com.datastrato.graviton.catalog.lakehouse.iceberg.IcebergTable;
+import com.datastrato.graviton.meta.AuditInfo;
+import com.datastrato.graviton.rel.Column;
+import com.datastrato.graviton.rel.SortOrder;
+import com.google.common.collect.Maps;
+import io.substrait.type.TypeCreator;
+import java.time.Instant;
+import java.util.Arrays;
+import java.util.List;
+import java.util.Map;
+import java.util.stream.Collectors;
+import org.apache.commons.lang3.ArrayUtils;
+import org.apache.commons.lang3.RandomStringUtils;
+import org.apache.iceberg.Schema;
+import org.apache.iceberg.types.Type;
+import org.apache.iceberg.types.Types;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
+
+/** Test class for {@link ConvertUtil}. */
+public class TestConvertUtil extends TestBaseConvert {
+ @Test
+ public void testToIcebergSchema() {
+ Column[] columns = createColumns("col_1", "col_2", "col_3", "col_4");
+ String col5Name = "col_5";
+ IcebergColumn col5 =
+ new IcebergColumn.Builder()
+ .withName(col5Name)
+ .withType(
+ TypeCreator.NULLABLE.map(
+ TypeCreator.NULLABLE.list(TypeCreator.NULLABLE.TIMESTAMP_TZ),
+ TypeCreator.NULLABLE.map(
+ TypeCreator.NULLABLE.STRING, TypeCreator.NULLABLE.DATE)))
+ .withComment(TEST_COMMENT)
+ .build();
+ columns = ArrayUtils.add(columns, col5);
+ SortOrder[] sortOrder = createSortOrder("col_1", "col_2", "col_3", "col_4", "col_5");
+ IcebergTable icebergTable =
+ new IcebergTable.Builder()
+ .withName(TEST_NAME)
+ .withAuditInfo(
+ new AuditInfo.Builder()
+ .withCreator(TEST_NAME)
+ .withCreateTime(Instant.now())
+ .build())
+ .withProperties(Maps.newHashMap())
+ .withSortOrders(sortOrder)
+ .withColumns(columns)
+ .withComment(TEST_COMMENT)
+ .build();
+ Schema icebergSchema = ConvertUtil.toIcebergSchema(icebergTable);
+ List<Types.NestedField> nestedFields = icebergSchema.columns();
+ Assertions.assertEquals(nestedFields.size(), columns.length);
+
+ Map<String, Column> columnByName =
+ Arrays.stream(columns).collect(Collectors.toMap(Column::name, v -> v));
+ for (Types.NestedField nestedField : nestedFields) {
+ Assertions.assertTrue(columnByName.containsKey(nestedField.name()));
+ Column column = columnByName.get(nestedField.name());
+ Assertions.assertEquals(column.comment(), nestedField.doc());
+ checkType(nestedField.type(), column.dataType());
+ }
+
+ Types.NestedField col5Field = icebergSchema.findField(col5Name);
+ Assertions.assertNotNull(col5Field);
+ Assertions.assertFalse(col5Field.type().isStructType());
+ Assertions.assertTrue(col5Field.type().isNestedType());
+ Assertions.assertTrue(col5Field.type().isMapType());
+ Types.MapType mapType = col5Field.type().asMapType();
+ Assertions.assertTrue(mapType.keyType().isListType());
+ Assertions.assertFalse(mapType.keyType().asListType().elementType().isNestedType());
+ Assertions.assertTrue(mapType.valueType().isMapType());
+ Assertions.assertTrue(mapType.valueType().asMapType().keyType().isPrimitiveType());
+ Assertions.assertTrue(mapType.valueType().asMapType().valueType().isPrimitiveType());
+ }
+
+ @Test
+ public void testToPrimitiveType() {
+ Assertions.assertTrue(
+ ConvertUtil.toIcebergType(TypeCreator.NULLABLE.BOOLEAN) instanceof Types.BooleanType);
+ Assertions.assertTrue(
+ ConvertUtil.toIcebergType(TypeCreator.NULLABLE.STRING) instanceof Types.StringType);
+ Assertions.assertTrue(
+ ConvertUtil.toIcebergType(TypeCreator.NULLABLE.I8) instanceof Types.IntegerType);
+ Assertions.assertTrue(
+ ConvertUtil.toIcebergType(TypeCreator.NULLABLE.I16) instanceof Types.IntegerType);
+ Assertions.assertTrue(
+ ConvertUtil.toIcebergType(TypeCreator.NULLABLE.I32) instanceof Types.IntegerType);
+ Assertions.assertTrue(
+ ConvertUtil.toIcebergType(TypeCreator.NULLABLE.I64) instanceof Types.LongType);
+ Assertions.assertTrue(
+ ConvertUtil.toIcebergType(TypeCreator.NULLABLE.FP32) instanceof Types.FloatType);
+ Assertions.assertTrue(
+ ConvertUtil.toIcebergType(TypeCreator.NULLABLE.FP64) instanceof Types.DoubleType);
+ Assertions.assertTrue(
+ ConvertUtil.toIcebergType(TypeCreator.NULLABLE.DATE) instanceof Types.DateType);
+ Assertions.assertTrue(
+ ConvertUtil.toIcebergType(TypeCreator.NULLABLE.TIME) instanceof Types.TimeType);
+ Assertions.assertTrue(
+ ConvertUtil.toIcebergType(TypeCreator.NULLABLE.BINARY) instanceof Types.BinaryType);
+ Assertions.assertTrue(
+ ConvertUtil.toIcebergType(TypeCreator.NULLABLE.UUID) instanceof Types.UUIDType);
+
+ Type timestampTZ = ConvertUtil.toIcebergType(TypeCreator.NULLABLE.TIMESTAMP_TZ);
+ Assertions.assertTrue(timestampTZ instanceof Types.TimestampType);
+ Assertions.assertTrue(((Types.TimestampType) timestampTZ).shouldAdjustToUTC());
+
+ Type timestamp = ConvertUtil.toIcebergType(TypeCreator.NULLABLE.TIMESTAMP);
+ Assertions.assertTrue(timestamp instanceof Types.TimestampType);
+ Assertions.assertFalse(((Types.TimestampType) timestamp).shouldAdjustToUTC());
+
+ Type decimalType = ConvertUtil.toIcebergType(TypeCreator.NULLABLE.decimal(9, 2));
+ Assertions.assertTrue(decimalType instanceof Types.DecimalType);
+ Assertions.assertEquals(((Types.DecimalType) decimalType).precision(), 9);
+ Assertions.assertEquals(((Types.DecimalType) decimalType).scale(), 2);
+
+ Type fixedCharType = ConvertUtil.toIcebergType(TypeCreator.NULLABLE.fixedChar(9));
+ Assertions.assertTrue(fixedCharType instanceof Types.FixedType);
+ Assertions.assertEquals(((Types.FixedType) fixedCharType).length(), 9);
+
+ io.substrait.type.Type mapType =
+ TypeCreator.NULLABLE.map(TypeCreator.NULLABLE.STRING, TypeCreator.NULLABLE.I8);
+ Type convertedMapType = ConvertUtil.toIcebergType(mapType);
+ Assertions.assertTrue(convertedMapType instanceof Types.MapType);
+ Assertions.assertTrue(((Types.MapType) convertedMapType).keyType() instanceof Types.StringType);
+ Assertions.assertTrue(
+ ((Types.MapType) convertedMapType).valueType() instanceof Types.IntegerType);
+
+ Type listType = ConvertUtil.toIcebergType(TypeCreator.NULLABLE.list(TypeCreator.NULLABLE.FP64));
+ Assertions.assertTrue(listType instanceof Types.ListType);
+ Assertions.assertTrue(listType.asListType().elementType() instanceof Types.DoubleType);
+ }
+
+ @Test
+ public void testFormIcebergType() {
+ Assertions.assertTrue(
+ ConvertUtil.formIcebergType(Types.StringType.get()) instanceof io.substrait.type.Type.Str);
+ Assertions.assertTrue(
+ ConvertUtil.formIcebergType(Types.BinaryType.get())
+ instanceof io.substrait.type.Type.Binary);
+ Assertions.assertTrue(
+ ConvertUtil.formIcebergType(Types.TimeType.get()) instanceof io.substrait.type.Type.Time);
+ Assertions.assertTrue(
+ ConvertUtil.formIcebergType(Types.TimestampType.withoutZone())
+ instanceof io.substrait.type.Type.Timestamp);
+ Assertions.assertTrue(
+ ConvertUtil.formIcebergType(Types.TimestampType.withZone())
+ instanceof io.substrait.type.Type.TimestampTZ);
+ Assertions.assertTrue(
+ ConvertUtil.formIcebergType(Types.DoubleType.get()) instanceof io.substrait.type.Type.FP64);
+ Assertions.assertTrue(
+ ConvertUtil.formIcebergType(Types.FloatType.get()) instanceof io.substrait.type.Type.FP32);
+ Assertions.assertTrue(
+ ConvertUtil.formIcebergType(Types.IntegerType.get()) instanceof io.substrait.type.Type.I32);
+ Assertions.assertTrue(
+ ConvertUtil.formIcebergType(Types.LongType.get()) instanceof io.substrait.type.Type.I64);
+ Assertions.assertTrue(
+ ConvertUtil.formIcebergType(Types.UUIDType.get()) instanceof io.substrait.type.Type.UUID);
+ Assertions.assertTrue(
+ ConvertUtil.formIcebergType(Types.DateType.get()) instanceof io.substrait.type.Type.Date);
+
+ io.substrait.type.Type decimalType = ConvertUtil.formIcebergType(Types.DecimalType.of(9, 2));
+ Assertions.assertTrue(decimalType instanceof io.substrait.type.Type.Decimal);
+ Assertions.assertEquals(((io.substrait.type.Type.Decimal) decimalType).precision(), 9);
+ Assertions.assertEquals(((io.substrait.type.Type.Decimal) decimalType).scale(), 2);
+
+ io.substrait.type.Type fixedType = ConvertUtil.formIcebergType(Types.FixedType.ofLength(2));
+ Assertions.assertTrue(fixedType instanceof io.substrait.type.Type.FixedChar);
+ Assertions.assertEquals(((io.substrait.type.Type.FixedChar) fixedType).length(), 2);
+
+ Types.MapType mapType =
+ Types.MapType.ofOptional(1, 2, Types.StringType.get(), Types.IntegerType.get());
+ io.substrait.type.Type gravitonMapType = ConvertUtil.formIcebergType(mapType);
+ Assertions.assertTrue(gravitonMapType instanceof io.substrait.type.Type.Map);
+ Assertions.assertTrue(
+ ((io.substrait.type.Type.Map) gravitonMapType).key() instanceof io.substrait.type.Type.Str);
+ Assertions.assertTrue(
+ ((io.substrait.type.Type.Map) gravitonMapType).value()
+ instanceof io.substrait.type.Type.I32);
+
+ Types.ListType listType = Types.ListType.ofOptional(1, Types.StringType.get());
+ io.substrait.type.Type gravitonListType = ConvertUtil.formIcebergType(listType);
+ Assertions.assertTrue(gravitonListType instanceof io.substrait.type.Type.ListType);
+ Assertions.assertTrue(
+ ((io.substrait.type.Type.ListType) gravitonListType).elementType()
+ instanceof io.substrait.type.Type.Str);
+ }
+
+ @Test
+ public void testFromNestedField() {
+ String colName = RandomStringUtils.randomAlphabetic(10);
+ String doc = RandomStringUtils.randomAlphabetic(20);
+ Types.NestedField colField =
+ Types.NestedField.optional(1, colName, Types.IntegerType.get(), doc);
+ IcebergColumn icebergColumn = ConvertUtil.fromNestedField(colField);
+ Assertions.assertEquals(icebergColumn.name(), colName);
+ Assertions.assertTrue(icebergColumn.isOptional());
+ Assertions.assertEquals(icebergColumn.comment(), doc);
+ Assertions.assertTrue(icebergColumn.dataType() instanceof io.substrait.type.Type.I32);
+
+ colName = RandomStringUtils.randomAlphabetic(10);
+ doc = RandomStringUtils.randomAlphabetic(20);
+ colField = Types.NestedField.required(1, colName, Types.StringType.get(), doc);
+ icebergColumn = ConvertUtil.fromNestedField(colField);
+ Assertions.assertEquals(icebergColumn.name(), colName);
+ Assertions.assertFalse(icebergColumn.isOptional());
+ Assertions.assertEquals(icebergColumn.comment(), doc);
+ Assertions.assertTrue(icebergColumn.dataType() instanceof io.substrait.type.Type.Str);
+
+ colName = RandomStringUtils.randomAlphabetic(10);
+ doc = RandomStringUtils.randomAlphabetic(20);
+ colField = Types.NestedField.required(1, colName, Types.DateType.get(), doc);
+ icebergColumn = ConvertUtil.fromNestedField(colField);
+ Assertions.assertEquals(icebergColumn.name(), colName);
+ Assertions.assertFalse(icebergColumn.isOptional());
+ Assertions.assertEquals(icebergColumn.comment(), doc);
+ Assertions.assertTrue(icebergColumn.dataType() instanceof io.substrait.type.Type.Date);
+
+ colName = RandomStringUtils.randomAlphabetic(10);
+ doc = RandomStringUtils.randomAlphabetic(20);
+ colField =
+ Types.NestedField.required(
+ 1,
+ colName,
+ Types.MapType.ofOptional(
+ 1,
+ 2,
+ Types.ListType.ofOptional(3, Types.StringType.get()),
+ Types.DecimalType.of(1, 13)),
+ doc);
+ icebergColumn = ConvertUtil.fromNestedField(colField);
+ Assertions.assertEquals(icebergColumn.name(), colName);
+ Assertions.assertFalse(icebergColumn.isOptional());
+ Assertions.assertEquals(icebergColumn.comment(), doc);
+ Assertions.assertTrue(icebergColumn.dataType() instanceof io.substrait.type.Type.Map);
+ }
+
+ private static void checkType(Type type, io.substrait.type.Type expected) {
+ io.substrait.type.Type actual = ConvertUtil.formIcebergType(type);
+ checkType(actual, expected);
+ }
+
+ private static void checkType(io.substrait.type.Type actual, io.substrait.type.Type expected) {
+ if (actual instanceof io.substrait.type.Type.Map) {
+ Assertions.assertTrue(expected instanceof io.substrait.type.Type.Map);
+ checkType(
+ ((io.substrait.type.Type.Map) actual).key(),
+ ((io.substrait.type.Type.Map) expected).key());
+ checkType(
+ ((io.substrait.type.Type.Map) actual).value(),
+ ((io.substrait.type.Type.Map) expected).value());
+ } else if (actual instanceof io.substrait.type.Type.ListType) {
+ Assertions.assertTrue(expected instanceof io.substrait.type.Type.ListType);
+ checkType(
+ ((io.substrait.type.Type.ListType) actual).elementType(),
+ ((io.substrait.type.Type.ListType) expected).elementType());
+ } else {
+ Assertions.assertEquals(expected.getClass(), actual.getClass());
+ }
+ }
+}
diff --git a/catalogs/catalog-lakehouse-iceberg/src/test/java/com/datastrato/graviton/catalog/lakehouse/iceberg/converter/TestFromIcebergPartitionSpec.java b/catalogs/catalog-lakehouse-iceberg/src/test/java/com/datastrato/graviton/catalog/lakehouse/iceberg/converter/TestFromIcebergPartitionSpec.java
new file mode 100644
index 0000000000..505ced46d7
--- /dev/null
+++ b/catalogs/catalog-lakehouse-iceberg/src/test/java/com/datastrato/graviton/catalog/lakehouse/iceberg/converter/TestFromIcebergPartitionSpec.java
@@ -0,0 +1,74 @@
+/*
+ * Copyright 2023 Datastrato.
+ * This software is licensed under the Apache License version 2.
+ */
+package com.datastrato.graviton.catalog.lakehouse.iceberg.converter;
+
+import com.datastrato.graviton.rel.transforms.Transform;
+import com.datastrato.graviton.rel.transforms.Transforms;
+import java.util.List;
+import java.util.Map;
+import java.util.stream.Collectors;
+import org.apache.commons.lang3.ArrayUtils;
+import org.apache.iceberg.PartitionField;
+import org.apache.iceberg.PartitionSpec;
+import org.apache.iceberg.Schema;
+import org.apache.iceberg.types.Types;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
+
+/** Test class for {@link FromIcebergPartitionSpec}. */
+public class TestFromIcebergPartitionSpec extends TestBaseConvert {
+
+ @Test
+ public void testFormTransform() {
+ Types.NestedField[] nestedFields = createNestedField("col_1", "col_2", "col_3");
+ nestedFields =
+ ArrayUtils.add(nestedFields, createNestedField(4, "col_4", Types.DateType.get()));
+ nestedFields =
+ ArrayUtils.add(nestedFields, createNestedField(5, "col_5", Types.DateType.get()));
+ nestedFields =
+ ArrayUtils.add(
+ nestedFields, createNestedField(6, "col_6", Types.TimestampType.withoutZone()));
+ nestedFields =
+ ArrayUtils.add(nestedFields, createNestedField(7, "col_7", Types.IntegerType.get()));
+ nestedFields =
+ ArrayUtils.add(nestedFields, createNestedField(8, "col_8", Types.IntegerType.get()));
+
+ Schema schema = new Schema(nestedFields);
+ PartitionSpec.Builder builder = PartitionSpec.builderFor(schema);
+ PartitionSpec partitionSpec =
+ builder
+ .year("col_4")
+ .day("col_5")
+ .hour("col_6")
+ .bucket("col_7", 5)
+ .truncate("col_8", 8)
+ .identity("col_1")
+ .build();
+ Transform[] transforms = FromIcebergPartitionSpec.fromPartitionSpec(partitionSpec, schema);
+ Assertions.assertEquals(6, transforms.length);
+
+ List<PartitionField> fields = partitionSpec.fields();
+ Map<Integer, String> idToName = schema.idToName();
+ Map<String, String> transformMapping =
+ fields.stream()
+ .collect(
+ Collectors.toMap(
+ PartitionField::name,
+ partitionField -> idToName.get(partitionField.sourceId())));
+
+ for (Transform transform : transforms) {
+ if (transform instanceof Transforms.FunctionTrans) {
+ String colName = ((Transforms.NamedReference) transform.arguments()[0]).value()[0];
+ String transformKey =
+ String.join(
+ "_", colName, "truncate".equals(transform.name()) ? "trunc" : transform.name());
+ Assertions.assertTrue(transformMapping.containsKey(transformKey));
+ Assertions.assertEquals(transformMapping.get(transformKey), colName);
+ } else if (transform instanceof Transforms.NamedReference) {
+ Assertions.assertEquals("col_1", ((Transforms.NamedReference) transform).value()[0]);
+ }
+ }
+ }
+}
diff --git a/catalogs/catalog-lakehouse-iceberg/src/test/java/com/datastrato/graviton/catalog/lakehouse/iceberg/converter/TestFromIcebergSortOrder.java b/catalogs/catalog-lakehouse-iceberg/src/test/java/com/datastrato/graviton/catalog/lakehouse/iceberg/converter/TestFromIcebergSortOrder.java
new file mode 100644
index 0000000000..11ab6e10f3
--- /dev/null
+++ b/catalogs/catalog-lakehouse-iceberg/src/test/java/com/datastrato/graviton/catalog/lakehouse/iceberg/converter/TestFromIcebergSortOrder.java
@@ -0,0 +1,90 @@
+/*
+ * Copyright 2023 Datastrato.
+ * This software is licensed under the Apache License version 2.
+ */
+package com.datastrato.graviton.catalog.lakehouse.iceberg.converter;
+
+import com.datastrato.graviton.rel.SortOrder;
+import com.datastrato.graviton.rel.transforms.Transforms;
+import java.util.Arrays;
+import java.util.List;
+import java.util.Map;
+import java.util.stream.Collectors;
+import org.apache.commons.lang3.ArrayUtils;
+import org.apache.iceberg.NullOrder;
+import org.apache.iceberg.Schema;
+import org.apache.iceberg.SortDirection;
+import org.apache.iceberg.SortField;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.types.Types;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
+
+/** Test class for {@link FromIcebergSortOrder}. */
+public class TestFromIcebergSortOrder extends TestBaseConvert {
+
+ @Test
+ public void testFromSortOrder() {
+ Types.NestedField[] nestedFields = createNestedField("col_1", "col_2", "col_3");
+ nestedFields =
+ ArrayUtils.add(nestedFields, createNestedField(4, "col_4", Types.DateType.get()));
+ nestedFields =
+ ArrayUtils.add(nestedFields, createNestedField(5, "col_5", Types.DateType.get()));
+ nestedFields =
+ ArrayUtils.add(
+ nestedFields, createNestedField(6, "col_6", Types.TimestampType.withoutZone()));
+ nestedFields =
+ ArrayUtils.add(nestedFields, createNestedField(7, "col_7", Types.IntegerType.get()));
+ nestedFields =
+ ArrayUtils.add(nestedFields, createNestedField(8, "col_8", Types.IntegerType.get()));
+
+ Schema schema = new Schema(nestedFields);
+ org.apache.iceberg.SortOrder.Builder sortOrderBuilder =
+ org.apache.iceberg.SortOrder.builderFor(schema);
+ sortOrderBuilder.sortBy("col_2", SortDirection.DESC, NullOrder.NULLS_FIRST);
+ sortOrderBuilder.sortBy("col_3", SortDirection.ASC, NullOrder.NULLS_LAST);
+ sortOrderBuilder.sortBy(Expressions.year("col_4"), SortDirection.DESC, NullOrder.NULLS_LAST);
+ sortOrderBuilder.sortBy(Expressions.day("col_5"), SortDirection.ASC, NullOrder.NULLS_FIRST);
+ sortOrderBuilder.sortBy(Expressions.hour("col_6"), SortDirection.ASC, NullOrder.NULLS_LAST);
+ sortOrderBuilder.sortBy(
+ Expressions.bucket("col_7", 5), SortDirection.DESC, NullOrder.NULLS_FIRST);
+ sortOrderBuilder.sortBy(
+ Expressions.truncate("col_8", 8), SortDirection.ASC, NullOrder.NULLS_FIRST);
+ org.apache.iceberg.SortOrder icebergSortOrder = sortOrderBuilder.build();
+ SortOrder[] sortOrders = FromIcebergSortOrder.fromSortOrder(sortOrderBuilder.build());
+ Assertions.assertEquals(sortOrders.length, 7);
+
+ Map<String, SortOrder> sortOrderByName =
+ Arrays.stream(sortOrders)
+ .collect(
+ Collectors.toMap(
+ sortOrder -> {
+ if (sortOrder.getTransform() instanceof Transforms.NamedReference) {
+ return ((Transforms.NamedReference) sortOrder.getTransform()).value()[0];
+ } else if (sortOrder.getTransform() instanceof Transforms.FunctionTrans) {
+ return ((Transforms.NamedReference) sortOrder.getTransform().arguments()[0])
+ .value()[0];
+ }
+ throw new RuntimeException("Unsupported transform type");
+ },
+ v -> v));
+ Map<Integer, String> idToName = schema.idToName();
+ List<SortField> sortFields = icebergSortOrder.fields();
+ for (SortField sortField : sortFields) {
+ Assertions.assertTrue(idToName.containsKey(sortField.sourceId()));
+ String sortOrderName = idToName.get(sortField.sourceId());
+ Assertions.assertTrue(sortOrderByName.containsKey(sortOrderName));
+ SortOrder sortOrder = sortOrderByName.get(sortOrderName);
+ Assertions.assertEquals(
+ sortField.direction() == SortDirection.ASC
+ ? SortOrder.Direction.ASC
+ : SortOrder.Direction.DESC,
+ sortOrder.getDirection());
+ Assertions.assertEquals(
+ sortField.nullOrder() == NullOrder.NULLS_FIRST
+ ? SortOrder.NullOrdering.FIRST
+ : SortOrder.NullOrdering.LAST,
+ sortOrder.getNullOrdering());
+ }
+ }
+}
diff --git a/catalogs/catalog-lakehouse-iceberg/src/test/java/com/datastrato/graviton/catalog/lakehouse/iceberg/converter/TestToIcebergPartitionSpec.java b/catalogs/catalog-lakehouse-iceberg/src/test/java/com/datastrato/graviton/catalog/lakehouse/iceberg/converter/TestToIcebergPartitionSpec.java
new file mode 100644
index 0000000000..777c73d0f1
--- /dev/null
+++ b/catalogs/catalog-lakehouse-iceberg/src/test/java/com/datastrato/graviton/catalog/lakehouse/iceberg/converter/TestToIcebergPartitionSpec.java
@@ -0,0 +1,64 @@
+/*
+ * Copyright 2023 Datastrato.
+ * This software is licensed under the Apache License version 2.
+ */
+package com.datastrato.graviton.catalog.lakehouse.iceberg.converter;
+
+import static com.datastrato.graviton.rel.transforms.Transforms.day;
+import static com.datastrato.graviton.rel.transforms.Transforms.hour;
+import static com.datastrato.graviton.rel.transforms.Transforms.identity;
+import static com.datastrato.graviton.rel.transforms.Transforms.month;
+
+import com.datastrato.graviton.rel.transforms.Transform;
+import java.util.Arrays;
+import java.util.List;
+import java.util.Map;
+import java.util.stream.Collectors;
+import org.apache.commons.lang3.ArrayUtils;
+import org.apache.iceberg.PartitionField;
+import org.apache.iceberg.PartitionSpec;
+import org.apache.iceberg.Schema;
+import org.apache.iceberg.types.Types;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
+
+/** Test class for {@link ToIcebergPartitionSpec}. */
+public class TestToIcebergPartitionSpec extends TestBaseConvert {
+
+ @Test
+ void testToPartitionSpec() {
+ Types.NestedField[] nestedFields = createNestedField("col_1", "col_2", "col_3", "col_4");
+
+ nestedFields =
+ ArrayUtils.add(nestedFields, createNestedField(5, "col_5", Types.DateType.get()));
+ nestedFields =
+ ArrayUtils.add(nestedFields, createNestedField(6, "col_6", Types.TimestampType.withZone()));
+ nestedFields =
+ ArrayUtils.add(nestedFields, createNestedField(7, "col_7", Types.DateType.get()));
+
+ Transform[] partitioning =
+ new Transform[] {
+ identity(new String[] {nestedFields[0].name()}),
+ day(new String[] {nestedFields[4].name()}),
+ hour(new String[] {nestedFields[5].name()}),
+ month(new String[] {nestedFields[6].name()})
+ };
+
+ Schema schema = new Schema(nestedFields);
+
+ PartitionSpec partitionSpec = ToIcebergPartitionSpec.toPartitionSpec(schema, partitioning);
+
+ List<PartitionField> fields = partitionSpec.fields();
+ Assertions.assertEquals(partitioning.length, fields.size());
+ Assertions.assertEquals(4, fields.size());
+ Map<Integer, String> idToName = schema.idToName();
+ Map<String, Types.NestedField> nestedFieldByName =
+ Arrays.stream(nestedFields).collect(Collectors.toMap(Types.NestedField::name, v -> v));
+ for (int i = 0; i < fields.size(); i++) {
+ PartitionField partitionField = fields.get(i);
+ Assertions.assertTrue(idToName.containsKey(partitionField.sourceId()));
+ String colName = idToName.get(partitionField.sourceId());
+ Assertions.assertTrue(nestedFieldByName.containsKey(colName));
+ }
+ }
+}
diff --git a/catalogs/catalog-lakehouse-iceberg/src/test/java/com/datastrato/graviton/catalog/lakehouse/iceberg/converter/TestToIcebergSortOrder.java b/catalogs/catalog-lakehouse-iceberg/src/test/java/com/datastrato/graviton/catalog/lakehouse/iceberg/converter/TestToIcebergSortOrder.java
new file mode 100644
index 0000000000..af43909595
--- /dev/null
+++ b/catalogs/catalog-lakehouse-iceberg/src/test/java/com/datastrato/graviton/catalog/lakehouse/iceberg/converter/TestToIcebergSortOrder.java
@@ -0,0 +1,95 @@
+/*
+ * Copyright 2023 Datastrato.
+ * This software is licensed under the Apache License version 2.
+ */
+package com.datastrato.graviton.catalog.lakehouse.iceberg.converter;
+
+import com.datastrato.graviton.rel.SortOrder;
+import com.datastrato.graviton.rel.transforms.Transforms;
+import java.util.Arrays;
+import java.util.List;
+import java.util.Map;
+import java.util.stream.Collectors;
+import org.apache.commons.lang3.ArrayUtils;
+import org.apache.iceberg.NullOrder;
+import org.apache.iceberg.Schema;
+import org.apache.iceberg.SortDirection;
+import org.apache.iceberg.SortField;
+import org.apache.iceberg.types.Types;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
+
+/** Test class for {@link ToIcebergSortOrder}. */
+public class TestToIcebergSortOrder extends TestBaseConvert {
+
+ @Test
+ public void testToSortOrder() {
+ SortOrder[] sortOrders = createSortOrder("col_1", "col_2", "col_3", "col_4", "col_5");
+ sortOrders =
+ ArrayUtils.add(sortOrders, createFunctionSortOrder(Transforms.NAME_OF_DAY, "col_6"));
+ sortOrders =
+ ArrayUtils.add(sortOrders, createFunctionSortOrder(Transforms.NAME_OF_HOUR, "col_7"));
+ sortOrders =
+ ArrayUtils.add(sortOrders, createFunctionSortOrder(Transforms.NAME_OF_MONTH, "col_8"));
+ sortOrders =
+ ArrayUtils.add(sortOrders, createFunctionSortOrder(Transforms.NAME_OF_YEAR, "col_9"));
+
+ Types.NestedField[] nestedFields =
+ createNestedField("col_1", "col_2", "col_3", "col_4", "col_5");
+ nestedFields =
+ ArrayUtils.add(nestedFields, createNestedField(6, "col_6", Types.DateType.get()));
+ nestedFields =
+ ArrayUtils.add(nestedFields, createNestedField(7, "col_7", Types.TimestampType.withZone()));
+ nestedFields =
+ ArrayUtils.add(nestedFields, createNestedField(8, "col_8", Types.DateType.get()));
+ nestedFields =
+ ArrayUtils.add(nestedFields, createNestedField(9, "col_9", Types.DateType.get()));
+ Schema schema = new Schema(nestedFields);
+ org.apache.iceberg.SortOrder icebergSortOrder =
+ ToIcebergSortOrder.toSortOrder(schema, sortOrders);
+
+ List<SortField> sortFields = icebergSortOrder.fields();
+ Assertions.assertEquals(sortOrders.length, sortFields.size());
+
+ Map<Integer, String> idToName = schema.idToName();
+ Map<String, SortOrder> sortOrderByName =
+ Arrays.stream(sortOrders)
+ .collect(
+ Collectors.toMap(
+ sortOrder -> {
+ if (sortOrder.getTransform() instanceof Transforms.NamedReference) {
+ return ((Transforms.NamedReference) sortOrder.getTransform()).value()[0];
+ } else if (sortOrder.getTransform() instanceof Transforms.FunctionTrans) {
+ return ((Transforms.NamedReference) sortOrder.getTransform().arguments()[0])
+ .value()[0];
+ } else {
+ throw new UnsupportedOperationException("Unsupported sort type.");
+ }
+ },
+ v -> v));
+ for (SortField sortField : sortFields) {
+ Assertions.assertTrue(idToName.containsKey(sortField.sourceId()));
+ String colName = idToName.get(sortField.sourceId());
+ Assertions.assertTrue(sortOrderByName.containsKey(colName));
+ SortOrder sortOrder = sortOrderByName.get(colName);
+ if (colName.equals("col_6")
+ || colName.equals("col_7")
+ || colName.equals("col_8")
+ || colName.equals("col_9")) {
+ Assertions.assertFalse(sortField.transform().isIdentity());
+ } else {
+ Assertions.assertTrue(sortField.transform().isIdentity());
+ }
+ Assertions.assertEquals(
+ sortOrder.getDirection() == SortOrder.Direction.ASC
+ ? SortDirection.ASC
+ : SortDirection.DESC,
+ sortField.direction());
+ Assertions.assertEquals(
+ sortOrder.getNullOrdering() == SortOrder.NullOrdering.FIRST
+ ? NullOrder.NULLS_FIRST
+ : NullOrder.NULLS_LAST,
+ sortField.nullOrder());
+ }
+ }
+}
diff --git a/core/src/main/java/com/datastrato/graviton/meta/AuditInfo.java b/core/src/main/java/com/datastrato/graviton/meta/AuditInfo.java
index caae45eb65..0d67b43015 100644
--- a/core/src/main/java/com/datastrato/graviton/meta/AuditInfo.java
+++ b/core/src/main/java/com/datastrato/graviton/meta/AuditInfo.java
@@ -32,6 +32,8 @@ public final class AuditInfo implements Audit, Entity {
Field.optional(
"last_modified_time", Instant.class, "The time when the entity was last modified");
+ public static final AuditInfo EMPTY = new AuditInfo.Builder().build();
+
@Nullable private String creator;
@Nullable private Instant createTime;
diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml
index 666075f7c5..ff4a96e5d7 100644
--- a/gradle/libs.versions.toml
+++ b/gradle/libs.versions.toml
@@ -84,6 +84,7 @@ caffeine = { group = "com.github.ben-manes.caffeine", name = "caffeine", version
rocksdbjni = { group = "org.rocksdb", name = "rocksdbjni", version.ref = "rocksdbjni" }
commons-collections4 = { group = "org.apache.commons", name = "commons-collections4", version.ref = "commons-collections4" }
iceberg-core = { group = "org.apache.iceberg", name = "iceberg-core", version.ref = "iceberg" }
+iceberg-api = { group = "org.apache.iceberg", name = "iceberg-api", version.ref = "iceberg" }
iceberg-hive-metastore = { group = "org.apache.iceberg", name = "iceberg-hive-metastore", version.ref = "iceberg" }
trino-spi= { group = "io.trino", name = "trino-spi", version.ref = "trino" }
trino-toolkit= { group = "io.trino", name = "trino-plugin-toolkit", version.ref = "trino" }
@@ -95,7 +96,7 @@ spark-sql = { group = "org.apache.spark", name = "spark-sql_2.13", version.ref =
log4j = ["slf4j-api", "log4j-slf4j2-impl", "log4j-api", "log4j-core", "log4j-12-api"]
jetty = ["jetty-server", "jetty-servlet"]
jersey = ["jersey-server", "jersey-container-servlet-core", "jersey-container-jetty-http", "jersey-media-json-jackson", "jersey-hk2"]
-iceberg = ["iceberg-core"]
+iceberg = ["iceberg-core", "iceberg-api"]
[plugins]
protobuf = { id = "com.google.protobuf", version.ref = "protobuf-plugin" }