the-other-tim-brown commented on code in PR #729: URL: https://github.com/apache/incubator-xtable/pull/729#discussion_r2410779270
########## xtable-core/src/main/java/org/apache/xtable/kernel/DeltaKernelActionsConverter.java: ########## @@ -0,0 +1,123 @@ +/* + * 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.xtable.kernel; + +import java.util.Collections; +import java.util.List; +import java.util.Map; + +import lombok.AccessLevel; +import lombok.NoArgsConstructor; + +import org.apache.hadoop.conf.Configuration; +import org.apache.hadoop.fs.Path; + +import scala.collection.JavaConverters; + +import io.delta.kernel.Table; +import io.delta.kernel.defaults.engine.DefaultEngine; +import io.delta.kernel.engine.Engine; +import io.delta.kernel.internal.actions.AddFile; +import io.delta.kernel.internal.actions.RemoveFile; + +import org.apache.xtable.exception.NotSupportedException; +import org.apache.xtable.model.schema.InternalField; +import org.apache.xtable.model.schema.InternalPartitionField; +import org.apache.xtable.model.stat.ColumnStat; +import org.apache.xtable.model.stat.FileStats; +import org.apache.xtable.model.storage.FileFormat; +import org.apache.xtable.model.storage.InternalDataFile; + +@NoArgsConstructor(access = AccessLevel.PRIVATE) +public class DeltaKernelActionsConverter { + private static final DeltaKernelActionsConverter INSTANCE = new DeltaKernelActionsConverter(); + + public static DeltaKernelActionsConverter getInstance() { + return INSTANCE; + } + + public InternalDataFile convertAddActionToInternalDataFile( + AddFile addFile, + Table table, + FileFormat fileFormat, + List<InternalPartitionField> partitionFields, + List<InternalField> fields, + boolean includeColumnStats, + DeltaKernelPartitionExtractor partitionExtractor, + DeltaKernelStatsExtractor fileStatsExtractor, + Map<String, String> partitionValues) { + FileStats fileStats = fileStatsExtractor.getColumnStatsForFile(addFile, fields); + List<ColumnStat> columnStats = + includeColumnStats ? fileStats.getColumnStats() : Collections.emptyList(); + long recordCount = fileStats.getNumRecords(); + // The immutable map from Java to Scala is not working, need to + + scala.collection.mutable.Map<String, String> scalaMap = + JavaConverters.mapAsScalaMap(partitionValues); + + return InternalDataFile.builder() + .physicalPath(getFullPathToFile(addFile.getPath(), table)) + .fileFormat(fileFormat) + .fileSizeBytes(addFile.getSize()) + .lastModified(addFile.getModificationTime()) + .partitionValues(partitionExtractor.partitionValueExtraction(scalaMap, partitionFields)) + .columnStats(columnStats) + .recordCount(recordCount) + .build(); + } + + public InternalDataFile convertRemoveActionToInternalDataFile( + RemoveFile removeFile, + Table table, + FileFormat fileFormat, + List<InternalPartitionField> partitionFields, + DeltaKernelPartitionExtractor partitionExtractor, + Map<String, String> partitionValues) { + scala.collection.mutable.Map<String, String> scalaMap = + JavaConverters.mapAsScalaMap(partitionValues); + + return InternalDataFile.builder() + .physicalPath(getFullPathToFile(removeFile.getPath(), table)) + .fileFormat(fileFormat) + .partitionValues(partitionExtractor.partitionValueExtraction(scalaMap, partitionFields)) + .build(); + } + + public FileFormat convertToFileFormat(String provider) { + if (provider.equals("parquet")) { + return FileFormat.APACHE_PARQUET; + } else if (provider.equals("orc")) { + return FileFormat.APACHE_ORC; + } + throw new NotSupportedException( + String.format("delta file format %s is not recognized", provider)); + } + + static String getFullPathToFile(String dataFilePath, Table table) { + Configuration hadoopConf = new Configuration(); + Engine myEngine = DefaultEngine.create(hadoopConf); + String tableBasePath = table.getPath(myEngine); + ; + // String tableBasePath = snapshot.dataPath().toUri().toString(); Review Comment: Can this be cleaned up? ########## xtable-core/src/main/java/org/apache/xtable/kernel/DeltaKernelDataFileExtractor.java: ########## @@ -0,0 +1,155 @@ +/* + * 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.xtable.kernel; + +// import scala.collection.Map; +import java.util.*; +import java.util.List; +import java.util.stream.Collectors; + +import lombok.Builder; + +import io.delta.kernel.Snapshot; +import io.delta.kernel.Table; +import io.delta.kernel.data.FilteredColumnarBatch; +import io.delta.kernel.data.Row; +import io.delta.kernel.engine.Engine; +import io.delta.kernel.internal.InternalScanFileUtils; +import io.delta.kernel.internal.ScanImpl; +import io.delta.kernel.internal.SnapshotImpl; +import io.delta.kernel.internal.actions.AddFile; +import io.delta.kernel.types.StructField; +import io.delta.kernel.types.StructType; +import io.delta.kernel.utils.CloseableIterator; + +import org.apache.xtable.model.schema.InternalField; +import org.apache.xtable.model.schema.InternalPartitionField; +import org.apache.xtable.model.schema.InternalSchema; +import org.apache.xtable.model.storage.FileFormat; +import org.apache.xtable.model.storage.InternalDataFile; +import org.apache.xtable.spi.extractor.DataFileIterator; + +/** DeltaDataFileExtractor lets the consumer iterate over partitions. */ +@Builder +public class DeltaKernelDataFileExtractor { + + @Builder.Default + private final DeltaKernelPartitionExtractor partitionExtractor = + DeltaKernelPartitionExtractor.getInstance(); + + @Builder.Default + private final DeltaKernelStatsExtractor fileStatsExtractor = + DeltaKernelStatsExtractor.getInstance(); + + @Builder.Default + private final DeltaKernelActionsConverter actionsConverter = + DeltaKernelActionsConverter.getInstance(); + + private final String basePath; + + /** + * Initializes an iterator for Delta Lake files. + * + * @return Delta table file iterator + */ + public DataFileIterator iterator( + Snapshot deltaSnapshot, Table table, Engine engine, InternalSchema schema) { + return new DeltaDataFileIterator(deltaSnapshot, table, engine, schema, true); + } + + public class DeltaDataFileIterator implements DataFileIterator { + private final FileFormat fileFormat; + private final List<InternalField> fields; + private final List<InternalPartitionField> partitionFields; + private Iterator<InternalDataFile> dataFilesIterator = Collections.emptyIterator(); + + private DeltaDataFileIterator( + Snapshot snapshot, + Table table, + Engine engine, + InternalSchema schema, + boolean includeColumnStats) { + String provider = ((SnapshotImpl) snapshot).getMetadata().getFormat().getProvider(); + this.fileFormat = actionsConverter.convertToFileFormat(provider); + + this.fields = schema.getFields(); + + StructType fullSchema = snapshot.getSchema(); // The full table schema + List<String> partitionColumns = snapshot.getPartitionColumnNames(); // List<String> Review Comment: Remove the comment `// List<String>`? ########## xtable-core/src/main/java/org/apache/xtable/delta/DeltaSchemaExtractor.java: ########## @@ -41,22 +37,10 @@ import org.apache.xtable.model.schema.InternalType; import org.apache.xtable.schema.SchemaUtils; -/** - * Converts between Delta and InternalTable schemas. Some items to be aware of: - * - * <ul> - * <li>Delta schemas are represented as Spark StructTypes which do not have enums so the enum Review Comment: @vaibhavk1992 let's remove the changes to this file. They don't seem necessary ########## xtable-core/src/main/java/org/apache/xtable/kernel/DeltaKernelConversionSource.java: ########## @@ -0,0 +1,237 @@ +/* + * 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.xtable.kernel; + +import java.io.IOException; +import java.sql.Timestamp; +import java.time.Instant; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; + +import lombok.Builder; + +import io.delta.kernel.Snapshot; +import io.delta.kernel.Table; +import io.delta.kernel.engine.Engine; +import io.delta.kernel.internal.SnapshotImpl; +import io.delta.kernel.internal.actions.AddFile; +import io.delta.kernel.internal.actions.RemoveFile; +import io.delta.kernel.internal.actions.RowBackedAction; +import io.delta.kernel.internal.util.VectorUtils; + +import org.apache.xtable.exception.ReadException; +import org.apache.xtable.model.CommitsBacklog; +import org.apache.xtable.model.InstantsForIncrementalSync; +import org.apache.xtable.model.InternalSnapshot; +import org.apache.xtable.model.InternalTable; +import org.apache.xtable.model.TableChange; +import org.apache.xtable.model.schema.InternalSchema; +import org.apache.xtable.model.storage.FileFormat; +import org.apache.xtable.model.storage.InternalDataFile; +import org.apache.xtable.model.storage.InternalFilesDiff; +import org.apache.xtable.model.storage.PartitionFileGroup; +import org.apache.xtable.spi.extractor.ConversionSource; +import org.apache.xtable.spi.extractor.DataFileIterator; + +@Builder +public class DeltaKernelConversionSource implements ConversionSource<Long> { + + @Builder.Default + private final DeltaKernelDataFileExtractor dataFileExtractor = + DeltaKernelDataFileExtractor.builder().build(); + + @Builder.Default + private final DeltaKernelActionsConverter actionsConverter = + DeltaKernelActionsConverter.getInstance(); + + private final String basePath; + private final String tableName; + private final Engine engine; + + @Builder.Default + private final DeltaKernelTableExtractor tableExtractor = + DeltaKernelTableExtractor.builder().build(); + + private Optional<DeltaKernelIncrementalChangesState> deltaKernelIncrementalChangesState = + Optional.empty(); + + @Override + public InternalTable getTable(Long version) { + try { + Table table = Table.forPath(engine, basePath); + Snapshot snapshot = table.getSnapshotAsOfVersion(engine, version); + return tableExtractor.table(table, snapshot, engine, tableName, basePath); + } catch (Exception e) { + throw new ReadException("Failed to get table at version " + version, e); + } + } + + @Override + public InternalTable getCurrentTable() { + Table table = Table.forPath(engine, basePath); + Snapshot snapshot = table.getLatestSnapshot(engine); + return getTable(snapshot.getVersion()); + } + + @Override + public InternalSnapshot getCurrentSnapshot() { + Table table_snapshot = Table.forPath(engine, basePath); + Snapshot snapshot = table_snapshot.getLatestSnapshot(engine); + InternalTable table = getTable(snapshot.getVersion()); + return InternalSnapshot.builder() + .table(table) + .partitionedDataFiles( + getInternalDataFiles(snapshot, table_snapshot, engine, table.getReadSchema())) + .sourceIdentifier(getCommitIdentifier(snapshot.getVersion())) + .build(); + } + + @Override + public TableChange getTableChangeForCommit(Long versionNumber) { + Table table = Table.forPath(engine, basePath); + Snapshot snapshot = table.getSnapshotAsOfVersion(engine, versionNumber); + InternalTable tableAtVersion = + tableExtractor.table(table, snapshot, engine, tableName, basePath); + Map<String, InternalDataFile> addedFiles = new HashMap<>(); + Map<String, InternalDataFile> removedFiles = new HashMap<>(); + String provider = ((SnapshotImpl) snapshot).getMetadata().getFormat().getProvider(); + FileFormat fileFormat = actionsConverter.convertToFileFormat(provider); + + List<RowBackedAction> actionsForVersion = getChangesState().getActionsForVersion(versionNumber); + + for (RowBackedAction action : actionsForVersion) { + if (action instanceof AddFile) { + AddFile addFile = (AddFile) action; + Map<String, String> partitionValues = VectorUtils.toJavaMap(addFile.getPartitionValues()); + InternalDataFile dataFile = + actionsConverter.convertAddActionToInternalDataFile( + addFile, + table, + fileFormat, + tableAtVersion.getPartitioningFields(), + tableAtVersion.getReadSchema().getFields(), + true, + DeltaKernelPartitionExtractor.getInstance(), + DeltaKernelStatsExtractor.getInstance(), + partitionValues); + addedFiles.put(dataFile.getPhysicalPath(), dataFile); + } else if (action instanceof RemoveFile) { + RemoveFile removeFile = (RemoveFile) action; + Map<String, String> partitionValues = + removeFile + .getPartitionValues() + .map(VectorUtils::<String, String>toJavaMap) + .orElse(Collections.emptyMap()); + InternalDataFile dataFile = + actionsConverter.convertRemoveActionToInternalDataFile( + removeFile, + table, + fileFormat, + tableAtVersion.getPartitioningFields(), + DeltaKernelPartitionExtractor.getInstance(), + partitionValues); + removedFiles.put(dataFile.getPhysicalPath(), dataFile); + } + } + + InternalFilesDiff internalFilesDiff = + InternalFilesDiff.builder() + .filesAdded(addedFiles.values()) + .filesRemoved(removedFiles.values()) + .build(); + return TableChange.builder() + .tableAsOfChange(tableAtVersion) + .filesDiff(internalFilesDiff) + .sourceIdentifier(getCommitIdentifier(versionNumber)) + .build(); + } + + @Override + public CommitsBacklog<Long> getCommitsBacklog( + InstantsForIncrementalSync instantsForIncrementalSync) { + Table table = Table.forPath(engine, basePath); + Snapshot snapshot = + table.getSnapshotAsOfTimestamp( + engine, Timestamp.from(instantsForIncrementalSync.getLastSyncInstant()).getTime()); + + long versionNumberAtLastSyncInstant = snapshot.getVersion(); + resetState(versionNumberAtLastSyncInstant + 1, engine, table); + return CommitsBacklog.<Long>builder() + .commitsToProcess(getChangesState().getVersionsInSortedOrder()) + .build(); + } + + @Override + public boolean isIncrementalSyncSafeFrom(Instant instant) { + try { + Table table = Table.forPath(engine, basePath); + Snapshot snapshot = table.getSnapshotAsOfTimestamp(engine, Timestamp.from(instant).getTime()); + + // There is a chance earliest commit of the table is returned if the instant is before the + // earliest commit of the table, hence the additional check. + Instant deltaCommitInstant = Instant.ofEpochMilli(snapshot.getTimestamp(engine)); + return deltaCommitInstant.equals(instant) || deltaCommitInstant.isBefore(instant); + } catch (Exception e) { + System.err.println( Review Comment: Use logging instead of print lines ########## xtable-core/src/main/java/org/apache/xtable/kernel/DeltaKernelDataFileExtractor.java: ########## @@ -0,0 +1,155 @@ +/* + * 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.xtable.kernel; + +// import scala.collection.Map; +import java.util.*; +import java.util.List; +import java.util.stream.Collectors; + +import lombok.Builder; + +import io.delta.kernel.Snapshot; +import io.delta.kernel.Table; +import io.delta.kernel.data.FilteredColumnarBatch; +import io.delta.kernel.data.Row; +import io.delta.kernel.engine.Engine; +import io.delta.kernel.internal.InternalScanFileUtils; +import io.delta.kernel.internal.ScanImpl; +import io.delta.kernel.internal.SnapshotImpl; +import io.delta.kernel.internal.actions.AddFile; +import io.delta.kernel.types.StructField; +import io.delta.kernel.types.StructType; +import io.delta.kernel.utils.CloseableIterator; + +import org.apache.xtable.model.schema.InternalField; +import org.apache.xtable.model.schema.InternalPartitionField; +import org.apache.xtable.model.schema.InternalSchema; +import org.apache.xtable.model.storage.FileFormat; +import org.apache.xtable.model.storage.InternalDataFile; +import org.apache.xtable.spi.extractor.DataFileIterator; + +/** DeltaDataFileExtractor lets the consumer iterate over partitions. */ +@Builder +public class DeltaKernelDataFileExtractor { + + @Builder.Default + private final DeltaKernelPartitionExtractor partitionExtractor = + DeltaKernelPartitionExtractor.getInstance(); + + @Builder.Default + private final DeltaKernelStatsExtractor fileStatsExtractor = + DeltaKernelStatsExtractor.getInstance(); + + @Builder.Default + private final DeltaKernelActionsConverter actionsConverter = + DeltaKernelActionsConverter.getInstance(); + + private final String basePath; + + /** + * Initializes an iterator for Delta Lake files. + * + * @return Delta table file iterator + */ + public DataFileIterator iterator( + Snapshot deltaSnapshot, Table table, Engine engine, InternalSchema schema) { + return new DeltaDataFileIterator(deltaSnapshot, table, engine, schema, true); + } + + public class DeltaDataFileIterator implements DataFileIterator { + private final FileFormat fileFormat; + private final List<InternalField> fields; + private final List<InternalPartitionField> partitionFields; + private Iterator<InternalDataFile> dataFilesIterator = Collections.emptyIterator(); + + private DeltaDataFileIterator( + Snapshot snapshot, + Table table, + Engine engine, + InternalSchema schema, + boolean includeColumnStats) { + String provider = ((SnapshotImpl) snapshot).getMetadata().getFormat().getProvider(); + this.fileFormat = actionsConverter.convertToFileFormat(provider); + + this.fields = schema.getFields(); + + StructType fullSchema = snapshot.getSchema(); // The full table schema + List<String> partitionColumns = snapshot.getPartitionColumnNames(); // List<String> + + List<StructField> partitionFields_strfld = Review Comment: Nitpick: Use camelCase for variable names ########## xtable-core/src/main/java/org/apache/xtable/kernel/DeltaKernelDataFileExtractor.java: ########## @@ -0,0 +1,155 @@ +/* + * 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.xtable.kernel; + +// import scala.collection.Map; +import java.util.*; +import java.util.List; +import java.util.stream.Collectors; + +import lombok.Builder; + +import io.delta.kernel.Snapshot; +import io.delta.kernel.Table; +import io.delta.kernel.data.FilteredColumnarBatch; +import io.delta.kernel.data.Row; +import io.delta.kernel.engine.Engine; +import io.delta.kernel.internal.InternalScanFileUtils; +import io.delta.kernel.internal.ScanImpl; +import io.delta.kernel.internal.SnapshotImpl; +import io.delta.kernel.internal.actions.AddFile; +import io.delta.kernel.types.StructField; +import io.delta.kernel.types.StructType; +import io.delta.kernel.utils.CloseableIterator; + +import org.apache.xtable.model.schema.InternalField; +import org.apache.xtable.model.schema.InternalPartitionField; +import org.apache.xtable.model.schema.InternalSchema; +import org.apache.xtable.model.storage.FileFormat; +import org.apache.xtable.model.storage.InternalDataFile; +import org.apache.xtable.spi.extractor.DataFileIterator; + +/** DeltaDataFileExtractor lets the consumer iterate over partitions. */ +@Builder +public class DeltaKernelDataFileExtractor { + + @Builder.Default + private final DeltaKernelPartitionExtractor partitionExtractor = + DeltaKernelPartitionExtractor.getInstance(); + + @Builder.Default + private final DeltaKernelStatsExtractor fileStatsExtractor = + DeltaKernelStatsExtractor.getInstance(); + + @Builder.Default + private final DeltaKernelActionsConverter actionsConverter = + DeltaKernelActionsConverter.getInstance(); + + private final String basePath; + + /** + * Initializes an iterator for Delta Lake files. + * + * @return Delta table file iterator + */ + public DataFileIterator iterator( + Snapshot deltaSnapshot, Table table, Engine engine, InternalSchema schema) { + return new DeltaDataFileIterator(deltaSnapshot, table, engine, schema, true); + } + + public class DeltaDataFileIterator implements DataFileIterator { + private final FileFormat fileFormat; + private final List<InternalField> fields; + private final List<InternalPartitionField> partitionFields; + private Iterator<InternalDataFile> dataFilesIterator = Collections.emptyIterator(); + + private DeltaDataFileIterator( + Snapshot snapshot, + Table table, + Engine engine, + InternalSchema schema, + boolean includeColumnStats) { + String provider = ((SnapshotImpl) snapshot).getMetadata().getFormat().getProvider(); + this.fileFormat = actionsConverter.convertToFileFormat(provider); + + this.fields = schema.getFields(); + + StructType fullSchema = snapshot.getSchema(); // The full table schema + List<String> partitionColumns = snapshot.getPartitionColumnNames(); // List<String> + + List<StructField> partitionFields_strfld = + fullSchema.fields().stream() + .filter(field -> partitionColumns.contains(field.getName())) + .collect(Collectors.toList()); + + StructType partitionSchema = new StructType(partitionFields_strfld); + + this.partitionFields = + partitionExtractor.convertFromDeltaPartitionFormat(schema, partitionSchema); + + ScanImpl myScan = (ScanImpl) snapshot.getScanBuilder().build(); + CloseableIterator<FilteredColumnarBatch> scanFiles = + myScan.getScanFiles(engine, includeColumnStats); + + List<InternalDataFile> dataFiles = new ArrayList<>(); + this.dataFilesIterator = + Collections + .emptyIterator(); // Initialize the dataFilesIterator by iterating over the scan files Review Comment: This assignment does not seem necessary since we assign at line 139 -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected]
