This is an automated email from the ASF dual-hosted git repository.

the-other-tim-brown pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/incubator-xtable.git


The following commit(s) were added to refs/heads/main by this push:
     new f0a5a6e3 [1013] Read Delta column stats by physical name when column 
mapping is enabled (#1014)
f0a5a6e3 is described below

commit f0a5a6e3b7c3eb3e6777df9d0542da1c22a9c640
Author: Indian-boult <[email protected]>
AuthorDate: Mon Nov 23 01:44:52 2026 +0530

    [1013] Read Delta column stats by physical name when column mapping is 
enabled (#1014)
    
    * [1013] Read Delta column stats by physical name when column mapping is 
enabled
    
    With delta.columnMapping.mode set to name or id, Delta keys the
    minValues, maxValues and nullCount maps in each file's stats by the
    physical column name. DeltaStatsUtils.parseColumnStatsFromJson, which
    both the Delta Standalone and Delta Kernel sources use, looked the
    stats up by the logical path instead.
    
    This had three effects:
    - A column whose physical name differs from its logical name, such as
      col-<uuid>, got no stats.
    - When column mapping is enabled on a table that already has data, the
      existing names become the physical names. After a rename, one
      column's logical name can be another column's physical name, so it
      got that column's stats. A column re-added under an old name reported
      zero nulls in files written before it existed.
    - If the other column had a different type, parsing could throw, for
      example a DateTimeParseException for a DATE column.
    
    Build a map from each field's logical path to its physical path, where
    each segment is the field's storage name when one is set, and look the
    stats up by the physical path. There is no fallback to the logical
    name, since it can be another column's physical name.
    
    Fixes #1013
    
    * [1013] Cover nested field stats under column mapping in 
ITDeltaConversionSource
    
    * [1013] Use long literals for ColumnStat counts in the new tests
    
    So the tests also compile once #1012 makes numNulls and totalSize Long.
    
    * [1013] Reuse SchemaUtils.getFullyQualifiedPath and share the stats test 
helper
    
    getPhysicalPaths builds each path with SchemaUtils.getFullyQualifiedPath. 
The test helper returns the FileStats, which holds the column stats and the 
record count, so the existing tests use it as well.
---
 .../org/apache/xtable/delta/DeltaStatsUtils.java   |  23 +++-
 .../xtable/delta/ITDeltaConversionSource.java      | 148 +++++++++++++++++++++
 .../xtable/delta/TestDeltaStatsExtractor.java      | 138 ++++++++++++++++---
 .../kernel/ITDeltaKernelConversionSource.java      |  69 ++++++++++
 4 files changed, 354 insertions(+), 24 deletions(-)

diff --git 
a/xtable-core/src/main/java/org/apache/xtable/delta/DeltaStatsUtils.java 
b/xtable-core/src/main/java/org/apache/xtable/delta/DeltaStatsUtils.java
index a5d3ae04..fe8b78ef 100644
--- a/xtable-core/src/main/java/org/apache/xtable/delta/DeltaStatsUtils.java
+++ b/xtable-core/src/main/java/org/apache/xtable/delta/DeltaStatsUtils.java
@@ -52,6 +52,7 @@ import org.apache.xtable.model.schema.InternalType;
 import org.apache.xtable.model.stat.ColumnStat;
 import org.apache.xtable.model.stat.FileStats;
 import org.apache.xtable.model.stat.Range;
+import org.apache.xtable.schema.SchemaUtils;
 
 /**
  * Shared utility for Delta stats conversion between XTable internal format 
and Delta format. Used
@@ -136,13 +137,14 @@ public class DeltaStatsUtils {
       Map<String, Object> fieldPathToMaxValue = 
flattenStatMap(deltaStats.getMaxValues());
       Map<String, Object> fieldPathToMinValue = 
flattenStatMap(deltaStats.getMinValues());
       Map<String, Object> fieldPathToNullCount = 
flattenStatMap(deltaStats.getNullCount());
+      Map<String, String> physicalPaths = getPhysicalPaths(fields);
 
       List<ColumnStat> columnStats =
           fields.stream()
-              .filter(field -> 
fieldPathToMaxValue.containsKey(field.getPath()))
+              .filter(field -> 
fieldPathToMaxValue.containsKey(physicalPaths.get(field.getPath())))
               .map(
                   field -> {
-                    String fieldPath = field.getPath();
+                    String fieldPath = physicalPaths.get(field.getPath());
                     Object minRaw = fieldPathToMinValue.get(fieldPath);
                     Object maxRaw = fieldPathToMaxValue.get(fieldPath);
                     Object nullCountRaw = fieldPathToNullCount.get(fieldPath);
@@ -179,6 +181,23 @@ public class DeltaStatsUtils {
     }
   }
 
+  /**
+   * Maps each field's path to the path its stats are keyed by. With column 
mapping, Delta keys the
+   * stats by physical name, so a path segment is the field's storage name 
when one is set. There is
+   * no fallback to the logical name, which can be another column's physical 
name after renames.
+   * Parents must come before their children, as in {@link 
InternalSchema#getAllFields()}.
+   */
+  private static Map<String, String> getPhysicalPaths(List<InternalField> 
fields) {
+    Map<String, String> physicalPaths = new HashMap<>();
+    for (InternalField field : fields) {
+      String name = field.getStorageName() != null ? field.getStorageName() : 
field.getName();
+      physicalPaths.put(
+          field.getPath(),
+          
SchemaUtils.getFullyQualifiedPath(physicalPaths.get(field.getParentPath()), 
name));
+    }
+    return physicalPaths;
+  }
+
   private static Set<String> 
getPathsFromStructSchemaForMinAndMaxStats(InternalSchema schema) {
     return schema.getAllFields().stream()
         .filter(
diff --git 
a/xtable-core/src/test/java/org/apache/xtable/delta/ITDeltaConversionSource.java
 
b/xtable-core/src/test/java/org/apache/xtable/delta/ITDeltaConversionSource.java
index 8224a8b5..a860a7ad 100644
--- 
a/xtable-core/src/test/java/org/apache/xtable/delta/ITDeltaConversionSource.java
+++ 
b/xtable-core/src/test/java/org/apache/xtable/delta/ITDeltaConversionSource.java
@@ -45,6 +45,7 @@ import java.util.Collections;
 import java.util.List;
 import java.util.Map;
 import java.util.Set;
+import java.util.function.Function;
 import java.util.stream.Collectors;
 import java.util.stream.Stream;
 
@@ -444,6 +445,142 @@ public class ITDeltaConversionSource {
     assertEquals(1, nullPartitionFiles);
   }
 
+  @Test
+  void getCurrentSnapshotColumnMappingStatsTest() {
+    // Column mapping enabled after data exists keeps a as the physical name 
of a. After renaming a
+    // to a_old and re-adding a, a_old has physical name a and the new a has a 
col-<uuid> name.
+    final String tableName = GenericTable.getTableName();
+    final Path basePath = tempDir.resolve(tableName);
+    sparkSession.sql(
+        "CREATE TABLE `" + tableName + "` (id INT, a INT) USING DELTA LOCATION 
'" + basePath + "'");
+    sparkSession.sql("INSERT INTO TABLE `" + tableName + "` VALUES (1, 10), 
(2, 20)");
+    sparkSession.sql(
+        "ALTER TABLE `"
+            + tableName
+            + "` SET TBLPROPERTIES ('delta.minReaderVersion'='2',"
+            + " 'delta.minWriterVersion'='5', 
'delta.columnMapping.mode'='name')");
+    sparkSession.sql("ALTER TABLE `" + tableName + "` RENAME COLUMN a TO 
a_old");
+    sparkSession.sql("ALTER TABLE `" + tableName + "` ADD COLUMNS (a INT)");
+    sparkSession.sql("INSERT INTO TABLE `" + tableName + "` VALUES (3, 30, 
300)");
+
+    InternalSnapshot snapshot = getCurrentSnapshot(tableName, basePath);
+
+    List<InternalField> fields = 
snapshot.getTable().getReadSchema().getFields();
+    assertEquals(
+        Arrays.asList("id", "a_old", "a"),
+        
fields.stream().map(InternalField::getName).collect(Collectors.toList()));
+    InternalField id = fields.get(0);
+    InternalField aOld = fields.get(1);
+    InternalField a = fields.get(2);
+    assertEquals("a", aOld.getStorageName());
+    assertTrue(a.getStorageName().startsWith("col-"));
+    Map<Long, List<ColumnStat>> columnStatsByRecordCount = 
getColumnStatsByRecordCount(snapshot);
+    assertEquals(2, columnStatsByRecordCount.size());
+    // The file written before a was re-added has no stats for the new a.
+    assertEquals(
+        Arrays.asList(columnStat(id, 1, 2, 2), columnStat(aOld, 10, 20, 2)),
+        columnStatsByRecordCount.get(2L));
+    assertEquals(
+        Arrays.asList(
+            columnStat(id, 3, 3, 1), columnStat(aOld, 30, 30, 1), 
columnStat(a, 300, 300, 1)),
+        columnStatsByRecordCount.get(1L));
+  }
+
+  @Test
+  void getCurrentSnapshotColumnMappingNestedStatsTest() {
+    // Delta keys nested stats by the dot path of the field, for example s.x. 
Column mapping enabled
+    // after data exists keeps s, x and y as the physical names. After 
renaming s.x to x_old and
+    // re-adding s.x, s.x_old has physical path s.x and the new s.x has 
physical path s.col-<uuid>.
+    final String tableName = GenericTable.getTableName();
+    final Path basePath = tempDir.resolve(tableName);
+    sparkSession.sql(
+        "CREATE TABLE `"
+            + tableName
+            + "` (id INT, s STRUCT<x: INT, y: STRING>) USING DELTA LOCATION '"
+            + basePath
+            + "'");
+    sparkSession.sql(
+        "INSERT INTO TABLE `"
+            + tableName
+            + "` VALUES (1, named_struct('x', 10, 'y', 'a')), (2, 
named_struct('x', 20, 'y', 'b'))");
+
+    // Without column mapping, the physical path is the logical path.
+    InternalSnapshot snapshot = getCurrentSnapshot(tableName, basePath);
+    Map<String, InternalField> fields = getFieldsByPath(snapshot);
+    assertEquals(
+        Arrays.asList(
+            columnStat(fields.get("id"), 1, 2, 2),
+            columnStat(fields.get("s.x"), 10, 20, 2),
+            columnStat(fields.get("s.y"), "a", "b", 2)),
+        getColumnStatsByRecordCount(snapshot).get(2L));
+
+    sparkSession.sql(
+        "ALTER TABLE `"
+            + tableName
+            + "` SET TBLPROPERTIES ('delta.minReaderVersion'='2',"
+            + " 'delta.minWriterVersion'='5', 
'delta.columnMapping.mode'='name')");
+    sparkSession.sql("ALTER TABLE `" + tableName + "` RENAME COLUMN s.x TO 
x_old");
+    sparkSession.sql("ALTER TABLE `" + tableName + "` ADD COLUMNS (s.x INT)");
+    sparkSession.sql(
+        "INSERT INTO TABLE `"
+            + tableName
+            + "` VALUES (3, named_struct('x_old', 30, 'y', 'c', 'x', 300))");
+    assertColumnMappedNestedStats(tableName, basePath, "s");
+
+    // Renaming the struct keeps its physical name, so its fields keep their 
physical paths.
+    sparkSession.sql("ALTER TABLE `" + tableName + "` RENAME COLUMN s TO 
s_renamed");
+    assertColumnMappedNestedStats(tableName, basePath, "s_renamed");
+  }
+
+  private void assertColumnMappedNestedStats(String tableName, Path basePath, 
String struct) {
+    InternalSnapshot snapshot = getCurrentSnapshot(tableName, basePath);
+    Map<String, InternalField> fields = getFieldsByPath(snapshot);
+    InternalField id = fields.get("id");
+    InternalField xOld = fields.get(struct + ".x_old");
+    InternalField y = fields.get(struct + ".y");
+    InternalField x = fields.get(struct + ".x");
+    assertEquals("s", fields.get(struct).getStorageName());
+    assertEquals("x", xOld.getStorageName());
+    assertTrue(x.getStorageName().startsWith("col-"));
+    Map<Long, List<ColumnStat>> columnStatsByRecordCount = 
getColumnStatsByRecordCount(snapshot);
+    assertEquals(2, columnStatsByRecordCount.size());
+    // The file written before s.x was re-added has no stats for the new s.x.
+    assertEquals(
+        Arrays.asList(
+            columnStat(id, 1, 2, 2), columnStat(xOld, 10, 20, 2), 
columnStat(y, "a", "b", 2)),
+        columnStatsByRecordCount.get(2L));
+    assertEquals(
+        Arrays.asList(
+            columnStat(id, 3, 3, 1),
+            columnStat(xOld, 30, 30, 1),
+            columnStat(y, "c", "c", 1),
+            columnStat(x, 300, 300, 1)),
+        columnStatsByRecordCount.get(1L));
+  }
+
+  private InternalSnapshot getCurrentSnapshot(String tableName, Path basePath) 
{
+    SourceTable tableConfig =
+        SourceTable.builder()
+            .name(tableName)
+            .basePath(basePath.toString())
+            .formatName(TableFormat.DELTA)
+            .build();
+    return 
conversionSourceProvider.getConversionSourceInstance(tableConfig).getCurrentSnapshot();
+  }
+
+  private static Map<String, InternalField> getFieldsByPath(InternalSnapshot 
snapshot) {
+    return snapshot.getTable().getReadSchema().getAllFields().stream()
+        .collect(Collectors.toMap(InternalField::getPath, 
Function.identity()));
+  }
+
+  private static Map<Long, List<ColumnStat>> getColumnStatsByRecordCount(
+      InternalSnapshot snapshot) {
+    return snapshot.getPartitionedDataFiles().stream()
+        .flatMap(group -> group.getDataFiles().stream())
+        .collect(
+            Collectors.toMap(InternalDataFile::getRecordCount, 
InternalDataFile::getColumnStats));
+  }
+
   @ParameterizedTest
   @MethodSource("testWithPartitionToggle")
   public void testInsertsUpsertsAndDeletes(boolean isPartitioned) {
@@ -829,6 +966,17 @@ public class ITDeltaConversionSource {
     return Stream.of(Arguments.of(false), Arguments.of(true));
   }
 
+  private static ColumnStat columnStat(
+      InternalField field, Object min, Object max, long numValues) {
+    return ColumnStat.builder()
+        .field(field)
+        .range(Range.vector(min, max))
+        .numNulls(0L)
+        .numValues(numValues)
+        .totalSize(0L)
+        .build();
+  }
+
   private boolean checkIfFileIsRemoved(String activePath, TableChange 
tableChange) {
     Set<String> filePathsRemoved =
         tableChange.getFilesDiff().getFilesRemoved().stream()
diff --git 
a/xtable-core/src/test/java/org/apache/xtable/delta/TestDeltaStatsExtractor.java
 
b/xtable-core/src/test/java/org/apache/xtable/delta/TestDeltaStatsExtractor.java
index bab9b884..f4288dc6 100644
--- 
a/xtable-core/src/test/java/org/apache/xtable/delta/TestDeltaStatsExtractor.java
+++ 
b/xtable-core/src/test/java/org/apache/xtable/delta/TestDeltaStatsExtractor.java
@@ -174,11 +174,7 @@ public class TestDeltaStatsExtractor {
     String stats =
         DeltaStatsExtractor.getInstance()
             .convertStatsToDeltaFormat(schema, numRecords, columnStats);
-    AddFile addFile = new AddFile("file://path/to/file", null, 0, 0, true, 
stats, null, null);
-    DeltaStatsExtractor extractor = DeltaStatsExtractor.getInstance();
-    FileStats actual = extractor.getColumnStatsForFile(addFile, fields);
-    List<ColumnStat> actualColumStats = actual.getColumnStats();
-    long actualNumRecords = actual.getNumRecords();
+    FileStats actual = extractFileStats(stats, fields);
 
     Set<ColumnStat> expected = new HashSet<>();
     columnStats.forEach(
@@ -191,8 +187,8 @@ public class TestDeltaStatsExtractor {
             expected.add(columnStatWithoutSize);
           }
         });
-    assertEquals(expected, new HashSet<>(actualColumStats));
-    assertEquals(numRecords, actualNumRecords);
+    assertEquals(expected, new HashSet<>(actual.getColumnStats()));
+    assertEquals(numRecords, actual.getNumRecords());
   }
 
   @Test
@@ -210,16 +206,12 @@ public class TestDeltaStatsExtractor {
     deltaStats.put("tightBounds", Boolean.TRUE);
     deltaStats.put("nonExisting", minValues);
     String stats = MAPPER.writeValueAsString(deltaStats);
-    AddFile addFile = new AddFile("file://path/to/file", null, 0, 0, true, 
stats, null, null);
-    DeltaStatsExtractor extractor = DeltaStatsExtractor.getInstance();
-    FileStats actual = extractor.getColumnStatsForFile(addFile, fields);
-    List<ColumnStat> actualColumStats = actual.getColumnStats();
-    long actualNumRecords = actual.getNumRecords();
-    Set<String> unsupportedStats = extractor.getUnsupportedStats();
+    FileStats actual = extractFileStats(stats, fields);
+    Set<String> unsupportedStats = 
DeltaStatsExtractor.getInstance().getUnsupportedStats();
     assertEquals(2, unsupportedStats.size());
     assertTrue(unsupportedStats.contains("tightBounds"));
     assertTrue(unsupportedStats.contains("nonExisting"));
-    assertEquals(numRecords, actualNumRecords);
+    assertEquals(numRecords, actual.getNumRecords());
 
     List<ColumnStat> expected =
         Arrays.asList(
@@ -247,7 +239,7 @@ public class TestDeltaStatsExtractor {
                 .numNulls(4L)
                 .range(Range.vector(10, 20))
                 .build());
-    assertEquals(expected, actualColumStats);
+    assertEquals(expected, actual.getColumnStats());
   }
 
   @Test
@@ -272,13 +264,115 @@ public class TestDeltaStatsExtractor {
   @Test
   void convertNullStatsToInternalRepresentation() {
     List<InternalField> fields = getSchemaFields();
-    AddFile addFile = new AddFile("file://path/to/file", null, 0, 0, true, 
null, null, null);
-    DeltaStatsExtractor extractor = DeltaStatsExtractor.getInstance();
-    FileStats actual = extractor.getColumnStatsForFile(addFile, fields);
-    List<ColumnStat> actualColumStats = actual.getColumnStats();
-    long actualNumRecords = actual.getNumRecords();
-    assertEquals(Collections.emptyList(), actualColumStats);
-    assertEquals(0, actualNumRecords);
+    FileStats actual = extractFileStats(null, fields);
+    assertEquals(Collections.emptyList(), actual.getColumnStats());
+    assertEquals(0, actual.getNumRecords());
+  }
+
+  @Test
+  void convertStatsWithColumnMappingPhysicalNames() {
+    // With column mapping, the stats are keyed by physical name at every 
level of nesting.
+    List<InternalField> fields =
+        Arrays.asList(
+            columnMappedField("top_level_string", "col-1f2e", null, 
InternalType.STRING),
+            columnMappedField("nested", "col-3d4c", null, InternalType.RECORD),
+            columnMappedField("int_field", "col-5b6a", "nested", 
InternalType.INT));
+    String stats =
+        "{\"numRecords\":100,"
+            + 
"\"minValues\":{\"col-1f2e\":\"a\",\"col-3d4c\":{\"col-5b6a\":1}},"
+            + 
"\"maxValues\":{\"col-1f2e\":\"b\",\"col-3d4c\":{\"col-5b6a\":2}},"
+            + "\"nullCount\":{\"col-1f2e\":3,\"col-3d4c\":{\"col-5b6a\":4}}}";
+    List<ColumnStat> expected =
+        Arrays.asList(
+            ColumnStat.builder()
+                .field(fields.get(0))
+                .numValues(100)
+                .numNulls(3L)
+                .range(Range.vector("a", "b"))
+                .build(),
+            ColumnStat.builder()
+                .field(fields.get(2))
+                .numValues(100)
+                .numNulls(4L)
+                .range(Range.vector(1, 2))
+                .build());
+    FileStats actual = extractFileStats(stats, fields);
+    assertEquals(expected, actual.getColumnStats());
+    assertEquals(100, actual.getNumRecords());
+  }
+
+  @Test
+  void convertStatsWithColumnMappingSwappedNames() {
+    // Column mapping enabled on an existing table keeps the old names as 
physical names. After a
+    // and b swap names, each logical name is the other column's physical name.
+    List<InternalField> fields =
+        Arrays.asList(
+            columnMappedField("a", "b", null, InternalType.INT),
+            columnMappedField("b", "a", null, InternalType.INT));
+    String stats =
+        "{\"numRecords\":100,"
+            + "\"minValues\":{\"a\":1,\"b\":10},"
+            + "\"maxValues\":{\"a\":2,\"b\":20},"
+            + "\"nullCount\":{\"a\":0,\"b\":5}}";
+    List<ColumnStat> expected =
+        Arrays.asList(
+            ColumnStat.builder()
+                .field(fields.get(0))
+                .numValues(100)
+                .numNulls(5L)
+                .range(Range.vector(10, 20))
+                .build(),
+            ColumnStat.builder()
+                .field(fields.get(1))
+                .numValues(100)
+                .numNulls(0L)
+                .range(Range.vector(1, 2))
+                .build());
+    FileStats actual = extractFileStats(stats, fields);
+    assertEquals(expected, actual.getColumnStats());
+    assertEquals(100, actual.getNumRecords());
+  }
+
+  @Test
+  void convertStatsWithColumnMappingReAddedColumn() {
+    // After renaming a to a_old, a_old keeps physical name a and a re-added a 
gets a new physical
+    // name. A file written before the re-add has stats keyed by a, but none 
for the new a. The new
+    // a is a DATE, so the INT stats of a_old do not parse as its stats.
+    List<InternalField> fields =
+        Arrays.asList(
+            columnMappedField("a_old", "a", null, InternalType.INT),
+            columnMappedField("a", "col-1f2e", null, InternalType.DATE));
+    String stats =
+        "{\"numRecords\":100,"
+            + "\"minValues\":{\"a\":1},"
+            + "\"maxValues\":{\"a\":2},"
+            + "\"nullCount\":{\"a\":0}}";
+    List<ColumnStat> expected =
+        Collections.singletonList(
+            ColumnStat.builder()
+                .field(fields.get(0))
+                .numValues(100)
+                .numNulls(0L)
+                .range(Range.vector(1, 2))
+                .build());
+    FileStats actual = extractFileStats(stats, fields);
+    assertEquals(expected, actual.getColumnStats());
+    assertEquals(100, actual.getNumRecords());
+  }
+
+  private static FileStats extractFileStats(String stats, List<InternalField> 
fields) {
+    AddFile addFile = new AddFile("file://path/to/file", null, 0, 0, true, 
stats, null, null);
+    return DeltaStatsExtractor.getInstance().getColumnStatsForFile(addFile, 
fields);
+  }
+
+  private static InternalField columnMappedField(
+      String name, String physicalName, String parentPath, InternalType 
dataType) {
+    return InternalField.builder()
+        .name(name)
+        .storageName(physicalName)
+        .parentPath(parentPath)
+        .schema(InternalSchema.builder().dataType(dataType).build())
+        .build();
   }
 
   private List<InternalField> getSchemaFields() {
diff --git 
a/xtable-core/src/test/java/org/apache/xtable/kernel/ITDeltaKernelConversionSource.java
 
b/xtable-core/src/test/java/org/apache/xtable/kernel/ITDeltaKernelConversionSource.java
index c6cfbe31..c92de971 100644
--- 
a/xtable-core/src/test/java/org/apache/xtable/kernel/ITDeltaKernelConversionSource.java
+++ 
b/xtable-core/src/test/java/org/apache/xtable/kernel/ITDeltaKernelConversionSource.java
@@ -356,6 +356,65 @@ public class ITDeltaKernelConversionSource {
         snapshot.getPartitionedDataFiles().get(0));
   }
 
+  @Test
+  void getCurrentSnapshotColumnMappingStatsTest() {
+    // Column mapping enabled after data exists keeps a as the physical name 
of a. After renaming a
+    // to a_old and re-adding a, a_old has physical name a and the new a has a 
col-<uuid> name.
+    final String tableName = GenericTable.getTableName();
+    final Path basePath = tempDir.resolve(tableName);
+    sparkSession.sql(
+        "CREATE TABLE `" + tableName + "` (id INT, a INT) USING DELTA LOCATION 
'" + basePath + "'");
+    sparkSession.sql("INSERT INTO TABLE `" + tableName + "` VALUES (1, 10), 
(2, 20)");
+    sparkSession.sql(
+        "ALTER TABLE `"
+            + tableName
+            + "` SET TBLPROPERTIES ('delta.minReaderVersion'='2',"
+            + " 'delta.minWriterVersion'='5', 
'delta.columnMapping.mode'='name')");
+    sparkSession.sql("ALTER TABLE `" + tableName + "` RENAME COLUMN a TO 
a_old");
+    sparkSession.sql("ALTER TABLE `" + tableName + "` ADD COLUMNS (a INT)");
+    sparkSession.sql("INSERT INTO TABLE `" + tableName + "` VALUES (3, 30, 
300)");
+    SourceTable tableConfig =
+        SourceTable.builder()
+            .name(tableName)
+            .basePath(basePath.toString())
+            .formatName(TableFormat.DELTA)
+            .build();
+    DeltaKernelConversionSource conversionSource =
+        conversionSourceProvider.getConversionSourceInstance(tableConfig);
+
+    InternalSnapshot snapshot = conversionSource.getCurrentSnapshot();
+
+    List<InternalField> fields = 
snapshot.getTable().getReadSchema().getFields();
+    assertEquals(
+        Arrays.asList("id", "a_old", "a"),
+        
fields.stream().map(InternalField::getName).collect(Collectors.toList()));
+    InternalField id = fields.get(0);
+    InternalField aOld = fields.get(1);
+    InternalField a = fields.get(2);
+    assertEquals("a", aOld.getStorageName());
+    assertTrue(a.getStorageName().startsWith("col-"));
+    List<InternalDataFile> dataFiles =
+        snapshot.getPartitionedDataFiles().stream()
+            .flatMap(group -> group.getDataFiles().stream())
+            .collect(Collectors.toList());
+    assertEquals(2, dataFiles.size());
+    Map<Long, List<ColumnStat>> columnStatsByRecordCount =
+        dataFiles.stream()
+            .collect(
+                Collectors.toMap(
+                    InternalDataFile::getRecordCount, 
InternalDataFile::getColumnStats));
+    // The file written before a was re-added has no stats for the new a.
+    assertEquals(
+        Arrays.asList(intColumnStat(id, 1, 2, 2), intColumnStat(aOld, 10, 20, 
2)),
+        columnStatsByRecordCount.get(2L));
+    assertEquals(
+        Arrays.asList(
+            intColumnStat(id, 3, 3, 1),
+            intColumnStat(aOld, 30, 30, 1),
+            intColumnStat(a, 300, 300, 1)),
+        columnStatsByRecordCount.get(1L));
+  }
+
   @ParameterizedTest
   @MethodSource("testWithPartitionToggle")
   public void testInsertsUpsertsAndDeletes(boolean isPartitioned) {
@@ -747,6 +806,16 @@ public class ITDeltaKernelConversionSource {
     return Stream.of(Arguments.of(false), Arguments.of(true));
   }
 
+  private static ColumnStat intColumnStat(InternalField field, int min, int 
max, long numValues) {
+    return ColumnStat.builder()
+        .field(field)
+        .range(Range.vector(min, max))
+        .numNulls(0L)
+        .numValues(numValues)
+        .totalSize(0L)
+        .build();
+  }
+
   private void validatePropertiesDataFile(InternalDataFile expected, 
InternalDataFile actual)
       throws URISyntaxException {
     assertTrue(

Reply via email to