This is an automated email from the ASF dual-hosted git repository.
kevinjqliu pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/iceberg.git
The following commit(s) were added to refs/heads/main by this push:
new f41a3ed59f Delta: Add Delta Kernel based snapshot action (#15407)
f41a3ed59f is described below
commit f41a3ed59f6485617c9c4a4ede4cbf79f2ace4cf
Author: Vladislav Sidorovich <[email protected]>
AuthorDate: Mon Nov 23 23:35:33 2026 +0100
Delta: Add Delta Kernel based snapshot action (#15407)
Co-authored-by: Fokko Driesprong <[email protected]>
---
build.gradle | 6 +-
...eltaLakeToIcebergMigrationSparkIntegration.java | 31 +
.../delta/TestSnapshotDeltaLakeKernelTable.java | 413 +++++++++++++
.../BaseSnapshotDeltaLakeKernelTableAction.java | 688 +++++++++++++++++++++
.../delta/BaseSnapshotDeltaLakeTableAction.java | 6 +-
.../delta/DeltaLakeActionsTranslationUtil.java | 66 ++
.../iceberg/delta/DeltaLakeDataTypeVisitor.java | 16 +-
...eToType.java => DeltaLakeKernelTypeToType.java} | 120 ++--
.../apache/iceberg/delta/DeltaLakeTypeToType.java | 5 +-
.../iceberg/delta/InternalDeltaKernelUtils.java | 232 +++++++
.../apache/iceberg/delta/DeltaKernelTestUtils.java | 209 +++++++
...TestBaseSnapshotDeltaLakeKernelTableAction.java | 284 +++++++++
.../delta/TestDeltaLakeKernelTypeToType.java | 240 +++++++
.../iceberg/delta/TestDeltaLakePathHandling.java | 55 ++
gradle/libs.versions.toml | 4 +
15 files changed, 2308 insertions(+), 67 deletions(-)
diff --git a/build.gradle b/build.gradle
index 400f7cecbb..f6b3542194 100644
--- a/build.gradle
+++ b/build.gradle
@@ -291,7 +291,7 @@ subprojects {
failedTests << "${descriptor.className}.${descriptor.name}"
}
}
-
+
void afterSuite(TestDescriptor descriptor, TestResult result) {
if (descriptor.parent == null && !failedTests.isEmpty()) {
println "\nFailures:"
@@ -300,7 +300,7 @@ subprojects {
}
}
}
-
+
void beforeTest(TestDescriptor descriptor) {}
void beforeSuite(TestDescriptor descriptor) {}
})
@@ -709,6 +709,8 @@ project(':iceberg-delta-lake') {
compileOnly libs.immutables.value
compileOnly
"io.delta:delta-standalone_${scalaVersion}:${libs.versions.delta.standalone.get()}"
+ compileOnly libs.delta.kernel.api
+ compileOnly libs.delta.kernel.defaults
compileOnly(libs.hadoop3.common) {
exclude group: 'org.apache.avro', module: 'avro'
diff --git
a/delta-lake/src/integration/java/org/apache/iceberg/delta/DeltaLakeToIcebergMigrationSparkIntegration.java
b/delta-lake/src/integration/java/org/apache/iceberg/delta/DeltaLakeToIcebergMigrationSparkIntegration.java
index 5a3ad24a0e..e1959844f8 100644
---
a/delta-lake/src/integration/java/org/apache/iceberg/delta/DeltaLakeToIcebergMigrationSparkIntegration.java
+++
b/delta-lake/src/integration/java/org/apache/iceberg/delta/DeltaLakeToIcebergMigrationSparkIntegration.java
@@ -60,4 +60,35 @@ class DeltaLakeToIcebergMigrationSparkIntegration {
.deltaLakeConfiguration(spark.sessionState().newHadoopConf())
.icebergCatalog(Spark3Util.loadIcebergCatalog(spark,
catalogAndIdent.catalog().name()));
}
+
+ /**
+ * Example of how to use a {@link SparkSession}, a table identifier and a
delta table location to
+ * construct an action for snapshotting the delta table to an iceberg table.
+ *
+ * @param spark a SparkSession with iceberg catalog configured.
+ * @param newTableIdentifier can be both 2 parts and 3 parts identifier, if
it is 2 parts, the
+ * default spark catalog will be used
+ * @param deltaTableLocation the location of the delta table
+ * @return an instance of snapshot delta lake table action.
+ */
+ static SnapshotDeltaLakeTable snapshotDeltaLakeKernelTable(
+ SparkSession spark, String newTableIdentifier, String
deltaTableLocation) {
+ Preconditions.checkArgument(
+ spark != null, "The SparkSession cannot be null, please provide a
valid SparkSession");
+ Preconditions.checkArgument(
+ newTableIdentifier != null,
+ "The table identifier cannot be null, please provide a valid table
identifier for the new Iceberg table");
+ Preconditions.checkArgument(
+ deltaTableLocation != null,
+ "The Delta Lake table location cannot be null, please provide a valid
location of the Delta Lake table to be snapshot");
+
+ String ctx = " Delta Lake snapshot target";
+ CatalogPlugin defaultCatalog =
spark.sessionState().catalogManager().currentCatalog();
+ Spark3Util.CatalogAndIdentifier catalogAndIdent =
+ Spark3Util.catalogAndIdentifier(ctx, spark, newTableIdentifier,
defaultCatalog);
+ return new BaseSnapshotDeltaLakeKernelTableAction(deltaTableLocation)
+ .as(TableIdentifier.parse(catalogAndIdent.identifier().toString()))
+ .deltaLakeConfiguration(spark.sessionState().newHadoopConf())
+ .icebergCatalog(Spark3Util.loadIcebergCatalog(spark,
catalogAndIdent.catalog().name()));
+ }
}
diff --git
a/delta-lake/src/integration/java/org/apache/iceberg/delta/TestSnapshotDeltaLakeKernelTable.java
b/delta-lake/src/integration/java/org/apache/iceberg/delta/TestSnapshotDeltaLakeKernelTable.java
new file mode 100644
index 0000000000..3291a87527
--- /dev/null
+++
b/delta-lake/src/integration/java/org/apache/iceberg/delta/TestSnapshotDeltaLakeKernelTable.java
@@ -0,0 +1,413 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.iceberg.delta;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+
+import io.delta.kernel.defaults.engine.DefaultEngine;
+import java.io.File;
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Paths;
+import java.sql.Timestamp;
+import java.util.Arrays;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.ThreadLocalRandom;
+import org.apache.iceberg.Snapshot;
+import org.apache.iceberg.SnapshotRef;
+import org.apache.iceberg.Table;
+import org.apache.iceberg.catalog.TableIdentifier;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableMap;
+import org.apache.iceberg.relocated.com.google.common.collect.Lists;
+import org.apache.iceberg.spark.Spark3Util;
+import org.apache.iceberg.spark.SparkCatalog;
+import org.apache.iceberg.util.LocationUtil;
+import org.apache.spark.sql.DataFrameWriter;
+import org.apache.spark.sql.Dataset;
+import org.apache.spark.sql.Row;
+import org.apache.spark.sql.RowFactory;
+import org.apache.spark.sql.SaveMode;
+import org.apache.spark.sql.connector.catalog.CatalogPlugin;
+import org.apache.spark.sql.delta.catalog.DeltaCatalog;
+import org.apache.spark.sql.types.DataTypes;
+import org.apache.spark.sql.types.Metadata;
+import org.apache.spark.sql.types.StructField;
+import org.apache.spark.sql.types.StructType;
+import org.junit.jupiter.api.AfterAll;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.io.TempDir;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.CsvSource;
+
+public class TestSnapshotDeltaLakeKernelTable extends
SparkDeltaLakeSnapshotTestBase {
+ private static final String NAMESPACE = "delta_conversion_test_ns";
+ private static final String DEFAULT_SPARK_CATALOG = "spark_catalog";
+ private static final String ICEBERG_CATALOG_NAME = "iceberg_hive";
+ private static final Map<String, String> BASE_SPARK_CONFIG =
+ ImmutableMap.of(
+ "type",
+ "hive",
+ "default-namespace",
+ "default",
+ "parquet-enabled",
+ "true",
+ "cache-enabled",
+ "false" // Spark will delete tables using v1, leaving the cache out
of sync
+ );
+
+ private static final int INITIAL_EMPTY_COMMIT = 1;
+
+ private static Dataset<Row> genericDataFrame;
+
+ @TempDir private File sourceLocation;
+
+ public TestSnapshotDeltaLakeKernelTable() {
+ super(ICEBERG_CATALOG_NAME, SparkCatalog.class.getName(),
BASE_SPARK_CONFIG);
+ spark.conf().set("spark.sql.catalog." + DEFAULT_SPARK_CATALOG,
DeltaCatalog.class.getName());
+ }
+
+ @BeforeAll
+ public static void beforeClass() {
+ spark.sql(String.format("CREATE DATABASE IF NOT EXISTS %s", NAMESPACE));
+ StructType schema =
+ new StructType(
+ new StructField[] {
+ new StructField("id", DataTypes.IntegerType, false,
Metadata.empty()),
+ new StructField("created_at", DataTypes.TimestampType, true,
Metadata.empty()),
+ new StructField("event_name", DataTypes.StringType, true,
Metadata.empty()),
+ new StructField("is_active", DataTypes.BooleanType, true,
Metadata.empty()),
+ new StructField("price", DataTypes.DoubleType, true,
Metadata.empty())
+ });
+ List<Row> data =
+ Arrays.asList(
+ RowFactory.create(1, Timestamp.valueOf("2025-01-01 10:00:00"),
"Signup", true, 0.00),
+ RowFactory.create(
+ 2, Timestamp.valueOf("2025-01-02 14:30:00"), "Purchase", true,
199.99),
+ RowFactory.create(
+ 3, Timestamp.valueOf("2025-01-03 09:15:00"), "Deactivation",
false, 0.00),
+ RowFactory.create(4, Timestamp.valueOf("2025-01-03 09:16:00"),
"Refund", false, 0.00),
+ RowFactory.create(5, Timestamp.valueOf("2025-01-03 09:17:00"),
"Refund", false, 0.00));
+ genericDataFrame = spark.createDataFrame(data, schema);
+ }
+
+ @AfterAll
+ public static void afterClass() {
+ spark.sql(String.format("DROP DATABASE IF EXISTS %s CASCADE", NAMESPACE));
+ }
+
+ @Test
+ public void testBasicPartitionedInsertsOnly() {
+ String sourceTable = toFullTableName(DEFAULT_SPARK_CATALOG,
"partitioned_table");
+ String sourceTableLocation = sourceLocation.toURI().toString();
+
+ writeDeltaTable(genericDataFrame, sourceTable, sourceTableLocation, "id");
+ spark.sql("INSERT INTO " + sourceTable + " VALUES (10, current_date(),
null, null, null);");
+ spark.sql("INSERT INTO " + sourceTable + " VALUES (11, current_date(),
null, null, null);");
+ spark.sql("INSERT INTO " + sourceTable + " VALUES (12, current_date(),
null, null, null);");
+
+ String newTableIdentifier = toFullTableName(ICEBERG_CATALOG_NAME,
"iceberg_partitioned_table");
+
+ // Act
+ SnapshotDeltaLakeTable conversionAction =
+
DeltaLakeToIcebergMigrationSparkIntegration.snapshotDeltaLakeKernelTable(
+ spark, newTableIdentifier, sourceTableLocation);
+ SnapshotDeltaLakeTable.Result result = conversionAction.execute();
+
+ // Assert
+ checkLatestSnapshotIntegrity(sourceTable, newTableIdentifier);
+ checkTagContentAndOrder(sourceTable, sourceTableLocation,
newTableIdentifier, 0);
+ checkIcebergTableLocation(newTableIdentifier, sourceTableLocation);
+ }
+
+ @Test
+ public void testInsertUpdateDeleteSqls() {
+ String sourceTable = toFullTableName(DEFAULT_SPARK_CATALOG, "crud_table");
+ String sourceTableLocation = sourceLocation.toURI().toString();
+
+ writeDeltaTable(genericDataFrame, sourceTable, sourceTableLocation, "id");
+ spark.sql("INSERT INTO " + sourceTable + " VALUES (10, current_date(),
null, null, null);");
+ spark.sql("DELETE FROM " + sourceTable + " WHERE id=3;");
+ spark.sql("UPDATE " + sourceTable + " SET id=3 WHERE id=1;");
+ spark.sql("INSERT INTO " + sourceTable + " VALUES (11, current_date(),
null, null, null);");
+
+ String newTableIdentifier = toFullTableName(ICEBERG_CATALOG_NAME,
"iceberg_crud_table");
+
+ // Act
+ SnapshotDeltaLakeTable conversionAction =
+
DeltaLakeToIcebergMigrationSparkIntegration.snapshotDeltaLakeKernelTable(
+ spark, newTableIdentifier, sourceTableLocation);
+ SnapshotDeltaLakeTable.Result result = conversionAction.execute();
+
+ // Assert
+ checkLatestSnapshotIntegrity(sourceTable, newTableIdentifier);
+ checkTagContentAndOrder(sourceTable, sourceTableLocation,
newTableIdentifier, 0);
+ checkIcebergTableLocation(newTableIdentifier, sourceTableLocation);
+ }
+
+ @Test
+ public void testConversionAfterVacuum() throws IOException {
+ String sourceTable = toFullTableName(DEFAULT_SPARK_CATALOG,
"vacuumed_table");
+ String sourceTableLocation = sourceLocation.toURI().toString();
+
+ writeDeltaTable(genericDataFrame, sourceTable, sourceTableLocation, "id");
+ for (int i = 0; i < 5; i++) {
+ spark.sql(
+ "UPDATE "
+ + sourceTable
+ + " SET price="
+ + ThreadLocalRandom.current().nextDouble(1000)
+ + " where id="
+ + i
+ + ";");
+ }
+ spark.sql("UPDATE " + sourceTable + " SET created_at=current_date() ;");
+ spark.sql("INSERT INTO " + sourceTable + " VALUES (10, current_date(),
null, null, null);");
+ spark.sql("INSERT INTO " + sourceTable + " VALUES (11, current_date(),
null, null, null);");
+ spark.sql("DELETE FROM " + sourceTable + " WHERE id>=10;");
+ spark.sql("VACUUM " + sourceTable + " RETAIN 0 HOURS");
+ spark.sql(
+ "INSERT INTO " + sourceTable + " VALUES (12, current_date(),
'after_vacuum', null, null);");
+ spark.sql("UPDATE " + sourceTable + " SET id=13 WHERE id=5;");
+
+ // Checkpoint generated. Simulate logs clean-up
+ assertThat(deleteDeltaLogFile("00000000000000000000.json")).isTrue();
+ assertThat(deleteDeltaLogFile("00000000000000000001.json")).isTrue();
+ assertThat(deleteDeltaLogFile("00000000000000000002.json")).isTrue();
+
+ String newTableIdentifier = toFullTableName(ICEBERG_CATALOG_NAME,
"iceberg_vacuumed_table");
+
+ // Act
+ SnapshotDeltaLakeTable conversionAction =
+
DeltaLakeToIcebergMigrationSparkIntegration.snapshotDeltaLakeKernelTable(
+ spark, newTableIdentifier, sourceTableLocation);
+ SnapshotDeltaLakeTable.Result result = conversionAction.execute();
+
+ // Assert
+ checkLatestSnapshotIntegrity(sourceTable, newTableIdentifier);
+ checkTagContentAndOrder(sourceTable, sourceTableLocation,
newTableIdentifier, 10);
+ checkIcebergTableLocation(newTableIdentifier, sourceTableLocation);
+ }
+
+ @Test
+ public void testConversionAfterVacuumNoCheckpoints() throws IOException {
+ String sourceTable = toFullTableName(DEFAULT_SPARK_CATALOG,
"vacuumed_table_no_checkpoints");
+ String sourceTableLocation = sourceLocation.toURI().toString();
+
+ writeDeltaTable(genericDataFrame, sourceTable, sourceTableLocation, "id");
+ spark.sql("UPDATE " + sourceTable + " SET created_at=current_date() ;");
+ spark.sql("VACUUM " + sourceTable + " RETAIN 0 HOURS");
+
+ String newTableIdentifier =
+ toFullTableName(ICEBERG_CATALOG_NAME,
"iceberg_vacuumed_table_no_checkpoints");
+
+ // Act
+ SnapshotDeltaLakeTable conversionAction =
+
DeltaLakeToIcebergMigrationSparkIntegration.snapshotDeltaLakeKernelTable(
+ spark, newTableIdentifier, sourceTableLocation);
+ SnapshotDeltaLakeTable.Result result = conversionAction.execute();
+
+ // Assert
+ checkLatestSnapshotIntegrity(sourceTable, newTableIdentifier);
+ checkTagContentAndOrder(sourceTable, sourceTableLocation,
newTableIdentifier, 1);
+ checkIcebergTableLocation(newTableIdentifier, sourceTableLocation);
+ }
+
+ @Test
+ public void testConversionWithDeletionVectors() {
+ String sourceTable = toFullTableName(DEFAULT_SPARK_CATALOG, "dv_table");
+ String sourceTableLocation = sourceLocation.toURI().toString();
+
+ spark.sql(String.format("DROP TABLE IF EXISTS %s", sourceTable));
+
+ // 10k records to force usage of DVs in Update operation
+ Dataset<Row> dvDf =
+ spark
+ .range(10000)
+ .selectExpr(
+ "CAST(id AS int) AS id",
+ "current_timestamp() AS created_at",
+ "CAST(id AS string) AS event_name",
+ "CAST(id % 2 == 0 AS boolean) AS is_active",
+ "CAST(id AS double) AS price");
+
+ dvDf.write()
+ .format("delta")
+ .mode(SaveMode.Append)
+ .option("path", sourceTableLocation)
+ .option("delta.enableDeletionVectors", "true")
+ .option("delta.enableInCommitTimestamps", "true")
+ .option("delta.enableRowTracking", "true")
+ .saveAsTable(sourceTable);
+
+ spark.sql("UPDATE " + sourceTable + " SET id=-1 WHERE id=1 OR id=2;");
+
+ String newTableIdentifier = toFullTableName(ICEBERG_CATALOG_NAME,
"iceberg_dv_table");
+
+ // Act
+ SnapshotDeltaLakeTable conversionAction =
+
DeltaLakeToIcebergMigrationSparkIntegration.snapshotDeltaLakeKernelTable(
+ spark, newTableIdentifier, sourceTableLocation);
+ conversionAction.execute();
+
+ // Assert
+ checkLatestSnapshotIntegrity(sourceTable, newTableIdentifier);
+ checkTagContentAndOrder(sourceTable, sourceTableLocation,
newTableIdentifier, 0);
+ checkIcebergTableLocation(newTableIdentifier, sourceTableLocation);
+ }
+
+ @ParameterizedTest
+ @CsvSource(
+ useHeadersInDisplayName = false,
+ value = {
+ "ALTER TABLE %s ADD COLUMNS (new_col string), schema",
+ "ALTER TABLE %s ALTER COLUMN price COMMENT 'new price comment',
schema",
+ "ALTER TABLE %s SET TBLPROPERTIES ('new_prop' = 'value'),
configuration",
+ "COMMENT ON TABLE %s IS 'new table comment', description"
+ })
+ public void testSchemaEvolutionAddColumn(String sqlTemplate, String
expectedChange) {
+ String sourceTable = toFullTableName(DEFAULT_SPARK_CATALOG,
"add_column_table");
+ String sourceTableLocation = sourceLocation.toURI().toString();
+
+ writeDeltaTable(genericDataFrame, sourceTable, sourceTableLocation);
+
+ // Schema evolution
+ spark.sql(String.format(sqlTemplate, sourceTable));
+
+ String newTableIdentifier = toFullTableName(ICEBERG_CATALOG_NAME,
"iceberg_add_column_table");
+
+ // Act & Assert
+ SnapshotDeltaLakeTable conversionAction =
+
DeltaLakeToIcebergMigrationSparkIntegration.snapshotDeltaLakeKernelTable(
+ spark, newTableIdentifier, sourceTableLocation);
+
+ assertThatThrownBy(conversionAction::execute)
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ String.format(
+ "Cannot convert Delta table: metadata change of '%s' is not
supported (detected at Delta version 1).",
+ expectedChange));
+ }
+
+ private void checkLatestSnapshotIntegrity(
+ String deltaTableIdentifier, String icebergTableIdentifier) {
+ checkSnapshotIntegrityForQuery(
+ "SELECT * FROM " + deltaTableIdentifier, "SELECT * FROM " +
icebergTableIdentifier);
+ }
+
+ private void checkSnapshotIntegrityForQuery(String deltaSql, String
icebergSql) {
+ List<Row> deltaTableContents = spark.sql(deltaSql).collectAsList();
+ List<Row> icebergTableContents = spark.sql(icebergSql).collectAsList();
+
+ assertThat(deltaTableContents).hasSize(icebergTableContents.size());
+
assertThat(icebergTableContents).containsExactlyInAnyOrderElementsOf(deltaTableContents);
+ }
+
+ private void checkTagContentAndOrder(
+ String deltaTableIdentifier,
+ String deltaTableLocation,
+ String icebergTableIdentifier,
+ long firstConstructableVersion) {
+ DefaultEngine deltaEngine =
DefaultEngine.create(spark.sessionState().newHadoopConf());
+ io.delta.kernel.Table deltaTable =
+ io.delta.kernel.Table.forPath(deltaEngine, deltaTableLocation);
+ io.delta.kernel.Snapshot latestSnapshot =
deltaTable.getLatestSnapshot(deltaEngine);
+ long currentVersion = latestSnapshot.getVersion();
+ Table icebergTable = getIcebergTable(icebergTableIdentifier);
+ Map<String, SnapshotRef> icebergSnapshotRefs = icebergTable.refs();
+ List<Snapshot> icebergSnapshots =
Lists.newArrayList(icebergTable.snapshots());
+
+ assertThat(icebergSnapshots)
+ .hasSize((int) (currentVersion - firstConstructableVersion + 1) +
INITIAL_EMPTY_COMMIT);
+
+ for (int i = 1; i < icebergSnapshots.size(); i++) {
+ long deltaVersion = firstConstructableVersion + i - INITIAL_EMPTY_COMMIT;
+ Snapshot currentIcebergSnapshot = icebergSnapshots.get(i);
+
+ String expectedVersionTag = "delta-version-" + deltaVersion;
+ icebergSnapshotRefs.get(expectedVersionTag);
+ assertThat(icebergSnapshotRefs.get(expectedVersionTag)).isNotNull();
+ assertThat(icebergSnapshotRefs.get(expectedVersionTag).isTag()).isTrue();
+ assertThat(icebergSnapshotRefs.get(expectedVersionTag).snapshotId())
+ .isEqualTo(currentIcebergSnapshot.snapshotId());
+
+ long deltaVersionTs =
+ deltaTable.getSnapshotAsOfVersion(deltaEngine,
deltaVersion).getTimestamp(deltaEngine);
+ String expectedTimestampTag = "delta-ts-" + deltaVersionTs;
+
+ assertThat(icebergSnapshotRefs.get(expectedTimestampTag)).isNotNull();
+
assertThat(icebergSnapshotRefs.get(expectedTimestampTag).isTag()).isTrue();
+ assertThat(icebergSnapshotRefs.get(expectedTimestampTag).snapshotId())
+ .isEqualTo(currentIcebergSnapshot.snapshotId());
+ checkSnapshotIntegrityForQuery(
+ "SELECT * FROM " + deltaTableIdentifier + " VERSION AS OF " +
deltaVersion,
+ "SELECT * FROM "
+ + icebergTableIdentifier
+ + " VERSION AS OF '"
+ + expectedVersionTag
+ + "'");
+ }
+ }
+
+ private void writeDeltaTable(
+ Dataset<Row> df, String identifier, String path, String...
partitionColumns) {
+ spark.sql(String.format("DROP TABLE IF EXISTS %s", identifier));
+ DataFrameWriter<Row> delta =
+ df.write()
+ .format("delta")
+ .mode(SaveMode.Append)
+ .option("path", path)
+ .option("delta.enableInCommitTimestamps", "true")
+ .option("delta.enableRowTracking", "true"); // Increase delta
writer version to 7
+
+ if (partitionColumns.length > 0) {
+ delta = delta.partitionBy(partitionColumns);
+ }
+ delta.saveAsTable(identifier);
+ }
+
+ private String toFullTableName(String catalogName, String dest) {
+ if (catalogName.equals(DEFAULT_SPARK_CATALOG)) {
+ return NAMESPACE + "." + catalogName + "_" + dest;
+ }
+ return catalogName + "." + NAMESPACE + "." + catalogName + "_" + dest;
+ }
+
+ private boolean deleteDeltaLogFile(String logName) throws IOException {
+ String tablePath = sourceLocation.toPath().toString();
+ return Files.deleteIfExists(Paths.get(tablePath, "/_delta_log/", logName));
+ }
+
+ private void checkIcebergTableLocation(String icebergTableIdentifier, String
expectedLocation) {
+ Table icebergTable = getIcebergTable(icebergTableIdentifier);
+ assertThat(icebergTable.location())
+ .isEqualTo(LocationUtil.stripTrailingSlash(expectedLocation));
+ }
+
+ private Table getIcebergTable(String icebergTableIdentifier) {
+ CatalogPlugin defaultCatalog =
spark.sessionState().catalogManager().currentCatalog();
+ Spark3Util.CatalogAndIdentifier catalogAndIdent =
+ Spark3Util.catalogAndIdentifier(
+ "test catalog", spark, icebergTableIdentifier, defaultCatalog);
+ return Spark3Util.loadIcebergCatalog(spark,
catalogAndIdent.catalog().name())
+
.loadTable(TableIdentifier.parse(catalogAndIdent.identifier().toString()));
+ }
+}
diff --git
a/delta-lake/src/main/java/org/apache/iceberg/delta/BaseSnapshotDeltaLakeKernelTableAction.java
b/delta-lake/src/main/java/org/apache/iceberg/delta/BaseSnapshotDeltaLakeKernelTableAction.java
new file mode 100644
index 0000000000..44d28f79f8
--- /dev/null
+++
b/delta-lake/src/main/java/org/apache/iceberg/delta/BaseSnapshotDeltaLakeKernelTableAction.java
@@ -0,0 +1,688 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.iceberg.delta;
+
+import io.delta.kernel.Scan;
+import io.delta.kernel.Snapshot;
+import io.delta.kernel.Table;
+import io.delta.kernel.data.ColumnarBatch;
+import io.delta.kernel.data.FilteredColumnarBatch;
+import io.delta.kernel.data.Row;
+import io.delta.kernel.defaults.engine.DefaultEngine;
+import io.delta.kernel.engine.Engine;
+import io.delta.kernel.exceptions.KernelException;
+import io.delta.kernel.exceptions.TableNotFoundException;
+import io.delta.kernel.types.StructType;
+import io.delta.kernel.utils.CloseableIterator;
+import java.io.File;
+import java.io.IOException;
+import java.io.UncheckedIOException;
+import java.net.URI;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.stream.Collectors;
+import javax.annotation.Nonnull;
+import org.apache.hadoop.conf.Configuration;
+import org.apache.iceberg.AppendFiles;
+import org.apache.iceberg.DataFile;
+import org.apache.iceberg.DataFiles;
+import org.apache.iceberg.DeleteFile;
+import org.apache.iceberg.DeleteFiles;
+import org.apache.iceberg.FileFormat;
+import org.apache.iceberg.ManageSnapshots;
+import org.apache.iceberg.Metrics;
+import org.apache.iceberg.MetricsConfig;
+import org.apache.iceberg.OverwriteFiles;
+import org.apache.iceberg.PartitionField;
+import org.apache.iceberg.PartitionSpec;
+import org.apache.iceberg.RowDelta;
+import org.apache.iceberg.Schema;
+import org.apache.iceberg.TableProperties;
+import org.apache.iceberg.Transaction;
+import org.apache.iceberg.catalog.Catalog;
+import org.apache.iceberg.catalog.TableIdentifier;
+import org.apache.iceberg.deletes.BaseDVFileWriter;
+import org.apache.iceberg.deletes.DVFileWriter;
+import org.apache.iceberg.delta.InternalDeltaKernelUtils.DeltaAddFile;
+import org.apache.iceberg.delta.InternalDeltaKernelUtils.DeltaMetadata;
+import org.apache.iceberg.delta.InternalDeltaKernelUtils.DeltaRemoveFile;
+import org.apache.iceberg.exceptions.NotFoundException;
+import org.apache.iceberg.exceptions.ValidationException;
+import org.apache.iceberg.hadoop.HadoopFileIO;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.io.OutputFileFactory;
+import org.apache.iceberg.mapping.MappingUtil;
+import org.apache.iceberg.mapping.NameMapping;
+import org.apache.iceberg.mapping.NameMappingParser;
+import org.apache.iceberg.parquet.ParquetUtil;
+import
org.apache.iceberg.relocated.com.google.common.annotations.VisibleForTesting;
+import org.apache.iceberg.relocated.com.google.common.base.Preconditions;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableMap;
+import org.apache.iceberg.relocated.com.google.common.collect.Iterators;
+import org.apache.iceberg.relocated.com.google.common.collect.Lists;
+import org.apache.iceberg.relocated.com.google.common.collect.Sets;
+import org.apache.iceberg.types.Type;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+class BaseSnapshotDeltaLakeKernelTableAction implements SnapshotDeltaLakeTable
{
+ private static final Logger LOG =
+ LoggerFactory.getLogger(BaseSnapshotDeltaLakeKernelTableAction.class);
+
+ private static final String SNAPSHOT_SOURCE_PROP = "snapshot_source";
+ private static final String DELTA_SOURCE_VALUE = "delta";
+ private static final String ORIGINAL_LOCATION_PROP = "original_location";
+ private static final String CONVERSION_TOOL_PROP = "conversion_tool";
+ private static final String CONVERSION_TOOL_VALUE = "iceberg-delta-lake";
+ private static final String DELTA_VERSION_TAG_PREFIX = "delta-version-";
+ private static final String DELTA_TIMESTAMP_TAG_PREFIX = "delta-ts-";
+ private static final String METADATA_CHANGE_SCHEMA = "schema";
+ private static final String METADATA_CHANGE_PARTITION_COLUMNS = "partition
columns";
+ private static final String METADATA_CHANGE_CONFIGURATION = "configuration";
+ private static final String METADATA_CHANGE_DESCRIPTION = "description";
+
+ private final ImmutableMap.Builder<String, String> icebergPropertiesBuilder =
+ ImmutableMap.builder();
+
+ private final String deltaTableLocation;
+ private Engine deltaEngine;
+ private Table deltaTable;
+ private Snapshot deltaLatestSnapshot;
+ private DeltaMetadata currentDeltaMetadata;
+
+ private Catalog icebergCatalog;
+ private TableIdentifier newTableIdentifier;
+ private String newTableLocation;
+ private HadoopFileIO deltaLakeFileIO;
+ private OutputFileFactory icebergDVFileFactory;
+ private final Set<Long> deltaTimestampTags = Sets.newHashSet();
+
+ BaseSnapshotDeltaLakeKernelTableAction(String deltaTableLocation) {
+ this.deltaTableLocation = deltaTableLocation;
+ this.newTableLocation = deltaTableLocation;
+ }
+
+ @Override
+ public SnapshotDeltaLakeTable tableProperties(Map<String, String>
properties) {
+ icebergPropertiesBuilder.putAll(properties);
+ return this;
+ }
+
+ @Override
+ public SnapshotDeltaLakeTable tableProperty(String name, String value) {
+ icebergPropertiesBuilder.put(name, value);
+ return this;
+ }
+
+ @Override
+ public SnapshotDeltaLakeTable tableLocation(String location) {
+ newTableLocation = location;
+ return this;
+ }
+
+ @Override
+ public SnapshotDeltaLakeTable as(TableIdentifier identifier) {
+ newTableIdentifier = identifier;
+ return this;
+ }
+
+ @Override
+ public SnapshotDeltaLakeTable icebergCatalog(Catalog catalog) {
+ icebergCatalog = catalog;
+ return this;
+ }
+
+ @Override
+ public SnapshotDeltaLakeTable deltaLakeConfiguration(Configuration conf) {
+ deltaEngine = DefaultEngine.create(conf);
+ deltaLakeFileIO = new HadoopFileIO(conf);
+ deltaTable = Table.forPath(deltaEngine, deltaTableLocation);
+ return this;
+ }
+
+ @Override
+ public Result execute() {
+ Preconditions.checkArgument(
+ icebergCatalog != null && newTableIdentifier != null,
+ "Iceberg catalog and identifier cannot be null. Make sure to configure
the action with a valid Iceberg catalog and identifier.");
+ Preconditions.checkArgument(
+ deltaTable != null && deltaLakeFileIO != null,
+ "Make sure to configure the action with a valid
deltaLakeConfiguration");
+
+ loadLatestDeltaSnapshot();
+ assertDeltaColumnMappingDisabled(
+ "Conversion of Delta Lake tables with columnMapping feature is not
supported.");
+
+ final long latestDeltaVersion = deltaLatestSnapshot.getVersion();
+ final long minimalAvailableVersionInDeltaLogs =
getLowerBoundAvailableDeltaVersion();
+
+ LOG.info(
+ "Converting Delta Lake table at {} from version {} to version {} into
Iceberg table {} ...",
+ deltaTableLocation,
+ minimalAvailableVersionInDeltaLogs,
+ latestDeltaVersion,
+ newTableIdentifier);
+
+ Schema icebergSchema =
convertToIcebergSchema(deltaLatestSnapshot.getSchema());
+ PartitionSpec partitionSpec =
+ buildPartitionSpec(icebergSchema,
deltaLatestSnapshot.getPartitionColumnNames());
+
+ Transaction transaction =
+ icebergCatalog.newCreateTableTransaction(
+ newTableIdentifier,
+ icebergSchema,
+ partitionSpec,
+ newTableLocation,
+ buildTablePropertiesWithDelta(deltaLatestSnapshot,
deltaTableLocation));
+ setDefaultNamingMapping(transaction);
+ // Create an initial empty snapshot so currentSnapshot() is never null
+ transaction.newAppend().commit();
+
+ icebergDVFileFactory =
+ OutputFileFactory.builderFor(transaction.table(), 1,
1).format(FileFormat.PUFFIN).build();
+
+ Set<String> processedDataFiles = Sets.newHashSet();
+ try {
+ long reconstructableStartVersion =
+ commitInitialDeltaSnapshotToIcebergTransaction(
+ minimalAvailableVersionInDeltaLogs,
+ latestDeltaVersion,
+ transaction,
+ processedDataFiles);
+ LOG.info(
+ "Converting Delta Lake table from frist re-constructable version {}",
+ reconstructableStartVersion);
+ convertEachDeltaVersion(
+ reconstructableStartVersion + 1, latestDeltaVersion, transaction,
processedDataFiles);
+ } catch (IOException e) {
+ throw new UncheckedIOException(e);
+ }
+
+ transaction.commitTransaction();
+
+ LOG.info(
+ "Successfully created Iceberg table {} from Delta Lake table at {},
processed data file count: {}",
+ newTableIdentifier,
+ deltaTableLocation,
+ processedDataFiles.size());
+ return ImmutableSnapshotDeltaLakeTable.Result.builder()
+ .snapshotDataFilesCount(processedDataFiles.size())
+ .build();
+ }
+
+ /**
+ * Commit the initial delta snapshot to iceberg transaction. It tries the
snapshot starting from
+ * {@code startVersion} to {@code latestVersion} and commit the first
constructable one.
+ *
+ * <p>There are two cases that the delta snapshot is not constructable:
+ *
+ * <ul>
+ * <li>the version is earlier than the earliest checkpoint
+ * <li>the corresponding data files are deleted by {@code VACUUM}
+ * </ul>
+ *
+ * <p>For more information, please refer to delta lake's <a
+ * href="https://docs.delta.io/latest/delta-batch.html#-data-retention">Data
Retention</a>
+ *
+ * @param startVersion the earliest recreatable delta log version
+ * @param latestVersion the latest version of the delta lake table
+ * @param transaction the iceberg transaction
+ * @param processedDataFiles the set to collect processed data file paths
+ * @return the initial version of the delta lake table that is successfully
committed to iceberg
+ */
+ private long commitInitialDeltaSnapshotToIcebergTransaction(
+ long startVersion,
+ long latestVersion,
+ Transaction transaction,
+ Set<String> processedDataFiles)
+ throws IOException {
+ long constructableStartVersion = startVersion;
+ while (constructableStartVersion <= latestVersion) {
+ try {
+ Snapshot deltaSnapshot =
getDeltaSnapshotAsOfVersion(constructableStartVersion);
+ commitDeltaSnapshotToIcebergTransaction(deltaSnapshot, transaction,
processedDataFiles);
+ return constructableStartVersion;
+ } catch (NotFoundException | IllegalArgumentException | KernelException
e) {
+ constructableStartVersion++;
+ }
+ }
+
+ throw new ValidationException(
+ "Delta Lake table at %s contains no constructable snapshot",
deltaTableLocation);
+ }
+
+ private void commitDeltaSnapshotToIcebergTransaction(
+ Snapshot deltaSnapshot, Transaction transaction, Set<String>
processedDataFiles)
+ throws IOException {
+ Scan scan = deltaSnapshot.getScanBuilder().build();
+ this.currentDeltaMetadata =
InternalDeltaKernelUtils.metadata(deltaSnapshot);
+ try (CloseableIterator<FilteredColumnarBatch> changes =
scan.getScanFiles(deltaEngine)) {
+
+ commitDeltaRowsToIcebergTransaction(
+ deltaSnapshot.getVersion(),
+ Iterators.transform(changes, FilteredColumnarBatch::getRows),
+ transaction,
+ processedDataFiles);
+ tagCurrentSnapshot(
+ deltaSnapshot.getVersion(), deltaSnapshot.getTimestamp(deltaEngine),
transaction);
+ }
+ }
+
+ private void convertEachDeltaVersion(
+ long initialDeltaVersion,
+ long latestDeltaVersion,
+ Transaction transaction,
+ Set<String> processedDataFiles)
+ throws IOException {
+
+ for (long currDeltaVersion = initialDeltaVersion;
+ currDeltaVersion <= latestDeltaVersion;
+ currDeltaVersion++) {
+ try (CloseableIterator<ColumnarBatch> changes =
+ InternalDeltaKernelUtils.changes(
+ deltaTable, deltaEngine, currDeltaVersion, currDeltaVersion)) {
+
+ Long commitTimestamp =
+ commitDeltaRowsToIcebergTransaction(
+ currDeltaVersion,
+ Iterators.transform(changes, ColumnarBatch::getRows),
+ transaction,
+ processedDataFiles);
+ tagCurrentSnapshot(currDeltaVersion, commitTimestamp, transaction);
+ }
+ }
+ }
+
+ /**
+ * Current implementation uses the schema conversion mapping based on the
logical names. Delta
+ * Lake supports three column mapping modes: none, name, id. So, the renames
with columnMapping
+ * feature can lead to data corruption.
+ */
+ private void assertDeltaColumnMappingDisabled(String errorMessage) {
+ Map<String, String> configuration =
+ InternalDeltaKernelUtils.metadataConfiguration(deltaLatestSnapshot);
+ String columnMappingMode =
configuration.getOrDefault("delta.columnMapping.mode", "none");
+ if (!"none".equals(columnMappingMode)) {
+ throw new UnsupportedOperationException(errorMessage);
+ }
+ }
+
+ private static void setDefaultNamingMapping(Transaction transaction) {
+ transaction
+ .table()
+ .updateProperties()
+ .set(
+ TableProperties.DEFAULT_NAME_MAPPING,
+
NameMappingParser.toJson(MappingUtil.create(transaction.table().schema())))
+ .commit();
+ }
+
+ private Snapshot getDeltaSnapshotAsOfVersion(long deltaVersion) {
+ Snapshot snapshot =
+ Preconditions.checkNotNull(
+ deltaTable.getSnapshotAsOfVersion(deltaEngine, deltaVersion),
+ "Delta snapshot for version %s is unreachable.",
+ deltaVersion);
+ InternalDeltaKernelUtils.assertSnapshotImpl(snapshot);
+ return snapshot;
+ }
+
+ /**
+ * Convert each delta log {@code Row} iterator to Iceberg action and commit
to the given {@code
+ * Transaction}. The complete <a
+ *
href="https://github.com/delta-io/delta/blob/master/PROTOCOL.md#Actions">spec</a>
of delta
+ * actions. <br>
+ * Supported:
+ * <li>Add
+ *
+ * @return commit timestamp
+ */
+ private Long commitDeltaRowsToIcebergTransaction(
+ Long deltaVersion,
+ Iterator<CloseableIterator<Row>> changes,
+ Transaction transaction,
+ Set<String> processedDataFiles)
+ throws IOException {
+
+ Long originalCommitTimestamp = null;
+ List<DataFile> dataFilesToAdd = Lists.newArrayList();
+ List<DataFile> dataFilesToRemove = Lists.newArrayList();
+ List<DeleteFile> deleteFilesToAdd = Lists.newArrayList();
+
+ while (changes.hasNext()) {
+ try (CloseableIterator<Row> rows = changes.next()) {
+ while (rows.hasNext()) {
+ Row row = rows.next();
+ if (DeltaLakeActionsTranslationUtil.isCommitInfo(row)) {
+ Row commitInfo =
row.getStruct(row.getSchema().indexOf("commitInfo"));
+ originalCommitTimestamp =
+
commitInfo.getLong(commitInfo.getSchema().indexOf("timestamp"));
+ } else if (DeltaLakeActionsTranslationUtil.isMetaData(row)) {
+ DeltaMetadata newMetadata =
InternalDeltaKernelUtils.toMetadata(row);
+ assertSupportedMetadataChange(deltaVersion, currentDeltaMetadata,
newMetadata);
+ this.currentDeltaMetadata = newMetadata;
+ } else if (DeltaLakeActionsTranslationUtil.isAdd(row)) {
+ DeltaAddFile addFile = InternalDeltaKernelUtils.toAddFile(row);
+ DataFile dataFile = buildDataFileFromAddDeltaAction(addFile,
transaction);
+ dataFilesToAdd.add(dataFile);
+
+ List<DeleteFile> deleteFiles =
+ convertDeltaDVsToIcebergDVs(transaction.table().spec(),
addFile, dataFile);
+
+ deleteFilesToAdd.addAll(deleteFiles);
+ } else if (DeltaLakeActionsTranslationUtil.isRemove(row)) {
+ DeltaRemoveFile remove =
InternalDeltaKernelUtils.toRemoveFile(row);
+ DataFile dataFile = buildDataFileFromRemoveDeltaAction(remove,
transaction);
+ dataFilesToRemove.add(dataFile);
+ }
+ }
+ }
+ }
+
+ // TODO support more actions
+ commitIcebergTransaction(transaction, dataFilesToAdd, dataFilesToRemove,
deleteFilesToAdd);
+ dataFilesToAdd.forEach(dataFile ->
processedDataFiles.add(dataFile.location()));
+ dataFilesToRemove.forEach(dataFile ->
processedDataFiles.add(dataFile.location()));
+
+ return originalCommitTimestamp;
+ }
+
+ private List<DeleteFile> convertDeltaDVsToIcebergDVs(
+ PartitionSpec partitionSpec, DeltaAddFile addFile, DataFile dataFile)
throws IOException {
+ if (!addFile.hasDeletionVector()) {
+ return List.of();
+ }
+
+ DVFileWriter dvWriter = new BaseDVFileWriter(icebergDVFileFactory, path ->
null);
+ try (DVFileWriter closeableWriter = dvWriter) {
+ long[] positions =
+ InternalDeltaKernelUtils.readDeltaDVPositions(deltaEngine,
deltaTableLocation, addFile);
+ for (long deletedRowIndex : positions) {
+ closeableWriter.delete(
+ dataFile.location(), deletedRowIndex, partitionSpec,
dataFile.partition());
+ }
+ }
+
+ return dvWriter.result().deleteFiles();
+ }
+
+ /**
+ * CASES:
+ *
+ * <ol>
+ * <li>Append only
+ * <li>Delete only
+ * <li>Append and Delete => overwrite
+ * <li>RowDelta with deletes.
+ * <li>No Append, No Delete => No data changes, append tag or snapshot.
+ * </ol>
+ */
+ private static void commitIcebergTransaction(
+ Transaction transaction,
+ List<DataFile> dataFilesToAdd,
+ List<DataFile> dataFilesToRemove,
+ List<DeleteFile> deleteFilesToAdd) {
+ if (!deleteFilesToAdd.isEmpty()) {
+ // Row Delta
+ RowDelta rowDelta = transaction.newRowDelta();
+ // Avoid validation for multiple DVs added in transaction
+ // org/apache/iceberg/MergingSnapshotProducer.java:854
+ // since we do the conversion sequentially in a single Iceberg
transaction
+
rowDelta.validateFromSnapshot(transaction.table().currentSnapshot().snapshotId());
+
+ dataFilesToAdd.forEach(rowDelta::addRows);
+ dataFilesToRemove.forEach(rowDelta::removeRows);
+ deleteFilesToAdd.forEach(rowDelta::addDeletes);
+ rowDelta.commit();
+ } else if (!dataFilesToAdd.isEmpty() && dataFilesToRemove.isEmpty()) {
+ // Append only
+ AppendFiles appendFiles = transaction.newAppend();
+ dataFilesToAdd.forEach(appendFiles::appendFile);
+ appendFiles.commit();
+ } else if (dataFilesToAdd.isEmpty() && !dataFilesToRemove.isEmpty()) {
+ // Delete only
+ DeleteFiles deleteFiles = transaction.newDelete();
+ dataFilesToRemove.forEach(deleteFiles::deleteFile);
+ deleteFiles.commit();
+ } else if (!dataFilesToAdd.isEmpty() && !dataFilesToRemove.isEmpty()) {
+ // Overwrite
+ OverwriteFiles overwriteFiles = transaction.newOverwrite();
+ dataFilesToAdd.forEach(overwriteFiles::addFile);
+ dataFilesToRemove.forEach(overwriteFiles::deleteFile);
+ overwriteFiles.commit();
+ } else {
+ // Tag case
+ transaction.newAppend().commit();
+ }
+ }
+
+ private DataFile buildDataFileFromAddDeltaAction(DeltaAddFile addFile,
Transaction transaction) {
+ String path = addFile.path();
+ long dataFileSize = addFile.size();
+ String fullFilePath = getFullFilePath(path,
deltaTable.getPath(deltaEngine));
+
+ InputFile inputDataFile = deltaLakeFileIO.newInputFile(fullFilePath);
+ if (!inputDataFile.exists()) {
+ throw new NotFoundException(
+ "File %s is referenced in the logs of Delta Lake table at %s, but
cannot be found in the storage",
+ fullFilePath, deltaTableLocation);
+ }
+
+ MetricsConfig metricsConfig = MetricsConfig.forTable(transaction.table());
+ String nameMappingString =
+
transaction.table().properties().get(TableProperties.DEFAULT_NAME_MAPPING);
+ NameMapping nameMapping =
+ nameMappingString != null ?
NameMappingParser.fromJson(nameMappingString) : null;
+ // TODO read metrics from Delta log to avoid data flies read
+ Metrics metrics = ParquetUtil.fileMetrics(inputDataFile, metricsConfig,
nameMapping);
+
+ Map<String, String> partitionValues = addFile.partitionValues();
+ PartitionSpec partitionSpec = transaction.table().spec();
+ List<String> partitionValueList =
+ partitionSpec.fields().stream()
+ .map(PartitionField::name)
+ .map(partitionValues::get)
+ .collect(Collectors.toList());
+
+ return DataFiles.builder(partitionSpec)
+ .withPath(fullFilePath)
+ .withFormat(FileFormat.PARQUET) // Delta supports only parquet
datafiles
+ .withFileSizeInBytes(dataFileSize)
+ .withMetrics(metrics)
+ .withPartitionValues(partitionValueList)
+ .build();
+ }
+
+ private DataFile buildDataFileFromRemoveDeltaAction(
+ DeltaRemoveFile removeFile, Transaction transaction) {
+ String path = removeFile.path();
+ String fullFilePath = getFullFilePath(path,
deltaTable.getPath(deltaEngine));
+
+ InputFile inputDataFile = deltaLakeFileIO.newInputFile(fullFilePath);
+ if (!inputDataFile.exists()) {
+ throw new NotFoundException(
+ "File %s is referenced in the logs of Delta Lake table at %s, but
cannot be found in the storage",
+ fullFilePath, deltaTableLocation);
+ }
+
+ MetricsConfig metricsConfig = MetricsConfig.forTable(transaction.table());
+ String nameMappingString =
+
transaction.table().properties().get(TableProperties.DEFAULT_NAME_MAPPING);
+ NameMapping nameMapping =
+ nameMappingString != null ?
NameMappingParser.fromJson(nameMappingString) : null;
+ Metrics metrics = ParquetUtil.fileMetrics(inputDataFile, metricsConfig,
nameMapping);
+
+ Map<String, String> partitionValues = removeFile.partitionValues();
+ PartitionSpec partitionSpec = transaction.table().spec();
+ List<String> partitionValueList =
+ partitionSpec.fields().stream()
+ .map(PartitionField::name)
+ .map(partitionValues::get)
+ .collect(Collectors.toList());
+
+ return DataFiles.builder(partitionSpec)
+ .withPath(fullFilePath)
+ .withFormat(FileFormat.PARQUET) // Delta supports only parquet
datafiles
+ .withMetrics(metrics)
+ .withFileSizeInBytes(inputDataFile.getLength())
+ .withPartitionValues(partitionValueList)
+ .build();
+ }
+
+ @Nonnull
+ private static Schema convertToIcebergSchema(StructType deltaSchema) {
+ Type converted = new DeltaLakeKernelTypeToType(deltaSchema).convertType();
+ return new Schema(converted.asNestedType().asStructType().fields());
+ }
+
+ /**
+ * Returns the minimal available commit version present in the Delta table
log.
+ *
+ * <p>Note that this method may return a Delta log version that points to
data files that no
+ * longer exist (e.g. removed by {@code VACUUM}), meaning that this version
may not be
+ * constructable.
+ *
+ * @return the earliest available commit version in the Delta log
+ */
+ private long getLowerBoundAvailableDeltaVersion() {
+ try {
+ return InternalDeltaKernelUtils.earliestRecreatableCommit(deltaEngine,
deltaTableLocation);
+ } catch (TableNotFoundException e) {
+ throw deltaTableNotFoundException(e);
+ }
+ }
+
+ private void loadLatestDeltaSnapshot() {
+ try {
+ this.deltaLatestSnapshot =
+ Preconditions.checkNotNull(
+ deltaTable.getLatestSnapshot(deltaEngine),
+ "The latest Delta table snapshot is unreachable.");
+
+ InternalDeltaKernelUtils.assertSnapshotImpl(deltaLatestSnapshot);
+ } catch (TableNotFoundException e) {
+ throw deltaTableNotFoundException(e);
+ }
+ }
+
+ private PartitionSpec buildPartitionSpec(Schema schema, List<String>
partitionNames) {
+ if (partitionNames.isEmpty()) {
+ return PartitionSpec.unpartitioned();
+ }
+
+ PartitionSpec.Builder builder = PartitionSpec.builderFor(schema);
+ for (String partitionName : partitionNames) {
+ builder.identity(partitionName);
+ }
+ return builder.build();
+ }
+
+ private Map<String, String> buildTablePropertiesWithDelta(
+ Snapshot deltaSnapshot, String originalLocation) {
+ icebergPropertiesBuilder.put(SNAPSHOT_SOURCE_PROP, DELTA_SOURCE_VALUE);
+ icebergPropertiesBuilder.put(ORIGINAL_LOCATION_PROP, originalLocation);
+ icebergPropertiesBuilder.put(CONVERSION_TOOL_PROP, CONVERSION_TOOL_VALUE);
+ // Always construct Iceber v3 Table
+ icebergPropertiesBuilder.put(TableProperties.FORMAT_VERSION, "3");
+
+ Map<String, String> configuration =
+ InternalDeltaKernelUtils.metadataConfiguration(deltaSnapshot);
+ icebergPropertiesBuilder.putAll(configuration);
+
+ return icebergPropertiesBuilder.build();
+ }
+
+ private void tagCurrentSnapshot(
+ long deltaVersion, Long deltaVersionTimestamp, Transaction transaction) {
+ long currentSnapshotId =
transaction.table().currentSnapshot().snapshotId();
+
+ ManageSnapshots manageSnapshots = transaction.manageSnapshots();
+ manageSnapshots.createTag(DELTA_VERSION_TAG_PREFIX + deltaVersion,
currentSnapshotId);
+
+ if (deltaVersionTimestamp != null &&
deltaTimestampTags.add(deltaVersionTimestamp)) {
+ // Avoid creating the same timestamp based tag multiple times for small
and often writes to
+ // source delta table
+ manageSnapshots.createTag(
+ DELTA_TIMESTAMP_TAG_PREFIX + deltaVersionTimestamp,
currentSnapshotId);
+ }
+ manageSnapshots.commit();
+ }
+
+ @Nonnull
+ private IllegalArgumentException
deltaTableNotFoundException(TableNotFoundException exception) {
+ return new IllegalArgumentException(
+ String.format(
+ "Delta Lake table does not exist at the given location: %s",
deltaTableLocation),
+ exception);
+ }
+
+ /**
+ * Asserts that a Delta "metaData" action does not change the table
metadata. A "metaData" action
+ * is required by the Delta protocol for every change of the table metadata,
so comparing it with
+ * the previously known metadata detects schema evolution regardless of the
optional "commitInfo"
+ * action.
+ */
+ private static void assertSupportedMetadataChange(
+ long deltaVersion, DeltaMetadata previousMetadata, DeltaMetadata
newMetadata) {
+ List<String> changes = Lists.newArrayList();
+ if (!previousMetadata.schema().equals(newMetadata.schema())) {
+ changes.add(METADATA_CHANGE_SCHEMA);
+ }
+
+ if
(!previousMetadata.partitionColumns().equals(newMetadata.partitionColumns())) {
+ changes.add(METADATA_CHANGE_PARTITION_COLUMNS);
+ }
+
+ if (!previousMetadata.configuration().equals(newMetadata.configuration()))
{
+ changes.add(METADATA_CHANGE_CONFIGURATION);
+ }
+
+ if (!Objects.equals(previousMetadata.description(),
newMetadata.description())) {
+ changes.add(METADATA_CHANGE_DESCRIPTION);
+ }
+
+ if (!changes.isEmpty()) {
+ throw new IllegalStateException(
+ String.format(
+ Locale.ROOT,
+ "Cannot convert Delta table: metadata change of '%s' is not
supported (detected at Delta version %d).",
+ String.join(", ", changes),
+ deltaVersion));
+ }
+ }
+
+ @VisibleForTesting
+ static String getFullFilePath(String path, String tableRoot) {
+ URI dataFileUri = URI.create(path);
+ if (dataFileUri.isAbsolute()) {
+ return dataFileUri.getScheme().equalsIgnoreCase("file") ?
dataFileUri.getPath() : path;
+ } else {
+ String decodedPath = dataFileUri.getPath();
+ String separator =
+ tableRoot.contains(":/")
+ ? "/"
+ : File.separator; // Cloud Storages path vs File System (windows
`\` and other)
+ return tableRoot + (tableRoot.endsWith(separator) ? "" : separator) +
decodedPath;
+ }
+ }
+}
diff --git
a/delta-lake/src/main/java/org/apache/iceberg/delta/BaseSnapshotDeltaLakeTableAction.java
b/delta-lake/src/main/java/org/apache/iceberg/delta/BaseSnapshotDeltaLakeTableAction.java
index c170aeed91..7326e66191 100644
---
a/delta-lake/src/main/java/org/apache/iceberg/delta/BaseSnapshotDeltaLakeTableAction.java
+++
b/delta-lake/src/main/java/org/apache/iceberg/delta/BaseSnapshotDeltaLakeTableAction.java
@@ -341,13 +341,11 @@ class BaseSnapshotDeltaLakeTableAction implements
SnapshotDeltaLakeTable {
Long nullableFileSize;
Map<String, String> partitionValues;
- if (action instanceof AddFile) {
- AddFile addFile = (AddFile) action;
+ if (action instanceof AddFile addFile) {
path = addFile.getPath();
nullableFileSize = addFile.getSize();
partitionValues = addFile.getPartitionValues();
- } else if (action instanceof RemoveFile) {
- RemoveFile removeFile = (RemoveFile) action;
+ } else if (action instanceof RemoveFile removeFile) {
path = removeFile.getPath();
nullableFileSize = removeFile.getSize().orElse(null);
partitionValues = removeFile.getPartitionValues();
diff --git
a/delta-lake/src/main/java/org/apache/iceberg/delta/DeltaLakeActionsTranslationUtil.java
b/delta-lake/src/main/java/org/apache/iceberg/delta/DeltaLakeActionsTranslationUtil.java
new file mode 100644
index 0000000000..18571eaf41
--- /dev/null
+++
b/delta-lake/src/main/java/org/apache/iceberg/delta/DeltaLakeActionsTranslationUtil.java
@@ -0,0 +1,66 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.iceberg.delta;
+
+import io.delta.kernel.data.Row;
+
+/**
+ * Util class helps to handle json operations for <a
+ *
href="https://github.com/delta-io/delta/blob/master/PROTOCOL.md#Actions">delta
action</a>
+ */
+class DeltaLakeActionsTranslationUtil {
+ private DeltaLakeActionsTranslationUtil() {}
+
+ public static boolean isAdd(Row row) {
+ return isNotNullAt(row, "add");
+ }
+
+ public static boolean isRemove(Row row) {
+ return isNotNullAt(row, "remove");
+ }
+
+ public static boolean isMetaData(Row row) {
+ return isNotNullAt(row, "metaData");
+ }
+
+ public static boolean isTxn(Row row) {
+ return isNotNullAt(row, "txn");
+ }
+
+ public static boolean isProtocol(Row row) {
+ return isNotNullAt(row, "protocol");
+ }
+
+ public static boolean isCdc(Row row) {
+ return isNotNullAt(row, "cdc");
+ }
+
+ public static boolean isCommitInfo(Row row) {
+ return isNotNullAt(row, "commitInfo");
+ }
+
+ private static boolean isNotNullAt(Row row, String fieldName) {
+ int position = getOrdinal(row, fieldName);
+ return position >= 0 && !row.isNullAt(position);
+ }
+
+ private static int getOrdinal(Row row, String filedName) {
+ return row.getSchema().indexOf(filedName);
+ }
+}
diff --git
a/delta-lake/src/main/java/org/apache/iceberg/delta/DeltaLakeDataTypeVisitor.java
b/delta-lake/src/main/java/org/apache/iceberg/delta/DeltaLakeDataTypeVisitor.java
index 8af654a97b..727776d9b5 100644
---
a/delta-lake/src/main/java/org/apache/iceberg/delta/DeltaLakeDataTypeVisitor.java
+++
b/delta-lake/src/main/java/org/apache/iceberg/delta/DeltaLakeDataTypeVisitor.java
@@ -28,24 +28,22 @@ import
org.apache.iceberg.relocated.com.google.common.collect.Lists;
abstract class DeltaLakeDataTypeVisitor<T> {
public static <T> T visit(DataType type, DeltaLakeDataTypeVisitor<T>
visitor) {
- if (type instanceof StructType) {
- StructField[] fields = ((StructType) type).getFields();
+ if (type instanceof StructType structType) {
+ StructField[] fields = structType.getFields();
List<T> fieldResults = Lists.newArrayListWithExpectedSize(fields.length);
for (StructField field : fields) {
fieldResults.add(visitor.field(field, visit(field.getDataType(),
visitor)));
}
- return visitor.struct((StructType) type, fieldResults);
+ return visitor.struct(structType, fieldResults);
- } else if (type instanceof MapType) {
+ } else if (type instanceof MapType mapType) {
return visitor.map(
- (MapType) type,
- visit(((MapType) type).getKeyType(), visitor),
- visit(((MapType) type).getValueType(), visitor));
+ mapType, visit(mapType.getKeyType(), visitor),
visit(mapType.getValueType(), visitor));
- } else if (type instanceof ArrayType) {
- return visitor.array((ArrayType) type, visit(((ArrayType)
type).getElementType(), visitor));
+ } else if (type instanceof ArrayType arrayType) {
+ return visitor.array(arrayType, visit(arrayType.getElementType(),
visitor));
} else {
return visitor.atomic(type);
diff --git
a/delta-lake/src/main/java/org/apache/iceberg/delta/DeltaLakeTypeToType.java
b/delta-lake/src/main/java/org/apache/iceberg/delta/DeltaLakeKernelTypeToType.java
similarity index 54%
copy from
delta-lake/src/main/java/org/apache/iceberg/delta/DeltaLakeTypeToType.java
copy to
delta-lake/src/main/java/org/apache/iceberg/delta/DeltaLakeKernelTypeToType.java
index 752fb11ba0..ed3de5b0f4 100644
--- a/delta-lake/src/main/java/org/apache/iceberg/delta/DeltaLakeTypeToType.java
+++
b/delta-lake/src/main/java/org/apache/iceberg/delta/DeltaLakeKernelTypeToType.java
@@ -18,40 +18,65 @@
*/
package org.apache.iceberg.delta;
-import io.delta.standalone.types.ArrayType;
-import io.delta.standalone.types.BinaryType;
-import io.delta.standalone.types.BooleanType;
-import io.delta.standalone.types.ByteType;
-import io.delta.standalone.types.DataType;
-import io.delta.standalone.types.DateType;
-import io.delta.standalone.types.DecimalType;
-import io.delta.standalone.types.DoubleType;
-import io.delta.standalone.types.FloatType;
-import io.delta.standalone.types.IntegerType;
-import io.delta.standalone.types.LongType;
-import io.delta.standalone.types.MapType;
-import io.delta.standalone.types.ShortType;
-import io.delta.standalone.types.StringType;
-import io.delta.standalone.types.StructField;
-import io.delta.standalone.types.StructType;
-import io.delta.standalone.types.TimestampType;
+import io.delta.kernel.types.ArrayType;
+import io.delta.kernel.types.BinaryType;
+import io.delta.kernel.types.BooleanType;
+import io.delta.kernel.types.ByteType;
+import io.delta.kernel.types.DataType;
+import io.delta.kernel.types.DateType;
+import io.delta.kernel.types.DecimalType;
+import io.delta.kernel.types.DoubleType;
+import io.delta.kernel.types.FieldMetadata;
+import io.delta.kernel.types.FloatType;
+import io.delta.kernel.types.IntegerType;
+import io.delta.kernel.types.LongType;
+import io.delta.kernel.types.MapType;
+import io.delta.kernel.types.ShortType;
+import io.delta.kernel.types.StringType;
+import io.delta.kernel.types.StructField;
+import io.delta.kernel.types.StructType;
+import io.delta.kernel.types.TimestampNTZType;
+import io.delta.kernel.types.TimestampType;
+import io.delta.kernel.types.VariantType;
import java.util.List;
import org.apache.iceberg.exceptions.ValidationException;
import org.apache.iceberg.relocated.com.google.common.collect.Lists;
import org.apache.iceberg.types.Type;
import org.apache.iceberg.types.Types;
-class DeltaLakeTypeToType extends DeltaLakeDataTypeVisitor<Type> {
+class DeltaLakeKernelTypeToType {
private final StructType root;
private int nextId = 0;
- DeltaLakeTypeToType() {
- this.root = null;
+ DeltaLakeKernelTypeToType(StructType root) {
+ this.root = root;
+ this.nextId = root.fields().size();
}
- DeltaLakeTypeToType(StructType root) {
- this.root = root;
- this.nextId = root.getFields().length;
+ public Type convertType() {
+ return convertType(root);
+ }
+
+ private Type convertType(DataType type) {
+ if (type instanceof StructType structType) {
+ List<StructField> fields = structType.fields();
+ List<Type> fieldResults =
Lists.newArrayListWithExpectedSize(fields.size());
+
+ for (StructField field : fields) {
+ fieldResults.add(convertType(field.getDataType()));
+ }
+
+ return struct(structType, fieldResults);
+
+ } else if (type instanceof MapType mapType) {
+ return map(mapType, convertType(mapType.getKeyType()),
convertType(mapType.getValueType()));
+
+ } else if (type instanceof ArrayType arrayType) {
+ return array(arrayType, convertType(arrayType.getElementType()));
+
+ } else {
+ return atomic(type);
+ }
}
private int getNextId() {
@@ -60,14 +85,14 @@ class DeltaLakeTypeToType extends
DeltaLakeDataTypeVisitor<Type> {
return next;
}
- @Override
@SuppressWarnings("ReferenceEquality")
- public Type struct(StructType struct, List<Type> types) {
- StructField[] fields = struct.getFields();
- List<Types.NestedField> newFields =
Lists.newArrayListWithExpectedSize(fields.length);
+ private Type struct(StructType struct, List<Type> types) {
+ List<StructField> fields = struct.fields();
+ List<Types.NestedField> newFields =
Lists.newArrayListWithExpectedSize(fields.size());
boolean isRoot = root == struct;
- for (int i = 0; i < fields.length; i += 1) {
- StructField field = fields[i];
+
+ for (int i = 0; i < fields.size(); i += 1) {
+ StructField field = fields.get(i);
Type type = types.get(i);
int id;
@@ -78,10 +103,9 @@ class DeltaLakeTypeToType extends
DeltaLakeDataTypeVisitor<Type> {
id = getNextId();
}
- String doc =
- field.getMetadata().contains("comment")
- ? field.getMetadata().get("comment").toString()
- : null;
+ // Delta Kernel StructField metadata is a Map<String, String>
+ FieldMetadata metadata = field.getMetadata();
+ String doc = metadata.contains("comment") ?
metadata.getString("comment") : null;
if (field.isNullable()) {
newFields.add(Types.NestedField.optional(id, field.getName(), type,
doc));
@@ -93,13 +117,7 @@ class DeltaLakeTypeToType extends
DeltaLakeDataTypeVisitor<Type> {
return Types.StructType.of(newFields);
}
- @Override
- public Type field(StructField field, Type typeResult) {
- return typeResult;
- }
-
- @Override
- public Type array(ArrayType array, Type elementType) {
+ private Type array(ArrayType array, Type elementType) {
if (array.containsNull()) {
return Types.ListType.ofOptional(getNextId(), elementType);
} else {
@@ -107,9 +125,8 @@ class DeltaLakeTypeToType extends
DeltaLakeDataTypeVisitor<Type> {
}
}
- @Override
- public Type map(MapType map, Type keyType, Type valueType) {
- if (map.valueContainsNull()) {
+ private Type map(MapType map, Type keyType, Type valueType) {
+ if (map.isValueContainsNull()) {
return Types.MapType.ofOptional(getNextId(), getNextId(), keyType,
valueType);
} else {
return Types.MapType.ofRequired(getNextId(), getNextId(), keyType,
valueType);
@@ -117,8 +134,7 @@ class DeltaLakeTypeToType extends
DeltaLakeDataTypeVisitor<Type> {
}
@SuppressWarnings("checkstyle:CyclomaticComplexity")
- @Override
- public Type atomic(DataType atomic) {
+ private Type atomic(DataType atomic) {
if (atomic instanceof BooleanType) {
return Types.BooleanType.get();
@@ -145,13 +161,19 @@ class DeltaLakeTypeToType extends
DeltaLakeDataTypeVisitor<Type> {
} else if (atomic instanceof TimestampType) {
return Types.TimestampType.withZone();
- } else if (atomic instanceof DecimalType) {
- return Types.DecimalType.of(
- ((DecimalType) atomic).getPrecision(), ((DecimalType)
atomic).getScale());
+ } else if (atomic instanceof TimestampNTZType) {
+ return Types.TimestampType.withoutZone();
+
+ } else if (atomic instanceof DecimalType decimalType) {
+ return Types.DecimalType.of(decimalType.getPrecision(),
decimalType.getScale());
+
} else if (atomic instanceof BinaryType) {
return Types.BinaryType.get();
+
+ } else if (atomic instanceof VariantType) {
+ return Types.VariantType.get();
}
- throw new ValidationException("Not a supported type: %s",
atomic.getCatalogString());
+ throw new ValidationException("Not a supported type: %s",
atomic.toString());
}
}
diff --git
a/delta-lake/src/main/java/org/apache/iceberg/delta/DeltaLakeTypeToType.java
b/delta-lake/src/main/java/org/apache/iceberg/delta/DeltaLakeTypeToType.java
index 752fb11ba0..f4b08b6e03 100644
--- a/delta-lake/src/main/java/org/apache/iceberg/delta/DeltaLakeTypeToType.java
+++ b/delta-lake/src/main/java/org/apache/iceberg/delta/DeltaLakeTypeToType.java
@@ -145,9 +145,8 @@ class DeltaLakeTypeToType extends
DeltaLakeDataTypeVisitor<Type> {
} else if (atomic instanceof TimestampType) {
return Types.TimestampType.withZone();
- } else if (atomic instanceof DecimalType) {
- return Types.DecimalType.of(
- ((DecimalType) atomic).getPrecision(), ((DecimalType)
atomic).getScale());
+ } else if (atomic instanceof DecimalType decimalType) {
+ return Types.DecimalType.of(decimalType.getPrecision(),
decimalType.getScale());
} else if (atomic instanceof BinaryType) {
return Types.BinaryType.get();
}
diff --git
a/delta-lake/src/main/java/org/apache/iceberg/delta/InternalDeltaKernelUtils.java
b/delta-lake/src/main/java/org/apache/iceberg/delta/InternalDeltaKernelUtils.java
new file mode 100644
index 0000000000..4da04f7b20
--- /dev/null
+++
b/delta-lake/src/main/java/org/apache/iceberg/delta/InternalDeltaKernelUtils.java
@@ -0,0 +1,232 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.iceberg.delta;
+
+import io.delta.kernel.Snapshot;
+import io.delta.kernel.Table;
+import io.delta.kernel.data.ColumnarBatch;
+import io.delta.kernel.data.Row;
+import io.delta.kernel.engine.Engine;
+import io.delta.kernel.exceptions.TableNotFoundException;
+import io.delta.kernel.internal.DeltaHistoryManager;
+import io.delta.kernel.internal.DeltaLogActionUtils;
+import io.delta.kernel.internal.SnapshotImpl;
+import io.delta.kernel.internal.TableImpl;
+import io.delta.kernel.internal.actions.DeletionVectorDescriptor;
+import io.delta.kernel.internal.deletionvectors.DeletionVectorUtils;
+import io.delta.kernel.internal.deletionvectors.RoaringBitmapArray;
+import io.delta.kernel.internal.fs.Path;
+import io.delta.kernel.internal.types.DataTypeJsonSerDe;
+import io.delta.kernel.internal.util.Tuple2;
+import io.delta.kernel.internal.util.VectorUtils;
+import io.delta.kernel.types.StructType;
+import io.delta.kernel.utils.CloseableIterator;
+import java.util.Arrays;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.stream.Collectors;
+
+/**
+ * A temporary utility class to encapsulate the usage of internal Delta Kernel
APIs.
+ *
+ * <p>This class is required because certain metadata and action APIs are not
yet exposed in the
+ * public Delta Kernel API. Once the Delta Kernel public API is improved to
support these use cases,
+ * this class will be deleted.
+ */
+class InternalDeltaKernelUtils {
+
+ private InternalDeltaKernelUtils() {}
+
+ static long earliestRecreatableCommit(Engine engine, String tableLocation)
+ throws TableNotFoundException {
+ // Note that this version isn't guaranteed to exist when performing an
action as a concurrent
+ // operation
+ // can delete the file during cleanup. This value must be used as a lower
bound.
+ return DeltaHistoryManager.getEarliestRecreatableCommit(
+ engine, new Path(tableLocation, "_delta_log"), Optional.empty());
+ }
+
+ static CloseableIterator<ColumnarBatch> changes(
+ Table table, Engine engine, long startVersion, long endVersion) {
+ return ((TableImpl) table)
+ .getChanges(
+ engine,
+ startVersion,
+ endVersion,
+
Arrays.stream(DeltaLogActionUtils.DeltaAction.values()).collect(Collectors.toSet()));
+ }
+
+ static Map<String, String> metadataConfiguration(Snapshot snapshot) {
+ return ((SnapshotImpl) snapshot).getMetadata().getConfiguration();
+ }
+
+ static DeltaAddFile toAddFile(Row row) {
+ return new DeltaAddFile(row);
+ }
+
+ static DeltaRemoveFile toRemoveFile(Row row) {
+ return new DeltaRemoveFile(row);
+ }
+
+ /** Creates a {@link DeltaMetadata} from a Delta log row that contains a
"metaData" action. */
+ static DeltaMetadata toMetadata(Row row) {
+ return new
DeltaMetadata(row.getStruct(row.getSchema().indexOf("metaData")));
+ }
+
+ /** Creates a {@link DeltaMetadata} that represents the metadata of the
given snapshot. */
+ static DeltaMetadata metadata(Snapshot snapshot) {
+ return new DeltaMetadata(((SnapshotImpl) snapshot).getMetadata().toRow());
+ }
+
+ static long[] readDeltaDVPositions(Engine engine, String tablePath,
DeltaAddFile addFile) {
+ DeletionVectorDescriptor descriptor = addFile.deletionVector();
+ if (descriptor == null) {
+ return new long[0];
+ }
+ Tuple2<DeletionVectorDescriptor, RoaringBitmapArray> tuple =
+ DeletionVectorUtils.loadNewDvAndBitmap(engine, tablePath, descriptor);
+ return tuple._2.toArray();
+ }
+
+ static void assertSnapshotImpl(Snapshot latestSnapshot) {
+ if (!(latestSnapshot instanceof SnapshotImpl)) {
+ throw new IllegalStateException(
+ "Unsupported impl of delta Snapshot: " + latestSnapshot.getClass());
+ }
+ }
+
+ /**
+ * A wrapper class around the Delta Lake "add" action Row.
+ *
+ * <p>The field names (such as "add", "path", "size", "partitionValues", and
"deletionVector") are
+ * defined by the Delta Transaction Log Protocol and are guaranteed to
remain stable. Therefore,
+ * it is safe to access them directly by name from the underlying Row.
+ *
+ * <p>For more information see {@link
io.delta.kernel.internal.actions.AddFile}.
+ */
+ static class DeltaAddFile {
+ private final Row addFileRow;
+
+ DeltaAddFile(Row row) {
+ this.addFileRow = row.getStruct(row.getSchema().indexOf("add"));
+ }
+
+ public String path() {
+ return addFileRow.getString(addFileRow.getSchema().indexOf("path"));
+ }
+
+ public long size() {
+ return addFileRow.getLong(addFileRow.getSchema().indexOf("size"));
+ }
+
+ public boolean hasDeletionVector() {
+ int dvIndex = addFileRow.getSchema().indexOf("deletionVector");
+ return dvIndex >= 0 && !addFileRow.isNullAt(dvIndex);
+ }
+
+ public Map<String, String> partitionValues() {
+ return VectorUtils.toJavaMap(
+
addFileRow.getMap(addFileRow.getSchema().indexOf("partitionValues")));
+ }
+
+ public DeletionVectorDescriptor deletionVector() {
+ int dvIndex = addFileRow.getSchema().indexOf("deletionVector");
+ if (dvIndex < 0 || addFileRow.isNullAt(dvIndex)) {
+ return null;
+ }
+ return DeletionVectorDescriptor.fromRow(addFileRow.getStruct(dvIndex));
+ }
+ }
+
+ /**
+ * A wrapper class around the Delta Lake "remove" action Row.
+ *
+ * <p>The field names (such as "remove", "path", and "partitionValues") are
defined by the Delta
+ * Transaction Log Protocol and are guaranteed to remain stable. Therefore,
it is safe to access
+ * them directly by name from the underlying Row.
+ *
+ * <p>For more information see {@link
io.delta.kernel.internal.actions.RemoveFile}.
+ */
+ static class DeltaRemoveFile {
+ private final Row removeFileRow;
+
+ DeltaRemoveFile(Row row) {
+ this.removeFileRow = row.getStruct(row.getSchema().indexOf("remove"));
+ }
+
+ public String path() {
+ return
removeFileRow.getString(removeFileRow.getSchema().indexOf("path"));
+ }
+
+ public Map<String, String> partitionValues() {
+ int partitionValuesIndex =
removeFileRow.getSchema().indexOf("partitionValues");
+ if (partitionValuesIndex < 0 ||
removeFileRow.isNullAt(partitionValuesIndex)) {
+ return Map.of();
+ }
+ return VectorUtils.toJavaMap(removeFileRow.getMap(partitionValuesIndex));
+ }
+ }
+
+ /**
+ * A wrapper class around the Delta Lake "metaData" action Row.
+ *
+ * <p>The field names (such as "metaData", "schemaString",
"partitionColumns", "configuration" and
+ * "description") are defined by the Delta Transaction Log Protocol and are
guaranteed to remain
+ * stable. Therefore, it is safe to access them directly by name from the
underlying Row.
+ *
+ * <p>For more information see {@link
io.delta.kernel.internal.actions.Metadata}.
+ */
+ static class DeltaMetadata {
+ private final Row metadataRow;
+
+ DeltaMetadata(Row metadataRow) {
+ this.metadataRow = metadataRow;
+ }
+
+ public StructType schema() {
+ return DataTypeJsonSerDe.deserializeStructType(
+
metadataRow.getString(metadataRow.getSchema().indexOf("schemaString")));
+ }
+
+ public List<String> partitionColumns() {
+ int index = metadataRow.getSchema().indexOf("partitionColumns");
+ if (index < 0 || metadataRow.isNullAt(index)) {
+ return List.of();
+ }
+ return VectorUtils.toJavaList(metadataRow.getArray(index));
+ }
+
+ public Map<String, String> configuration() {
+ int index = metadataRow.getSchema().indexOf("configuration");
+ if (index < 0 || metadataRow.isNullAt(index)) {
+ return Map.of();
+ }
+ return VectorUtils.toJavaMap(metadataRow.getMap(index));
+ }
+
+ public String description() {
+ int index = metadataRow.getSchema().indexOf("description");
+ if (index < 0 || metadataRow.isNullAt(index)) {
+ return null;
+ }
+ return metadataRow.getString(index);
+ }
+ }
+}
diff --git
a/delta-lake/src/test/java/org/apache/iceberg/delta/DeltaKernelTestUtils.java
b/delta-lake/src/test/java/org/apache/iceberg/delta/DeltaKernelTestUtils.java
new file mode 100644
index 0000000000..389c828ae0
--- /dev/null
+++
b/delta-lake/src/test/java/org/apache/iceberg/delta/DeltaKernelTestUtils.java
@@ -0,0 +1,209 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.iceberg.delta;
+
+import io.delta.kernel.DataWriteContext;
+import io.delta.kernel.Operation;
+import io.delta.kernel.Table;
+import io.delta.kernel.Transaction;
+import io.delta.kernel.data.ColumnVector;
+import io.delta.kernel.data.ColumnarBatch;
+import io.delta.kernel.data.FilteredColumnarBatch;
+import io.delta.kernel.data.Row;
+import io.delta.kernel.defaults.engine.DefaultEngine;
+import io.delta.kernel.engine.Engine;
+import io.delta.kernel.types.DataType;
+import io.delta.kernel.types.DecimalType;
+import io.delta.kernel.types.IntegerType;
+import io.delta.kernel.types.StringType;
+import io.delta.kernel.types.StructType;
+import io.delta.kernel.utils.CloseableIterable;
+import io.delta.kernel.utils.CloseableIterator;
+import io.delta.kernel.utils.DataFileStatus;
+import java.io.IOException;
+import java.math.BigDecimal;
+import java.util.Collections;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import org.apache.hadoop.conf.Configuration;
+
+final class DeltaKernelTestUtils {
+ private static final int DECIMAL_PRECISION = 10;
+ private static final int DECIMAL_SCALE = 2;
+
+ private DeltaKernelTestUtils() {}
+
+ static void createBasicDeltaTable(Configuration hadoopConf, String
tableLocation)
+ throws IOException {
+ Engine engine = DefaultEngine.create(hadoopConf);
+ DecimalType decimalType = new DecimalType(DECIMAL_PRECISION,
DECIMAL_SCALE);
+ StructType schema =
+ new StructType()
+ .add("id", IntegerType.INTEGER)
+ .add("status", StringType.STRING)
+ .add("amount", decimalType);
+
+ Transaction txn =
+ Table.forPath(engine, tableLocation)
+ .createTransactionBuilder(
+ engine, "Delta-Iceberg-Converter-Tests",
Operation.CREATE_TABLE)
+ .withSchema(engine, schema)
+ .build(engine);
+ Row txnState = txn.getTransactionState(engine);
+
+ FilteredColumnarBatch batch = createSampleBatch(schema, decimalType);
+ Iterator<FilteredColumnarBatch> batchIter =
Collections.singletonList(batch).iterator();
+ CloseableIterator<FilteredColumnarBatch> logicalData =
+ new CloseableIterator<>() {
+ @Override
+ public boolean hasNext() {
+ return batchIter.hasNext();
+ }
+
+ @Override
+ public FilteredColumnarBatch next() {
+ return batchIter.next();
+ }
+
+ @Override
+ public void close() {}
+ };
+
+ DataWriteContext writeContext = Transaction.getWriteContext(engine,
txnState, Map.of());
+ try (CloseableIterator<FilteredColumnarBatch> physicalData =
+ Transaction.transformLogicalData(engine, txnState, logicalData,
Map.of());
+ CloseableIterator<DataFileStatus> dataFiles =
+ engine
+ .getParquetHandler()
+ .writeParquetFiles(
+ writeContext.getTargetDirectory(),
+ physicalData,
+ writeContext.getStatisticsColumns());
+ CloseableIterator<Row> dataActions =
+ Transaction.generateAppendActions(engine, txnState, dataFiles,
writeContext);
+ CloseableIterable<Row> actionsIterable =
CloseableIterable.inMemoryIterable(dataActions)) {
+ txn.commit(engine, actionsIterable);
+ }
+ }
+
+ private static FilteredColumnarBatch createSampleBatch(
+ StructType schema, DecimalType decimalType) {
+ List<Integer> ids = List.of(1, 2);
+ List<String> statuses = List.of("active", "inactive");
+ List<BigDecimal> amounts = List.of(new BigDecimal("12.34"), new
BigDecimal("56.78"));
+
+ ColumnVector[] vectors =
+ new ColumnVector[] {
+ new ColumnVector() {
+ @Override
+ public DataType getDataType() {
+ return IntegerType.INTEGER;
+ }
+
+ @Override
+ public int getSize() {
+ return ids.size();
+ }
+
+ @Override
+ public void close() {}
+
+ @Override
+ public boolean isNullAt(int rowId) {
+ return false;
+ }
+
+ @Override
+ public int getInt(int rowId) {
+ return ids.get(rowId);
+ }
+ },
+ new ColumnVector() {
+ @Override
+ public DataType getDataType() {
+ return StringType.STRING;
+ }
+
+ @Override
+ public int getSize() {
+ return statuses.size();
+ }
+
+ @Override
+ public void close() {}
+
+ @Override
+ public boolean isNullAt(int rowId) {
+ return false;
+ }
+
+ @Override
+ public String getString(int rowId) {
+ return statuses.get(rowId);
+ }
+ },
+ new ColumnVector() {
+ @Override
+ public DataType getDataType() {
+ return decimalType;
+ }
+
+ @Override
+ public int getSize() {
+ return amounts.size();
+ }
+
+ @Override
+ public void close() {}
+
+ @Override
+ public boolean isNullAt(int rowId) {
+ return false;
+ }
+
+ @Override
+ public BigDecimal getDecimal(int rowId) {
+ return amounts.get(rowId);
+ }
+ }
+ };
+
+ ColumnarBatch batch =
+ new ColumnarBatch() {
+ @Override
+ public StructType getSchema() {
+ return schema;
+ }
+
+ @Override
+ public ColumnVector getColumnVector(int ordinal) {
+ return vectors[ordinal];
+ }
+
+ @Override
+ public int getSize() {
+ return ids.size();
+ }
+ };
+
+ return new FilteredColumnarBatch(batch, Optional.empty());
+ }
+}
diff --git
a/delta-lake/src/test/java/org/apache/iceberg/delta/TestBaseSnapshotDeltaLakeKernelTableAction.java
b/delta-lake/src/test/java/org/apache/iceberg/delta/TestBaseSnapshotDeltaLakeKernelTableAction.java
new file mode 100644
index 0000000000..324bcd7809
--- /dev/null
+++
b/delta-lake/src/test/java/org/apache/iceberg/delta/TestBaseSnapshotDeltaLakeKernelTableAction.java
@@ -0,0 +1,284 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.iceberg.delta;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+
+import io.delta.kernel.Operation;
+import io.delta.kernel.Table;
+import io.delta.kernel.Transaction;
+import io.delta.kernel.TransactionBuilder;
+import io.delta.kernel.defaults.engine.DefaultEngine;
+import io.delta.kernel.engine.Engine;
+import io.delta.kernel.types.IntegerType;
+import io.delta.kernel.types.StringType;
+import io.delta.kernel.types.StructType;
+import io.delta.kernel.utils.CloseableIterable;
+import java.io.File;
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.Map;
+import org.apache.hadoop.conf.Configuration;
+import org.apache.iceberg.BaseTable;
+import org.apache.iceberg.CatalogProperties;
+import org.apache.iceberg.TableProperties;
+import org.apache.iceberg.catalog.Catalog;
+import org.apache.iceberg.catalog.TableIdentifier;
+import org.apache.iceberg.hadoop.HadoopCatalog;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableMap;
+import org.apache.iceberg.relocated.com.google.common.collect.Maps;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.io.TempDir;
+
+public class TestBaseSnapshotDeltaLakeKernelTableAction {
+
+ @TempDir private File sourceDeltaFolder;
+ @TempDir private File icebergWarehouseFolder;
+ private String sourceTableLocation;
+ private final Configuration testHadoopConf = new Configuration();
+ private String newTableLocation;
+ private Catalog testCatalog;
+
+ @BeforeEach
+ public void before() throws IOException {
+ sourceTableLocation = sourceDeltaFolder.toURI().toString();
+
+ Path icebergTablePath =
icebergWarehouseFolder.toPath().resolve("iceberg_table");
+ newTableLocation = icebergTablePath.toString();
+ Files.createDirectories(icebergTablePath);
+
+ Map<String, String> properties = Maps.newHashMap();
+ properties.put(CatalogProperties.WAREHOUSE_LOCATION,
icebergWarehouseFolder.toString());
+
+ HadoopCatalog icebergCatalog = new HadoopCatalog();
+ icebergCatalog.setConf(new Configuration());
+ icebergCatalog.initialize("hadoop_catalog", properties);
+ testCatalog = icebergCatalog;
+ }
+
+ @Test
+ public void testRequiredTableIdentifier() {
+ SnapshotDeltaLakeTable testAction =
+ new BaseSnapshotDeltaLakeKernelTableAction(sourceTableLocation)
+ .icebergCatalog(testCatalog)
+ .deltaLakeConfiguration(testHadoopConf)
+ .tableLocation(newTableLocation);
+ assertThatThrownBy(testAction::execute)
+ .isInstanceOf(IllegalArgumentException.class)
+ .hasMessage(
+ "Iceberg catalog and identifier cannot be null. Make sure to
configure the action with a valid Iceberg catalog and identifier.");
+ }
+
+ @Test
+ public void testRequiredIcebergCatalog() {
+ SnapshotDeltaLakeTable testAction =
+ new BaseSnapshotDeltaLakeKernelTableAction(sourceTableLocation)
+ .as(TableIdentifier.of("test", "test"))
+ .deltaLakeConfiguration(testHadoopConf)
+ .tableLocation(newTableLocation);
+ assertThatThrownBy(testAction::execute)
+ .isInstanceOf(IllegalArgumentException.class)
+ .hasMessage(
+ "Iceberg catalog and identifier cannot be null. Make sure to
configure the action with a valid Iceberg catalog and identifier.");
+ }
+
+ @Test
+ public void testRequiredDeltaLakeConfiguration() {
+ SnapshotDeltaLakeTable testAction =
+ new BaseSnapshotDeltaLakeKernelTableAction(sourceTableLocation)
+ .as(TableIdentifier.of("test", "test"))
+ .icebergCatalog(testCatalog)
+ .tableLocation(newTableLocation);
+ assertThatThrownBy(testAction::execute)
+ .isInstanceOf(IllegalArgumentException.class)
+ .hasMessage("Make sure to configure the action with a valid
deltaLakeConfiguration");
+ }
+
+ @Test
+ public void testDeltaTableColumnMappingFeatureDisabled() throws Exception {
+ Engine engine = DefaultEngine.create(testHadoopConf);
+ Transaction txn =
+ createEmptyDeltaTableTransaction(engine)
+ .withTableProperties(engine, Map.of("delta.columnMapping.mode",
"name"))
+ .build(engine);
+ txn.commit(engine, CloseableIterable.emptyIterable());
+
+ SnapshotDeltaLakeTable testAction =
+ new BaseSnapshotDeltaLakeKernelTableAction(sourceTableLocation)
+ .as(TableIdentifier.of("iceberg_table"))
+ .deltaLakeConfiguration(testHadoopConf)
+ .icebergCatalog(testCatalog)
+ .tableLocation(newTableLocation);
+
+ // Act & check
+ assertThatThrownBy(testAction::execute)
+ .isInstanceOf(UnsupportedOperationException.class)
+ .hasMessage("Conversion of Delta Lake tables with columnMapping
feature is not supported.");
+ }
+
+ @Test
+ public void testEmptyTableConversion() {
+ Engine engine = DefaultEngine.create(testHadoopConf);
+ createEmptyDeltaTableTransaction(engine)
+ .build(engine)
+ .commit(engine, CloseableIterable.emptyIterable());
+
+ TableIdentifier icebergTable = TableIdentifier.of("iceberg_table");
+ SnapshotDeltaLakeTable testAction =
+ new BaseSnapshotDeltaLakeKernelTableAction(sourceTableLocation)
+ .as(icebergTable)
+ .deltaLakeConfiguration(testHadoopConf)
+ .icebergCatalog(testCatalog)
+ .tableLocation(newTableLocation);
+
+ assertThat(testCatalog.tableExists(icebergTable)).isFalse();
+
+ testAction.execute();
+
+ assertThat(testCatalog.tableExists(icebergTable)).isTrue();
+
+ org.apache.iceberg.Table table = testCatalog.loadTable(icebergTable);
+ assertThat(((BaseTable)
table).operations().current().formatVersion()).isEqualTo(3);
+ }
+
+ @Test
+ public void testTableCreated() throws Exception {
+ DeltaKernelTestUtils.createBasicDeltaTable(testHadoopConf,
sourceTableLocation);
+
+ TableIdentifier icebergTable = TableIdentifier.of("iceberg_table");
+ SnapshotDeltaLakeTable testAction =
+ new BaseSnapshotDeltaLakeKernelTableAction(sourceTableLocation)
+ .as(icebergTable)
+ .deltaLakeConfiguration(testHadoopConf)
+ .icebergCatalog(testCatalog)
+ .tableLocation(newTableLocation);
+
+ assertThat(testCatalog.tableExists(icebergTable)).isFalse();
+
+ testAction.execute();
+
+ assertThat(testCatalog.tableExists(icebergTable)).isTrue();
+ }
+
+ @Test
+ public void testDefaultTableProperties() throws Exception {
+ DeltaKernelTestUtils.createBasicDeltaTable(testHadoopConf,
sourceTableLocation);
+
+ TableIdentifier icebergTableIdentifier =
TableIdentifier.of("iceberg_table");
+ SnapshotDeltaLakeTable testAction =
+ new BaseSnapshotDeltaLakeKernelTableAction(sourceTableLocation)
+ .as(icebergTableIdentifier)
+ .deltaLakeConfiguration(testHadoopConf)
+ .icebergCatalog(testCatalog)
+ .tableLocation(newTableLocation);
+
+ assertThat(testCatalog.tableExists(icebergTableIdentifier)).isFalse();
+
+ testAction.execute();
+
+ assertThat(testCatalog.tableExists(icebergTableIdentifier)).isTrue();
+
+ Map<String, String> properties =
testCatalog.loadTable(icebergTableIdentifier).properties();
+
assertThat(properties.get("original_location")).isEqualTo(sourceTableLocation);
+ assertThat(properties.get("snapshot_source")).isEqualTo("delta");
+
assertThat(properties.get("conversion_tool")).isEqualTo("iceberg-delta-lake");
+
assertThat(properties.containsKey(TableProperties.DEFAULT_NAME_MAPPING)).isTrue();
+ }
+
+ @Test
+ public void testCustomTableProperties() throws Exception {
+ DeltaKernelTestUtils.createBasicDeltaTable(testHadoopConf,
sourceTableLocation);
+
+ TableIdentifier icebergTableIdentifier =
TableIdentifier.of("iceberg_table");
+ SnapshotDeltaLakeTable testAction =
+ new BaseSnapshotDeltaLakeKernelTableAction(sourceTableLocation)
+ .as(icebergTableIdentifier)
+ .deltaLakeConfiguration(testHadoopConf)
+ .icebergCatalog(testCatalog)
+ .tableLocation(newTableLocation)
+ .tableProperty("custom_prop_1", "custom val 1")
+ .tableProperty("custom_prop_2", "custom val 2")
+ .tableProperties(
+ ImmutableMap.of(
+ "custom_map_prop1", "val 1",
+ "custom_map_prop2", "val 2"));
+
+ assertThat(testCatalog.tableExists(icebergTableIdentifier)).isFalse();
+
+ testAction.execute();
+
+ assertThat(testCatalog.tableExists(icebergTableIdentifier)).isTrue();
+
+ Map<String, String> properties =
testCatalog.loadTable(icebergTableIdentifier).properties();
+ assertThat(properties.get("custom_prop_1")).isEqualTo("custom val 1");
+ assertThat(properties.get("custom_prop_2")).isEqualTo("custom val 2");
+ assertThat(properties.get("custom_map_prop1")).isEqualTo("val 1");
+ assertThat(properties.get("custom_map_prop2")).isEqualTo("val 2");
+ }
+
+ @Test
+ public void testCustomTablePropertiesOverlap() throws Exception {
+ DeltaKernelTestUtils.createBasicDeltaTable(testHadoopConf,
sourceTableLocation);
+
+ TableIdentifier icebergTableIdentifier =
TableIdentifier.of("iceberg_table");
+ SnapshotDeltaLakeTable testAction =
+ new BaseSnapshotDeltaLakeKernelTableAction(sourceTableLocation)
+ .as(icebergTableIdentifier)
+ .deltaLakeConfiguration(testHadoopConf)
+ .icebergCatalog(testCatalog)
+ .tableLocation(newTableLocation)
+ .tableProperty("custom_prop_1", "custom val 1")
+ .tableProperty("custom_prop_1", "custom val 1"); // Overlap
+
+ assertThat(testCatalog.tableExists(icebergTableIdentifier)).isFalse();
+
+ assertThatThrownBy(testAction::execute)
+ .isInstanceOf(IllegalArgumentException.class)
+ .hasMessage(
+ "Multiple entries with same key: custom_prop_1=custom val 1 and
custom_prop_1=custom val 1");
+ }
+
+ @Test
+ void testDeltaTableNotExist() {
+ SnapshotDeltaLakeTable testAction =
+ new BaseSnapshotDeltaLakeKernelTableAction(sourceTableLocation)
+ .as(TableIdentifier.of("test", "test"))
+ .deltaLakeConfiguration(testHadoopConf)
+ .icebergCatalog(testCatalog)
+ .tableLocation(newTableLocation);
+
+ assertThatThrownBy(testAction::execute)
+ .isInstanceOf(IllegalArgumentException.class)
+ .hasMessage(
+ "Delta Lake table does not exist at the given location: %s",
sourceTableLocation);
+ }
+
+ private TransactionBuilder createEmptyDeltaTableTransaction(Engine engine) {
+ StructType schema =
+ new StructType().add("id", IntegerType.INTEGER).add("status",
StringType.STRING);
+ Table table = Table.forPath(engine, sourceTableLocation);
+
+ return table
+ .createTransactionBuilder(engine, "Delta-Iceberg-Converter-Tests",
Operation.CREATE_TABLE)
+ .withSchema(engine, schema);
+ }
+}
diff --git
a/delta-lake/src/test/java/org/apache/iceberg/delta/TestDeltaLakeKernelTypeToType.java
b/delta-lake/src/test/java/org/apache/iceberg/delta/TestDeltaLakeKernelTypeToType.java
new file mode 100644
index 0000000000..c9012c52e0
--- /dev/null
+++
b/delta-lake/src/test/java/org/apache/iceberg/delta/TestDeltaLakeKernelTypeToType.java
@@ -0,0 +1,240 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.iceberg.delta;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+import io.delta.kernel.types.ArrayType;
+import io.delta.kernel.types.BinaryType;
+import io.delta.kernel.types.BooleanType;
+import io.delta.kernel.types.ByteType;
+import io.delta.kernel.types.DateType;
+import io.delta.kernel.types.DecimalType;
+import io.delta.kernel.types.DoubleType;
+import io.delta.kernel.types.FloatType;
+import io.delta.kernel.types.IntegerType;
+import io.delta.kernel.types.LongType;
+import io.delta.kernel.types.MapType;
+import io.delta.kernel.types.ShortType;
+import io.delta.kernel.types.StringType;
+import io.delta.kernel.types.StructField;
+import io.delta.kernel.types.StructType;
+import io.delta.kernel.types.TimestampNTZType;
+import io.delta.kernel.types.TimestampType;
+import io.delta.kernel.types.VariantType;
+import org.apache.iceberg.Schema;
+import org.apache.iceberg.types.Type;
+import org.apache.iceberg.types.Types;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+
+public class TestDeltaLakeKernelTypeToType {
+ private StructType deltaAtomicSchema;
+
+ @BeforeEach
+ public void constructDeltaLakeSchema() {
+ deltaAtomicSchema =
+ new StructType()
+ .add("testBoolType", BooleanType.BOOLEAN, false)
+ .add("testIntType", IntegerType.INTEGER)
+ .add("testLongType", LongType.LONG, false)
+ .add("testFloatType", FloatType.FLOAT)
+ .add("testDoubleType", DoubleType.DOUBLE, false)
+ .add("testStringType", StringType.STRING)
+ .add("testBinaryType", BinaryType.BINARY, false)
+ .add("testDateType", DateType.DATE)
+ .add("testDecimalType", DecimalType.USER_DEFAULT, false)
+ .add("testDecimalMaxType", new DecimalType(38, 38));
+ }
+
+ @Test
+ public void testAtomicTypeConversion() {
+ Type converted = new
DeltaLakeKernelTypeToType(deltaAtomicSchema).convertType();
+ Schema convertedSchema = new
Schema(converted.asNestedType().asStructType().fields());
+
+ assertToAtomicSchema(convertedSchema);
+ }
+
+ private void assertToAtomicSchema(Schema convertedSchema) {
+
assertThat(convertedSchema.columns().size()).isEqualTo(deltaAtomicSchema.fields().size());
+ for (StructField field : deltaAtomicSchema.fields()) {
+ assertThat(convertedSchema.findField(field.getName())).isNotNull();
+ assertThat(convertedSchema.findField(field.getName()).isOptional())
+ .isEqualTo(field.isNullable());
+ }
+
+
assertThat(convertedSchema.findType("testBoolType")).isInstanceOf(Types.BooleanType.class);
+
assertThat(convertedSchema.findType("testIntType")).isInstanceOf(Types.IntegerType.class);
+
assertThat(convertedSchema.findType("testLongType")).isInstanceOf(Types.LongType.class);
+
assertThat(convertedSchema.findType("testFloatType")).isInstanceOf(Types.FloatType.class);
+
assertThat(convertedSchema.findType("testDoubleType")).isInstanceOf(Types.DoubleType.class);
+
assertThat(convertedSchema.findType("testStringType")).isInstanceOf(Types.StringType.class);
+
assertThat(convertedSchema.findType("testBinaryType")).isInstanceOf(Types.BinaryType.class);
+
assertThat(convertedSchema.findType("testDateType")).isInstanceOf(Types.DateType.class);
+
assertThat(convertedSchema.findType("testDecimalType")).isInstanceOf(Types.DecimalType.class);
+
+ assertThat(convertedSchema.findType("testDecimalMaxType"))
+ .isInstanceOf(Types.DecimalType.class);
+ Types.DecimalType testDecimalMaxType =
+ (Types.DecimalType) convertedSchema.findType("testDecimalMaxType");
+ assertThat(testDecimalMaxType.precision()).isEqualTo(38);
+ assertThat(testDecimalMaxType.scale()).isEqualTo(38);
+ }
+
+ @Test
+ public void testUpcastConversion() {
+ StructType deltaSchema =
+ new StructType()
+ .add("nullableByte", ByteType.BYTE)
+ .add("requiredShort", ShortType.SHORT, false);
+ Type converted = new DeltaLakeKernelTypeToType(deltaSchema).convertType();
+
+ Schema convertedSchema = new
Schema(converted.asNestedType().asStructType().fields());
+
+
assertThat(convertedSchema.findType("nullableByte")).isInstanceOf(Types.IntegerType.class);
+
assertThat(convertedSchema.findField("nullableByte").isOptional()).isTrue();
+
assertThat(convertedSchema.findType("requiredShort")).isInstanceOf(Types.IntegerType.class);
+
assertThat(convertedSchema.findField("requiredShort").isRequired()).isTrue();
+ }
+
+ @Test
+ public void testTimestampsConversion() {
+ StructType deltaSchema =
+ new StructType()
+ .add("nullableTimestamp", TimestampType.TIMESTAMP)
+ .add("requiredTimestampNtz", TimestampNTZType.TIMESTAMP_NTZ,
false);
+ Type converted = new DeltaLakeKernelTypeToType(deltaSchema).convertType();
+
+ Schema convertedSchema = new
Schema(converted.asNestedType().asStructType().fields());
+
+ assertThat(convertedSchema.findType("nullableTimestamp"))
+ .isInstanceOf(Types.TimestampType.class);
+ assertThat(
+ ((Types.TimestampType)
convertedSchema.findType("nullableTimestamp"))
+ .shouldAdjustToUTC())
+ .isTrue();
+
assertThat(convertedSchema.findField("nullableTimestamp").isOptional()).isTrue();
+ assertThat(convertedSchema.findType("requiredTimestampNtz"))
+ .isInstanceOf(Types.TimestampType.class);
+ assertThat(
+ ((Types.TimestampType)
convertedSchema.findType("requiredTimestampNtz"))
+ .shouldAdjustToUTC())
+ .isFalse();
+
assertThat(convertedSchema.findField("requiredTimestampNtz").isRequired()).isTrue();
+ }
+
+ @Test
+ public void testVariantConversion() {
+ StructType deltaSchema =
+ new StructType() // Spec v3 is required
+ .add("nullableVariant", VariantType.VARIANT);
+ Type converted = new DeltaLakeKernelTypeToType(deltaSchema).convertType();
+
+ Schema convertedSchema = new
Schema(converted.asNestedType().asStructType().fields());
+
+
assertThat(convertedSchema.findType("nullableVariant")).isInstanceOf(Types.VariantType.class);
+
assertThat(convertedSchema.findField("nullableVariant").isOptional()).isTrue();
+ }
+
+ @Test
+ public void testArrayConversion() {
+ StructType deltaSchema =
+ new StructType().add("testDoubleArray", new
ArrayType(DoubleType.DOUBLE, true), false);
+
+ Type converted = new DeltaLakeKernelTypeToType(deltaSchema).convertType();
+
+ Schema convertedSchema = new
Schema(converted.asNestedType().asStructType().fields());
+
+
assertThat(convertedSchema.findType("testDoubleArray")).isInstanceOf(Types.ListType.class);
+
assertThat(convertedSchema.findField("testDoubleArray").isRequired()).isTrue();
+
assertThat(convertedSchema.findType("testDoubleArray").asListType().elementType())
+ .isInstanceOf(Types.DoubleType.class);
+
assertThat(convertedSchema.findType("testDoubleArray").asListType().isElementOptional())
+ .isTrue();
+ }
+
+ @Test
+ public void testMapConversion() {
+ StructType deltaSchema =
+ new StructType()
+ .add("testStringLongMap", new MapType(StringType.STRING,
LongType.LONG, false), false);
+ Type converted = new DeltaLakeKernelTypeToType(deltaSchema).convertType();
+
+ Schema convertedSchema = new
Schema(converted.asNestedType().asStructType().fields());
+
+
assertThat(convertedSchema.findType("testStringLongMap")).isInstanceOf(Types.MapType.class);
+
assertThat(convertedSchema.findField("testStringLongMap").isRequired()).isTrue();
+
assertThat(convertedSchema.findType("testStringLongMap").asMapType().keyType())
+ .isInstanceOf(Types.StringType.class);
+
assertThat(convertedSchema.findType("testStringLongMap").asMapType().valueType())
+ .isInstanceOf(Types.LongType.class);
+
assertThat(convertedSchema.findType("testStringLongMap").asMapType().isValueRequired())
+ .isTrue();
+ }
+
+ @Test
+ public void testNestedTypeConversion() {
+ StructType deltaNestedSchema =
+ new StructType()
+ .add("testInnerAtomicSchema", deltaAtomicSchema)
+ .add("testStructArrayType", new ArrayType(deltaAtomicSchema,
true), false)
+ .add(
+ "testStringStructMap",
+ new MapType(StringType.STRING, deltaAtomicSchema, false),
+ false);
+ Type converted = new
DeltaLakeKernelTypeToType(deltaNestedSchema).convertType();
+ Schema convertedSchema = new
Schema(converted.asNestedType().asStructType().fields());
+
+ assertThat(convertedSchema.findType("testInnerAtomicSchema"))
+ .isInstanceOf(Types.StructType.class);
+
assertThat(convertedSchema.findField("testInnerAtomicSchema").isOptional()).isTrue();
+ assertToAtomicSchema(
+
convertedSchema.findType("testInnerAtomicSchema").asStructType().asSchema());
+
+
assertThat(convertedSchema.findType("testStructArrayType")).isInstanceOf(Types.ListType.class);
+
assertThat(convertedSchema.findField("testStructArrayType").isRequired()).isTrue();
+
assertThat(convertedSchema.findType("testStructArrayType").asListType().isElementOptional())
+ .isTrue();
+
assertThat(convertedSchema.findType("testStructArrayType").asListType().elementType())
+ .isInstanceOf(Types.StructType.class);
+ assertToAtomicSchema(
+ convertedSchema
+ .findType("testStructArrayType")
+ .asListType()
+ .elementType()
+ .asStructType()
+ .asSchema());
+
+
assertThat(convertedSchema.findType("testStringStructMap")).isInstanceOf(Types.MapType.class);
+
assertThat(convertedSchema.findField("testStringStructMap").isRequired()).isTrue();
+
assertThat(convertedSchema.findType("testStringStructMap").asMapType().keyType())
+ .isInstanceOf(Types.StringType.class);
+
assertThat(convertedSchema.findType("testStringStructMap").asMapType().valueType())
+ .isInstanceOf(Types.StructType.class);
+
assertThat(convertedSchema.findType("testStringStructMap").asMapType().isValueRequired())
+ .isTrue();
+ assertToAtomicSchema(
+ convertedSchema
+ .findType("testStringStructMap")
+ .asMapType()
+ .valueType()
+ .asStructType()
+ .asSchema());
+ }
+}
diff --git
a/delta-lake/src/test/java/org/apache/iceberg/delta/TestDeltaLakePathHandling.java
b/delta-lake/src/test/java/org/apache/iceberg/delta/TestDeltaLakePathHandling.java
new file mode 100644
index 0000000000..c2240cde79
--- /dev/null
+++
b/delta-lake/src/test/java/org/apache/iceberg/delta/TestDeltaLakePathHandling.java
@@ -0,0 +1,55 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.iceberg.delta;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+import java.io.File;
+import java.util.stream.Stream;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.MethodSource;
+
+public class TestDeltaLakePathHandling {
+
+ @ParameterizedTest
+ @MethodSource("pathHandlingCases")
+ public void testGetFullFilePath(String path, String tableRoot, String
expected) {
+ String result =
BaseSnapshotDeltaLakeKernelTableAction.getFullFilePath(path, tableRoot);
+ assertThat(result).isEqualTo(expected);
+ }
+
+ private static Stream<Arguments> pathHandlingCases() {
+ return Stream.of(
+ Arguments.of(
+ "a+b%20c.parquet", "/tmp/table", "/tmp/table" + File.separator +
"a+b c.parquet"),
+ Arguments.of("a+b%20c.parquet", "s3://bucket/table",
"s3://bucket/table/a+b c.parquet"),
+ Arguments.of("a+b%20c.parquet", "s3://bucket/table/",
"s3://bucket/table/a+b c.parquet"),
+ Arguments.of("file:/tmp/other/a+b%20c.parquet", "/tmp/table",
"/tmp/other/a+b c.parquet"),
+ Arguments.of(
+ "s3://bucket/other/a+b%20c.parquet", "/tmp/table",
"s3://bucket/other/a+b%20c.parquet"),
+ Arguments.of(
+ "dir/a.parquet", "/tmp/table", "/tmp/table" + File.separator +
"dir/a.parquet"),
+ Arguments.of("dir/a.parquet", "s3://bucket/table",
"s3://bucket/table/dir/a.parquet"),
+ Arguments.of("file:///tmp/other/a.parquet", "/tmp/table",
"/tmp/other/a.parquet"),
+ Arguments.of(
+ "a%23b%3Fc.parquet", "/tmp/table", "/tmp/table" + File.separator +
"a#b?c.parquet"),
+ Arguments.of("p.parquet", "C:\\table", "C:\\table" + File.separator +
"p.parquet"));
+ }
+}
diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml
index 36bbe03e18..ff73a65373 100644
--- a/gradle/libs.versions.toml
+++ b/gradle/libs.versions.toml
@@ -40,6 +40,7 @@ bouncycastle = "1.87"
bson-ver = "5.15.0"
caffeine = "3.3.1"
datasketches = "6.2.0"
+delta-kernel = "4.4.0"
delta-standalone = "3.3.3"
delta-spark = "3.3.3"
derby = "10.15.2.0"
@@ -113,6 +114,9 @@ bouncycastle-bcprov = { module =
"org.bouncycastle:bcprov-jdk18on", version.ref
bouncycastle-bcutil = { module = "org.bouncycastle:bcutil-jdk18on",
version.ref = "bouncycastle" }
caffeine = { module = "com.github.ben-manes.caffeine:caffeine", version.ref =
"caffeine" }
datasketches = { module = "org.apache.datasketches:datasketches-java",
version.ref = "datasketches" }
+delta-kernel-api = { module = "io.delta:delta-kernel-api", version.ref =
"delta-kernel" }
+delta-kernel-defaults = { module = "io.delta:delta-kernel-defaults",
version.ref = "delta-kernel" }
+delta-standalone = { module = "io.delta:delta-standalone_2.12", version.ref =
"delta-standalone" }
errorprone-annotations = { module =
"com.google.errorprone:error_prone_annotations", version.ref =
"errorprone-annotations" }
failsafe = { module = "dev.failsafe:failsafe", version.ref = "failsafe"}
findbugs-jsr305 = { module = "com.google.code.findbugs:jsr305", version.ref =
"findbugs-jsr305" }