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


##########
crates/iceberg/src/metadata_scan.rs:
##########
@@ -0,0 +1,407 @@
+// 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::sync::Arc;
+
+use arrow_array::builder::{MapBuilder, PrimitiveBuilder, StringBuilder};
+use arrow_array::types::{Int32Type, 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,
+    metadata_location: Option<String>,
+}
+
+impl MetadataScan {
+    /// Creates a new metadata scan.
+    pub fn new(table: &Table) -> Self {
+        Self {
+            metadata_ref: table.metadata_ref(),
+            metadata_location: table.metadata_location().map(String::from),
+        }
+    }
+
+    /// Returns the snapshots of the table.
+    pub fn snapshots(&self) -> Result<RecordBatch> {
+        SnapshotsTable::scan(self)
+    }
+
+    /// Return the metadata log entries of the table.
+    pub fn metadata_log_entries(&self) -> Result<RecordBatch> {
+        MetadataLogEntriesTable::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()),
+        ])?)
+    }
+}
+
+/// Metadata log entries table.
+///
+/// Use to inspect the current and historical metadata files in the table.
+/// Contains every metadata file and the time it was added. For each metadata
+/// file, the table contains information about the latest snapshot at the time.
+pub struct MetadataLogEntriesTable;
+
+impl MetadataLogEntriesTable {
+    fn snapshot_id_as_of_time(
+        table_metadata: &TableMetadataRef,
+        timestamp_ms_inclusive: i64,
+    ) -> Option<&SnapshotRef> {
+        let mut snapshot_id = None;
+        // The table metadata snapshot log is chronological
+        for log_entry in table_metadata.history() {
+            if log_entry.timestamp_ms <= timestamp_ms_inclusive {
+                snapshot_id = Some(log_entry.snapshot_id);
+            }
+        }
+        snapshot_id.and_then(|id| table_metadata.snapshot_by_id(id))
+    }
+}
+
+impl MetadataTable for MetadataLogEntriesTable {
+    fn schema() -> Schema {
+        Schema::new(vec![
+            Field::new(
+                "timestamp",
+                DataType::Timestamp(TimeUnit::Millisecond, 
Some("+00:00".into())),
+                false,
+            ),
+            Field::new("file", DataType::Utf8, false),
+            Field::new("latest_snapshot_id", DataType::Int64, true),
+            Field::new("latest_schema_id", DataType::Int32, true),
+            Field::new("latest_sequence_number", DataType::Int64, true),
+        ])
+    }
+
+    fn scan(scan: &MetadataScan) -> Result<RecordBatch> {
+        let mut timestamp =
+            
PrimitiveBuilder::<TimestampMillisecondType>::new().with_timezone("+00:00");
+        let mut file = StringBuilder::new();
+        let mut latest_snapshot_id = PrimitiveBuilder::<Int64Type>::new();
+        let mut latest_schema_id = PrimitiveBuilder::<Int32Type>::new();
+        let mut latest_sequence_number = PrimitiveBuilder::<Int64Type>::new();
+
+        let mut append_metadata_log_entry = |timestamp_ms: i64, metadata_file: 
&str| {
+            timestamp.append_value(timestamp_ms);
+            file.append_value(metadata_file);
+
+            let snapshot =
+                
MetadataLogEntriesTable::snapshot_id_as_of_time(&scan.metadata_ref, 
timestamp_ms);
+            latest_snapshot_id.append_option(snapshot.map(|s| 
s.snapshot_id()));
+            latest_schema_id.append_option(snapshot.and_then(|s| 
s.schema_id()));
+            latest_sequence_number.append_option(snapshot.map(|s| 
s.sequence_number()));
+        };
+
+        for metadata_log_entry in scan.metadata_ref.metadata_log() {
+            append_metadata_log_entry(
+                metadata_log_entry.timestamp_ms,
+                &metadata_log_entry.metadata_file,
+            );
+        }
+
+        // Include the current metadata locaction and modification time in the 
table. This matches
+        // the Java implementation. Unlike the Java implementation, a current 
metadata location is
+        // optional here. In that case, we omit current metadata from the 
metadata log table.
+        if let Some(current_metadata_location) = &scan.metadata_location {
+            append_metadata_log_entry(
+                scan.metadata_ref.last_updated_ms(),
+                current_metadata_location,
+            );
+        }

Review Comment:
   Linking [Java] and [Python] implementations. As commented, the difference is 
that the metadata location is optional in `Table`.
   
   Alternatively, we could `expect` here.
   
   [Java]: 
https://github.com/apache/iceberg/blob/8a70fe0ff5f241aec8856f8091c77fdce35ad256/core/src/main/java/org/apache/iceberg/MetadataLogEntriesTable.java#L62-L66
   [Python]: 
https://github.com/apache/iceberg-python/blob/0e5086ceb77351bc0b6ec3a592f5eda70a0afe46/pyiceberg/table/inspect.py#L438-L442



-- 
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: issues-unsubscr...@iceberg.apache.org

For queries about this service, please contact Infrastructure at:
us...@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscr...@iceberg.apache.org
For additional commands, e-mail: issues-h...@iceberg.apache.org

Reply via email to