|
| 1 | +// Licensed to the Apache Software Foundation (ASF) under one |
| 2 | +// or more contributor license agreements. See the NOTICE file |
| 3 | +// distributed with this work for additional information |
| 4 | +// regarding copyright ownership. The ASF licenses this file |
| 5 | +// to you under the Apache License, Version 2.0 (the |
| 6 | +// "License"); you may not use this file except in compliance |
| 7 | +// with the License. You may obtain a copy of the License at |
| 8 | +// |
| 9 | +// http://www.apache.org/licenses/LICENSE-2.0 |
| 10 | +// |
| 11 | +// Unless required by applicable law or agreed to in writing, |
| 12 | +// software distributed under the License is distributed on an |
| 13 | +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY |
| 14 | +// KIND, either express or implied. See the License for the |
| 15 | +// specific language governing permissions and limitations |
| 16 | +// under the License. |
| 17 | + |
| 18 | +//! Position delete file writer. |
| 19 | +use std::sync::Arc; |
| 20 | + |
| 21 | +use arrow_array::builder::{PrimitiveBuilder, StringBuilder}; |
| 22 | +use arrow_array::types::Int64Type; |
| 23 | +use arrow_array::RecordBatch; |
| 24 | +use once_cell::sync::Lazy; |
| 25 | + |
| 26 | +use crate::arrow::schema_to_arrow_schema; |
| 27 | +use crate::spec::{DataContentType, DataFile, NestedField, PrimitiveType, Schema, Struct, Type}; |
| 28 | +use crate::writer::file_writer::{FileWriter, FileWriterBuilder}; |
| 29 | +use crate::writer::{IcebergWriter, IcebergWriterBuilder}; |
| 30 | +use crate::{Error, ErrorKind, Result}; |
| 31 | + |
| 32 | +static POSITION_DELETE_SCHEMA: Lazy<Schema> = Lazy::new(|| { |
| 33 | + Schema::builder() |
| 34 | + .with_fields(vec![ |
| 35 | + Arc::new(NestedField::required( |
| 36 | + 2147483546, |
| 37 | + "file_path", |
| 38 | + Type::Primitive(PrimitiveType::String), |
| 39 | + )), |
| 40 | + Arc::new(NestedField::required( |
| 41 | + 2147483545, |
| 42 | + "pos", |
| 43 | + Type::Primitive(PrimitiveType::Long), |
| 44 | + )), |
| 45 | + ]) |
| 46 | + .build() |
| 47 | + .unwrap() |
| 48 | +}); |
| 49 | + |
| 50 | +/// Position delete input. |
| 51 | +#[derive(Clone, PartialEq, Eq, Ord, PartialOrd, Debug)] |
| 52 | +pub struct PositionDeleteInput { |
| 53 | + /// The path of the file. |
| 54 | + pub path: String, |
| 55 | + /// The offset of the position delete. |
| 56 | + pub offsets: Vec<i64>, |
| 57 | +} |
| 58 | + |
| 59 | +impl PositionDeleteInput { |
| 60 | + /// Create a new `PositionDeleteInput`. |
| 61 | + pub fn new(path: String, offsets: Vec<i64>) -> Self { |
| 62 | + PositionDeleteInput { path, offsets } |
| 63 | + } |
| 64 | +} |
| 65 | +/// Builder for `MemoryPositionDeleteWriter`. |
| 66 | +#[derive(Clone)] |
| 67 | +pub struct PositionDeleteWriterBuilder<B: FileWriterBuilder> { |
| 68 | + inner: B, |
| 69 | + partition_value: Option<Struct>, |
| 70 | +} |
| 71 | + |
| 72 | +impl<B: FileWriterBuilder> PositionDeleteWriterBuilder<B> { |
| 73 | + /// Create a new `MemoryPositionDeleteWriterBuilder` using a `FileWriterBuilder`. |
| 74 | + pub fn new(inner: B, partition_value: Option<Struct>) -> Self { |
| 75 | + Self { |
| 76 | + inner, |
| 77 | + partition_value, |
| 78 | + } |
| 79 | + } |
| 80 | +} |
| 81 | + |
| 82 | +#[async_trait::async_trait] |
| 83 | +impl<B: FileWriterBuilder> IcebergWriterBuilder<Vec<PositionDeleteInput>> |
| 84 | + for PositionDeleteWriterBuilder<B> |
| 85 | +{ |
| 86 | + type R = PositionDeleteWriter<B>; |
| 87 | + |
| 88 | + async fn build(self) -> Result<Self::R> { |
| 89 | + Ok(PositionDeleteWriter { |
| 90 | + inner_writer: Some(self.inner.build().await?), |
| 91 | + partition_value: self.partition_value.unwrap_or(Struct::empty()), |
| 92 | + }) |
| 93 | + } |
| 94 | +} |
| 95 | + |
| 96 | +/// Position delete writer. |
| 97 | +pub struct PositionDeleteWriter<B: FileWriterBuilder> { |
| 98 | + inner_writer: Option<B::R>, |
| 99 | + partition_value: Struct, |
| 100 | +} |
| 101 | + |
| 102 | +#[async_trait::async_trait] |
| 103 | +impl<B: FileWriterBuilder> IcebergWriter<Vec<PositionDeleteInput>> for PositionDeleteWriter<B> { |
| 104 | + async fn write(&mut self, input: Vec<PositionDeleteInput>) -> Result<()> { |
| 105 | + let mut path_column_builder = StringBuilder::new(); |
| 106 | + let mut offset_column_builder = PrimitiveBuilder::<Int64Type>::new(); |
| 107 | + for input in input.into_iter() { |
| 108 | + for offset in input.offsets { |
| 109 | + path_column_builder.append_value(&input.path); |
| 110 | + offset_column_builder.append_value(offset); |
| 111 | + } |
| 112 | + } |
| 113 | + let record_batch = RecordBatch::try_new( |
| 114 | + Arc::new(schema_to_arrow_schema(&POSITION_DELETE_SCHEMA).unwrap()), |
| 115 | + vec![ |
| 116 | + Arc::new(path_column_builder.finish()), |
| 117 | + Arc::new(offset_column_builder.finish()), |
| 118 | + ], |
| 119 | + ) |
| 120 | + .map_err(|e| Error::new(ErrorKind::DataInvalid, e.to_string()))?; |
| 121 | + |
| 122 | + if let Some(inner_writer) = &mut self.inner_writer { |
| 123 | + inner_writer.write(&record_batch).await?; |
| 124 | + } else { |
| 125 | + return Err(Error::new(ErrorKind::Unexpected, "write has been closed")); |
| 126 | + } |
| 127 | + Ok(()) |
| 128 | + } |
| 129 | + |
| 130 | + async fn close(&mut self) -> Result<Vec<DataFile>> { |
| 131 | + let writer = self.inner_writer.take().unwrap(); |
| 132 | + Ok(writer |
| 133 | + .close() |
| 134 | + .await? |
| 135 | + .into_iter() |
| 136 | + .map(|mut res| { |
| 137 | + res.content(DataContentType::PositionDeletes); |
| 138 | + res.partition(self.partition_value.clone()); |
| 139 | + res.build().expect("Guaranteed to be valid") |
| 140 | + }) |
| 141 | + .collect()) |
| 142 | + } |
| 143 | +} |
| 144 | + |
| 145 | +#[cfg(test)] |
| 146 | +mod test { |
| 147 | + use std::sync::Arc; |
| 148 | + |
| 149 | + use arrow_array::{Int64Array, StringArray}; |
| 150 | + use itertools::Itertools; |
| 151 | + use parquet::arrow::arrow_reader::ParquetRecordBatchReaderBuilder; |
| 152 | + use parquet::file::properties::WriterProperties; |
| 153 | + use tempfile::TempDir; |
| 154 | + |
| 155 | + use crate::io::FileIOBuilder; |
| 156 | + use crate::spec::{DataContentType, DataFileFormat, Struct}; |
| 157 | + use crate::writer::base_writer::position_delete_file_writer::{ |
| 158 | + PositionDeleteInput, PositionDeleteWriterBuilder, POSITION_DELETE_SCHEMA, |
| 159 | + }; |
| 160 | + use crate::writer::file_writer::location_generator::test::MockLocationGenerator; |
| 161 | + use crate::writer::file_writer::location_generator::DefaultFileNameGenerator; |
| 162 | + use crate::writer::file_writer::ParquetWriterBuilder; |
| 163 | + use crate::writer::{IcebergWriter, IcebergWriterBuilder}; |
| 164 | + use crate::Result; |
| 165 | + |
| 166 | + #[tokio::test] |
| 167 | + async fn test_position_delete_writer() -> Result<()> { |
| 168 | + let temp_dir = TempDir::new().unwrap(); |
| 169 | + let file_io = FileIOBuilder::new("memory").build().unwrap(); |
| 170 | + let location_gen = |
| 171 | + MockLocationGenerator::new(temp_dir.path().to_str().unwrap().to_string()); |
| 172 | + let file_name_gen = |
| 173 | + DefaultFileNameGenerator::new("test".to_string(), None, DataFileFormat::Parquet); |
| 174 | + |
| 175 | + let pw = ParquetWriterBuilder::new( |
| 176 | + WriterProperties::builder().build(), |
| 177 | + Arc::new(POSITION_DELETE_SCHEMA.clone()), |
| 178 | + file_io.clone(), |
| 179 | + location_gen, |
| 180 | + file_name_gen, |
| 181 | + ); |
| 182 | + let mut position_delete_writer = PositionDeleteWriterBuilder::new(pw, None).build().await?; |
| 183 | + |
| 184 | + // Write some position delete inputs |
| 185 | + let inputs: Vec<PositionDeleteInput> = vec![ |
| 186 | + PositionDeleteInput { |
| 187 | + path: "file2.parquet".to_string(), |
| 188 | + offsets: vec![2, 1, 3], |
| 189 | + }, |
| 190 | + PositionDeleteInput { |
| 191 | + path: "file3.parquet".to_string(), |
| 192 | + offsets: vec![2], |
| 193 | + }, |
| 194 | + PositionDeleteInput { |
| 195 | + path: "file1.parquet".to_string(), |
| 196 | + offsets: vec![5, 4, 1], |
| 197 | + }, |
| 198 | + ]; |
| 199 | + let expect_inputs = inputs |
| 200 | + .clone() |
| 201 | + .into_iter() |
| 202 | + .flat_map(|input| { |
| 203 | + input |
| 204 | + .offsets |
| 205 | + .iter() |
| 206 | + .map(|off| (input.path.clone(), *off)) |
| 207 | + .collect::<Vec<_>>() |
| 208 | + }) |
| 209 | + .collect_vec(); |
| 210 | + position_delete_writer.write(inputs.clone()).await?; |
| 211 | + |
| 212 | + let data_files = position_delete_writer.close().await.unwrap(); |
| 213 | + assert_eq!(data_files.len(), 1); |
| 214 | + assert_eq!(data_files[0].file_format, DataFileFormat::Parquet); |
| 215 | + assert_eq!(data_files[0].content, DataContentType::PositionDeletes); |
| 216 | + assert_eq!(data_files[0].partition, Struct::empty()); |
| 217 | + |
| 218 | + let parquet_file = file_io |
| 219 | + .new_input(&data_files[0].file_path)? |
| 220 | + .read() |
| 221 | + .await |
| 222 | + .unwrap(); |
| 223 | + let builder = ParquetRecordBatchReaderBuilder::try_new(parquet_file).unwrap(); |
| 224 | + let reader = builder.build().unwrap(); |
| 225 | + let batches = reader.map(|x| x.unwrap()).collect::<Vec<_>>(); |
| 226 | + |
| 227 | + let path_column = batches[0] |
| 228 | + .column(0) |
| 229 | + .as_any() |
| 230 | + .downcast_ref::<StringArray>() |
| 231 | + .unwrap(); |
| 232 | + let offset_column = batches[0] |
| 233 | + .column(1) |
| 234 | + .as_any() |
| 235 | + .downcast_ref::<Int64Array>() |
| 236 | + .unwrap(); |
| 237 | + |
| 238 | + for (i, (path, offset)) in expect_inputs.into_iter().enumerate() { |
| 239 | + assert_eq!(path_column.value(i), path); |
| 240 | + assert_eq!(offset_column.value(i), offset); |
| 241 | + } |
| 242 | + |
| 243 | + Ok(()) |
| 244 | + } |
| 245 | +} |
0 commit comments