liurenjie1024 commented on code in PR #704: URL: https://github.com/apache/iceberg-rust/pull/704#discussion_r1860049342
########## crates/iceberg/src/writer/base_writer/position_delete_file_writer.rs: ########## @@ -0,0 +1,320 @@ +// 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. + +//! Position delete file writer. +use std::collections::BTreeMap; +use std::sync::Arc; + +use arrow_array::{ArrayRef, Int64Array, RecordBatch, StringArray}; +use arrow_schema::{Schema, SchemaRef}; +use once_cell::sync::Lazy; + +use crate::arrow::field_to_arrow_field; +use crate::spec::{DataFile, NestedField, PrimitiveType, Struct, Type}; +use crate::writer::file_writer::{FileWriter, FileWriterBuilder}; +use crate::writer::{IcebergWriter, IcebergWriterBuilder}; +use crate::Result; + +/// Builder for `MemoryPositionDeleteWriter`. +#[derive(Clone)] +pub struct MemoryPositionDeleteWriterBuilder<B: FileWriterBuilder> { + inner: B, +} + +impl<B: FileWriterBuilder> MemoryPositionDeleteWriterBuilder<B> { + /// Create a new `MemoryPositionDeleteWriterBuilder` using a `FileWriterBuilder`. + pub fn new(inner: B) -> Self { + Self { inner } + } +} + +/// The config for `MemoryPositionDeleteWriter`. +pub struct MemoryPositionDeleteWriterConfig { + /// The number of max rows to cache in memory. + pub cache_num: usize, + /// The partition value of the position delete file. + pub partition_value: Struct, +} + +impl MemoryPositionDeleteWriterConfig { + /// Create a new `MemoryPositionDeleteWriterConfig`. + pub fn new(cache_num: usize, partition_value: Option<Struct>) -> Self { + Self { + cache_num, + partition_value: partition_value.unwrap_or(Struct::empty()), + } + } +} + +static POSITION_DELETE_SCHEMA: Lazy<SchemaRef> = Lazy::new(|| { + Schema::new(vec![ + field_to_arrow_field(&Arc::new(NestedField::required( + 2147483546, + "file_path", + Type::Primitive(PrimitiveType::String), + ))) + .unwrap(), + field_to_arrow_field(&Arc::new(NestedField::required( + 2147483545, + "pos", + Type::Primitive(PrimitiveType::Long), + ))) + .unwrap(), + ]) + .into() +}); + +#[async_trait::async_trait] +impl<'a, B: FileWriterBuilder> IcebergWriterBuilder<PositionDeleteInput<'a>, Vec<DataFile>> + for MemoryPositionDeleteWriterBuilder<B> +{ + type R = MemoryPositionDeleteWriter<B>; + type C = MemoryPositionDeleteWriterConfig; + + async fn build(self, config: Self::C) -> Result<Self::R> { + Ok(MemoryPositionDeleteWriter { + inner_writer_builder: self.inner.clone(), + cache_num: config.cache_num, + cache: BTreeMap::new(), + data_files: Vec::new(), + partition_value: config.partition_value, + }) + } +} + +/// Position delete input. +#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Debug)] +pub struct PositionDeleteInput<'a> { + /// The path of the file. + pub path: &'a str, + /// The offset of the position delete. + pub offset: i64, +} + +/// The memory position delete writer. +pub struct MemoryPositionDeleteWriter<B: FileWriterBuilder> { Review Comment: ```suggestion pub struct PositionDeleteWriter<B: FileWriterBuilder> { ``` I don't think we should add a `Memory` prefix here since it make people feel that we are storing everything in memory, and it applies to all structs. ########## crates/iceberg/src/writer/base_writer/position_delete_file_writer.rs: ########## @@ -0,0 +1,320 @@ +// 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. + +//! Position delete file writer. +use std::collections::BTreeMap; +use std::sync::Arc; + +use arrow_array::{ArrayRef, Int64Array, RecordBatch, StringArray}; +use arrow_schema::{Schema, SchemaRef}; +use once_cell::sync::Lazy; + +use crate::arrow::field_to_arrow_field; +use crate::spec::{DataFile, NestedField, PrimitiveType, Struct, Type}; +use crate::writer::file_writer::{FileWriter, FileWriterBuilder}; +use crate::writer::{IcebergWriter, IcebergWriterBuilder}; +use crate::Result; + +/// Builder for `MemoryPositionDeleteWriter`. +#[derive(Clone)] +pub struct MemoryPositionDeleteWriterBuilder<B: FileWriterBuilder> { + inner: B, +} + +impl<B: FileWriterBuilder> MemoryPositionDeleteWriterBuilder<B> { + /// Create a new `MemoryPositionDeleteWriterBuilder` using a `FileWriterBuilder`. + pub fn new(inner: B) -> Self { + Self { inner } + } +} + +/// The config for `MemoryPositionDeleteWriter`. +pub struct MemoryPositionDeleteWriterConfig { + /// The number of max rows to cache in memory. + pub cache_num: usize, + /// The partition value of the position delete file. + pub partition_value: Struct, +} + +impl MemoryPositionDeleteWriterConfig { + /// Create a new `MemoryPositionDeleteWriterConfig`. + pub fn new(cache_num: usize, partition_value: Option<Struct>) -> Self { + Self { + cache_num, + partition_value: partition_value.unwrap_or(Struct::empty()), + } + } +} + +static POSITION_DELETE_SCHEMA: Lazy<SchemaRef> = Lazy::new(|| { + Schema::new(vec![ + field_to_arrow_field(&Arc::new(NestedField::required( + 2147483546, + "file_path", + Type::Primitive(PrimitiveType::String), + ))) + .unwrap(), + field_to_arrow_field(&Arc::new(NestedField::required( + 2147483545, + "pos", + Type::Primitive(PrimitiveType::Long), + ))) + .unwrap(), + ]) + .into() +}); + +#[async_trait::async_trait] +impl<'a, B: FileWriterBuilder> IcebergWriterBuilder<PositionDeleteInput<'a>, Vec<DataFile>> + for MemoryPositionDeleteWriterBuilder<B> +{ + type R = MemoryPositionDeleteWriter<B>; + type C = MemoryPositionDeleteWriterConfig; + + async fn build(self, config: Self::C) -> Result<Self::R> { + Ok(MemoryPositionDeleteWriter { + inner_writer_builder: self.inner.clone(), + cache_num: config.cache_num, + cache: BTreeMap::new(), + data_files: Vec::new(), + partition_value: config.partition_value, + }) + } +} + +/// Position delete input. +#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Debug)] +pub struct PositionDeleteInput<'a> { + /// The path of the file. + pub path: &'a str, + /// The offset of the position delete. + pub offset: i64, +} + +/// The memory position delete writer. +pub struct MemoryPositionDeleteWriter<B: FileWriterBuilder> { + inner_writer_builder: B, + cache_num: usize, + cache: BTreeMap<String, Vec<i64>>, + data_files: Vec<DataFile>, + partition_value: Struct, +} + +impl<'a, B: FileWriterBuilder> MemoryPositionDeleteWriter<B> { + async fn write_cache_out(&mut self) -> Result<()> { + let mut keys = Vec::new(); + let mut values = Vec::new(); + let mut cache = std::mem::take(&mut self.cache); + for (key, offsets) in cache.iter_mut() { + offsets.sort(); + let key_ref = key.as_str(); + for offset in offsets { + keys.push(key_ref); + values.push(*offset); + } + } + let key_array = Arc::new(StringArray::from(keys)) as ArrayRef; + let value_array = Arc::new(Int64Array::from(values)) as ArrayRef; + let record_batch = + RecordBatch::try_new(POSITION_DELETE_SCHEMA.clone(), vec![key_array, value_array])?; + let mut writer = self.inner_writer_builder.clone().build().await?; + writer.write(&record_batch).await?; + self.data_files + .extend(writer.close().await?.into_iter().map(|mut res| { + res.content(crate::spec::DataContentType::PositionDeletes); + res.partition(self.partition_value.clone()); + res.build().expect("Guaranteed to be valid") + })); + Ok(()) + } +} + +/// Implement `IcebergWriter` for `PositionDeleteWriter`. +impl<'a, B: FileWriterBuilder> IcebergWriter<PositionDeleteInput<'a>> + for MemoryPositionDeleteWriter<B> +{ + #[doc = " Write data to iceberg table."] + #[must_use] + #[allow(clippy::type_complexity, clippy::type_repetition_in_bounds)] + fn write<'life0, 'async_trait>( + &'life0 mut self, + input: PositionDeleteInput<'a>, + ) -> ::core::pin::Pin< + Box<dyn ::core::future::Future<Output = Result<()>> + ::core::marker::Send + 'async_trait>, + > + where + 'life0: 'async_trait, + Self: 'async_trait, Review Comment: Please remove these auto generated lifetime markers and prefix of types ########## crates/iceberg/src/arrow/schema.rs: ########## @@ -607,6 +607,19 @@ impl SchemaVisitor for ToArrowSchemaConverter { } } +/// Convert iceberg field to an arrow field. +pub fn field_to_arrow_field(field: &crate::spec::NestedFieldRef) -> Result<FieldRef> { + let mut converter = ToArrowSchemaConverter; Review Comment: The implementation is a little hack to me. How about just create a one field schema, and convert it using arrow schema, then get the result? -- 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