Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions crates/iceberg/public-api.txt
Original file line number Diff line number Diff line change
Expand Up @@ -2655,6 +2655,7 @@ pub fn iceberg::spec::PartitionSpec::is_compatible_with(&self, other: &iceberg::
pub fn iceberg::spec::PartitionSpec::is_unpartitioned(&self) -> bool
pub fn iceberg::spec::PartitionSpec::partition_to_path(&self, data: &iceberg::spec::Struct, schema: iceberg::spec::SchemaRef) -> alloc::string::String
pub fn iceberg::spec::PartitionSpec::partition_type(&self, schema: &iceberg::spec::Schema) -> iceberg::Result<iceberg::spec::StructType>
pub fn iceberg::spec::PartitionSpec::resolve(&self, schema: &iceberg::spec::Schema, partition: iceberg::spec::Struct) -> iceberg::Result<iceberg::spec::Struct>
pub fn iceberg::spec::PartitionSpec::spec_id(&self) -> i32
pub fn iceberg::spec::PartitionSpec::unpartition_spec() -> Self
pub fn iceberg::spec::PartitionSpec::with_spec_id(self, spec_id: i32) -> Self
Expand Down
6 changes: 5 additions & 1 deletion crates/iceberg/src/io/object_cache.rs
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,10 @@ pub(crate) enum CachedObjectKey {
Manifest(ManifestKey),
}

/// Identifies a parsed manifest: its path plus every manifest-list value the
/// reader inherits onto its entries. Two references to one physical manifest
/// with different inherited values parse to different entries, so anything
/// derived from parsed entries must be keyed by this, not by path alone.
#[derive(Clone, Debug, Hash, Eq, PartialEq)]
pub(crate) struct ManifestKey {
path: String,
Expand All @@ -62,7 +66,7 @@ pub(crate) struct ManifestKey {
}

impl ManifestKey {
fn new(manifest_file: &ManifestFile) -> Self {
pub(crate) fn new(manifest_file: &ManifestFile) -> Self {
Self {
path: manifest_file.manifest_path.clone(),
added_snapshot_id: manifest_file.added_snapshot_id,
Expand Down
8 changes: 0 additions & 8 deletions crates/iceberg/src/spec/manifest/writer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -316,10 +316,6 @@ impl ManifestWriter {
/// Add a delete manifest entry. This method will update following status of the entry:
/// - Update the entry status to `Deleted`
/// - Set the snapshot id to the current snapshot id
///
/// # TODO
/// Remove this allow later
#[allow(dead_code)]
pub(crate) fn add_delete_entry(&mut self, mut entry: ManifestEntry) -> Result<()> {
self.check_data_file(&entry.data_file)?;
entry.status = ManifestStatus::Deleted;
Expand Down Expand Up @@ -351,10 +347,6 @@ impl ManifestWriter {

/// Add an existing manifest entry. This method will update following status of the entry:
/// - Update the entry status to `Existing`
///
/// # TODO
/// Remove this allow later
#[allow(dead_code)]
pub(crate) fn add_existing_entry(&mut self, mut entry: ManifestEntry) -> Result<()> {
self.check_data_file(&entry.data_file)?;
entry.status = ManifestStatus::Existing;
Expand Down
106 changes: 105 additions & 1 deletion crates/iceberg/src/spec/partition.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ use super::transform::Transform;
use super::{NestedField, PrimitiveType, Schema, SchemaRef, StructType};
use crate::Result;
use crate::error::invalid_data;
use crate::spec::Struct;
use crate::spec::{Literal, Struct};

pub(crate) const UNPARTITIONED_LAST_ASSIGNED_ID: i32 = 999;
pub(crate) const DEFAULT_PARTITION_SPEC_ID: i32 = 0;
Expand Down Expand Up @@ -180,6 +180,30 @@ impl PartitionSpec {
true
}

/// Resolves `partition` against the partition type this spec has under
/// `schema`, widening a value whose source column was promoted since it was
/// written (`int` to `long`, `float` to `double`).
///
/// A partition value read from a manifest keeps the literal type it was
/// written with. Java reads manifests against the current partition type
/// and so never sees the difference; a caller that renders or compares a
/// stored value under the current schema resolves it first.
pub fn resolve(&self, schema: &Schema, partition: Struct) -> Result<Struct> {
let partition_type = self.partition_type(schema)?;
Ok(partition
.iter()
.zip(partition_type.fields())
.map(|(value, field)| {
value
.and_then(Literal::as_primitive_literal)
.zip(field.field_type.as_primitive_type())
.and_then(|(literal, target)| literal.promote_to(target))
.map(Literal::Primitive)
.or_else(|| value.cloned())
})
.collect())
}

/// Returns partition path string containing partition type and partition
/// value as key-value pairs.
pub fn partition_to_path(&self, data: &Struct, schema: SchemaRef) -> String {
Expand Down Expand Up @@ -2169,6 +2193,86 @@ mod tests {
);
}

#[test]
fn test_resolve_widens_only_promoted_values() {
let field = |id, name, ty| NestedField::required(id, name, Type::Primitive(ty)).into();
let written = Schema::builder()
.with_fields(vec![
field(1, "i", PrimitiveType::Int),
field(2, "f", PrimitiveType::Float),
field(3, "s", PrimitiveType::String),
])
.build()
.unwrap();
let spec = PartitionSpec::builder(written)
.add_partition_field("i", "i", Transform::Identity)
.unwrap()
.add_partition_field("f", "f", Transform::Identity)
.unwrap()
.add_partition_field("s", "s", Transform::Identity)
.unwrap()
.build()
.unwrap();
let promoted = Schema::builder()
.with_fields(vec![
field(1, "i", PrimitiveType::Long),
field(2, "f", PrimitiveType::Double),
field(3, "s", PrimitiveType::String),
])
.build()
.unwrap();

let stale = Struct::from_iter([Some(Literal::int(7)), Some(Literal::float(0.1_f32)), None]);
assert_eq!(
spec.resolve(&promoted, stale).unwrap(),
Struct::from_iter([
Some(Literal::long(7)),
Some(Literal::double(f64::from(0.1_f32))),
None,
])
);

let current = Struct::from_iter([
Some(Literal::long(7)),
Some(Literal::double(0.1)),
Some(Literal::string("s")),
]);
assert_eq!(spec.resolve(&promoted, current.clone()).unwrap(), current);
}

/// A value written before its source column was promoted renders under
/// the promoted type once resolved: a `float` widened to `double` prints
/// as Java does.
#[test]
fn test_resolve_then_partition_to_path_matches_java() {
let written = Schema::builder()
.with_fields(vec![
NestedField::required(1, "f", Type::Primitive(PrimitiveType::Float)).into(),
])
.build()
.unwrap();
let spec = PartitionSpec::builder(written)
.add_partition_field("f", "f", Transform::Identity)
.unwrap()
.build()
.unwrap();
let promoted: SchemaRef = Schema::builder()
.with_fields(vec![
NestedField::required(1, "f", Type::Primitive(PrimitiveType::Double)).into(),
])
.build()
.unwrap()
.into();

let stale = Struct::from_iter([Some(Literal::float(0.1_f32))]);
let resolved = spec.resolve(&promoted, stale).unwrap();
// Not exact in f32: the widened double is rendered.
assert_eq!(
spec.partition_to_path(&resolved, promoted),
"f=0.10000000149011612"
);
}

#[test]
fn test_partition_to_path_float_matches_java() {
let schema = Schema::builder()
Expand Down
2 changes: 1 addition & 1 deletion crates/iceberg/src/test_utils/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,4 +32,4 @@ pub(crate) use delete_vector::encode_dv_blob;
pub(crate) use encryption::{make_encrypted_table, make_encryption_manager};
pub(crate) use record_batch::check_record_batches;
pub(crate) use runtime::test_runtime;
pub(crate) use transaction::commit_with_fresh_state;
pub(crate) use transaction::{append_to, commit_with_fresh_state, data_file, with_snapshot};
58 changes: 57 additions & 1 deletion crates/iceberg/src/test_utils/transaction.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,17 @@
// specific language governing permissions and limitations
// under the License.

use std::collections::HashMap;
use std::sync::Arc;

use crate::error::Result;
use crate::spec::{
DataContentType, DataFile, DataFileBuilder, DataFileFormat, Literal, MAIN_BRANCH, SnapshotRef,
SnapshotReference, SnapshotRetention, Struct,
};
use crate::table::Table;
use crate::transaction::{ActionCommit, TransactionAction};
use crate::transaction::snapshot::simple::{AppendIntent, SimpleSnapshotProducer};
use crate::transaction::{ActionCommit, Transaction, TransactionAction};

/// Runs a single commit attempt of an action with fresh state.
pub(crate) async fn commit_with_fresh_state<A: TransactionAction>(
Expand All @@ -27,3 +35,51 @@ pub(crate) async fn commit_with_fresh_state<A: TransactionAction>(
let mut state = action.new_state();
action.commit(&mut state, table).await
}

pub(crate) fn data_file(table: &Table, path: &str, record_count: u64) -> DataFile {
DataFileBuilder::default()
.content(DataContentType::Data)
.file_path(path.to_string())
.file_format(DataFileFormat::Parquet)
.file_size_in_bytes(100)
.record_count(record_count)
.partition_spec_id(table.metadata().default_partition_spec_id())
.partition(Struct::from_iter([Some(Literal::long(300))]))
.build()
.unwrap()
}

/// Commits `data_files` to `table` through a fresh producer, returning the
/// table with every update applied, as `TableCommit::apply` would.
pub(crate) async fn append_to(table: &Table, data_files: Vec<DataFile>) -> Table {
let mut producer = SimpleSnapshotProducer::new(AppendIntent {
commit_uuid: None,
snapshot_properties: HashMap::new(),
data_files,
});
let updates = producer.apply(table).await.unwrap().take_updates();
Transaction::update_table_metadata(table.clone(), &updates).unwrap()
}

/// Returns `table` with `snapshot` added and set as current, as a local
/// `TableCommit::apply` would.
pub(crate) fn with_snapshot(table: &Table, snapshot: SnapshotRef) -> Table {
let metadata = table
.metadata()
.clone()
.into_builder(None)
.add_snapshot(snapshot.as_ref().clone())
.unwrap()
.set_ref(
MAIN_BRANCH,
SnapshotReference::new(
snapshot.snapshot_id(),
SnapshotRetention::branch(None, None, None),
),
)
.unwrap()
.build()
.unwrap()
.metadata;
table.clone().with_metadata(Arc::new(metadata))
}
4 changes: 2 additions & 2 deletions crates/iceberg/src/transaction/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ mod action;
pub use action::*;
mod append;
mod expire_snapshots;
mod snapshot;
pub(crate) mod snapshot;
mod sort_order;
mod update_location;
mod update_properties;
Expand Down Expand Up @@ -98,7 +98,7 @@ impl Transaction {
}
}

fn update_table_metadata(table: Table, updates: &[TableUpdate]) -> Result<Table> {
pub(crate) fn update_table_metadata(table: Table, updates: &[TableUpdate]) -> Result<Table> {
let mut metadata_builder = table.metadata().clone().into_builder(None);
for update in updates {
metadata_builder = update.clone().apply(metadata_builder)?;
Expand Down
Loading
Loading