rshkv commented on code in PR #841:
URL: https://github.com/apache/iceberg-rust/pull/841#discussion_r1896841369


##########
crates/iceberg/src/metadata_scan.rs:
##########
@@ -0,0 +1,395 @@
+// 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.
+
+//! Metadata table api.
+
+use std::collections::HashSet;
+use std::sync::Arc;
+
+use arrow_array::builder::{BooleanBuilder, MapBuilder, PrimitiveBuilder, 
StringBuilder};
+use arrow_array::types::{Int64Type, TimestampMillisecondType};
+use arrow_array::RecordBatch;
+use arrow_schema::{DataType, Field, Schema, TimeUnit};
+
+use crate::spec::{SnapshotRef, TableMetadataRef};
+use crate::table::Table;
+use crate::Result;
+
+/// Table metadata scan.
+///
+/// Used to inspect a table's history, snapshots, and other metadata as a 
table.
+///
+/// See also 
<https://iceberg.apache.org/docs/latest/spark-queries/#inspecting-tables>.
+#[derive(Debug)]
+pub struct MetadataScan {
+    metadata_ref: TableMetadataRef,
+}
+
+impl MetadataScan {
+    /// Creates a new metadata scan.
+    pub fn new(table: &Table) -> Self {
+        Self {
+            metadata_ref: table.metadata_ref(),
+        }
+    }
+
+    /// Returns the snapshots of the table.
+    pub fn snapshots(&self) -> Result<RecordBatch> {
+        SnapshotsTable::scan(self)
+    }
+
+    /// Return the history of the table.
+    pub fn history(&self) -> Result<RecordBatch> {
+        HistoryTable::scan(self)
+    }
+}
+
+/// Table metadata scan.
+///
+/// Use to inspect a table's history, snapshots, and other metadata as a table.
+///
+/// References:
+/// - 
<https://github.com/apache/iceberg/blob/ac865e334e143dfd9e33011d8cf710b46d91f1e5/core/src/main/java/org/apache/iceberg/MetadataTableType.java#L23-L39>
+/// - <https://iceberg.apache.org/docs/latest/spark-queries/#querying-with-sql>
+/// - <https://py.iceberg.apache.org/api/#inspecting-tables>
+pub trait MetadataTable {
+    /// Returns the schema of the metadata table.
+    fn schema() -> Schema;
+
+    /// Scans the metadata table.
+    fn scan(scan: &MetadataScan) -> Result<RecordBatch>;
+}
+
+/// Snapshots table.
+pub struct SnapshotsTable;
+
+impl MetadataTable for SnapshotsTable {
+    fn schema() -> Schema {
+        Schema::new(vec![
+            Field::new(
+                "committed_at",
+                DataType::Timestamp(TimeUnit::Millisecond, 
Some("+00:00".into())),
+                false,
+            ),
+            Field::new("snapshot_id", DataType::Int64, false),
+            Field::new("parent_id", DataType::Int64, true),
+            Field::new("operation", DataType::Utf8, false),
+            Field::new("manifest_list", DataType::Utf8, false),
+            Field::new(
+                "summary",
+                DataType::Map(
+                    Arc::new(Field::new(
+                        "entries",
+                        DataType::Struct(
+                            vec![
+                                Field::new("keys", DataType::Utf8, false),
+                                Field::new("values", DataType::Utf8, true),
+                            ]
+                            .into(),
+                        ),
+                        false,
+                    )),
+                    false,
+                ),
+                false,
+            ),
+        ])
+    }
+
+    fn scan(scan: &MetadataScan) -> Result<RecordBatch> {
+        let mut committed_at =
+            
PrimitiveBuilder::<TimestampMillisecondType>::new().with_timezone("+00:00");
+        let mut snapshot_id = PrimitiveBuilder::<Int64Type>::new();
+        let mut parent_id = PrimitiveBuilder::<Int64Type>::new();
+        let mut operation = StringBuilder::new();
+        let mut manifest_list = StringBuilder::new();
+        let mut summary = MapBuilder::new(None, StringBuilder::new(), 
StringBuilder::new());
+
+        for snapshot in scan.metadata_ref.snapshots() {
+            committed_at.append_value(snapshot.timestamp_ms());
+            snapshot_id.append_value(snapshot.snapshot_id());
+            parent_id.append_option(snapshot.parent_snapshot_id());
+            manifest_list.append_value(snapshot.manifest_list());
+            operation.append_value(snapshot.summary().operation.as_str());
+            for (key, value) in &snapshot.summary().additional_properties {
+                summary.keys().append_value(key);
+                summary.values().append_value(value);
+            }
+            summary.append(true)?;
+        }
+
+        Ok(RecordBatch::try_new(Arc::new(Self::schema()), vec![
+            Arc::new(committed_at.finish()),
+            Arc::new(snapshot_id.finish()),
+            Arc::new(parent_id.finish()),
+            Arc::new(operation.finish()),
+            Arc::new(manifest_list.finish()),
+            Arc::new(summary.finish()),
+        ])?)
+    }
+}
+
+/// History table.
+///
+/// Shows how the table's current snapshot has changed over time and when each
+/// snapshot became the current snapshot.
+///
+/// Unlike the [Snapshots][SnapshotsTable], this metadata table has less detail
+/// per snapshot but includes ancestry information of the current snapshot.
+///
+/// `is_current_ancestor` indicates whether the snapshot is an ancestor of the
+/// current snapshot. If `false`, then the snapshot was rolled back.
+pub struct HistoryTable;
+
+impl MetadataTable for HistoryTable {
+    fn schema() -> Schema {
+        Schema::new(vec![
+            Field::new(
+                "made_current_at",
+                DataType::Timestamp(TimeUnit::Millisecond, 
Some("+00:00".into())),
+                false,
+            ),
+            Field::new("snapshot_id", DataType::Int64, false),
+            Field::new("parent_id", DataType::Int64, true),
+            Field::new("is_current_ancestor", DataType::Boolean, false),
+        ])
+    }
+
+    fn scan(scan: &MetadataScan) -> Result<RecordBatch> {
+        let mut made_current_at =
+            
PrimitiveBuilder::<TimestampMillisecondType>::new().with_timezone("+00:00");
+        let mut snapshot_id = PrimitiveBuilder::<Int64Type>::new();
+        let mut parent_id = PrimitiveBuilder::<Int64Type>::new();
+        let mut is_current_ancestor = BooleanBuilder::new();
+
+        let ancestors: HashSet<i64> =
+            Ancestors::new(scan.metadata_ref.current_snapshot(), 
&scan.metadata_ref)
+                .map(|snapshot| snapshot.snapshot_id())
+                .collect();
+
+        for snapshot in scan.metadata_ref.snapshots() {
+            made_current_at.append_value(snapshot.timestamp_ms());
+            snapshot_id.append_value(snapshot.snapshot_id());
+            parent_id.append_option(snapshot.parent_snapshot_id());
+            
is_current_ancestor.append_value(ancestors.contains(&snapshot.snapshot_id()));
+        }
+
+        Ok(RecordBatch::try_new(Arc::new(Self::schema()), vec![
+            Arc::new(made_current_at.finish()),
+            Arc::new(snapshot_id.finish()),
+            Arc::new(parent_id.finish()),
+            Arc::new(is_current_ancestor.finish()),
+        ])?)
+    }
+}
+
+struct Ancestors<'a> {
+    current_snapshot: Option<&'a SnapshotRef>,
+    table_metadata: &'a TableMetadataRef,
+}
+
+impl<'a> Ancestors<'a> {
+    fn new(
+        current_snapshot: Option<&'a SnapshotRef>,
+        table_metadata: &'a TableMetadataRef,
+    ) -> Self {
+        Ancestors {
+            current_snapshot,
+            table_metadata,
+        }
+    }
+}
+
+impl<'a> Iterator for Ancestors<'a> {
+    type Item = &'a SnapshotRef;
+
+    fn next(&mut self) -> Option<Self::Item> {
+        if let Some(snapshot) = self.current_snapshot {
+            self.current_snapshot = match snapshot.parent_snapshot_id() {
+                Some(parent_snapshot_id) => 
self.table_metadata.snapshot_by_id(parent_snapshot_id),
+                None => None,
+            };
+            Some(snapshot)
+        } else {
+            None
+        }
+    }
+}

Review Comment:
   PyIceberg's `ancestors_of` is 
[here](https://github.com/apache/iceberg-python/blob/0e5086ceb77351bc0b6ec3a592f5eda70a0afe46/pyiceberg/table/snapshots.py#L424-L431)



-- 
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]


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to