repo
stringclasses
1 value
pull_number
int64
443
6.37k
instance_id
stringlengths
20
21
issue_numbers
listlengths
1
1
base_commit
stringlengths
40
40
patch
stringlengths
602
65k
test_patch
stringlengths
543
17.6k
problem_statement
stringlengths
495
4.62k
hints_text
stringlengths
0
5.6k
created_at
stringlengths
20
20
version
stringlengths
3
4
environment_setup_commit
stringlengths
40
40
FAIL_TO_PASS
listlengths
1
5
PASS_TO_PASS
listlengths
2
67
FAIL_TO_FAIL
listlengths
0
0
PASS_TO_FAIL
listlengths
0
1
apache/arrow-rs
4,351
apache__arrow-rs-4351
[ "4350" ]
008cf9c27424d581a67ba97f338a22b6eace9cc1
diff --git a/object_store/Cargo.toml b/object_store/Cargo.toml index 28bf29f7f1e0..4002a1865fa6 100644 --- a/object_store/Cargo.toml +++ b/object_store/Cargo.toml @@ -75,3 +75,7 @@ tempfile = "3.1.0" futures-test = "0.3" rand = "0.8" hyper = { version = "0.14.24", features = ["server"] } + +[[test]] +name = "get_range_file" +path = "tests/get_range_file.rs" diff --git a/object_store/src/lib.rs b/object_store/src/lib.rs index 98bbb7adceb9..864cabc4a8c0 100644 --- a/object_store/src/lib.rs +++ b/object_store/src/lib.rs @@ -359,10 +359,20 @@ pub trait ObjectStore: std::fmt::Display + Send + Sync + Debug + 'static { /// in the given byte range async fn get_range(&self, location: &Path, range: Range<usize>) -> Result<Bytes> { let options = GetOptions { - range: Some(range), + range: Some(range.clone()), ..Default::default() }; - self.get_opts(location, options).await?.bytes().await + // Temporary until GetResult::File supports range (#4352) + match self.get_opts(location, options).await? { + GetResult::Stream(s) => collect_bytes(s, None).await, + #[cfg(not(target_arch = "wasm32"))] + GetResult::File(mut file, path) => { + maybe_spawn_blocking(move || local::read_range(&mut file, &path, range)) + .await + } + #[cfg(target_arch = "wasm32")] + _ => unimplemented!("File IO not implemented on wasm32."), + } } /// Return the bytes that are stored at the specified location diff --git a/object_store/src/local.rs b/object_store/src/local.rs index 6039f8dbadf3..ffff6a5739d5 100644 --- a/object_store/src/local.rs +++ b/object_store/src/local.rs @@ -863,7 +863,7 @@ impl AsyncWrite for LocalUpload { } } -fn read_range(file: &mut File, path: &PathBuf, range: Range<usize>) -> Result<Bytes> { +pub(crate) fn read_range(file: &mut File, path: &PathBuf, range: Range<usize>) -> Result<Bytes> { let to_read = range.end - range.start; file.seek(SeekFrom::Start(range.start as u64)) .context(SeekSnafu { path })?;
diff --git a/object_store/tests/get_range_file.rs b/object_store/tests/get_range_file.rs new file mode 100644 index 000000000000..f926e3b07f2a --- /dev/null +++ b/object_store/tests/get_range_file.rs @@ -0,0 +1,116 @@ +// 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. + +//! Tests the default implementation of get_range handles GetResult::File correctly (#4350) + +use async_trait::async_trait; +use bytes::Bytes; +use futures::stream::BoxStream; +use object_store::local::LocalFileSystem; +use object_store::path::Path; +use object_store::{ + GetOptions, GetResult, ListResult, MultipartId, ObjectMeta, ObjectStore, +}; +use std::fmt::Formatter; +use tempfile::tempdir; +use tokio::io::AsyncWrite; + +#[derive(Debug)] +struct MyStore(LocalFileSystem); + +impl std::fmt::Display for MyStore { + fn fmt(&self, _: &mut Formatter<'_>) -> std::fmt::Result { + todo!() + } +} + +#[async_trait] +impl ObjectStore for MyStore { + async fn put(&self, path: &Path, data: Bytes) -> object_store::Result<()> { + self.0.put(path, data).await + } + + async fn put_multipart( + &self, + _: &Path, + ) -> object_store::Result<(MultipartId, Box<dyn AsyncWrite + Unpin + Send>)> { + todo!() + } + + async fn abort_multipart( + &self, + _: &Path, + _: &MultipartId, + ) -> object_store::Result<()> { + todo!() + } + + async fn get_opts( + &self, + location: &Path, + options: GetOptions, + ) -> object_store::Result<GetResult> { + self.0.get_opts(location, options).await + } + + async fn head(&self, _: &Path) -> object_store::Result<ObjectMeta> { + todo!() + } + + async fn delete(&self, _: &Path) -> object_store::Result<()> { + todo!() + } + + async fn list( + &self, + _: Option<&Path>, + ) -> object_store::Result<BoxStream<'_, object_store::Result<ObjectMeta>>> { + todo!() + } + + async fn list_with_delimiter( + &self, + _: Option<&Path>, + ) -> object_store::Result<ListResult> { + todo!() + } + + async fn copy(&self, _: &Path, _: &Path) -> object_store::Result<()> { + todo!() + } + + async fn copy_if_not_exists(&self, _: &Path, _: &Path) -> object_store::Result<()> { + todo!() + } +} + +#[tokio::test] +async fn test_get_range() { + let tmp = tempdir().unwrap(); + let store = MyStore(LocalFileSystem::new_with_prefix(tmp.path()).unwrap()); + let path = Path::from("foo"); + + let expected = Bytes::from_static(b"hello world"); + store.put(&path, expected.clone()).await.unwrap(); + let fetched = store.get(&path).await.unwrap().bytes().await.unwrap(); + assert_eq!(expected, fetched); + + for range in [0..10, 3..5, 0..expected.len()] { + let data = store.get_range(&path, range.clone()).await.unwrap(); + assert_eq!(&data[..], &expected[range]) + } +}
Default ObjectStore::get_range Doesn't Apply Range to GetResult::File **Describe the bug** <!-- A clear and concise description of what the bug is. --> The default implementation of `ObjectStore::get_range` added in #4212 incorrectly handles if `GetResult::File` is returned, instead returning the entire byte range. This is incorrect **To Reproduce** <!-- Steps to reproduce the behavior: --> **Expected behavior** <!-- A clear and concise description of what you expected to happen. --> **Additional context** <!-- Add any other context about the problem here. -->
2023-06-02T16:36:39Z
40.0
008cf9c27424d581a67ba97f338a22b6eace9cc1
[ "test_get_range" ]
[ "src/lib.rs - (line 154)", "src/lib.rs - (line 53)", "src/lib.rs - (line 178)", "src/lib.rs - (line 106)", "src/limit.rs - limit::LimitStore (line 39)", "src/path/mod.rs - path::Path (line 123)", "src/path/mod.rs - path::Path (line 102)", "src/path/mod.rs - path::Path (line 112)" ]
[]
[]
apache/arrow-rs
4,343
apache__arrow-rs-4343
[ "4324" ]
795259502d8d19f1e929d8ebf1b2819b6ab145c4
diff --git a/arrow-data/src/transform/mod.rs b/arrow-data/src/transform/mod.rs index c74875072233..f4b2b46d1723 100644 --- a/arrow-data/src/transform/mod.rs +++ b/arrow-data/src/transform/mod.rs @@ -53,7 +53,7 @@ struct _MutableArrayData<'a> { pub null_count: usize, pub len: usize, - pub null_buffer: MutableBuffer, + pub null_buffer: Option<MutableBuffer>, // arrow specification only allows up to 3 buffers (2 ignoring the nulls above). // Thus, we place them in the stack to avoid bound checks and greater data locality. @@ -63,6 +63,12 @@ struct _MutableArrayData<'a> { } impl<'a> _MutableArrayData<'a> { + fn null_buffer(&mut self) -> &mut MutableBuffer { + self.null_buffer + .as_mut() + .expect("MutableArrayData not nullable") + } + fn freeze(self, dictionary: Option<ArrayData>) -> ArrayDataBuilder { let buffers = into_buffers(&self.data_type, self.buffer1, self.buffer2); @@ -77,10 +83,13 @@ impl<'a> _MutableArrayData<'a> { } }; - let nulls = (self.null_count > 0).then(|| { - let bools = BooleanBuffer::new(self.null_buffer.into(), 0, self.len); - unsafe { NullBuffer::new_unchecked(bools, self.null_count) } - }); + let nulls = self + .null_buffer + .map(|nulls| { + let bools = BooleanBuffer::new(nulls.into(), 0, self.len); + unsafe { NullBuffer::new_unchecked(bools, self.null_count) } + }) + .filter(|n| n.null_count() > 0); ArrayDataBuilder::new(self.data_type) .offset(0) @@ -95,22 +104,25 @@ fn build_extend_null_bits(array: &ArrayData, use_nulls: bool) -> ExtendNullBits if let Some(nulls) = array.nulls() { let bytes = nulls.validity(); Box::new(move |mutable, start, len| { - utils::resize_for_bits(&mut mutable.null_buffer, mutable.len + len); + let mutable_len = mutable.len; + let out = mutable.null_buffer(); + utils::resize_for_bits(out, mutable_len + len); mutable.null_count += set_bits( - mutable.null_buffer.as_slice_mut(), + out.as_slice_mut(), bytes, - mutable.len, + mutable_len, nulls.offset() + start, len, ); }) } else if use_nulls { Box::new(|mutable, _, len| { - utils::resize_for_bits(&mut mutable.null_buffer, mutable.len + len); - let write_data = mutable.null_buffer.as_slice_mut(); - let offset = mutable.len; + let mutable_len = mutable.len; + let out = mutable.null_buffer(); + utils::resize_for_bits(out, mutable_len + len); + let write_data = out.as_slice_mut(); (0..len).for_each(|i| { - bit_util::set_bit(write_data, offset + i); + bit_util::set_bit(write_data, mutable_len + i); }); }) } else { @@ -555,13 +567,10 @@ impl<'a> MutableArrayData<'a> { .map(|array| build_extend_null_bits(array, use_nulls)) .collect(); - let null_buffer = if use_nulls { + let null_buffer = use_nulls.then(|| { let null_bytes = bit_util::ceil(array_capacity, 8); MutableBuffer::from_len_zeroed(null_bytes) - } else { - // create 0 capacity mutable buffer with the intention that it won't be used - MutableBuffer::with_capacity(0) - }; + }); let extend_values = match &data_type { DataType::Dictionary(_, _) => { @@ -624,13 +633,18 @@ impl<'a> MutableArrayData<'a> { } /// Extends this [MutableArrayData] with null elements, disregarding the bound arrays + /// + /// # Panics + /// + /// Panics if [`MutableArrayData`] not created with `use_nulls` or nullable source arrays + /// pub fn extend_nulls(&mut self, len: usize) { - // TODO: null_buffer should probably be extended here as well - // otherwise is_valid() could later panic - // add test to confirm + self.data.len += len; + let bit_len = bit_util::ceil(self.data.len, 8); + let nulls = self.data.null_buffer(); + nulls.resize(bit_len, 0); self.data.null_count += len; (self.extend_nulls)(&mut self.data, len); - self.data.len += len; } /// Returns the current length
diff --git a/arrow/tests/array_transform.rs b/arrow/tests/array_transform.rs index 40938c80f4c3..ebbadc00aecd 100644 --- a/arrow/tests/array_transform.rs +++ b/arrow/tests/array_transform.rs @@ -922,6 +922,29 @@ fn test_fixed_size_binary_append() { assert_eq!(result, expected); } +#[test] +fn test_extend_nulls() { + let int = Int32Array::from(vec![1, 2, 3, 4]).into_data(); + let mut mutable = MutableArrayData::new(vec![&int], true, 4); + mutable.extend(0, 2, 3); + mutable.extend_nulls(2); + + let data = mutable.freeze(); + data.validate_full().unwrap(); + let out = Int32Array::from(data); + + assert_eq!(out.null_count(), 2); + assert_eq!(out.iter().collect::<Vec<_>>(), vec![Some(3), None, None]); +} + +#[test] +#[should_panic(expected = "MutableArrayData not nullable")] +fn test_extend_nulls_panic() { + let int = Int32Array::from(vec![1, 2, 3, 4]).into_data(); + let mut mutable = MutableArrayData::new(vec![&int], false, 4); + mutable.extend_nulls(2); +} + /* // this is an old test used on a meanwhile removed dead code // that is still useful when `MutableArrayData` supports fixed-size lists.
concat_batches panics with total_len <= bit_len assertion for records with lists **Describe the bug** `concat`, used by `concat_batches`, does not appear to allocate sufficient `capacities` when constructing the `MutableArrayData`. Concatenating records that contain lists of structs results in the following panic: ``` assertion failed: total_len <= bit_len thread 'concat_test' panicked at 'assertion failed: total_len <= bit_len', /Users/x/.cargo/registry/src/index.crates.io-6f17d22bba15001f/arrow-buffer-40.0.0/src/buffer/boolean.rs:55:9 stack backtrace: 0: rust_begin_unwind at /rustc/84c898d65adf2f39a5a98507f1fe0ce10a2b8dbc/library/std/src/panicking.rs:579:5 1: core::panicking::panic_fmt at /rustc/84c898d65adf2f39a5a98507f1fe0ce10a2b8dbc/library/core/src/panicking.rs:64:14 2: core::panicking::panic at /rustc/84c898d65adf2f39a5a98507f1fe0ce10a2b8dbc/library/core/src/panicking.rs:114:5 3: arrow_buffer::buffer::boolean::BooleanBuffer::new at /Users/x/.cargo/registry/src/index.crates.io-6f17d22bba15001f/arrow-buffer-40.0.0/src/buffer/boolean.rs:55:9 4: arrow_data::transform::_MutableArrayData::freeze::{{closure}} at /Users/x/.cargo/registry/src/index.crates.io-6f17d22bba15001f/arrow-data-40.0.0/src/transform/mod.rs:81:25 5: core::bool::<impl bool>::then at /rustc/84c898d65adf2f39a5a98507f1fe0ce10a2b8dbc/library/core/src/bool.rs:71:24 6: arrow_data::transform::_MutableArrayData::freeze at /Users/x/.cargo/registry/src/index.crates.io-6f17d22bba15001f/arrow-data-40.0.0/src/transform/mod.rs:80:21 7: arrow_data::transform::MutableArrayData::freeze at /Users/x/.cargo/registry/src/index.crates.io-6f17d22bba15001f/arrow-data-40.0.0/src/transform/mod.rs:656:18 8: arrow_data::transform::_MutableArrayData::freeze at /Users/x/.cargo/registry/src/index.crates.io-6f17d22bba15001f/arrow-data-40.0.0/src/transform/mod.rs:74:37 9: arrow_data::transform::MutableArrayData::freeze at /Users/x/.cargo/registry/src/index.crates.io-6f17d22bba15001f/arrow-data-40.0.0/src/transform/mod.rs:656:18 10: arrow_data::transform::_MutableArrayData::freeze at /Users/x/.cargo/registry/src/index.crates.io-6f17d22bba15001f/arrow-data-40.0.0/src/transform/mod.rs:74:37 11: arrow_data::transform::MutableArrayData::freeze at /Users/x/.cargo/registry/src/index.crates.io-6f17d22bba15001f/arrow-data-40.0.0/src/transform/mod.rs:656:18 12: arrow_data::transform::_MutableArrayData::freeze at /Users/x/.cargo/registry/src/index.crates.io-6f17d22bba15001f/arrow-data-40.0.0/src/transform/mod.rs:74:37 13: arrow_data::transform::MutableArrayData::freeze at /Users/x/.cargo/registry/src/index.crates.io-6f17d22bba15001f/arrow-data-40.0.0/src/transform/mod.rs:656:18 ``` **To Reproduce** Call `concat_batches` with `RecordBatch`s that contain lists of structs (on the order of 20–50 structs in the list per `RecordBatch`). If I modify [the capacity calculation in concat](https://github.com/apache/arrow-rs/blob/c295b172b37902d5fa41ef275ff5b86caf9fde75/arrow-select/src/concat.rs#L76-L82) to add a constant factor for lists, the error does not occur: ```rust let capacity = match d { DataType::Utf8 => binary_capacity::<Utf8Type>(arrays), DataType::LargeUtf8 => binary_capacity::<LargeUtf8Type>(arrays), DataType::Binary => binary_capacity::<BinaryType>(arrays), DataType::LargeBinary => binary_capacity::<LargeBinaryType>(arrays), DataType::List(_) => { Capacities::Array(arrays.iter().map(|a| a.len()).sum::<usize>() + 500) // <- 500 added here } _ => Capacities::Array(arrays.iter().map(|a| a.len()).sum()), }; ``` **Expected behavior** No panics when concatenating `RecordBatch`s with lists. **Additional context** Reproduced with Arrow versions 37–40.
Possibly related to https://github.com/apache/arrow-rs/issues/1230. The error would suggest that the validity buffer is not the correct length. I'll take a look in a bit, MutableArrayData is overdue some TLC in this regard (#1225) Are you able to share a reproducer for this? Sure, see https://github.com/ElementalCognition/arrow-bug. Thank you, very helpful. It looks like this is https://github.com/apache/arrow-rs/issues/1230, which I will fix now As a happy accident https://github.com/apache/arrow-rs/pull/4333 fixed your reproducer as it removed the use of extend_nulls when appending structs
2023-06-02T07:51:43Z
40.0
008cf9c27424d581a67ba97f338a22b6eace9cc1
[ "test_extend_nulls_panic - should panic" ]
[ "arrow/src/lib.rs - (line 140)", "arrow/src/lib.rs - (line 121)", "arrow/src/lib.rs - (line 253)", "arrow/src/lib.rs - (line 63)", "arrow/src/lib.rs - (line 227)", "arrow/src/lib.rs - (line 282)", "arrow/src/util/string_writer.rs - util::string_writer (line 25)", "arrow/src/lib.rs - (line 97)", "arrow/src/lib.rs - (line 78)", "arrow/src/lib.rs - (line 161)", "arrow/src/lib.rs - (line 198)", "test_binary_fixed_sized_offsets", "test_bool", "test_decimal", "test_decimal_null_offset_nulls", "test_extend_nulls", "test_decimal_offset", "test_fixed_size_binary_append", "test_dictionary", "test_list_append", "test_list_null_offset", "test_list_nulls_append", "test_list_of_strings_append", "test_map_nulls_append", "test_multiple_with_nulls", "test_null", "test_primitive", "test_primitive_null_offset", "test_primitive_null_offset_nulls", "test_primitive_offset", "test_string_null_offset_nulls", "test_string_offsets", "test_struct", "test_struct_many", "test_struct_nulls", "test_struct_offset", "test_variable_sized_offsets", "test_variable_sized_nulls" ]
[]
[]
apache/arrow-rs
4,327
apache__arrow-rs-4327
[ "3680" ]
30196d89bfab698c50bcde6c304f0599011a1100
diff --git a/parquet/src/column/writer/mod.rs b/parquet/src/column/writer/mod.rs index 310519f4a39c..fc5e29b03256 100644 --- a/parquet/src/column/writer/mod.rs +++ b/parquet/src/column/writer/mod.rs @@ -308,6 +308,17 @@ impl<'a, E: ColumnValueEncoder> GenericColumnWriter<'a, E> { max: Option<&E::T>, distinct_count: Option<u64>, ) -> Result<usize> { + // Check if number of definition levels is the same as number of repetition levels. + if let (Some(def), Some(rep)) = (def_levels, rep_levels) { + if def.len() != rep.len() { + return Err(general_err!( + "Inconsistent length of definition and repetition levels: {} != {}", + def.len(), + rep.len() + )); + } + } + // We check for DataPage limits only after we have inserted the values. If a user // writes a large number of values, the DataPage size can be well above the limit. // @@ -323,10 +334,6 @@ impl<'a, E: ColumnValueEncoder> GenericColumnWriter<'a, E> { None => values.len(), }; - // Find out number of batches to process. - let write_batch_size = self.props.write_batch_size(); - let num_batches = num_levels / write_batch_size; - // If only computing chunk-level statistics compute them here, page-level statistics // are computed in [`Self::write_mini_batch`] and used to update chunk statistics in // [`Self::add_data_page`] @@ -374,27 +381,28 @@ impl<'a, E: ColumnValueEncoder> GenericColumnWriter<'a, E> { let mut values_offset = 0; let mut levels_offset = 0; - for _ in 0..num_batches { + let base_batch_size = self.props.write_batch_size(); + while levels_offset < num_levels { + let mut end_offset = num_levels.min(levels_offset + base_batch_size); + + // Split at record boundary + if let Some(r) = rep_levels { + while end_offset < r.len() && r[end_offset] != 0 { + end_offset += 1; + } + } + values_offset += self.write_mini_batch( values, values_offset, value_indices, - write_batch_size, - def_levels.map(|lv| &lv[levels_offset..levels_offset + write_batch_size]), - rep_levels.map(|lv| &lv[levels_offset..levels_offset + write_batch_size]), + end_offset - levels_offset, + def_levels.map(|lv| &lv[levels_offset..end_offset]), + rep_levels.map(|lv| &lv[levels_offset..end_offset]), )?; - levels_offset += write_batch_size; + levels_offset = end_offset; } - values_offset += self.write_mini_batch( - values, - values_offset, - value_indices, - num_levels - levels_offset, - def_levels.map(|lv| &lv[levels_offset..]), - rep_levels.map(|lv| &lv[levels_offset..]), - )?; - // Return total number of values processed. Ok(values_offset) } @@ -522,18 +530,6 @@ impl<'a, E: ColumnValueEncoder> GenericColumnWriter<'a, E> { def_levels: Option<&[i16]>, rep_levels: Option<&[i16]>, ) -> Result<usize> { - // Check if number of definition levels is the same as number of repetition - // levels. - if let (Some(def), Some(rep)) = (def_levels, rep_levels) { - if def.len() != rep.len() { - return Err(general_err!( - "Inconsistent length of definition and repetition levels: {} != {}", - def.len(), - rep.len() - )); - } - } - // Process definition levels and determine how many values to write. let values_to_write = if self.descr.max_def_level() > 0 { let levels = def_levels.ok_or_else(|| { @@ -569,6 +565,13 @@ impl<'a, E: ColumnValueEncoder> GenericColumnWriter<'a, E> { ) })?; + if !levels.is_empty() && levels[0] != 0 { + return Err(general_err!( + "Write must start at a record boundary, got non-zero repetition level of {}", + levels[0] + )); + } + // Count the occasions where we start a new row for &level in levels { self.page_metrics.num_buffered_rows += (level == 0) as u32 @@ -2255,6 +2258,7 @@ mod tests { let mut buf: Vec<i16> = Vec::new(); let rep_levels = if max_rep_level > 0 { random_numbers_range(max_size, 0, max_rep_level + 1, &mut buf); + buf[0] = 0; // Must start on record boundary Some(&buf[..]) } else { None
diff --git a/parquet/tests/arrow_writer_layout.rs b/parquet/tests/arrow_writer_layout.rs index 142112b7b686..3142c8c52063 100644 --- a/parquet/tests/arrow_writer_layout.rs +++ b/parquet/tests/arrow_writer_layout.rs @@ -19,6 +19,7 @@ use arrow::array::{Int32Array, StringArray}; use arrow::record_batch::RecordBatch; +use arrow_array::builder::{Int32Builder, ListBuilder}; use bytes::Bytes; use parquet::arrow::arrow_reader::{ArrowReaderOptions, ParquetRecordBatchReaderBuilder}; use parquet::arrow::ArrowWriter; @@ -502,3 +503,45 @@ fn test_string() { }, }); } + +#[test] +fn test_list() { + let mut list = ListBuilder::new(Int32Builder::new()); + for _ in 0..200 { + let values = list.values(); + for i in 0..8 { + values.append_value(i); + } + list.append(true); + } + let array = Arc::new(list.finish()) as _; + + let batch = RecordBatch::try_from_iter([("col", array)]).unwrap(); + let props = WriterProperties::builder() + .set_dictionary_enabled(false) + .set_data_page_row_count_limit(20) + .set_write_batch_size(3) + .build(); + + // Test rows not split across pages + do_test(LayoutTest { + props, + batches: vec![batch], + layout: Layout { + row_groups: vec![RowGroup { + columns: vec![ColumnChunk { + pages: (0..10) + .map(|_| Page { + rows: 20, + page_header_size: 34, + compressed_size: 672, + encoding: Encoding::PLAIN, + page_type: PageType::DATA_PAGE, + }) + .collect(), + dictionary_page: None, + }], + }], + }, + }); +}
Should Parquet pages begin on the start of a row? **Which part is this question about** Parquet writer <!-- Is it code base, library api, documentation or some other part? --> **Describe your question** In #1777 it was brought up [here](https://github.com/apache/arrow-rs/issues/1777#issuecomment-1147686956) that the Parquet spec seems to require that pages begin on record boundaries when writing offset indices. Additionally, the same can be said for V2 page headers (see comment in the parquet-format [thrift](https://github.com/apache/parquet-format/blob/5205dc7b7c0b910ea6af33cadbd2963c0c47c726/src/main/thrift/parquet.thrift#L564) file). It appears that this reasoning was rejected, and the Parquet writer continues to write files where rows can span multiple pages. I'm wondering if this should still be considered a bug given how difficult finding individual rows is made with this behavior in place. <!-- A clear and concise description of what the question is. --> **Additional context** I've been working with the cuDF Parquet reader, and files with large nested rows can create havoc when rows span pages. Parquet-mr appears to hew to the "pages start with R=0" rule. <!-- Add any other context about the problem here. -->
I'm not sure it is a bug per se, but I definitely think the APIs shouldn't do it unilaterally as they currently do. I would support making `GenericColumnWriter::write_batch_internal` call `write_mini_batch` treating the `WriterProperties::write_batch_size` as being a number of rows, as opposed to levels. Tbh this is probably what most people assume it does anyway. I'll try to get something up today This should mean that if the user writes in a whole number of rows, the rows won't be split across multiple pages. Handling if the user writes partial rows would be significantly more complicated, and I think we can safely punt on it. Edit: Ran out of time today, will do first thing tomorrow. Will try to ensure this makes the release slated for tomorrow, but will depend on reviews > Will try to ensure this makes the release slated for tomorrow, but will depend on reviews No rush, this might want some thought. One thing to consider is that this can lead to very uneven page sizes if the data is very "lumpy". That's the price to pay when using V2 headers or page indexes, but you may want to consider keeping the current behavior when neither of those is requested.
2023-05-31T19:17:10Z
40.0
008cf9c27424d581a67ba97f338a22b6eace9cc1
[ "test_list" ]
[ "parquet/src/file/mod.rs - file (line 63) - compile", "parquet/src/record/api.rs - record::api::Row::get_column_iter (line 62) - compile", "parquet/src/file/mod.rs - file (line 80) - compile", "parquet/src/file/mod.rs - file (line 29) - compile", "parquet/src/column/mod.rs - column (line 38) - compile", "parquet/src/schema/types.rs - schema::types::ColumnPath::append (line 687)", "parquet/src/file/properties.rs - file::properties (line 55)", "parquet/src/schema/types.rs - schema::types::ColumnPath::string (line 676)", "parquet/src/file/statistics.rs - file::statistics (line 23)", "parquet/src/arrow/mod.rs - arrow (line 52)", "parquet/src/arrow/arrow_reader/selection.rs - arrow::arrow_reader::selection::RowSelection (line 63)", "parquet/src/file/properties.rs - file::properties (line 22)", "parquet/src/schema/parser.rs - schema::parser (line 24)", "parquet/src/schema/printer.rs - schema::printer (line 23)", "parquet/src/schema/mod.rs - schema (line 22)", "parquet/src/record/api.rs - record::api::RowFormatter (line 140)", "parquet/src/arrow/mod.rs - arrow (line 27)", "parquet/src/arrow/arrow_writer/mod.rs - arrow::arrow_writer::ArrowWriter (line 64)", "parquet/src/arrow/mod.rs - arrow (line 65)", "test_primitive", "test_string" ]
[]
[]
apache/arrow-rs
5,439
apache__arrow-rs-5439
[ "5438" ]
ef5c45cf4186a8124da5a1603ebdbc09ef9928fc
diff --git a/arrow-flight/src/error.rs b/arrow-flight/src/error.rs index e054883e965d..ba979ca9f7a6 100644 --- a/arrow-flight/src/error.rs +++ b/arrow-flight/src/error.rs @@ -49,17 +49,24 @@ impl FlightError { impl std::fmt::Display for FlightError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - // TODO better format / error - write!(f, "{self:?}") + match self { + FlightError::Arrow(source) => write!(f, "Arrow error: {}", source), + FlightError::NotYetImplemented(desc) => write!(f, "Not yet implemented: {}", desc), + FlightError::Tonic(source) => write!(f, "Tonic error: {}", source), + FlightError::ProtocolError(desc) => write!(f, "Protocol error: {}", desc), + FlightError::DecodeError(desc) => write!(f, "Decode error: {}", desc), + FlightError::ExternalError(source) => write!(f, "External error: {}", source), + } } } impl Error for FlightError { fn source(&self) -> Option<&(dyn Error + 'static)> { - if let Self::ExternalError(e) = self { - Some(e.as_ref()) - } else { - None + match self { + FlightError::Arrow(source) => Some(source), + FlightError::Tonic(source) => Some(source), + FlightError::ExternalError(source) => Some(source.as_ref()), + _ => None, } } } diff --git a/arrow-schema/src/error.rs b/arrow-schema/src/error.rs index b7bf8d6e12a6..d9a0f3452c86 100644 --- a/arrow-schema/src/error.rs +++ b/arrow-schema/src/error.rs @@ -114,10 +114,10 @@ impl Display for ArrowError { impl Error for ArrowError { fn source(&self) -> Option<&(dyn Error + 'static)> { - if let Self::ExternalError(e) = self { - Some(e.as_ref()) - } else { - None + match self { + ArrowError::ExternalError(source) => Some(source.as_ref()), + ArrowError::IoError(_, source) => Some(source), + _ => None, } } }
diff --git a/arrow-flight/tests/client.rs b/arrow-flight/tests/client.rs index 9e19bce92338..47565334cb63 100644 --- a/arrow-flight/tests/client.rs +++ b/arrow-flight/tests/client.rs @@ -935,7 +935,7 @@ async fn test_cancel_flight_info_error_no_response() { assert_eq!( err.to_string(), - "ProtocolError(\"Received no response for cancel_flight_info call\")" + "Protocol error: Received no response for cancel_flight_info call" ); // server still got the request let expected_request = Action::new("CancelFlightInfo", request.encode_to_vec()); @@ -985,7 +985,7 @@ async fn test_renew_flight_endpoint_error_no_response() { assert_eq!( err.to_string(), - "ProtocolError(\"Received no response for renew_flight_endpoint call\")" + "Protocol error: Received no response for renew_flight_endpoint call" ); // server still got the request let expected_request = Action::new("RenewFlightEndpoint", request.encode_to_vec()); diff --git a/arrow-flight/tests/encode_decode.rs b/arrow-flight/tests/encode_decode.rs index f4741d743e57..789233b918d0 100644 --- a/arrow-flight/tests/encode_decode.rs +++ b/arrow-flight/tests/encode_decode.rs @@ -57,7 +57,7 @@ async fn test_error() { let result: Result<Vec<_>, _> = decode_stream.try_collect().await; let result = result.unwrap_err(); - assert_eq!(result.to_string(), r#"NotYetImplemented("foo")"#); + assert_eq!(result.to_string(), "Not yet implemented: foo"); } #[tokio::test] @@ -287,7 +287,7 @@ async fn test_mismatched_record_batch_schema() { let err = result.unwrap_err(); assert_eq!( err.to_string(), - "Arrow(InvalidArgumentError(\"number of columns(1) must match number of fields(2) in schema\"))" + "Arrow error: Invalid argument error: number of columns(1) must match number of fields(2) in schema" ); } @@ -312,7 +312,7 @@ async fn test_chained_streams_batch_decoder() { let err = result.unwrap_err(); assert_eq!( err.to_string(), - "ProtocolError(\"Unexpectedly saw multiple Schema messages in FlightData stream\")" + "Protocol error: Unexpectedly saw multiple Schema messages in FlightData stream" ); }
Refine `Display` implementation for `FlightError` **Is your feature request related to a problem or challenge? Please describe what you are trying to do.** There's a `TODO` for a better `std::fmt::Display` implementation on `FlightError`. Currently it forwards to `std::fmt::Debug`, which does not appear to be a good practice as errors should describe themselves with friendly messages provided by `Display`. https://github.com/apache/arrow-rs/blob/ef5c45cf4186a8124da5a1603ebdbc09ef9928fc/arrow-flight/src/error.rs#L50-L55 **Describe the solution you'd like** Match the variants of the error and specify different prompts like what we did for `ArrowError`. https://github.com/apache/arrow-rs/blob/ef5c45cf4186a8124da5a1603ebdbc09ef9928fc/arrow-schema/src/error.rs#L79-L87 **Describe alternatives you've considered** Derive the implementation with `thiserror`. The code can be more concise with the cost of introducing a new build-time dependency. **Additional context** A better practice to implement `Display` for errors is **NOT** to include the error source. AWS SDK has adopted this as described in https://github.com/awslabs/aws-sdk-rust/issues/657. However, this could be considered as a breaking change as many developers have not realize that one should leverage something like [`std::error::Report`](https://doc.rust-lang.org/stable/std/error/struct.Report.html) to get the error sources printed.
2024-02-27T07:27:28Z
50.0
82fc0df73ab97e239ce5c748a05c57ce582f3d5d
[ "test_cancel_flight_info_error_no_response", "test_renew_flight_endpoint_error_no_response", "test_chained_streams_batch_decoder", "test_error", "test_mismatched_record_batch_schema" ]
[ "arrow-flight/src/client.rs - client::FlightClient::cancel_flight_info (line 609) - compile", "arrow-flight/src/client.rs - client::FlightClient::get_schema (line 497) - compile", "arrow-flight/src/client.rs - client::FlightClient::do_action (line 564) - compile", "arrow-flight/src/client.rs - client::FlightClient (line 49) - compile", "arrow-flight/src/client.rs - client::FlightClient::list_flights (line 454) - compile", "arrow-flight/src/client.rs - client::FlightClient::do_get (line 182) - compile", "arrow-flight/src/client.rs - client::FlightClient::renew_flight_endpoint (line 647) - compile", "arrow-flight/src/client.rs - client::FlightClient::poll_flight_info (line 283) - compile", "arrow-flight/src/client.rs - client::FlightClient::get_flight_info (line 227) - compile", "arrow-flight/src/decode.rs - decode::FlightRecordBatchStream (line 39) - compile", "arrow-flight/src/client.rs - client::FlightClient::list_actions (line 529) - compile", "arrow-flight/src/client.rs - client::FlightClient::do_put (line 335) - compile", "arrow-flight/src/client.rs - client::FlightClient::do_exchange (line 404) - compile", "arrow-flight/src/encode.rs - encode::FlightDataEncoderBuilder (line 46) - compile", "arrow-flight/src/encode.rs - encode::FlightDataEncoderBuilder (line 74)", "arrow-flight/src/lib.rs - FlightData::new (line 461)", "arrow-flight/src/lib.rs - FlightInfo::new (line 536)", "arrow-flight/src/lib.rs - FlightEndpoint::new (line 761)", "arrow-flight/src/lib.rs - PollInfo::new (line 634)", "arrow-flight/src/lib.rs - Ticket::new (line 745)", "test_cancel_flight_info", "test_do_get_error", "test_do_action_error", "test_do_action", "test_do_exchange_error_stream", "test_do_put_error_stream_server", "test_do_put_error_client", "test_do_put_error_client_and_server", "test_do_exchange_error", "test_do_action_error_in_stream", "test_do_put", "test_do_get_error_in_record_batch_stream", "test_do_put_error_server", "test_get_flight_info_error", "test_get_schema_error", "test_list_flights_error", "test_poll_flight_info", "test_get_schema", "test_list_actions", "test_get_flight_info", "test_handshake_error", "test_list_flights", "test_list_actions_error_in_stream", "test_list_actions_error", "test_handshake", "test_list_flights_error_in_stream", "test_poll_flight_info_error", "test_renew_flight_endpoint", "test_do_get", "test_do_exchange", "test_empty", "test_app_metadata", "test_empty_batch", "test_dictionary_one", "test_chained_streams_data_decoder", "test_max_message_size", "test_dictionary_many", "test_primitive_empty", "test_primitive_many", "test_mismatched_schema_message", "test_schema_metadata", "test_with_flight_descriptor", "test_zero_batches_schema_specified", "test_zero_batches_no_schema", "test_zero_batches_dictionary_schema_specified", "test_primitive_one", "test_max_message_size_fuzz" ]
[]
[]
apache/arrow-rs
443
apache__arrow-rs-443
[ "349" ]
0c0077697e55eb154dbfcf3127a3f39e63be2df8
diff --git a/parquet/src/data_type.rs b/parquet/src/data_type.rs index aa1def3db977..f97df3cdaf59 100644 --- a/parquet/src/data_type.rs +++ b/parquet/src/data_type.rs @@ -661,8 +661,15 @@ pub(crate) mod private { _: &mut W, bit_writer: &mut BitWriter, ) -> Result<()> { + if bit_writer.bytes_written() + values.len() / 8 >= bit_writer.capacity() { + bit_writer.extend(256); + } for value in values { - bit_writer.put_value(*value as u64, 1); + if !bit_writer.put_value(*value as u64, 1) { + return Err(ParquetError::EOF( + "unable to put boolean value".to_string(), + )); + } } Ok(()) } diff --git a/parquet/src/util/bit_util.rs b/parquet/src/util/bit_util.rs index 8dfb63122bcc..45cfe2b6d48f 100644 --- a/parquet/src/util/bit_util.rs +++ b/parquet/src/util/bit_util.rs @@ -223,6 +223,20 @@ impl BitWriter { } } + /// Extend buffer size + #[inline] + pub fn extend(&mut self, increment: usize) { + self.max_bytes += increment; + let extra = vec![0; increment]; + self.buffer.extend(extra); + } + + /// Report buffer size + #[inline] + pub fn capacity(&mut self) -> usize { + self.max_bytes + } + /// Consumes and returns the current buffer. #[inline] pub fn consume(mut self) -> Vec<u8> {
diff --git a/parquet/tests/boolean_writer.rs b/parquet/tests/boolean_writer.rs new file mode 100644 index 000000000000..b9d757e71a8e --- /dev/null +++ b/parquet/tests/boolean_writer.rs @@ -0,0 +1,100 @@ +// 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. + +use parquet::column::writer::ColumnWriter; +use parquet::file::properties::WriterProperties; +use parquet::file::reader::FileReader; +use parquet::file::serialized_reader::SerializedFileReader; +use parquet::file::writer::FileWriter; +use parquet::file::writer::SerializedFileWriter; +use parquet::schema::parser::parse_message_type; +use std::fs; +use std::path::Path; +use std::sync::{mpsc, Arc}; +use std::thread; +use std::time::Duration; + +#[test] +fn it_writes_data_without_hanging() { + let path = Path::new("it_writes_data_without_hanging.parquet"); + + let message_type = " + message BooleanType { + REQUIRED BOOLEAN DIM0; + } +"; + let schema = Arc::new(parse_message_type(message_type).expect("parse schema")); + let props = Arc::new(WriterProperties::builder().build()); + let file = fs::File::create(&path).expect("create file"); + let mut writer = + SerializedFileWriter::new(file, schema, props).expect("create parquet writer"); + for _group in 0..1 { + let mut row_group_writer = writer.next_row_group().expect("get row group writer"); + let values: Vec<i64> = vec![0; 2049]; + let my_bool_values: Vec<bool> = values + .iter() + .enumerate() + .map(|(count, _x)| count % 2 == 0) + .collect(); + while let Some(mut col_writer) = + row_group_writer.next_column().expect("next column") + { + match col_writer { + ColumnWriter::BoolColumnWriter(ref mut typed_writer) => { + typed_writer + .write_batch(&my_bool_values, None, None) + .expect("writing bool column"); + } + _ => { + panic!("only test boolean values"); + } + } + row_group_writer + .close_column(col_writer) + .expect("close column"); + } + let rg_md = row_group_writer.close().expect("close row group"); + println!("total rows written: {}", rg_md.num_rows()); + writer + .close_row_group(row_group_writer) + .expect("close row groups"); + } + writer.close().expect("close writer"); + + let bytes = fs::read(&path).expect("read file"); + assert_eq!(&bytes[0..4], &[b'P', b'A', b'R', b'1']); + + // Now that we have written our data and are happy with it, make + // sure we can read it back in < 5 seconds... + let (sender, receiver) = mpsc::channel(); + let _t = thread::spawn(move || { + let file = fs::File::open(&Path::new("it_writes_data_without_hanging.parquet")) + .expect("open file"); + let reader = SerializedFileReader::new(file).expect("get serialized reader"); + let iter = reader.get_row_iter(None).expect("get iterator"); + for record in iter { + println!("reading: {}", record); + } + println!("finished reading"); + if let Ok(()) = sender.send(true) {} + }); + assert_ne!( + Err(mpsc::RecvTimeoutError::Timeout), + receiver.recv_timeout(Duration::from_millis(5000)) + ); + fs::remove_file("it_writes_data_without_hanging.parquet").expect("remove file"); +}
parquet reading hangs when row_group contains more than 2048 rows of data **Describe the bug** Reading an apparently valid parquet file (which can be read by java tools such as parquet-tools) from any rust program will hang. CPU load goes to 100%. Reproduced on both 4.0.0 and 4.1.0. rustc: 1.51.0 **To Reproduce** Create a parquet file with at least 1 row group (e.g.: 1). Each row group must have > 2048 rows (e.g.: 2049). Run a (rust) program to read the file and it will hang when visiting the 2048th row. Java program (parquet-tools) reads with no issue. This test program can be used to produce a file that can then be read using parquet-read to reproduce: ``` #[test] fn it_writes_data() { let path = Path::new("sample.parquet"); let message_type = " message ItHangs { REQUIRED INT64 DIM0; REQUIRED DOUBLE DIM1; REQUIRED BYTE_ARRAY DIM2; REQUIRED BOOLEAN DIM3; } "; let schema = Arc::new(parse_message_type(message_type).unwrap()); let props = Arc::new(WriterProperties::builder().build()); let file = fs::File::create(&path).unwrap(); let mut writer = SerializedFileWriter::new(file, schema, props).unwrap(); for _group in 0..1 { let mut row_group_writer = writer.next_row_group().unwrap(); let values: Vec<i64> = vec![0; 2049]; let my_values: Vec<i64> = values .iter() .enumerate() .map(|(count, _x)| count.try_into().unwrap()) .collect(); let my_double_values: Vec<f64> = values .iter() .enumerate() .map(|(count, _x)| count as f64) .collect(); let my_bool_values: Vec<bool> = values .iter() .enumerate() .map(|(count, _x)| count % 2 == 0) .collect(); let my_ba_values: Vec<ByteArray> = values .iter() .enumerate() .map(|(count, _x)| { let s = format!("{}", count); ByteArray::from(s.as_ref()) }) .collect(); while let Some(mut col_writer) = row_group_writer.next_column().expect("next column") { match col_writer { // ... write values to a column writer // You can also use `get_typed_column_writer` method to extract typed writer. ColumnWriter::Int64ColumnWriter(ref mut typed_writer) => { typed_writer .write_batch(&my_values, None, None) .expect("writing int column"); } ColumnWriter::DoubleColumnWriter(ref mut typed_writer) => { typed_writer .write_batch(&my_double_values, None, None) .expect("writing double column"); } ColumnWriter::BoolColumnWriter(ref mut typed_writer) => { typed_writer .write_batch(&my_bool_values, None, None) .expect("writing bool column"); } ColumnWriter::ByteArrayColumnWriter(ref mut typed_writer) => { typed_writer .write_batch(&my_ba_values, None, None) .expect("writing bytes column"); } _ => { println!("huh:!"); } } row_group_writer .close_column(col_writer) .expect("close column"); } let rg_md = row_group_writer.close().expect("close row group"); println!("total rows written: {}", rg_md.num_rows()); writer .close_row_group(row_group_writer) .expect("close row groups"); } writer.close().expect("close writer"); let bytes = fs::read(&path).unwrap(); assert_eq!(&bytes[0..4], &[b'P', b'A', b'R', b'1']); } ``` **Expected behavior** The read will complete without hanging. **Additional context** My development system is Mac OS X, so only tested on OS X. rustup reports: active toolchain ---------------- 1.51.0-x86_64-apple-darwin (default) rustc 1.51.0 (2fd73fabe 2021-03-23)
Thanks for the report @garyanaplan ! yw. Extra Info: It happens with debug or release builds and I reproduced it with 1.51.0 on a linux system. I've also just encountered it. Common element with this reproduction is BOOLEAN field. It worked without BOOLEAN as well. After quick investigation of the looping code, I've found something suspect, but it's just about naming - not sure if it's actual bug. This function returns something initialized as input's length and called `values_to_read`: https://github.com/apache/arrow-rs/blob/0f55b828883b3b3afda43ae404b130d374e6f1a1/parquet/src/util/bit_util.rs#L588 Meanwhile calling site (which I can't find on Github, because admittedly I'm using older version - will add it later) assigns the return value to `values_read`. Btw it loops because after reading 2048 values, this returned value is 0. Yep. If I update my test to remove BOOLEAN from the schema, the problem goes away. I've done some digging around today and noticed that it looks like the problem might lie in the generation of the file. I previously reported that parquet-tools dump <file> would happily process the file, however I trimmed down the example to just include BOOLEAN field in schema and increased the number of rows in the group and noted the following when dumping: `value 2039: R:0 D:0 V:true value 2040: R:0 D:0 V:false value 2041: R:0 D:0 V:true value 2042: R:0 D:0 V:false value 2043: R:0 D:0 V:true value 2044: R:0 D:0 V:false value 2045: R:0 D:0 V:true value 2046: R:0 D:0 V:false value 2047: R:0 D:0 V:true value 2048: R:0 D:0 V:false value 2049: R:0 D:0 V:false value 2050: R:0 D:0 V:false value 2051: R:0 D:0 V:false value 2052: R:0 D:0 V:false value 2053: R:0 D:0 V:false value 2054: R:0 D:0 V:false value 2055: R:0 D:0 V:false ` All the values after 2048 are false and they continue to be false until the end of the file. It looks like the generated input file is invalid, so I'm going to poke around there a little next. More poking reveals that PlainEncoder has a bit_writer with a hard-coded size of 256 (big enough to hold 2048 bits...). `src/encodings/encoding.rs: line bit_writer: BitWriter::new(256), ` If you adjust that value up or down you trip the error at different times. So, that looks like it's a contributing factor. I'm now trying to understand the logic around buffer flushing and re-use. Feel, like I'm getting close to the root cause. Looks like that hard-coded value (256) in the bit-writer is the root cause. When writing, if we try to put > 2048 boolean values, then the writer just "ignores" the writes. This is caused by the fact that bool encoder silently ignores calls to put_value that return false. I have a fix for this which works by extending the size of the BitWriter (in 256 byte) increments and also checks the return of put_value in BoolType::encode() and raises an error if the call fails. Can anyone comment on this approach? (diff attached) [a.diff.txt](https://github.com/apache/arrow-rs/files/6631262/a.diff.txt) @garyanaplan -- I think the best way to get feedback on the approach would be to open a pull request Yeah. I'm not really happy with it, because I don't love the special handling for Booleans via the BitWriter. Just growing the buffer indefinitely seems "wrong", but I think any other kind of fix would be much more extensive/intrusive. I'll file the PR and see what feedback I get.
2021-06-10T13:13:10Z
0.3
4c7d4189e72901a78fb4f4250c11421241dd9e13
[ "it_writes_data_without_hanging" ]
[ "parquet/src/compression.rs - compression (line 25) - compile", "parquet/src/file/mod.rs - file (line 29) - compile", "parquet/src/arrow/mod.rs - arrow (line 25) - compile", "parquet/src/file/mod.rs - file (line 64) - compile", "parquet/src/file/mod.rs - file (line 81) - compile", "parquet/src/record/api.rs - record::api::Row::get_column_iter (line 62) - compile", "parquet/src/column/mod.rs - column (line 38) - compile", "parquet/src/file/properties.rs - file::properties (line 22)", "parquet/src/file/statistics.rs - file::statistics (line 23)", "parquet/src/schema/types.rs - schema::types::ColumnPath::string (line 663)", "parquet/src/schema/mod.rs - schema (line 22)", "parquet/src/schema/printer.rs - schema::printer (line 23)", "parquet/src/schema/parser.rs - schema::parser (line 24)", "parquet/src/schema/types.rs - schema::types::ColumnPath::append (line 674)" ]
[]
[]
apache/arrow-rs
4,201
apache__arrow-rs-4201
[ "1936" ]
378a9fcc9ee31fff4a9a13f5de5a326dc449541e
diff --git a/arrow-cast/src/cast.rs b/arrow-cast/src/cast.rs index 37fede0a6fe0..2b286bfa9119 100644 --- a/arrow-cast/src/cast.rs +++ b/arrow-cast/src/cast.rs @@ -35,7 +35,7 @@ //! assert_eq!(7.0, c.value(2)); //! ``` -use chrono::{NaiveTime, TimeZone, Timelike, Utc}; +use chrono::{NaiveTime, Offset, TimeZone, Timelike, Utc}; use std::cmp::Ordering; use std::sync::Arc; @@ -1770,7 +1770,7 @@ pub fn cast_with_options( tz.clone(), )), - (Timestamp(from_unit, _), Timestamp(to_unit, to_tz)) => { + (Timestamp(from_unit, from_tz), Timestamp(to_unit, to_tz)) => { let array = cast_with_options(array, &Int64, cast_options)?; let time_array = array.as_primitive::<Int64Type>(); let from_size = time_unit_multiple(from_unit); @@ -1792,8 +1792,52 @@ pub fn cast_with_options( } } }; + // Normalize timezone + let adjusted = match (from_tz, to_tz) { + // Only this case needs to be adjusted because we're casting from + // unknown time offset to some time offset, we want the time to be + // unchanged. + // + // i.e. Timestamp('2001-01-01T00:00', None) -> Timestamp('2001-01-01T00:00', '+0700') + (None, Some(to_tz)) => { + let to_tz: Tz = to_tz.parse()?; + match to_unit { + TimeUnit::Second => { + adjust_timestamp_to_timezone::<TimestampSecondType>( + converted, + &to_tz, + cast_options, + )? + } + TimeUnit::Millisecond => { + adjust_timestamp_to_timezone::<TimestampMillisecondType>( + converted, + &to_tz, + cast_options, + )? + } + TimeUnit::Microsecond => { + adjust_timestamp_to_timezone::<TimestampMicrosecondType>( + converted, + &to_tz, + cast_options, + )? + } + TimeUnit::Nanosecond => { + adjust_timestamp_to_timezone::<TimestampNanosecondType>( + converted, + &to_tz, + cast_options, + )? + } + } + } + _ => { + converted + } + }; Ok(make_timestamp_array( - &converted, + &adjusted, to_unit.clone(), to_tz.clone(), )) @@ -3005,6 +3049,30 @@ fn cast_string_to_month_day_nano_interval<Offset: OffsetSizeTrait>( Ok(Arc::new(interval_array) as ArrayRef) } +fn adjust_timestamp_to_timezone<T: ArrowTimestampType>( + array: PrimitiveArray<Int64Type>, + to_tz: &Tz, + cast_options: &CastOptions, +) -> Result<PrimitiveArray<Int64Type>, ArrowError> { + let adjust = |o| { + let local = as_datetime::<T>(o)?; + let offset = to_tz.offset_from_local_datetime(&local).single()?; + T::make_value(local - offset.fix()) + }; + let adjusted = if cast_options.safe { + array.unary_opt::<_, Int64Type>(adjust) + } else { + array.try_unary::<_, Int64Type, _>(|o| { + adjust(o).ok_or_else(|| { + ArrowError::CastError( + "Cannot cast timezone to different timezone".to_string(), + ) + }) + })? + }; + Ok(adjusted) +} + /// Casts Utf8 to Boolean fn cast_utf8_to_boolean<OffsetSize>( from: &dyn Array, @@ -5978,6 +6046,83 @@ mod tests { assert!(b.is_err()); } + // Cast Timestamp(_, None) -> Timestamp(_, Some(timezone)) + #[test] + fn test_cast_timestamp_with_timezone_1() { + let string_array: Arc<dyn Array> = Arc::new(StringArray::from(vec![ + Some("2000-01-01T00:00:00.123456789"), + Some("2010-01-01T00:00:00.123456789"), + None, + ])); + let to_type = DataType::Timestamp(TimeUnit::Nanosecond, None); + let timestamp_array = cast(&string_array, &to_type).unwrap(); + + let to_type = DataType::Timestamp(TimeUnit::Microsecond, Some("+0700".into())); + let timestamp_array = cast(&timestamp_array, &to_type).unwrap(); + + let string_array = cast(&timestamp_array, &DataType::Utf8).unwrap(); + let result = string_array.as_string::<i32>(); + assert_eq!("2000-01-01T00:00:00.123456+07:00", result.value(0)); + assert_eq!("2010-01-01T00:00:00.123456+07:00", result.value(1)); + assert!(result.is_null(2)); + } + + // Cast Timestamp(_, Some(timezone)) -> Timestamp(_, None) + #[test] + fn test_cast_timestamp_with_timezone_2() { + let string_array: Arc<dyn Array> = Arc::new(StringArray::from(vec![ + Some("2000-01-01T07:00:00.123456789"), + Some("2010-01-01T07:00:00.123456789"), + None, + ])); + let to_type = DataType::Timestamp(TimeUnit::Millisecond, Some("+0700".into())); + let timestamp_array = cast(&string_array, &to_type).unwrap(); + + // Check intermediate representation is correct + let string_array = cast(&timestamp_array, &DataType::Utf8).unwrap(); + let result = string_array.as_string::<i32>(); + assert_eq!("2000-01-01T07:00:00.123+07:00", result.value(0)); + assert_eq!("2010-01-01T07:00:00.123+07:00", result.value(1)); + assert!(result.is_null(2)); + + let to_type = DataType::Timestamp(TimeUnit::Nanosecond, None); + let timestamp_array = cast(&timestamp_array, &to_type).unwrap(); + + let string_array = cast(&timestamp_array, &DataType::Utf8).unwrap(); + let result = string_array.as_string::<i32>(); + assert_eq!("2000-01-01T00:00:00.123", result.value(0)); + assert_eq!("2010-01-01T00:00:00.123", result.value(1)); + assert!(result.is_null(2)); + } + + // Cast Timestamp(_, Some(timezone)) -> Timestamp(_, Some(timezone)) + #[test] + fn test_cast_timestamp_with_timezone_3() { + let string_array: Arc<dyn Array> = Arc::new(StringArray::from(vec![ + Some("2000-01-01T07:00:00.123456789"), + Some("2010-01-01T07:00:00.123456789"), + None, + ])); + let to_type = DataType::Timestamp(TimeUnit::Microsecond, Some("+0700".into())); + let timestamp_array = cast(&string_array, &to_type).unwrap(); + + // Check intermediate representation is correct + let string_array = cast(&timestamp_array, &DataType::Utf8).unwrap(); + let result = string_array.as_string::<i32>(); + assert_eq!("2000-01-01T07:00:00.123456+07:00", result.value(0)); + assert_eq!("2010-01-01T07:00:00.123456+07:00", result.value(1)); + assert!(result.is_null(2)); + + let to_type = DataType::Timestamp(TimeUnit::Second, Some("-08:00".into())); + let timestamp_array = cast(&timestamp_array, &to_type).unwrap(); + + let string_array = cast(&timestamp_array, &DataType::Utf8).unwrap(); + let result = string_array.as_string::<i32>(); + assert_eq!("1999-12-31T16:00:00-08:00", result.value(0)); + assert_eq!("2009-12-31T16:00:00-08:00", result.value(1)); + assert!(result.is_null(2)); + } + #[test] fn test_cast_date64_to_timestamp() { let array =
diff --git a/arrow/tests/array_cast.rs b/arrow/tests/array_cast.rs index bf7e7a326efc..43dc6dd0eb0a 100644 --- a/arrow/tests/array_cast.rs +++ b/arrow/tests/array_cast.rs @@ -18,6 +18,7 @@ use arrow_array::builder::{ PrimitiveDictionaryBuilder, StringDictionaryBuilder, UnionBuilder, }; +use arrow_array::cast::AsArray; use arrow_array::types::{ ArrowDictionaryKeyType, Decimal128Type, Decimal256Type, Int16Type, Int32Type, Int64Type, Int8Type, TimestampMicrosecondType, UInt16Type, UInt32Type, UInt64Type, @@ -64,6 +65,97 @@ fn test_cast_timestamp_to_string() { assert!(c.is_null(2)); } +// See: https://en.wikipedia.org/wiki/List_of_tz_database_time_zones for list of valid +// timezones + +// Cast Timestamp(_, None) -> Timestamp(_, Some(timezone)) +#[test] +fn test_cast_timestamp_with_timezone_daylight_1() { + let string_array: Arc<dyn Array> = Arc::new(StringArray::from(vec![ + // This is winter in New York so daylight saving is not in effect + // UTC offset is -05:00 + Some("2000-01-01T00:00:00.123456789"), + // This is summer in New York so daylight saving is in effect + // UTC offset is -04:00 + Some("2010-07-01T00:00:00.123456789"), + None, + ])); + let to_type = DataType::Timestamp(TimeUnit::Nanosecond, None); + let timestamp_array = cast(&string_array, &to_type).unwrap(); + + let to_type = + DataType::Timestamp(TimeUnit::Microsecond, Some("America/New_York".into())); + let timestamp_array = cast(&timestamp_array, &to_type).unwrap(); + + let string_array = cast(&timestamp_array, &DataType::Utf8).unwrap(); + let result = string_array.as_string::<i32>(); + assert_eq!("2000-01-01T00:00:00.123456-05:00", result.value(0)); + assert_eq!("2010-07-01T00:00:00.123456-04:00", result.value(1)); + assert!(result.is_null(2)); +} + +// Cast Timestamp(_, Some(timezone)) -> Timestamp(_, None) +#[test] +fn test_cast_timestamp_with_timezone_daylight_2() { + let string_array: Arc<dyn Array> = Arc::new(StringArray::from(vec![ + Some("2000-01-01T07:00:00.123456789"), + Some("2010-07-01T07:00:00.123456789"), + None, + ])); + let to_type = + DataType::Timestamp(TimeUnit::Millisecond, Some("America/New_York".into())); + let timestamp_array = cast(&string_array, &to_type).unwrap(); + + // Check intermediate representation is correct + let string_array = cast(&timestamp_array, &DataType::Utf8).unwrap(); + let result = string_array.as_string::<i32>(); + assert_eq!("2000-01-01T07:00:00.123-05:00", result.value(0)); + assert_eq!("2010-07-01T07:00:00.123-04:00", result.value(1)); + assert!(result.is_null(2)); + + let to_type = DataType::Timestamp(TimeUnit::Nanosecond, None); + let timestamp_array = cast(&timestamp_array, &to_type).unwrap(); + + let string_array = cast(&timestamp_array, &DataType::Utf8).unwrap(); + let result = string_array.as_string::<i32>(); + assert_eq!("2000-01-01T12:00:00.123", result.value(0)); + assert_eq!("2010-07-01T11:00:00.123", result.value(1)); + assert!(result.is_null(2)); +} + +// Cast Timestamp(_, Some(timezone)) -> Timestamp(_, Some(timezone)) +#[test] +fn test_cast_timestamp_with_timezone_daylight_3() { + let string_array: Arc<dyn Array> = Arc::new(StringArray::from(vec![ + // Winter in New York, summer in Sydney + // UTC offset is -05:00 (New York) and +11:00 (Sydney) + Some("2000-01-01T00:00:00.123456789"), + // Summer in New York, winter in Sydney + // UTC offset is -04:00 (New York) and +10:00 (Sydney) + Some("2010-07-01T00:00:00.123456789"), + None, + ])); + let to_type = + DataType::Timestamp(TimeUnit::Microsecond, Some("America/New_York".into())); + let timestamp_array = cast(&string_array, &to_type).unwrap(); + + // Check intermediate representation is correct + let string_array = cast(&timestamp_array, &DataType::Utf8).unwrap(); + let result = string_array.as_string::<i32>(); + assert_eq!("2000-01-01T00:00:00.123456-05:00", result.value(0)); + assert_eq!("2010-07-01T00:00:00.123456-04:00", result.value(1)); + assert!(result.is_null(2)); + + let to_type = DataType::Timestamp(TimeUnit::Second, Some("Australia/Sydney".into())); + let timestamp_array = cast(&timestamp_array, &to_type).unwrap(); + + let string_array = cast(&timestamp_array, &DataType::Utf8).unwrap(); + let result = string_array.as_string::<i32>(); + assert_eq!("2000-01-01T16:00:00+11:00", result.value(0)); + assert_eq!("2010-07-01T14:00:00+10:00", result.value(1)); + assert!(result.is_null(2)); +} + #[test] #[cfg_attr(miri, ignore)] // running forever fn test_can_cast_types() {
Cast Kernel Ignores Timezone **Is your feature request related to a problem or challenge? Please describe what you are trying to do.** The beginnings of timezone support were added in #824, however, this is currently ignored by the cast kernel **Describe the solution you'd like** Timezones should be correctly handled by the cast kernel **Describe alternatives you've considered** We could not support timezones **Additional context** Noticed whilst investigating #1932
I'd like to work on this. And I think `fmt` of timestamp array cannot ignore timezone too. Could you assign it to me? @tustvold I would recommend writing up the expected behaviour first, as timezone handling is notoriously messy, and once we have consensus we can move forward with implementing that. FYI @avantgardnerio @waitingkuo @tustvold thank you for pinging me, i'm working on these things now as well. @doki23 it would be great if you could help ❤️ You could find some other related issues here apache/arrow-datafusion#3148 (search timezone) some hints that might help 1 https://github.com/apache/arrow-rs/blob/3bf6eb98ceb3962e1d9419da6dc93e609f7893e6/arrow/src/compute/kernels/cast.rs#L1284 to make casting function consider timezone, we have to fix the second `_` identifier and check whether it's `None` or `Some` 2 https://github.com/apache/arrow-rs/blob/3bf6eb98ceb3962e1d9419da6dc93e609f7893e6/arrow/src/array/array_primitive.rs#L209 while using fmt to print, we first convert it to `NaiveDateTime` (from chrono-rs) which contains no timezone info so that you could only see timestamp without timezone @doki23 are you planning to draft the proposal? > @doki23 are you planning to draft the proposal? sure, plz wait me hours We consider tz only if from_type and to_type both needs it. For example, ignoring tz is ok when we cast ts to i64, because i64 array doesn't care about timezone. So, there're 2 situations: 1. ts is from_type, and the to_type needs tz. 2. ts is to_type, and the from_type has tz. I noticed that timestamp array is always treat as `PrimitiveArray`. We can't get tz from `ArrowPrimitiveType::DATA_TYPE`, because there're only utc ts definitions like: ```rust make_type!( TimestampSecondType, i64, DataType::Timestamp(TimeUnit::Second, None) ); ``` So, we may need a `TimestampBuilder` in place of `TimestampSecondArray::from_xxx` which can realize the timezone. And it has a valid `ArrayData::data_type`. what's expected behavior for casting timestamp with timezone to timestamp without time zone? e.g. if the timestamp with timezone is `1970-01-01T08:00:00+08:00` (note that the timestamp underline is 0), what's the casted result? `1970-01-01T08:00:00` (underline timestamp as 28800000000000) or `1970-01-01T00:00:00` (underline timestamp as 0)? i recommend that listing these ambiguous cases and your proposed behavior so we could discuss btw i tested it on pyarrow, it simply changes the datatype but not change the underline timestamp (`1970-01-01T08:00:00+08:00` becomes `1970-01-01T00:00:00` > what's expected behavior for casting timestamp with timezone to timestamp without time zone? The intuitive answer would be to convert it to UTC. I think postgres effectively casts it to server (local) time. I believe this section of the arrow schema definition is relevant - https://github.com/apache/arrow-rs/blob/master/format/Schema.fbs#L280 In particular > One possibility is to assume that the original timestamp values are relative to the epoch of the timezone being set; timestamp values should then adjusted to the Unix epoch Given this is the only possibility enumerated in the schema, I feel this is probably the one we should follow unless people feel strongly otherwise. My 2 cents is that anything relying on the local timezone of the system is best avoided if at all possible, it just feels fragile and error-prone. > local timezone of the system Yes - these RecordBatches could be part of Flights, yes? In which case the whole point is to send them around to different computers that may be in different timezones, so it kind of forces our hand here. And if we are doing it this way in arrow where we don't have the luxury of following postgres, maybe this is also where we break postgres compatibility in DataFusion. Just because postgres did it wrong doesn't mean we should follow... > what's expected behavior for casting timestamp with timezone to timestamp without time zone? Tz has no affect to the value of timestamp, it's just used for display. > what's expected behavior for casting timestamp with timezone to timestamp without time zone? The specification states > /// However, if a Timestamp column has no timezone value, changing it to a > /// non-empty value requires to think about the desired semantics. > /// One possibility is to assume that the original timestamp values are > /// relative to the epoch of the timezone being set; timestamp values should > /// then adjusted to the Unix epoch (for example, changing the timezone from > /// empty to "Europe/Paris" would require converting the timestamp values > /// from "Europe/Paris" to "UTC", which seems counter-intuitive but is > /// nevertheless correct). As stated above, given this is the only possibility enumerated I think we should follow this. The inverse operation, i.e. removing a timezone, I would therefore expect to do the reverse i.e. `1970-01-01 01:00:01 +01:00` would become `1970-01-01 01:00:01`. This is consistent with both postgres and chrono. thank you @tustvold , didn't aware this spec before This looks good to me btw, i think `with_timezone_opt` already covered another possibility - keep the underline i64 value and change the metadata Yeah let's do the "hard" operation in the cast kernel, and if people don't like it, they can perform a metadata-only cast using`with_timezone_opt` :+1: https://github.com/apache/arrow-rs/issues/3794 is related to this, and implements the necessary machinery for timezone aware parsing of strings
2023-05-11T11:37:13Z
39.0
378a9fcc9ee31fff4a9a13f5de5a326dc449541e
[ "test_cast_timestamp_with_timezone_daylight_1" ]
[ "arrow/src/lib.rs - (line 121)", "arrow/src/lib.rs - (line 140)", "arrow/src/lib.rs - (line 253)", "arrow/src/lib.rs - (line 282)", "arrow/src/lib.rs - (line 78)", "arrow/src/util/string_writer.rs - util::string_writer (line 25)", "arrow/src/lib.rs - (line 63)", "arrow/src/lib.rs - (line 97)", "arrow/src/lib.rs - (line 227)", "arrow/src/lib.rs - (line 161)", "arrow/src/lib.rs - (line 198)", "test_cast_timestamp_to_string", "test_pretty_format_timestamp_second_with_incorrect_fixed_offset_timezone", "test_cast_timestamp_with_timezone_daylight_3", "test_pretty_format_timestamp_second_with_non_utc_timezone", "test_cast_timestamp_with_timezone_daylight_2", "test_pretty_format_timestamp_second_with_unknown_timezone", "test_timestamp_cast_utf8", "test_pretty_format_timestamp_second_with_utc_timezone", "test_can_cast_types" ]
[]
[]
apache/arrow-rs
5,717
apache__arrow-rs-5717
[ "5716" ]
a126d5097b71273428fba68d1c430f3d4beee684
diff --git a/parquet_derive/src/parquet_field.rs b/parquet_derive/src/parquet_field.rs index 9fff76c42d1d..f99ea3e0356c 100644 --- a/parquet_derive/src/parquet_field.rs +++ b/parquet_derive/src/parquet_field.rs @@ -239,7 +239,8 @@ impl Field { /// because this parsing logic is not sophisticated enough for definition /// levels beyond 2. /// - /// `Option` types and references not supported + /// `Option` types and references not supported, but the column itself can be nullable + /// (i.e., def_level==1), as long as the values are all valid. pub fn reader_snippet(&self) -> proc_macro2::TokenStream { let ident = &self.ident; let column_reader = self.ty.column_reader(); @@ -248,7 +249,13 @@ impl Field { let write_batch_expr = quote! { let mut vals = Vec::new(); if let #column_reader(mut typed) = column_reader { - typed.read_records(num_records, None, None, &mut vals)?; + let mut definition_levels = Vec::new(); + let (total_num, valid_num, decoded_num) = typed.read_records( + num_records, Some(&mut definition_levels), None, &mut vals)?; + if valid_num != decoded_num { + panic!("Support only valid records, found {} null records in column type {}", + decoded_num - valid_num, stringify!{#ident}); + } } else { panic!("Schema and struct disagree on type for {}", stringify!{#ident}); } @@ -876,15 +883,21 @@ mod test { snippet, (quote! { { - let mut vals = Vec::new(); - if let ColumnReader::Int64ColumnReader(mut typed) = column_reader { - typed.read_records(num_records, None, None, &mut vals)?; - } else { - panic!("Schema and struct disagree on type for {}", stringify!{ counter }); - } - for (i, r) in &mut records[..num_records].iter_mut().enumerate() { - r.counter = vals[i] as usize; - } + let mut vals = Vec::new(); + if let ColumnReader::Int64ColumnReader(mut typed) = column_reader { + let mut definition_levels = Vec::new(); + let (total_num, valid_num, decoded_num) = typed.read_records( + num_records, Some(&mut definition_levels), None, &mut vals)?; + if valid_num != decoded_num { + panic!("Support only valid records, found {} null records in column type {}", + decoded_num - valid_num, stringify!{counter}); + } + } else { + panic!("Schema and struct disagree on type for {}", stringify!{counter}); + } + for (i, r) in &mut records[..num_records].iter_mut().enumerate() { + r.counter = vals[i] as usize; + } } }) .to_string() @@ -1291,7 +1304,13 @@ mod test { { let mut vals = Vec::new(); if let ColumnReader::Int64ColumnReader(mut typed) = column_reader { - typed.read_records(num_records, None, None, &mut vals)?; + let mut definition_levels = Vec::new(); + let (total_num, valid_num, decoded_num) = typed.read_records( + num_records, Some(&mut definition_levels), None, &mut vals)?; + if valid_num != decoded_num { + panic!("Support only valid records, found {} null records in column type {}", + decoded_num - valid_num, stringify!{henceforth}); + } } else { panic!("Schema and struct disagree on type for {}", stringify!{ henceforth }); } @@ -1359,7 +1378,13 @@ mod test { { let mut vals = Vec::new(); if let ColumnReader::Int32ColumnReader(mut typed) = column_reader { - typed.read_records(num_records, None, None, &mut vals)?; + let mut definition_levels = Vec::new(); + let (total_num, valid_num, decoded_num) = typed.read_records( + num_records, Some(&mut definition_levels), None, &mut vals)?; + if valid_num != decoded_num { + panic!("Support only valid records, found {} null records in column type {}", + decoded_num - valid_num, stringify!{henceforth}); + } } else { panic!("Schema and struct disagree on type for {}", stringify!{ henceforth }); } @@ -1427,7 +1452,13 @@ mod test { { let mut vals = Vec::new(); if let ColumnReader::FixedLenByteArrayColumnReader(mut typed) = column_reader { - typed.read_records(num_records, None, None, &mut vals)?; + let mut definition_levels = Vec::new(); + let (total_num, valid_num, decoded_num) = typed.read_records( + num_records, Some(&mut definition_levels), None, &mut vals)?; + if valid_num != decoded_num { + panic!("Support only valid records, found {} null records in column type {}", + decoded_num - valid_num, stringify!{unique_id}); + } } else { panic!("Schema and struct disagree on type for {}", stringify!{ unique_id }); }
diff --git a/parquet_derive_test/src/lib.rs b/parquet_derive_test/src/lib.rs index 3743c6b55c7c..e168ad5b980a 100644 --- a/parquet_derive_test/src/lib.rs +++ b/parquet_derive_test/src/lib.rs @@ -66,6 +66,25 @@ struct APartiallyCompleteRecord { pub byte_vec: Vec<u8>, } +// This struct has OPTIONAL columns +// If these fields are guaranteed to be valid +// we can load this struct into APartiallyCompleteRecord +#[derive(PartialEq, ParquetRecordWriter, Debug)] +struct APartiallyOptionalRecord { + pub bool: bool, + pub string: String, + pub maybe_i16: Option<i16>, + pub maybe_i32: Option<i32>, + pub maybe_u64: Option<u64>, + pub isize: isize, + pub float: f32, + pub double: f64, + pub now: chrono::NaiveDateTime, + pub date: chrono::NaiveDate, + pub uuid: uuid::Uuid, + pub byte_vec: Vec<u8>, +} + #[cfg(test)] mod tests { use super::*; @@ -218,6 +237,47 @@ mod tests { assert_eq!(drs[0], out[0]); } + #[test] + fn test_parquet_derive_read_optional_but_valid_column() { + let file = get_temp_file("test_parquet_derive_read_optional", &[]); + let drs: Vec<APartiallyOptionalRecord> = vec![APartiallyOptionalRecord { + bool: true, + string: "a string".into(), + maybe_i16: Some(-45), + maybe_i32: Some(456), + maybe_u64: Some(4563424), + isize: -365, + float: 3.5, + double: std::f64::NAN, + now: chrono::Utc::now().naive_local(), + date: chrono::naive::NaiveDate::from_ymd_opt(2015, 3, 14).unwrap(), + uuid: uuid::Uuid::new_v4(), + byte_vec: vec![0x65, 0x66, 0x67], + }]; + + let generated_schema = drs.as_slice().schema().unwrap(); + + let props = Default::default(); + let mut writer = + SerializedFileWriter::new(file.try_clone().unwrap(), generated_schema, props).unwrap(); + + let mut row_group = writer.next_row_group().unwrap(); + drs.as_slice().write_to_row_group(&mut row_group).unwrap(); + row_group.close().unwrap(); + writer.close().unwrap(); + + use parquet::file::{reader::FileReader, serialized_reader::SerializedFileReader}; + let reader = SerializedFileReader::new(file).unwrap(); + let mut out: Vec<APartiallyCompleteRecord> = Vec::new(); + + let mut row_group = reader.get_row_group(0).unwrap(); + out.read_from_row_group(&mut *row_group, 1).unwrap(); + + assert_eq!(drs[0].maybe_i16.unwrap(), out[0].i16); + assert_eq!(drs[0].maybe_i32.unwrap(), out[0].i32); + assert_eq!(drs[0].maybe_u64.unwrap(), out[0].u64); + } + /// Returns file handle for a temp file in 'target' directory with a provided content pub fn get_temp_file(file_name: &str, content: &[u8]) -> fs::File { // build tmp path to a file in "target/debug/testdata"
[parquet_derive] support OPTIONAL (def_level = 1) columns by default ## Problem Description <!-- A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] (This section helps Arrow developers understand the context and *why* for this feature, in addition to the *what*) --> I'm working on parquet files written by `pyarrow` (embedded in `pandas`). I came across `parquet_derive` and it avoids boilerplates in my project. The problem is, it doesn't work on the parquet files that is written by `pandas` with default setup, it throws error information: ```text Parquet error: must specify definition levels ``` After digging into this, I found that the problem is the parquet file generated by `pyarrow` has def_level=1, i.e., every column, even without a null value, is OPTIONAL. <img width="677" alt="image" src="https://github.com/apache/arrow-rs/assets/27212391/b6b4cc96-8c53-4d41-9c66-4f802476dd7a"> However, the macro generate code that does not allow definition level, thus it fails to parsing columns with OPTIONAL value, even there is no actual NULL values: ```rust typed.read_records(num_records, None, None, &mut vals)?; ``` The API it calls is: https://docs.rs/parquet/latest/parquet/column/reader/struct.GenericColumnReader.html#method.read_records . ## My Solution The solution is straight-forward. I have fixed the problem locally, I'm willing to contribute a pull request, but I don't know if this solution is reasonable in the scope of the whole `arrow` project. Basically, I think we need to provide definition level in `read_record`: ```rust typed.read_records(num_records, None /*should use a Some(&mut Vec<i16>)*/, None, &mut vals)?; ``` In one word, with this solution, `parquet_derive` can now handle: 1. (already supported) parquet file with all columns REQUIRED 2. **(new introduced) parquet file with OPTIONAL columns but are always guaranteed to be valid**. ### Pros - This solution does not break current features - This solution makes parquet_derive more general in handling parquet files. It can pass the tests in `parquet_derive_tests`. I also add checks against the parsed records and valid records, to avoid abusing it for columns with NULLs. ### Cons - It will be slightly slower since it allocates an extra `Vec<i16>` for each column when invoking `read_from_row_group`. I don't think it is a big deal, though, compared to the inconvenience of not supporting OPTIONAL columns. Moreover, we can make use of the max_def_levels (for REQUIRED column, it is 0) to skip creating the Vec.
What happens if you specify the field as `Option` to match the schema? > What happens if you specify the field as `Option` to match the schema? I have tried, it does not work, because: 1. the OPTIONAL, REQUIRED, REPEATED tags are generated automatically in the macro. 2. even I workaround 1 by enforce the field to be OPTIONAL, the actual parsing code, i.e.: ```rust typed.read_records(num_records, None, None, &mut vals)?; ``` is not dynamic and still provide no definition level. Hmm... My knowledge of parquet_derive is limited, but I would have expected an optional field to map to `Option<T>` on the annotated struct. It might also be that it simply doesn't support nulls, in which case I'm a little unsure about adding partial support in a manner that might prevent adding such support in future > Hmm... My knowledge of parquet_derive is limited, but I would have expected an optional field to map to `Option<T>` on the annotated struct. > > It might also be that it simply doesn't support nulls, in which case I'm a little unsure about adding partial support in a manner that might prevent adding such support in future I understand your concern, and that is why I said this in the description: > but I don't know if this solution is reasonable in the scope of the whole arrow project. Yes, I agree it is more natural and rigorous to map and OPTIONAL column to `Option<T>` in theory. The pipeline should be like this: ```text OPTIONAL columns --> struct with Option<T> (by parquet_derive, not implemented) --> struct without Option<T> (by user) ``` However, in practice, when write a parquet file, the default attribute of a column is OPTIONAL (see https://arrow.apache.org/docs/python/generated/pyarrow.field.html), no matter whether there is a NULL. Those APIs are not even exposed to user in higher level APIs. So, most of the parquet files users deal with have OPTIONAL columns everywhere, though values in those columns are in fact all valid. I don't think it is handy for users to declare a struct with all fields in `Option<T>`. Another point I want to say is, this change DOES NOT mean that the reader support `Option<T>` in struct now, if you derive `ParquetRecordReader` for a struct with `Option<T>`, it fails to compile as before: ```text help: message: not implemented: Unsupported: Option(...) ``` The only difference is that if a parquet file is written with OPTIONAL columns, but in fact the values in those columns are in fact all valid, the reader should still be able to load the records into a struct WITHOUT `Option<T>`, i.e., the pipeline becomes: ```text OPTIONAL columns --> struct without Option<T> (by parquet_derive, with checks) ``` This change is only to relax parquet_derive's restriction against parquet input, without introducing risk since checks are done after parsing. If user's input does have NULL values, the parser will panic, like what it is doing now. To sum up, I think this change does not make things worse or unsafe. I really appreciate your time to review this issue, and even better if you can invite more experts to review it. > However, in practice, when write a parquet file, the default attribute of a column is OPTIONAL Is this the case if you set `nullable` to `false`? If so I would probably raise a bug on pyarrow as that is incorrect. > This change is only to relax parquet_derive's restriction against parquet input, without introducing risk since checks are done after parsing. If user's input does have NULL values, the parser will panic, like what it is doing now. So long as we don't regress performance for existing workloads I suppose this is an acceptable workaround. I will try to take a look next week at your PR, although I will need to allocate enough time to get up to speed on that crate (there isn't really anyone maintaining it actively anymore). FWIW reading parquet via the arrow interface will be faster, especially for string columns, but appreciate if you'd rather stick to a row-oriented model > Is this the case if you set nullable to false? If so I would probably raise a bug on pyarrow as that is incorrect. `pyarrow` is not the culprit. I believe "convention" is the one to blame. `pandas` has a [to_parquet](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.to_parquet.html) interface, and it does not accept schema before https://github.com/pandas-dev/pandas/pull/30270 . Even after this improvement, most people use the default schema, which falls in to `OPTIONAL` columns by default (nullable=True in `pyarrow`). > I will try to take a look next week at your PR, although I will need to allocate enough time to get up to speed on that crate I really appreciate your time, my use case requires a row-oriented model, and this crate is still very useful to our project, that's why I raise this issue. I'm willing to spend time polishing this pull request.
2024-05-04T11:18:22Z
51.0
30767a687b48d0dbd2e030eef327826c39095123
[ "tests::test_parquet_derive_read_optional_but_valid_column" ]
[ "tests::test_parquet_derive_hello", "tests::test_parquet_derive_read_write_combined" ]
[]
[]
apache/arrow-rs
6,269
apache__arrow-rs-6269
[ "6268" ]
acdd27a66ac7b5e07816dc648db00532110fb89a
diff --git a/parquet_derive/src/lib.rs b/parquet_derive/src/lib.rs index 16b6a6699e2d..9c93e2cca978 100644 --- a/parquet_derive/src/lib.rs +++ b/parquet_derive/src/lib.rs @@ -146,10 +146,10 @@ pub fn parquet_record_writer(input: proc_macro::TokenStream) -> proc_macro::Toke /// Derive flat, simple RecordReader implementations. Works by parsing /// a struct tagged with `#[derive(ParquetRecordReader)]` and emitting /// the correct writing code for each field of the struct. Column readers -/// are generated in the order they are defined. +/// are generated by matching names in the schema to the names in the struct. /// -/// It is up to the programmer to keep the order of the struct -/// fields lined up with the schema. +/// It is up to the programmer to ensure the names in the struct +/// fields line up with the schema. /// /// Example: /// @@ -189,7 +189,6 @@ pub fn parquet_record_reader(input: proc_macro::TokenStream) -> proc_macro::Toke let field_names: Vec<_> = fields.iter().map(|f| f.ident.clone()).collect(); let reader_snippets: Vec<proc_macro2::TokenStream> = field_infos.iter().map(|x| x.reader_snippet()).collect(); - let i: Vec<_> = (0..reader_snippets.len()).collect(); let derived_for = input.ident; let generics = input.generics; @@ -206,6 +205,12 @@ pub fn parquet_record_reader(input: proc_macro::TokenStream) -> proc_macro::Toke let mut row_group_reader = row_group_reader; + // key: parquet file column name, value: column index + let mut name_to_index = std::collections::HashMap::new(); + for (idx, col) in row_group_reader.metadata().schema_descr().columns().iter().enumerate() { + name_to_index.insert(col.name().to_string(), idx); + } + for _ in 0..num_records { self.push(#derived_for { #( @@ -218,7 +223,14 @@ pub fn parquet_record_reader(input: proc_macro::TokenStream) -> proc_macro::Toke #( { - if let Ok(mut column_reader) = row_group_reader.get_column_reader(#i) { + let idx: usize = match name_to_index.get(stringify!(#field_names)) { + Some(&col_idx) => col_idx, + None => { + let error_msg = format!("column name '{}' is not found in parquet file!", stringify!(#field_names)); + return Err(::parquet::errors::ParquetError::General(error_msg)); + } + }; + if let Ok(mut column_reader) = row_group_reader.get_column_reader(idx) { #reader_snippets } else { return Err(::parquet::errors::ParquetError::General("Failed to get next column".into()))
diff --git a/parquet_derive_test/src/lib.rs b/parquet_derive_test/src/lib.rs index e7c7896cb7f3..2cd69d03d731 100644 --- a/parquet_derive_test/src/lib.rs +++ b/parquet_derive_test/src/lib.rs @@ -73,9 +73,9 @@ struct APartiallyCompleteRecord { struct APartiallyOptionalRecord { pub bool: bool, pub string: String, - pub maybe_i16: Option<i16>, - pub maybe_i32: Option<i32>, - pub maybe_u64: Option<u64>, + pub i16: Option<i16>, + pub i32: Option<i32>, + pub u64: Option<u64>, pub isize: isize, pub float: f32, pub double: f64, @@ -85,6 +85,22 @@ struct APartiallyOptionalRecord { pub byte_vec: Vec<u8>, } +// This struct removes several fields from the "APartiallyCompleteRecord", +// and it shuffles the fields. +// we should still be able to load it from APartiallyCompleteRecord parquet file +#[derive(PartialEq, ParquetRecordReader, Debug)] +struct APrunedRecord { + pub bool: bool, + pub string: String, + pub byte_vec: Vec<u8>, + pub float: f32, + pub double: f64, + pub i16: i16, + pub i32: i32, + pub u64: u64, + pub isize: isize, +} + #[cfg(test)] mod tests { use super::*; @@ -240,12 +256,12 @@ mod tests { #[test] fn test_parquet_derive_read_optional_but_valid_column() { let file = get_temp_file("test_parquet_derive_read_optional", &[]); - let drs: Vec<APartiallyOptionalRecord> = vec![APartiallyOptionalRecord { + let drs = vec![APartiallyOptionalRecord { bool: true, string: "a string".into(), - maybe_i16: Some(-45), - maybe_i32: Some(456), - maybe_u64: Some(4563424), + i16: Some(-45), + i32: Some(456), + u64: Some(4563424), isize: -365, float: 3.5, double: f64::NAN, @@ -273,9 +289,57 @@ mod tests { let mut row_group = reader.get_row_group(0).unwrap(); out.read_from_row_group(&mut *row_group, 1).unwrap(); - assert_eq!(drs[0].maybe_i16.unwrap(), out[0].i16); - assert_eq!(drs[0].maybe_i32.unwrap(), out[0].i32); - assert_eq!(drs[0].maybe_u64.unwrap(), out[0].u64); + assert_eq!(drs[0].i16.unwrap(), out[0].i16); + assert_eq!(drs[0].i32.unwrap(), out[0].i32); + assert_eq!(drs[0].u64.unwrap(), out[0].u64); + } + + #[test] + fn test_parquet_derive_read_pruned_and_shuffled_columns() { + let file = get_temp_file("test_parquet_derive_read_pruned", &[]); + let drs = vec![APartiallyCompleteRecord { + bool: true, + string: "a string".into(), + i16: -45, + i32: 456, + u64: 4563424, + isize: -365, + float: 3.5, + double: f64::NAN, + now: chrono::Utc::now().naive_local(), + date: chrono::naive::NaiveDate::from_ymd_opt(2015, 3, 14).unwrap(), + uuid: uuid::Uuid::new_v4(), + byte_vec: vec![0x65, 0x66, 0x67], + }]; + + let generated_schema = drs.as_slice().schema().unwrap(); + + let props = Default::default(); + let mut writer = + SerializedFileWriter::new(file.try_clone().unwrap(), generated_schema, props).unwrap(); + + let mut row_group = writer.next_row_group().unwrap(); + drs.as_slice().write_to_row_group(&mut row_group).unwrap(); + row_group.close().unwrap(); + writer.close().unwrap(); + + use parquet::file::{reader::FileReader, serialized_reader::SerializedFileReader}; + let reader = SerializedFileReader::new(file).unwrap(); + let mut out: Vec<APrunedRecord> = Vec::new(); + + let mut row_group = reader.get_row_group(0).unwrap(); + out.read_from_row_group(&mut *row_group, 1).unwrap(); + + assert_eq!(drs[0].bool, out[0].bool); + assert_eq!(drs[0].string, out[0].string); + assert_eq!(drs[0].byte_vec, out[0].byte_vec); + assert_eq!(drs[0].float, out[0].float); + assert!(drs[0].double.is_nan()); + assert!(out[0].double.is_nan()); + assert_eq!(drs[0].i16, out[0].i16); + assert_eq!(drs[0].i32, out[0].i32); + assert_eq!(drs[0].u64, out[0].u64); + assert_eq!(drs[0].isize, out[0].isize); } /// Returns file handle for a temp file in 'target' directory with a provided content
parquet_derive: support reading selected columns from parquet file # Feature Description I'm effectively using `parquet_derive` in my project, and I found that there are two inconvenient constraints: 1. The `ParquetRecordReader` enforces the struct to organize fields exactly in the **same order** in the parquet file. 2. The `ParquetRecordReader` enforces the struct to parse **all fields** in the parquet file. "all" might be exaggerating, but it is what happens if you want to get the last column, even only the last column. As describe in its document: > Derive flat, simple RecordReader implementations. Works by parsing a struct tagged with #[derive(ParquetRecordReader)] and emitting the correct writing code for each field of the struct. Column readers are generated in the order they are defined. In my use cases (and I believe these are common requests), user should be able to read pruned parquet file, and they should have the freedom to re-organize fields' ordering in decoded struct. # My Solution I introduced a `HashMap` to map field name to its index. Of course, it assumes field name is unique, and this is always true since the current `parquet_derive` macro is applied to a flat struct without nesting. # Pros and Cons Obviously removing those two constraints makes `parquet_derive` a more handy tool. But it has some implied changes: - previously, since the `ParquetRecordReader` relies only on the index of fields, it allows that a field is named as `abc` to implicitly rename itself to `bcd` in the encoded struct. After this change, user must guarantee that the field name in `ParquetRecordReader` to exist in parquet columns. - I think it is more intuitive and more natural to constrain the "field name" rather than "index", if we use `ParquetRecordReader` to derive a decoder macro. - allowing reading partial parquet file may improve the performance for some users, but introducing a `HashMap` in the parser may slowdown the function a bit. - when the `num_records` in a single parsing call is large enough, the cost of `HashMap` lookup is negligible. Both implied changes seem to have a more positive impact than negative impact. Please review if this is a reasonable feature request.
2024-08-18T14:39:49Z
52.2
678517018ddfd21b202a94df13b06dfa1ab8a378
[ "tests::test_parquet_derive_read_pruned_and_shuffled_columns" ]
[ "tests::test_parquet_derive_hello", "tests::test_parquet_derive_read_write_combined", "tests::test_parquet_derive_read_optional_but_valid_column" ]
[]
[]
apache/arrow-rs
2,407
apache__arrow-rs-2407
[ "2406" ]
27f4762c8794ef1c5d042933562185980eb85ae5
diff --git a/parquet/src/arrow/record_reader/mod.rs b/parquet/src/arrow/record_reader/mod.rs index 88d45f3d746a..18b4c9e07026 100644 --- a/parquet/src/arrow/record_reader/mod.rs +++ b/parquet/src/arrow/record_reader/mod.rs @@ -786,4 +786,186 @@ mod tests { assert_eq!(record_reader.num_records(), 8); assert_eq!(record_reader.num_values(), 14); } + + #[test] + fn test_skip_required_records() { + // Construct column schema + let message_type = " + message test_schema { + REQUIRED INT32 leaf; + } + "; + let desc = parse_message_type(message_type) + .map(|t| SchemaDescriptor::new(Arc::new(t))) + .map(|s| s.column(0)) + .unwrap(); + + // Construct record reader + let mut record_reader = RecordReader::<Int32Type>::new(desc.clone()); + + // First page + + // Records data: + // test_schema + // leaf: 4 + // test_schema + // leaf: 7 + // test_schema + // leaf: 6 + // test_schema + // left: 3 + // test_schema + // left: 2 + { + let values = [4, 7, 6, 3, 2]; + let mut pb = DataPageBuilderImpl::new(desc.clone(), 5, true); + pb.add_values::<Int32Type>(Encoding::PLAIN, &values); + let page = pb.consume(); + + let page_reader = Box::new(InMemoryPageReader::new(vec![page])); + record_reader.set_page_reader(page_reader).unwrap(); + assert_eq!(2, record_reader.skip_records(2).unwrap()); + assert_eq!(0, record_reader.num_records()); + assert_eq!(0, record_reader.num_values()); + assert_eq!(3, record_reader.read_records(3).unwrap()); + assert_eq!(3, record_reader.num_records()); + assert_eq!(3, record_reader.num_values()); + } + + // Second page + + // Records data: + // test_schema + // leaf: 8 + // test_schema + // leaf: 9 + { + let values = [8, 9]; + let mut pb = DataPageBuilderImpl::new(desc, 2, true); + pb.add_values::<Int32Type>(Encoding::PLAIN, &values); + let page = pb.consume(); + + let page_reader = Box::new(InMemoryPageReader::new(vec![page])); + record_reader.set_page_reader(page_reader).unwrap(); + assert_eq!(2, record_reader.skip_records(10).unwrap()); + assert_eq!(3, record_reader.num_records()); + assert_eq!(3, record_reader.num_values()); + assert_eq!(0, record_reader.read_records(10).unwrap()); + } + + let mut bb = Int32BufferBuilder::new(3); + bb.append_slice(&[6, 3, 2]); + let expected_buffer = bb.finish(); + assert_eq!(expected_buffer, record_reader.consume_record_data()); + assert_eq!(None, record_reader.consume_def_levels()); + assert_eq!(None, record_reader.consume_bitmap()); + } + + #[test] + fn test_skip_optional_records() { + // Construct column schema + let message_type = " + message test_schema { + OPTIONAL Group test_struct { + OPTIONAL INT32 leaf; + } + } + "; + + let desc = parse_message_type(message_type) + .map(|t| SchemaDescriptor::new(Arc::new(t))) + .map(|s| s.column(0)) + .unwrap(); + + // Construct record reader + let mut record_reader = RecordReader::<Int32Type>::new(desc.clone()); + + // First page + + // Records data: + // test_schema + // test_struct + // test_schema + // test_struct + // leaf: 7 + // test_schema + // test_schema + // test_struct + // leaf: 6 + // test_schema + // test_struct + // leaf: 6 + { + let values = [7, 6, 3]; + //empty, non-empty, empty, non-empty, non-empty + let def_levels = [1i16, 2i16, 0i16, 2i16, 2i16]; + let mut pb = DataPageBuilderImpl::new(desc.clone(), 5, true); + pb.add_def_levels(2, &def_levels); + pb.add_values::<Int32Type>(Encoding::PLAIN, &values); + let page = pb.consume(); + + let page_reader = Box::new(InMemoryPageReader::new(vec![page])); + record_reader.set_page_reader(page_reader).unwrap(); + assert_eq!(2, record_reader.skip_records(2).unwrap()); + assert_eq!(0, record_reader.num_records()); + assert_eq!(0, record_reader.num_values()); + assert_eq!(3, record_reader.read_records(3).unwrap()); + assert_eq!(3, record_reader.num_records()); + assert_eq!(3, record_reader.num_values()); + } + + // Second page + + // Records data: + // test_schema + // test_schema + // test_struct + // left: 8 + { + let values = [8]; + //empty, non-empty + let def_levels = [0i16, 2i16]; + let mut pb = DataPageBuilderImpl::new(desc, 2, true); + pb.add_def_levels(2, &def_levels); + pb.add_values::<Int32Type>(Encoding::PLAIN, &values); + let page = pb.consume(); + + let page_reader = Box::new(InMemoryPageReader::new(vec![page])); + record_reader.set_page_reader(page_reader).unwrap(); + assert_eq!(2, record_reader.skip_records(10).unwrap()); + assert_eq!(3, record_reader.num_records()); + assert_eq!(3, record_reader.num_values()); + assert_eq!(0, record_reader.read_records(10).unwrap()); + } + + // Verify result def levels + let mut bb = Int16BufferBuilder::new(7); + bb.append_slice(&[0i16, 2i16, 2i16]); + let expected_def_levels = bb.finish(); + assert_eq!( + Some(expected_def_levels), + record_reader.consume_def_levels() + ); + + // Verify bitmap + let expected_valid = &[false, true, true]; + let expected_buffer = Buffer::from_iter(expected_valid.iter().cloned()); + let expected_bitmap = Bitmap::from(expected_buffer); + assert_eq!(Some(expected_bitmap), record_reader.consume_bitmap()); + + // Verify result record data + let actual = record_reader.consume_record_data(); + let actual_values = actual.typed_data::<i32>(); + + let expected = &[0, 6, 3]; + assert_eq!(actual_values.len(), expected.len()); + + // Only validate valid values are equal + let iter = expected_valid.iter().zip(actual_values).zip(expected); + for ((valid, actual), expected) in iter { + if *valid { + assert_eq!(actual, expected) + } + } + } }
diff --git a/parquet/src/util/test_common/page_util.rs b/parquet/src/util/test_common/page_util.rs index dffcb2a44e87..243fb6f8b897 100644 --- a/parquet/src/util/test_common/page_util.rs +++ b/parquet/src/util/test_common/page_util.rs @@ -24,6 +24,7 @@ use crate::encodings::levels::LevelEncoder; use crate::errors::Result; use crate::schema::types::{ColumnDescPtr, SchemaDescPtr}; use crate::util::memory::ByteBufferPtr; +use std::iter::Peekable; use std::mem; pub trait DataPageBuilder { @@ -127,8 +128,8 @@ impl DataPageBuilder for DataPageBuilderImpl { encoding: self.encoding.unwrap(), num_nulls: 0, /* set to dummy value - don't need this when reading * data page */ - num_rows: self.num_values, /* also don't need this when reading - * data page */ + num_rows: self.num_values, /* num_rows only needs in skip_records, now we not support skip REPEATED field, + * so we can assume num_values == num_rows */ def_levels_byte_len: self.def_levels_byte_len, rep_levels_byte_len: self.rep_levels_byte_len, is_compressed: false, @@ -149,13 +150,13 @@ impl DataPageBuilder for DataPageBuilderImpl { /// A utility page reader which stores pages in memory. pub struct InMemoryPageReader<P: Iterator<Item = Page>> { - page_iter: P, + page_iter: Peekable<P>, } impl<P: Iterator<Item = Page>> InMemoryPageReader<P> { pub fn new(pages: impl IntoIterator<Item = Page, IntoIter = P>) -> Self { Self { - page_iter: pages.into_iter(), + page_iter: pages.into_iter().peekable(), } } } @@ -166,11 +167,29 @@ impl<P: Iterator<Item = Page> + Send> PageReader for InMemoryPageReader<P> { } fn peek_next_page(&mut self) -> Result<Option<PageMetadata>> { - unimplemented!() + if let Some(x) = self.page_iter.peek() { + match x { + Page::DataPage { num_values, .. } => Ok(Some(PageMetadata { + num_rows: *num_values as usize, + is_dict: false, + })), + Page::DataPageV2 { num_rows, .. } => Ok(Some(PageMetadata { + num_rows: *num_rows as usize, + is_dict: false, + })), + Page::DictionaryPage { .. } => Ok(Some(PageMetadata { + num_rows: 0, + is_dict: true, + })), + } + } else { + Ok(None) + } } fn skip_next_page(&mut self) -> Result<()> { - unimplemented!() + self.page_iter.next(); + Ok(()) } }
Support `peek_next_page` and `skip_next_page` in `InMemoryPageReader` **Is your feature request related to a problem or challenge? Please describe what you are trying to do.** when i was implementing bench using `skip_records` got ``` Benchmarking arrow_array_reader/Int32Array/binary packed skip, mandatory, no NULLs: Warming up for 3.0000 sthread 'main' panicked at 'not implemented', /CLionProjects/github/arrow-rs/parquet/src/util/test_common/page_util.rs:169:9 ``` which is unimplemented **Describe the solution you'd like** <!-- A clear and concise description of what you want to happen. --> **Describe alternatives you've considered** <!-- A clear and concise description of any alternative solutions or features you've considered. --> **Additional context** <!-- Add any other context or screenshots about the feature request here. -->
2022-08-11T07:39:09Z
20.0
27f4762c8794ef1c5d042933562185980eb85ae5
[ "parquet/src/arrow/mod.rs - arrow (line 55)" ]
[ "parquet/src/file/mod.rs - file (line 81) - compile", "parquet/src/arrow/arrow_reader.rs - arrow::arrow_reader::ParquetFileArrowReader::try_new (line 203) - compile", "parquet/src/file/mod.rs - file (line 64) - compile", "parquet/src/file/mod.rs - file (line 29) - compile", "parquet/src/record/api.rs - record::api::Row::get_column_iter (line 62) - compile", "parquet/src/column/mod.rs - column (line 38) - compile", "parquet/src/arrow/arrow_writer/mod.rs - arrow::arrow_writer::ArrowWriter (line 54)", "parquet/src/arrow/mod.rs - arrow (line 27)", "parquet/src/schema/types.rs - schema::types::ColumnPath::append (line 674)", "parquet/src/schema/parser.rs - schema::parser (line 24)", "parquet/src/schema/types.rs - schema::types::ColumnPath::string (line 663)", "parquet/src/record/api.rs - record::api::RowFormatter (line 140)", "parquet/src/file/statistics.rs - file::statistics (line 23)", "parquet/src/schema/mod.rs - schema (line 22)", "parquet/src/file/properties.rs - file::properties (line 22)", "parquet/src/schema/printer.rs - schema::printer (line 23)", "parquet/src/arrow/mod.rs - arrow (line 68)" ]
[]
[]
apache/arrow-rs
2,377
apache__arrow-rs-2377
[ "1254" ]
613b99dcc43ef3af9603fd823f8fe42a801bac19
diff --git a/.github/workflows/parquet.yml b/.github/workflows/parquet.yml index d8e09f04ba83..ad694ec60399 100644 --- a/.github/workflows/parquet.yml +++ b/.github/workflows/parquet.yml @@ -128,8 +128,4 @@ jobs: rustup component add clippy - name: Run clippy run: | - # Only run clippy for the library at this time, - # as there are clippy errors for other targets - cargo clippy -p parquet --all-features --lib -- -D warnings - # https://github.com/apache/arrow-rs/issues/1254 - #cargo clippy -p parquet --all-targets --all-features -- -D warnings + cargo clippy -p parquet --all-targets --all-features -- -D warnings diff --git a/parquet/src/arrow/array_reader/builder.rs b/parquet/src/arrow/array_reader/builder.rs index d9c1bedb246c..32ffaeb9d5cc 100644 --- a/parquet/src/arrow/array_reader/builder.rs +++ b/parquet/src/arrow/array_reader/builder.rs @@ -104,13 +104,11 @@ fn build_list_reader( let data_type = field.arrow_type.clone(); let item_reader = build_reader(&children[0], row_groups)?; - let item_type = item_reader.get_data_type().clone(); match is_large { false => Ok(Box::new(ListArrayReader::<i32>::new( item_reader, data_type, - item_type, field.def_level, field.rep_level, field.nullable, @@ -118,7 +116,6 @@ fn build_list_reader( true => Ok(Box::new(ListArrayReader::<i64>::new( item_reader, data_type, - item_type, field.def_level, field.rep_level, field.nullable, @@ -318,7 +315,7 @@ mod tests { use super::*; use crate::arrow::parquet_to_arrow_schema; use crate::file::reader::{FileReader, SerializedFileReader}; - use crate::util::test_common::get_test_file; + use crate::util::test_common::file_util::get_test_file; use arrow::datatypes::Field; use std::sync::Arc; diff --git a/parquet/src/arrow/array_reader/list_array.rs b/parquet/src/arrow/array_reader/list_array.rs index 94770794cb73..2acd59dcc24f 100644 --- a/parquet/src/arrow/array_reader/list_array.rs +++ b/parquet/src/arrow/array_reader/list_array.rs @@ -34,7 +34,6 @@ use std::sync::Arc; pub struct ListArrayReader<OffsetSize: OffsetSizeTrait> { item_reader: Box<dyn ArrayReader>, data_type: ArrowType, - item_type: ArrowType, /// The definition level at which this list is not null def_level: i16, /// The repetition level that corresponds to a new value in this array @@ -49,7 +48,6 @@ impl<OffsetSize: OffsetSizeTrait> ListArrayReader<OffsetSize> { pub fn new( item_reader: Box<dyn ArrayReader>, data_type: ArrowType, - item_type: ArrowType, def_level: i16, rep_level: i16, nullable: bool, @@ -57,7 +55,6 @@ impl<OffsetSize: OffsetSizeTrait> ListArrayReader<OffsetSize> { Self { item_reader, data_type, - item_type, def_level, rep_level, nullable, @@ -304,13 +301,13 @@ mod tests { // ] let l3_item_type = ArrowType::Int32; - let l3_type = list_type::<OffsetSize>(l3_item_type.clone(), true); + let l3_type = list_type::<OffsetSize>(l3_item_type, true); let l2_item_type = l3_type.clone(); - let l2_type = list_type::<OffsetSize>(l2_item_type.clone(), true); + let l2_type = list_type::<OffsetSize>(l2_item_type, true); let l1_item_type = l2_type.clone(); - let l1_type = list_type::<OffsetSize>(l1_item_type.clone(), false); + let l1_type = list_type::<OffsetSize>(l1_item_type, false); let leaf = PrimitiveArray::<Int32Type>::from_iter(vec![ Some(1), @@ -387,7 +384,6 @@ mod tests { let l3 = ListArrayReader::<OffsetSize>::new( Box::new(item_array_reader), l3_type, - l3_item_type, 5, 3, true, @@ -396,7 +392,6 @@ mod tests { let l2 = ListArrayReader::<OffsetSize>::new( Box::new(l3), l2_type, - l2_item_type, 3, 2, false, @@ -405,7 +400,6 @@ mod tests { let mut l1 = ListArrayReader::<OffsetSize>::new( Box::new(l2), l1_type, - l1_item_type, 2, 1, true, @@ -456,7 +450,6 @@ mod tests { let mut list_array_reader = ListArrayReader::<OffsetSize>::new( Box::new(item_array_reader), list_type::<OffsetSize>(ArrowType::Int32, true), - ArrowType::Int32, 1, 1, false, @@ -509,7 +502,6 @@ mod tests { let mut list_array_reader = ListArrayReader::<OffsetSize>::new( Box::new(item_array_reader), list_type::<OffsetSize>(ArrowType::Int32, true), - ArrowType::Int32, 2, 1, true, diff --git a/parquet/src/arrow/array_reader/map_array.rs b/parquet/src/arrow/array_reader/map_array.rs index 83ba63ca1706..3ba7f6960ec3 100644 --- a/parquet/src/arrow/array_reader/map_array.rs +++ b/parquet/src/arrow/array_reader/map_array.rs @@ -32,6 +32,7 @@ pub struct MapArrayReader { value_reader: Box<dyn ArrayReader>, data_type: ArrowType, map_def_level: i16, + #[allow(unused)] map_rep_level: i16, } @@ -47,6 +48,7 @@ impl MapArrayReader { key_reader, value_reader, data_type, + // These are the wrong way round https://github.com/apache/arrow-rs/issues/1699 map_def_level: rep_level, map_rep_level: def_level, } diff --git a/parquet/src/arrow/array_reader/null_array.rs b/parquet/src/arrow/array_reader/null_array.rs index 682d15f8a177..405633f0a823 100644 --- a/parquet/src/arrow/array_reader/null_array.rs +++ b/parquet/src/arrow/array_reader/null_array.rs @@ -39,7 +39,6 @@ where pages: Box<dyn PageIterator>, def_levels_buffer: Option<Buffer>, rep_levels_buffer: Option<Buffer>, - column_desc: ColumnDescPtr, record_reader: RecordReader<T>, } @@ -50,14 +49,13 @@ where { /// Construct null array reader. pub fn new(pages: Box<dyn PageIterator>, column_desc: ColumnDescPtr) -> Result<Self> { - let record_reader = RecordReader::<T>::new(column_desc.clone()); + let record_reader = RecordReader::<T>::new(column_desc); Ok(Self { data_type: ArrowType::Null, pages, def_levels_buffer: None, rep_levels_buffer: None, - column_desc, record_reader, }) } diff --git a/parquet/src/arrow/array_reader/primitive_array.rs b/parquet/src/arrow/array_reader/primitive_array.rs index 45614d50941c..516a3f50c712 100644 --- a/parquet/src/arrow/array_reader/primitive_array.rs +++ b/parquet/src/arrow/array_reader/primitive_array.rs @@ -44,7 +44,6 @@ where pages: Box<dyn PageIterator>, def_levels_buffer: Option<Buffer>, rep_levels_buffer: Option<Buffer>, - column_desc: ColumnDescPtr, record_reader: RecordReader<T>, } @@ -67,14 +66,13 @@ where .clone(), }; - let record_reader = RecordReader::<T>::new(column_desc.clone()); + let record_reader = RecordReader::<T>::new(column_desc); Ok(Self { data_type, pages, def_levels_buffer: None, rep_levels_buffer: None, - column_desc, record_reader, }) } @@ -244,7 +242,7 @@ mod tests { use crate::data_type::Int32Type; use crate::schema::parser::parse_message_type; use crate::schema::types::SchemaDescriptor; - use crate::util::test_common::make_pages; + use crate::util::test_common::rand_gen::make_pages; use crate::util::InMemoryPageIterator; use arrow::array::PrimitiveArray; use arrow::datatypes::ArrowPrimitiveType; @@ -252,6 +250,7 @@ mod tests { use rand::distributions::uniform::SampleUniform; use std::collections::VecDeque; + #[allow(clippy::too_many_arguments)] fn make_column_chunks<T: DataType>( column_desc: ColumnDescPtr, encoding: Encoding, diff --git a/parquet/src/arrow/array_reader/struct_array.rs b/parquet/src/arrow/array_reader/struct_array.rs index b333c66cb213..f682f146c721 100644 --- a/parquet/src/arrow/array_reader/struct_array.rs +++ b/parquet/src/arrow/array_reader/struct_array.rs @@ -314,7 +314,6 @@ mod tests { let list_reader = ListArrayReader::<i32>::new( Box::new(reader), expected_l.data_type().clone(), - ArrowType::Int32, 3, 1, true, diff --git a/parquet/src/arrow/arrow_reader.rs b/parquet/src/arrow/arrow_reader.rs index 594b416761bb..726c200606fc 100644 --- a/parquet/src/arrow/arrow_reader.rs +++ b/parquet/src/arrow/arrow_reader.rs @@ -85,6 +85,7 @@ pub(crate) struct RowSelection { impl RowSelection { /// Select `row_count` rows + #[allow(unused)] pub fn select(row_count: usize) -> Self { Self { row_count, @@ -93,6 +94,7 @@ impl RowSelection { } /// Skip `row_count` rows + #[allow(unused)] pub fn skip(row_count: usize) -> Self { Self { row_count, @@ -109,7 +111,7 @@ pub struct ArrowReaderOptions { impl ArrowReaderOptions { /// Create a new [`ArrowReaderOptions`] with the default settings - fn new() -> Self { + pub fn new() -> Self { Self::default() } @@ -129,6 +131,7 @@ impl ArrowReaderOptions { /// Scan rows from the parquet file according to the provided `selection` /// /// TODO: Make public once row selection fully implemented (#1792) + #[allow(unused)] pub(crate) fn with_row_selection( self, selection: impl Into<Vec<RowSelection>>, @@ -433,7 +436,7 @@ mod tests { use crate::file::writer::SerializedFileWriter; use crate::schema::parser::parse_message_type; use crate::schema::types::{Type, TypePtr}; - use crate::util::test_common::RandGen; + use crate::util::test_common::rand_gen::RandGen; #[test] fn test_arrow_reader_all_columns() { diff --git a/parquet/src/arrow/buffer/converter.rs b/parquet/src/arrow/buffer/converter.rs index 4cd0589424fc..d8cbd256a460 100644 --- a/parquet/src/arrow/buffer/converter.rs +++ b/parquet/src/arrow/buffer/converter.rs @@ -17,18 +17,21 @@ use crate::data_type::{ByteArray, FixedLenByteArray, Int96}; use arrow::array::{ - Array, ArrayRef, BasicDecimalArray, BinaryArray, BinaryBuilder, Decimal128Array, - FixedSizeBinaryArray, FixedSizeBinaryBuilder, IntervalDayTimeArray, - IntervalDayTimeBuilder, IntervalYearMonthArray, IntervalYearMonthBuilder, - LargeBinaryArray, LargeBinaryBuilder, LargeStringArray, LargeStringBuilder, - StringArray, StringBuilder, TimestampNanosecondArray, + Array, ArrayRef, BasicDecimalArray, Decimal128Array, FixedSizeBinaryArray, + FixedSizeBinaryBuilder, IntervalDayTimeArray, IntervalDayTimeBuilder, + IntervalYearMonthArray, IntervalYearMonthBuilder, TimestampNanosecondArray, }; -use std::convert::{From, TryInto}; use std::sync::Arc; use crate::errors::Result; use std::marker::PhantomData; +#[cfg(test)] +use arrow::array::{ + BinaryArray, BinaryBuilder, LargeStringArray, LargeStringBuilder, StringArray, + StringBuilder, +}; + /// A converter is used to consume record reader's content and convert it to arrow /// primitive array. pub trait Converter<S, T> { @@ -185,8 +188,10 @@ impl Converter<Vec<Option<Int96>>, TimestampNanosecondArray> for Int96ArrayConve } } +#[cfg(test)] pub struct Utf8ArrayConverter {} +#[cfg(test)] impl Converter<Vec<Option<ByteArray>>, StringArray> for Utf8ArrayConverter { fn convert(&self, source: Vec<Option<ByteArray>>) -> Result<StringArray> { let data_size = source @@ -206,8 +211,10 @@ impl Converter<Vec<Option<ByteArray>>, StringArray> for Utf8ArrayConverter { } } +#[cfg(test)] pub struct LargeUtf8ArrayConverter {} +#[cfg(test)] impl Converter<Vec<Option<ByteArray>>, LargeStringArray> for LargeUtf8ArrayConverter { fn convert(&self, source: Vec<Option<ByteArray>>) -> Result<LargeStringArray> { let data_size = source @@ -227,8 +234,10 @@ impl Converter<Vec<Option<ByteArray>>, LargeStringArray> for LargeUtf8ArrayConve } } +#[cfg(test)] pub struct BinaryArrayConverter {} +#[cfg(test)] impl Converter<Vec<Option<ByteArray>>, BinaryArray> for BinaryArrayConverter { fn convert(&self, source: Vec<Option<ByteArray>>) -> Result<BinaryArray> { let mut builder = BinaryBuilder::new(source.len()); @@ -243,33 +252,9 @@ impl Converter<Vec<Option<ByteArray>>, BinaryArray> for BinaryArrayConverter { } } -pub struct LargeBinaryArrayConverter {} - -impl Converter<Vec<Option<ByteArray>>, LargeBinaryArray> for LargeBinaryArrayConverter { - fn convert(&self, source: Vec<Option<ByteArray>>) -> Result<LargeBinaryArray> { - let mut builder = LargeBinaryBuilder::new(source.len()); - for v in source { - match v { - Some(array) => builder.append_value(array.data()), - None => builder.append_null(), - } - } - - Ok(builder.finish()) - } -} - +#[cfg(test)] pub type Utf8Converter = ArrayRefConverter<Vec<Option<ByteArray>>, StringArray, Utf8ArrayConverter>; -pub type LargeUtf8Converter = - ArrayRefConverter<Vec<Option<ByteArray>>, LargeStringArray, LargeUtf8ArrayConverter>; -pub type BinaryConverter = - ArrayRefConverter<Vec<Option<ByteArray>>, BinaryArray, BinaryArrayConverter>; -pub type LargeBinaryConverter = ArrayRefConverter< - Vec<Option<ByteArray>>, - LargeBinaryArray, - LargeBinaryArrayConverter, ->; pub type Int96Converter = ArrayRefConverter<Vec<Option<Int96>>, TimestampNanosecondArray, Int96ArrayConverter>; @@ -299,11 +284,13 @@ pub type DecimalFixedLengthByteArrayConverter = ArrayRefConverter< pub type DecimalByteArrayConvert = ArrayRefConverter<Vec<Option<ByteArray>>, Decimal128Array, DecimalArrayConverter>; +#[cfg(test)] pub struct FromConverter<S, T> { _source: PhantomData<S>, _dest: PhantomData<T>, } +#[cfg(test)] impl<S, T> FromConverter<S, T> where T: From<S>, @@ -316,6 +303,7 @@ where } } +#[cfg(test)] impl<S, T> Converter<S, T> for FromConverter<S, T> where T: From<S>, diff --git a/parquet/src/arrow/buffer/dictionary_buffer.rs b/parquet/src/arrow/buffer/dictionary_buffer.rs index b64b2946b91a..ae9e3590de3f 100644 --- a/parquet/src/arrow/buffer/dictionary_buffer.rs +++ b/parquet/src/arrow/buffer/dictionary_buffer.rs @@ -49,6 +49,7 @@ impl<K: ScalarValue, V: ScalarValue> Default for DictionaryBuffer<K, V> { impl<K: ScalarValue + ArrowNativeType + Ord, V: ScalarValue + OffsetSizeTrait> DictionaryBuffer<K, V> { + #[allow(unused)] pub fn len(&self) -> usize { match self { Self::Dict { keys, .. } => keys.len(), diff --git a/parquet/src/arrow/record_reader/mod.rs b/parquet/src/arrow/record_reader/mod.rs index 60fe4cdc9c96..88d45f3d746a 100644 --- a/parquet/src/arrow/record_reader/mod.rs +++ b/parquet/src/arrow/record_reader/mod.rs @@ -214,6 +214,7 @@ where } /// Returns number of records stored in buffer. + #[allow(unused)] pub fn num_records(&self) -> usize { self.num_records } @@ -273,11 +274,6 @@ where .map(|levels| levels.split_bitmask(self.num_values)) } - /// Returns column reader. - pub(crate) fn column_reader(&self) -> Option<&ColumnReader<CV>> { - self.column_reader.as_ref() - } - /// Try to read one batch of data. fn read_one_batch(&mut self, batch_size: usize) -> Result<usize> { let rep_levels = self diff --git a/parquet/src/arrow/schema.rs b/parquet/src/arrow/schema.rs index 2cb47bc00e7e..01aefcd48e1d 100644 --- a/parquet/src/arrow/schema.rs +++ b/parquet/src/arrow/schema.rs @@ -73,7 +73,7 @@ pub fn parquet_to_arrow_schema_by_columns( // Add the Arrow metadata to the Parquet metadata skipping keys that collide if let Some(arrow_schema) = &maybe_schema { arrow_schema.metadata().iter().for_each(|(k, v)| { - metadata.entry(k.clone()).or_insert(v.clone()); + metadata.entry(k.clone()).or_insert_with(|| v.clone()); }); } @@ -100,7 +100,7 @@ fn get_arrow_schema_from_metadata(encoded_meta: &str) -> Result<Schema> { Ok(message) => message .header_as_schema() .map(arrow::ipc::convert::fb_to_schema) - .ok_or(arrow_err!("the message is not Arrow Schema")), + .ok_or_else(|| arrow_err!("the message is not Arrow Schema")), Err(err) => { // The flatbuffers implementation returns an error on verification error. Err(arrow_err!( diff --git a/parquet/src/basic.rs b/parquet/src/basic.rs index 0cf1d5121b7e..9c58f764cb2c 100644 --- a/parquet/src/basic.rs +++ b/parquet/src/basic.rs @@ -18,7 +18,7 @@ //! Contains Rust mappings for Thrift definition. //! Refer to `parquet.thrift` file to see raw definitions. -use std::{convert, fmt, result, str}; +use std::{fmt, result, str}; use parquet_format as parquet; @@ -42,6 +42,7 @@ pub use parquet_format::{ /// For example INT16 is not included as a type since a good encoding of INT32 /// would handle this. #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +#[allow(non_camel_case_types)] pub enum Type { BOOLEAN, INT32, @@ -63,6 +64,7 @@ pub enum Type { /// This struct was renamed from `LogicalType` in version 4.0.0. /// If targeting Parquet format 2.4.0 or above, please use [LogicalType] instead. #[derive(Debug, Clone, Copy, PartialEq)] +#[allow(non_camel_case_types)] pub enum ConvertedType { NONE, /// A BYTE_ARRAY actually contains UTF8 encoded chars. @@ -197,6 +199,7 @@ pub enum LogicalType { /// Representation of field types in schema. #[derive(Debug, Clone, Copy, PartialEq)] +#[allow(non_camel_case_types)] pub enum Repetition { /// Field is required (can not be null) and each record has exactly 1 value. REQUIRED, @@ -213,6 +216,7 @@ pub enum Repetition { /// Not all encodings are valid for all types. These enums are also used to specify the /// encoding of definition and repetition levels. #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Ord, PartialOrd)] +#[allow(non_camel_case_types)] pub enum Encoding { /// Default byte encoding. /// - BOOLEAN - 1 bit per value, 0 is false; 1 is true. @@ -294,6 +298,7 @@ pub enum Compression { /// Available data pages for Parquet file format. /// Note that some of the page types may not be supported. #[derive(Debug, Clone, Copy, PartialEq)] +#[allow(non_camel_case_types)] pub enum PageType { DATA_PAGE, INDEX_PAGE, @@ -313,6 +318,7 @@ pub enum PageType { /// See reference in /// <https://github.com/apache/parquet-cpp/blob/master/src/parquet/types.h> #[derive(Debug, Clone, Copy, PartialEq)] +#[allow(non_camel_case_types)] pub enum SortOrder { /// Signed (either value or legacy byte-wise) comparison. SIGNED, @@ -328,6 +334,7 @@ pub enum SortOrder { /// If column order is undefined, then it is the legacy behaviour and all values should /// be compared as signed values/bytes. #[derive(Debug, Clone, Copy, PartialEq)] +#[allow(non_camel_case_types)] pub enum ColumnOrder { /// Column uses the order defined by its logical or physical type /// (if there is no logical type), parquet-format 2.4.0+. @@ -489,7 +496,7 @@ impl fmt::Display for ColumnOrder { // ---------------------------------------------------------------------- // parquet::Type <=> Type conversion -impl convert::From<parquet::Type> for Type { +impl From<parquet::Type> for Type { fn from(value: parquet::Type) -> Self { match value { parquet::Type::Boolean => Type::BOOLEAN, @@ -504,7 +511,7 @@ impl convert::From<parquet::Type> for Type { } } -impl convert::From<Type> for parquet::Type { +impl From<Type> for parquet::Type { fn from(value: Type) -> Self { match value { Type::BOOLEAN => parquet::Type::Boolean, @@ -522,7 +529,7 @@ impl convert::From<Type> for parquet::Type { // ---------------------------------------------------------------------- // parquet::ConvertedType <=> ConvertedType conversion -impl convert::From<Option<parquet::ConvertedType>> for ConvertedType { +impl From<Option<parquet::ConvertedType>> for ConvertedType { fn from(option: Option<parquet::ConvertedType>) -> Self { match option { None => ConvertedType::NONE, @@ -558,7 +565,7 @@ impl convert::From<Option<parquet::ConvertedType>> for ConvertedType { } } -impl convert::From<ConvertedType> for Option<parquet::ConvertedType> { +impl From<ConvertedType> for Option<parquet::ConvertedType> { fn from(value: ConvertedType) -> Self { match value { ConvertedType::NONE => None, @@ -595,7 +602,7 @@ impl convert::From<ConvertedType> for Option<parquet::ConvertedType> { // ---------------------------------------------------------------------- // parquet::LogicalType <=> LogicalType conversion -impl convert::From<parquet::LogicalType> for LogicalType { +impl From<parquet::LogicalType> for LogicalType { fn from(value: parquet::LogicalType) -> Self { match value { parquet::LogicalType::STRING(_) => LogicalType::String, @@ -627,7 +634,7 @@ impl convert::From<parquet::LogicalType> for LogicalType { } } -impl convert::From<LogicalType> for parquet::LogicalType { +impl From<LogicalType> for parquet::LogicalType { fn from(value: LogicalType) -> Self { match value { LogicalType::String => parquet::LogicalType::STRING(Default::default()), @@ -723,7 +730,7 @@ impl From<Option<LogicalType>> for ConvertedType { // ---------------------------------------------------------------------- // parquet::FieldRepetitionType <=> Repetition conversion -impl convert::From<parquet::FieldRepetitionType> for Repetition { +impl From<parquet::FieldRepetitionType> for Repetition { fn from(value: parquet::FieldRepetitionType) -> Self { match value { parquet::FieldRepetitionType::Required => Repetition::REQUIRED, @@ -733,7 +740,7 @@ impl convert::From<parquet::FieldRepetitionType> for Repetition { } } -impl convert::From<Repetition> for parquet::FieldRepetitionType { +impl From<Repetition> for parquet::FieldRepetitionType { fn from(value: Repetition) -> Self { match value { Repetition::REQUIRED => parquet::FieldRepetitionType::Required, @@ -746,7 +753,7 @@ impl convert::From<Repetition> for parquet::FieldRepetitionType { // ---------------------------------------------------------------------- // parquet::Encoding <=> Encoding conversion -impl convert::From<parquet::Encoding> for Encoding { +impl From<parquet::Encoding> for Encoding { fn from(value: parquet::Encoding) -> Self { match value { parquet::Encoding::Plain => Encoding::PLAIN, @@ -762,7 +769,7 @@ impl convert::From<parquet::Encoding> for Encoding { } } -impl convert::From<Encoding> for parquet::Encoding { +impl From<Encoding> for parquet::Encoding { fn from(value: Encoding) -> Self { match value { Encoding::PLAIN => parquet::Encoding::Plain, @@ -781,7 +788,7 @@ impl convert::From<Encoding> for parquet::Encoding { // ---------------------------------------------------------------------- // parquet::CompressionCodec <=> Compression conversion -impl convert::From<parquet::CompressionCodec> for Compression { +impl From<parquet::CompressionCodec> for Compression { fn from(value: parquet::CompressionCodec) -> Self { match value { parquet::CompressionCodec::Uncompressed => Compression::UNCOMPRESSED, @@ -795,7 +802,7 @@ impl convert::From<parquet::CompressionCodec> for Compression { } } -impl convert::From<Compression> for parquet::CompressionCodec { +impl From<Compression> for parquet::CompressionCodec { fn from(value: Compression) -> Self { match value { Compression::UNCOMPRESSED => parquet::CompressionCodec::Uncompressed, @@ -812,7 +819,7 @@ impl convert::From<Compression> for parquet::CompressionCodec { // ---------------------------------------------------------------------- // parquet::PageType <=> PageType conversion -impl convert::From<parquet::PageType> for PageType { +impl From<parquet::PageType> for PageType { fn from(value: parquet::PageType) -> Self { match value { parquet::PageType::DataPage => PageType::DATA_PAGE, @@ -823,7 +830,7 @@ impl convert::From<parquet::PageType> for PageType { } } -impl convert::From<PageType> for parquet::PageType { +impl From<PageType> for parquet::PageType { fn from(value: PageType) -> Self { match value { PageType::DATA_PAGE => parquet::PageType::DataPage, diff --git a/parquet/src/bin/parquet-fromcsv.rs b/parquet/src/bin/parquet-fromcsv.rs index aa1d50563cd9..827aa7311f58 100644 --- a/parquet/src/bin/parquet-fromcsv.rs +++ b/parquet/src/bin/parquet-fromcsv.rs @@ -439,7 +439,7 @@ mod tests { // test default values assert_eq!(args.input_format, CsvDialect::Csv); assert_eq!(args.batch_size, 1000); - assert_eq!(args.has_header, false); + assert!(!args.has_header); assert_eq!(args.delimiter, None); assert_eq!(args.get_delimiter(), b','); assert_eq!(args.record_terminator, None); @@ -553,7 +553,7 @@ mod tests { Field::new("field5", DataType::Utf8, false), ])); - let reader_builder = configure_reader_builder(&args, arrow_schema.clone()); + let reader_builder = configure_reader_builder(&args, arrow_schema); let builder_debug = format!("{:?}", reader_builder); assert_debug_text(&builder_debug, "has_header", "false"); assert_debug_text(&builder_debug, "delimiter", "Some(44)"); @@ -585,7 +585,7 @@ mod tests { Field::new("field4", DataType::Utf8, false), Field::new("field5", DataType::Utf8, false), ])); - let reader_builder = configure_reader_builder(&args, arrow_schema.clone()); + let reader_builder = configure_reader_builder(&args, arrow_schema); let builder_debug = format!("{:?}", reader_builder); assert_debug_text(&builder_debug, "has_header", "true"); assert_debug_text(&builder_debug, "delimiter", "Some(9)"); diff --git a/parquet/src/bin/parquet-read.rs b/parquet/src/bin/parquet-read.rs index 0530afaa786a..927d96f8cde7 100644 --- a/parquet/src/bin/parquet-read.rs +++ b/parquet/src/bin/parquet-read.rs @@ -93,6 +93,6 @@ fn print_row(row: &Row, json: bool) { if json { println!("{}", row.to_json_value()) } else { - println!("{}", row.to_string()); + println!("{}", row); } } diff --git a/parquet/src/bin/parquet-schema.rs b/parquet/src/bin/parquet-schema.rs index b875b0e7102b..68c52def7c44 100644 --- a/parquet/src/bin/parquet-schema.rs +++ b/parquet/src/bin/parquet-schema.rs @@ -67,9 +67,9 @@ fn main() { println!("Metadata for file: {}", &filename); println!(); if verbose { - print_parquet_metadata(&mut std::io::stdout(), &metadata); + print_parquet_metadata(&mut std::io::stdout(), metadata); } else { - print_file_metadata(&mut std::io::stdout(), &metadata.file_metadata()); + print_file_metadata(&mut std::io::stdout(), metadata.file_metadata()); } } } diff --git a/parquet/src/column/page.rs b/parquet/src/column/page.rs index c61e9c0b343e..1658797cee7d 100644 --- a/parquet/src/column/page.rs +++ b/parquet/src/column/page.rs @@ -174,6 +174,12 @@ pub struct PageWriteSpec { pub bytes_written: u64, } +impl Default for PageWriteSpec { + fn default() -> Self { + Self::new() + } +} + impl PageWriteSpec { /// Creates new spec with default page write metrics. pub fn new() -> Self { diff --git a/parquet/src/column/reader.rs b/parquet/src/column/reader.rs index 8e0fa5a4d5aa..8eee807c2bed 100644 --- a/parquet/src/column/reader.rs +++ b/parquet/src/column/reader.rs @@ -544,8 +544,8 @@ mod tests { use crate::basic::Type as PhysicalType; use crate::schema::types::{ColumnDescriptor, ColumnPath, Type as SchemaType}; - use crate::util::test_common::make_pages; use crate::util::test_common::page_util::InMemoryPageReader; + use crate::util::test_common::rand_gen::make_pages; const NUM_LEVELS: usize = 128; const NUM_PAGES: usize = 2; @@ -1231,6 +1231,7 @@ mod tests { // Helper function for the general case of `read_batch()` where `values`, // `def_levels` and `rep_levels` are always provided with enough space. + #[allow(clippy::too_many_arguments)] fn test_read_batch_general( &mut self, desc: ColumnDescPtr, @@ -1262,6 +1263,7 @@ mod tests { // Helper function to test `read_batch()` method with custom buffers for values, // definition and repetition levels. + #[allow(clippy::too_many_arguments)] fn test_read_batch( &mut self, desc: ColumnDescPtr, diff --git a/parquet/src/column/writer/encoder.rs b/parquet/src/column/writer/encoder.rs index d7363129f1ea..4fb4f210e146 100644 --- a/parquet/src/column/writer/encoder.rs +++ b/parquet/src/column/writer/encoder.rs @@ -168,7 +168,6 @@ impl<T: DataType> ColumnValueEncoder for ColumnValueEncoderImpl<T> { // Set either main encoder or fallback encoder. let encoder = get_encoder( - descr.clone(), props .encoding(descr.path()) .unwrap_or_else(|| fallback_encoding(T::get_physical_type(), props)), diff --git a/parquet/src/column/writer/mod.rs b/parquet/src/column/writer/mod.rs index 20a3babd8aa5..669cacee6460 100644 --- a/parquet/src/column/writer/mod.rs +++ b/parquet/src/column/writer/mod.rs @@ -258,6 +258,7 @@ impl<'a, E: ColumnValueEncoder> GenericColumnWriter<'a, E> { } } + #[allow(clippy::too_many_arguments)] pub(crate) fn write_batch_internal( &mut self, values: &E::Values, @@ -907,12 +908,6 @@ impl<'a, E: ColumnValueEncoder> GenericColumnWriter<'a, E> { _ => {} } } - - /// Returns reference to the underlying page writer. - /// This method is intended to use in tests only. - fn get_page_writer_ref(&self) -> &dyn PageWriter { - self.page_writer.as_ref() - } } fn update_min<T: ParquetValueType>( @@ -1101,7 +1096,7 @@ mod tests { writer::SerializedPageWriter, }; use crate::schema::types::{ColumnDescriptor, ColumnPath, Type as SchemaType}; - use crate::util::{io::FileSource, test_common::random_numbers_range}; + use crate::util::{io::FileSource, test_common::rand_gen::random_numbers_range}; use super::*; @@ -2408,20 +2403,6 @@ mod tests { get_typed_column_writer::<T>(column_writer) } - /// Returns decimals column reader. - fn get_test_decimals_column_reader<T: DataType>( - page_reader: Box<dyn PageReader>, - max_def_level: i16, - max_rep_level: i16, - ) -> ColumnReaderImpl<T> { - let descr = Arc::new(get_test_decimals_column_descr::<T>( - max_def_level, - max_rep_level, - )); - let column_reader = get_column_reader(descr, page_reader); - get_typed_column_reader::<T>(column_reader) - } - /// Returns descriptor for Decimal type with primitive column. fn get_test_decimals_column_descr<T: DataType>( max_def_level: i16, @@ -2456,20 +2437,6 @@ mod tests { get_typed_column_writer::<T>(column_writer) } - /// Returns column reader for UINT32 Column provided as ConvertedType only - fn get_test_unsigned_int_given_as_converted_column_reader<T: DataType>( - page_reader: Box<dyn PageReader>, - max_def_level: i16, - max_rep_level: i16, - ) -> ColumnReaderImpl<T> { - let descr = Arc::new(get_test_converted_type_unsigned_integer_column_descr::<T>( - max_def_level, - max_rep_level, - )); - let column_reader = get_column_reader(descr, page_reader); - get_typed_column_reader::<T>(column_reader) - } - /// Returns column descriptor for UINT32 Column provided as ConvertedType only fn get_test_converted_type_unsigned_integer_column_descr<T: DataType>( max_def_level: i16, diff --git a/parquet/src/compression.rs b/parquet/src/compression.rs index a5e49360a28a..ee5141cbe140 100644 --- a/parquet/src/compression.rs +++ b/parquet/src/compression.rs @@ -329,7 +329,7 @@ pub use zstd_codec::*; mod tests { use super::*; - use crate::util::test_common::*; + use crate::util::test_common::rand_gen::random_bytes; fn test_roundtrip(c: CodecType, data: &[u8]) { let mut c1 = create_codec(c).unwrap().unwrap(); diff --git a/parquet/src/data_type.rs b/parquet/src/data_type.rs index 43c9a4238a71..005b35570a32 100644 --- a/parquet/src/data_type.rs +++ b/parquet/src/data_type.rs @@ -574,8 +574,6 @@ pub(crate) mod private { use super::{ParquetError, Result, SliceAsBytes}; - pub type BitIndex = u64; - /// Sealed trait to start to remove specialisation from implementations /// /// This is done to force the associated value type to be unimplementable outside of this @@ -710,19 +708,6 @@ pub(crate) mod private { } } - /// Hopelessly unsafe function that emulates `num::as_ne_bytes` - /// - /// It is not recommended to use this outside of this private module as, while it - /// _should_ work for primitive values, it is little better than a transmutation - /// and can act as a backdoor into mis-interpreting types as arbitary byte slices - #[inline] - fn as_raw<'a, T>(value: *const T) -> &'a [u8] { - unsafe { - let value = value as *const u8; - std::slice::from_raw_parts(value, std::mem::size_of::<T>()) - } - } - macro_rules! impl_from_raw { ($ty: ty, $physical_ty: expr, $self: ident => $as_i64: block) => { impl ParquetValueType for $ty { diff --git a/parquet/src/encodings/decoding.rs b/parquet/src/encodings/decoding.rs index 58aa592d1424..3db050a0f43d 100644 --- a/parquet/src/encodings/decoding.rs +++ b/parquet/src/encodings/decoding.rs @@ -322,6 +322,12 @@ pub struct DictDecoder<T: DataType> { num_values: usize, } +impl<T: DataType> Default for DictDecoder<T> { + fn default() -> Self { + Self::new() + } +} + impl<T: DataType> DictDecoder<T> { /// Creates new dictionary decoder. pub fn new() -> Self { @@ -394,6 +400,12 @@ pub struct RleValueDecoder<T: DataType> { _phantom: PhantomData<T>, } +impl<T: DataType> Default for RleValueDecoder<T> { + fn default() -> Self { + Self::new() + } +} + impl<T: DataType> RleValueDecoder<T> { pub fn new() -> Self { Self { @@ -485,6 +497,15 @@ pub struct DeltaBitPackDecoder<T: DataType> { last_value: T::T, } +impl<T: DataType> Default for DeltaBitPackDecoder<T> +where + T::T: Default + FromPrimitive + WrappingAdd + Copy, +{ + fn default() -> Self { + Self::new() + } +} + impl<T: DataType> DeltaBitPackDecoder<T> where T::T: Default + FromPrimitive + WrappingAdd + Copy, @@ -706,8 +727,6 @@ where Ok(to_read) } - - fn values_left(&self) -> usize { self.values_left } @@ -751,6 +770,12 @@ pub struct DeltaLengthByteArrayDecoder<T: DataType> { _phantom: PhantomData<T>, } +impl<T: DataType> Default for DeltaLengthByteArrayDecoder<T> { + fn default() -> Self { + Self::new() + } +} + impl<T: DataType> DeltaLengthByteArrayDecoder<T> { /// Creates new delta length byte array decoder. pub fn new() -> Self { @@ -829,7 +854,10 @@ impl<T: DataType> Decoder<T> for DeltaLengthByteArrayDecoder<T> { Type::BYTE_ARRAY => { let num_values = cmp::min(num_values, self.num_values); - let next_offset: i32 = self.lengths[self.current_idx..self.current_idx + num_values].iter().sum(); + let next_offset: i32 = self.lengths + [self.current_idx..self.current_idx + num_values] + .iter() + .sum(); self.current_idx += num_values; self.offset += next_offset as usize; @@ -837,8 +865,9 @@ impl<T: DataType> Decoder<T> for DeltaLengthByteArrayDecoder<T> { self.num_values -= num_values; Ok(num_values) } - other_type => Err(general_err!( - "DeltaLengthByteArrayDecoder not support {}, only support byte array", other_type + other_type => Err(general_err!( + "DeltaLengthByteArrayDecoder not support {}, only support byte array", + other_type )), } } @@ -874,6 +903,12 @@ pub struct DeltaByteArrayDecoder<T: DataType> { _phantom: PhantomData<T>, } +impl<T: DataType> Default for DeltaByteArrayDecoder<T> { + fn default() -> Self { + Self::new() + } +} + impl<T: DataType> DeltaByteArrayDecoder<T> { /// Creates new delta byte array decoder. pub fn new() -> Self { @@ -990,7 +1025,7 @@ mod tests { use crate::schema::types::{ ColumnDescPtr, ColumnDescriptor, ColumnPath, Type as SchemaType, }; - use crate::util::{bit_util::set_array_bit, test_common::RandGen}; + use crate::util::test_common::rand_gen::RandGen; #[test] fn test_get_decoders() { @@ -1068,13 +1103,7 @@ mod tests { fn test_plain_skip_all_int32() { let data = vec![42, 18, 52]; let data_bytes = Int32Type::to_byte_array(&data[..]); - test_plain_skip::<Int32Type>( - ByteBufferPtr::new(data_bytes), - 3, - 5, - -1, - &[], - ); + test_plain_skip::<Int32Type>(ByteBufferPtr::new(data_bytes), 3, 5, -1, &[]); } #[test] @@ -1096,7 +1125,6 @@ mod tests { ); } - #[test] fn test_plain_decode_int64() { let data = vec![42, 18, 52]; @@ -1128,16 +1156,9 @@ mod tests { fn test_plain_skip_all_int64() { let data = vec![42, 18, 52]; let data_bytes = Int64Type::to_byte_array(&data[..]); - test_plain_skip::<Int64Type>( - ByteBufferPtr::new(data_bytes), - 3, - 3, - -1, - &[], - ); + test_plain_skip::<Int64Type>(ByteBufferPtr::new(data_bytes), 3, 3, -1, &[]); } - #[test] fn test_plain_decode_float() { let data = vec![3.14, 2.414, 12.51]; @@ -1169,13 +1190,7 @@ mod tests { fn test_plain_skip_all_float() { let data = vec![3.14, 2.414, 12.51]; let data_bytes = FloatType::to_byte_array(&data[..]); - test_plain_skip::<FloatType>( - ByteBufferPtr::new(data_bytes), - 3, - 4, - -1, - &[], - ); + test_plain_skip::<FloatType>(ByteBufferPtr::new(data_bytes), 3, 4, -1, &[]); } #[test] @@ -1195,13 +1210,7 @@ mod tests { fn test_plain_skip_all_double() { let data = vec![3.14f64, 2.414f64, 12.51f64]; let data_bytes = DoubleType::to_byte_array(&data[..]); - test_plain_skip::<DoubleType>( - ByteBufferPtr::new(data_bytes), - 3, - 5, - -1, - &[], - ); + test_plain_skip::<DoubleType>(ByteBufferPtr::new(data_bytes), 3, 5, -1, &[]); } #[test] @@ -1261,13 +1270,7 @@ mod tests { data[2].set_data(10, 20, 30); data[3].set_data(40, 50, 60); let data_bytes = Int96Type::to_byte_array(&data[..]); - test_plain_skip::<Int96Type>( - ByteBufferPtr::new(data_bytes), - 4, - 8, - -1, - &[], - ); + test_plain_skip::<Int96Type>(ByteBufferPtr::new(data_bytes), 4, 8, -1, &[]); } #[test] @@ -1307,16 +1310,9 @@ mod tests { false, true, false, false, true, false, true, true, false, true, ]; let data_bytes = BoolType::to_byte_array(&data[..]); - test_plain_skip::<BoolType>( - ByteBufferPtr::new(data_bytes), - 10, - 20, - -1, - &[], - ); + test_plain_skip::<BoolType>(ByteBufferPtr::new(data_bytes), 10, 20, -1, &[]); } - #[test] fn test_plain_decode_byte_array() { let mut data = vec![ByteArray::new(); 2]; @@ -1354,13 +1350,7 @@ mod tests { data[0].set_data(ByteBufferPtr::new(String::from("hello").into_bytes())); data[1].set_data(ByteBufferPtr::new(String::from("parquet").into_bytes())); let data_bytes = ByteArrayType::to_byte_array(&data[..]); - test_plain_skip::<ByteArrayType>( - ByteBufferPtr::new(data_bytes), - 2, - 2, - -1, - &[], - ); + test_plain_skip::<ByteArrayType>(ByteBufferPtr::new(data_bytes), 2, 2, -1, &[]); } #[test] @@ -1587,7 +1577,6 @@ mod tests { ]; test_skip::<Int32Type>(block_data.clone(), Encoding::DELTA_BINARY_PACKED, 5); test_skip::<Int32Type>(block_data, Encoding::DELTA_BINARY_PACKED, 100); - } #[test] @@ -1833,8 +1822,7 @@ mod tests { let col_descr = create_test_col_desc_ptr(-1, T::get_physical_type()); // Encode data - let mut encoder = - get_encoder::<T>(col_descr.clone(), encoding).expect("get encoder"); + let mut encoder = get_encoder::<T>(encoding).expect("get encoder"); for v in &data[..] { encoder.put(&v[..]).expect("ok to encode"); @@ -1867,17 +1855,14 @@ mod tests { let col_descr = create_test_col_desc_ptr(-1, T::get_physical_type()); // Encode data - let mut encoder = - get_encoder::<T>(col_descr.clone(), encoding).expect("get encoder"); + let mut encoder = get_encoder::<T>(encoding).expect("get encoder"); encoder.put(&data).expect("ok to encode"); let bytes = encoder.flush_buffer().expect("ok to flush buffer"); let mut decoder = get_decoder::<T>(col_descr, encoding).expect("get decoder"); - decoder - .set_data(bytes, data.len()) - .expect("ok to set data"); + decoder.set_data(bytes, data.len()).expect("ok to set data"); if skip >= data.len() { let skipped = decoder.skip(skip).expect("ok to skip"); @@ -1894,7 +1879,7 @@ mod tests { let expected = &data[skip..]; let mut buffer = vec![T::T::default(); remaining]; let fetched = decoder.get(&mut buffer).expect("ok to decode"); - assert_eq!(remaining,fetched); + assert_eq!(remaining, fetched); assert_eq!(&buffer, expected); } } @@ -1966,7 +1951,7 @@ mod tests { v.push(0); } if *item { - set_array_bit(&mut v[..], i); + v[i / 8] |= 1 << (i % 8); } } v diff --git a/parquet/src/encodings/encoding/dict_encoder.rs b/parquet/src/encodings/encoding/dict_encoder.rs index a7855cc84606..18deba65e687 100644 --- a/parquet/src/encodings/encoding/dict_encoder.rs +++ b/parquet/src/encodings/encoding/dict_encoder.rs @@ -73,9 +73,6 @@ impl<T: DataType> Storage for KeyStorage<T> { /// (max bit width = 32), followed by the values encoded using RLE/Bit packed described /// above (with the given bit width). pub struct DictEncoder<T: DataType> { - /// Descriptor for the column to be encoded. - desc: ColumnDescPtr, - interner: Interner<KeyStorage<T>>, /// The buffered indices @@ -92,7 +89,6 @@ impl<T: DataType> DictEncoder<T> { }; Self { - desc, interner: Interner::new(storage), indices: vec![], } @@ -117,7 +113,7 @@ impl<T: DataType> DictEncoder<T> { /// Writes out the dictionary values with PLAIN encoding in a byte buffer, and return /// the result. pub fn write_dict(&self) -> Result<ByteBufferPtr> { - let mut plain_encoder = PlainEncoder::<T>::new(self.desc.clone(), vec![]); + let mut plain_encoder = PlainEncoder::<T>::new(); plain_encoder.put(&self.interner.storage().uniques)?; plain_encoder.flush_buffer() } diff --git a/parquet/src/encodings/encoding/mod.rs b/parquet/src/encodings/encoding/mod.rs index 2c6bd9b371a0..050f1b9f8a63 100644 --- a/parquet/src/encodings/encoding/mod.rs +++ b/parquet/src/encodings/encoding/mod.rs @@ -24,7 +24,6 @@ use crate::data_type::private::ParquetValueType; use crate::data_type::*; use crate::encodings::rle::RleEncoder; use crate::errors::{ParquetError, Result}; -use crate::schema::types::ColumnDescPtr; use crate::util::{ bit_util::{self, num_required_bits, BitWriter}, memory::ByteBufferPtr, @@ -76,12 +75,9 @@ pub trait Encoder<T: DataType> { /// Gets a encoder for the particular data type `T` and encoding `encoding`. Memory usage /// for the encoder instance is tracked by `mem_tracker`. -pub fn get_encoder<T: DataType>( - desc: ColumnDescPtr, - encoding: Encoding, -) -> Result<Box<dyn Encoder<T>>> { +pub fn get_encoder<T: DataType>(encoding: Encoding) -> Result<Box<dyn Encoder<T>>> { let encoder: Box<dyn Encoder<T>> = match encoding { - Encoding::PLAIN => Box::new(PlainEncoder::new(desc, vec![])), + Encoding::PLAIN => Box::new(PlainEncoder::new()), Encoding::RLE_DICTIONARY | Encoding::PLAIN_DICTIONARY => { return Err(general_err!( "Cannot initialize this encoding through this function" @@ -113,17 +109,21 @@ pub fn get_encoder<T: DataType>( pub struct PlainEncoder<T: DataType> { buffer: Vec<u8>, bit_writer: BitWriter, - desc: ColumnDescPtr, _phantom: PhantomData<T>, } +impl<T: DataType> Default for PlainEncoder<T> { + fn default() -> Self { + Self::new() + } +} + impl<T: DataType> PlainEncoder<T> { /// Creates new plain encoder. - pub fn new(desc: ColumnDescPtr, buffer: Vec<u8>) -> Self { + pub fn new() -> Self { Self { - buffer, + buffer: vec![], bit_writer: BitWriter::new(256), - desc, _phantom: PhantomData, } } @@ -171,6 +171,12 @@ pub struct RleValueEncoder<T: DataType> { _phantom: PhantomData<T>, } +impl<T: DataType> Default for RleValueEncoder<T> { + fn default() -> Self { + Self::new() + } +} + impl<T: DataType> RleValueEncoder<T> { /// Creates new rle value encoder. pub fn new() -> Self { @@ -280,6 +286,12 @@ pub struct DeltaBitPackEncoder<T: DataType> { _phantom: PhantomData<T>, } +impl<T: DataType> Default for DeltaBitPackEncoder<T> { + fn default() -> Self { + Self::new() + } +} + impl<T: DataType> DeltaBitPackEncoder<T> { /// Creates new delta bit packed encoder. pub fn new() -> Self { @@ -531,6 +543,12 @@ pub struct DeltaLengthByteArrayEncoder<T: DataType> { _phantom: PhantomData<T>, } +impl<T: DataType> Default for DeltaLengthByteArrayEncoder<T> { + fn default() -> Self { + Self::new() + } +} + impl<T: DataType> DeltaLengthByteArrayEncoder<T> { /// Creates new delta length byte array encoder. pub fn new() -> Self { @@ -610,6 +628,12 @@ pub struct DeltaByteArrayEncoder<T: DataType> { _phantom: PhantomData<T>, } +impl<T: DataType> Default for DeltaByteArrayEncoder<T> { + fn default() -> Self { + Self::new() + } +} + impl<T: DataType> DeltaByteArrayEncoder<T> { /// Creates new delta byte array encoder. pub fn new() -> Self { @@ -705,7 +729,7 @@ mod tests { use crate::schema::types::{ ColumnDescPtr, ColumnDescriptor, ColumnPath, Type as SchemaType, }; - use crate::util::test_common::{random_bytes, RandGen}; + use crate::util::test_common::rand_gen::{random_bytes, RandGen}; const TEST_SET_SIZE: usize = 1024; @@ -847,7 +871,7 @@ mod tests { Encoding::PLAIN_DICTIONARY | Encoding::RLE_DICTIONARY => { Box::new(create_test_dict_encoder::<T>(type_length)) } - _ => create_test_encoder::<T>(type_length, encoding), + _ => create_test_encoder::<T>(encoding), }; assert_eq!(encoder.estimated_data_encoded_size(), initial_size); @@ -900,7 +924,7 @@ mod tests { #[test] fn test_issue_47() { let mut encoder = - create_test_encoder::<ByteArrayType>(0, Encoding::DELTA_BYTE_ARRAY); + create_test_encoder::<ByteArrayType>(Encoding::DELTA_BYTE_ARRAY); let mut decoder = create_test_decoder::<ByteArrayType>(0, Encoding::DELTA_BYTE_ARRAY); @@ -952,7 +976,7 @@ mod tests { impl<T: DataType + RandGen<T>> EncodingTester<T> for T { fn test_internal(enc: Encoding, total: usize, type_length: i32) -> Result<()> { - let mut encoder = create_test_encoder::<T>(type_length, enc); + let mut encoder = create_test_encoder::<T>(enc); let mut decoder = create_test_decoder::<T>(type_length, enc); let mut values = <T as RandGen<T>>::gen_vec(type_length, total); let mut result_data = vec![T::T::default(); total]; @@ -1054,8 +1078,7 @@ mod tests { encoding: Encoding, err: Option<ParquetError>, ) { - let descr = create_test_col_desc_ptr(-1, T::get_physical_type()); - let encoder = get_encoder::<T>(descr, encoding); + let encoder = get_encoder::<T>(encoding); match err { Some(parquet_error) => { assert!(encoder.is_err()); @@ -1082,12 +1105,8 @@ mod tests { )) } - fn create_test_encoder<T: DataType>( - type_len: i32, - enc: Encoding, - ) -> Box<dyn Encoder<T>> { - let desc = create_test_col_desc_ptr(type_len, T::get_physical_type()); - get_encoder(desc, enc).unwrap() + fn create_test_encoder<T: DataType>(enc: Encoding) -> Box<dyn Encoder<T>> { + get_encoder(enc).unwrap() } fn create_test_decoder<T: DataType>( diff --git a/parquet/src/encodings/levels.rs b/parquet/src/encodings/levels.rs index 62c68d843c71..40af135ff28d 100644 --- a/parquet/src/encodings/levels.rs +++ b/parquet/src/encodings/levels.rs @@ -142,12 +142,14 @@ impl LevelEncoder { /// Decoder for definition/repetition levels. /// Currently only supports RLE and BIT_PACKED encoding for Data Page v1 and /// RLE for Data Page v2. +#[allow(unused)] pub enum LevelDecoder { Rle(Option<usize>, RleDecoder), RleV2(Option<usize>, RleDecoder), BitPacked(Option<usize>, u8, BitReader), } +#[allow(unused)] impl LevelDecoder { /// Creates new level decoder based on encoding and max definition/repetition level. /// This method only initializes level decoder, `set_data` method must be called @@ -274,7 +276,7 @@ impl LevelDecoder { mod tests { use super::*; - use crate::util::test_common::random_numbers_range; + use crate::util::test_common::rand_gen::random_numbers_range; fn test_internal_roundtrip(enc: Encoding, levels: &[i16], max_level: i16, v2: bool) { let mut encoder = if v2 { diff --git a/parquet/src/encodings/rle.rs b/parquet/src/encodings/rle.rs index aad833e0eee3..39a0aa4d03da 100644 --- a/parquet/src/encodings/rle.rs +++ b/parquet/src/encodings/rle.rs @@ -45,7 +45,6 @@ use crate::util::{ /// Maximum groups per bit-packed run. Current value is 64. const MAX_GROUPS_PER_BIT_PACKED_RUN: usize = 1 << 6; const MAX_VALUES_PER_BIT_PACKED_RUN: usize = MAX_GROUPS_PER_BIT_PACKED_RUN * 8; -const MAX_WRITER_BUF_SIZE: usize = 1 << 10; /// A RLE/Bit-Packing hybrid encoder. // TODO: tracking memory usage @@ -56,9 +55,6 @@ pub struct RleEncoder { // Underlying writer which holds an internal buffer. bit_writer: BitWriter, - // The maximum byte size a single run can take. - max_run_byte_size: usize, - // Buffered values for bit-packed runs. buffered_values: [u64; 8], @@ -82,6 +78,7 @@ pub struct RleEncoder { } impl RleEncoder { + #[allow(unused)] pub fn new(bit_width: u8, buffer_len: usize) -> Self { let buffer = Vec::with_capacity(buffer_len); RleEncoder::new_from_buf(bit_width, buffer) @@ -89,12 +86,10 @@ impl RleEncoder { /// Initialize the encoder from existing `buffer` pub fn new_from_buf(bit_width: u8, buffer: Vec<u8>) -> Self { - let max_run_byte_size = RleEncoder::min_buffer_size(bit_width); let bit_writer = BitWriter::new_from_buf(buffer); RleEncoder { bit_width, bit_writer, - max_run_byte_size, buffered_values: [0; 8], num_buffered_values: 0, current_value: 0, @@ -162,6 +157,7 @@ impl RleEncoder { } #[inline] + #[allow(unused)] pub fn buffer(&self) -> &[u8] { self.bit_writer.buffer() } @@ -171,6 +167,7 @@ impl RleEncoder { self.bit_writer.bytes_written() } + #[allow(unused)] pub fn is_empty(&self) -> bool { self.bit_writer.bytes_written() == 0 } @@ -184,6 +181,7 @@ impl RleEncoder { /// Borrow equivalent of the `consume` method. /// Call `clear()` after invoking this method. #[inline] + #[allow(unused)] pub fn flush_buffer(&mut self) -> &[u8] { self.flush(); self.bit_writer.flush_buffer() @@ -192,6 +190,7 @@ impl RleEncoder { /// Clears the internal state so this encoder can be reused (e.g., after becoming /// full). #[inline] + #[allow(unused)] pub fn clear(&mut self) { self.bit_writer.clear(); self.num_buffered_values = 0; diff --git a/parquet/src/errors.rs b/parquet/src/errors.rs index c2fb5bd66cf9..68378419330e 100644 --- a/parquet/src/errors.rs +++ b/parquet/src/errors.rs @@ -148,8 +148,8 @@ macro_rules! arrow_err { // Convert parquet error into other errors #[cfg(any(feature = "arrow", test))] -impl Into<ArrowError> for ParquetError { - fn into(self) -> ArrowError { - ArrowError::ParquetError(format!("{}", self)) +impl From<ParquetError> for ArrowError { + fn from(p: ParquetError) -> Self { + Self::ParquetError(format!("{}", p)) } } diff --git a/parquet/src/file/metadata.rs b/parquet/src/file/metadata.rs index 58eaf7a8c875..018dd95d9f35 100644 --- a/parquet/src/file/metadata.rs +++ b/parquet/src/file/metadata.rs @@ -834,6 +834,12 @@ pub struct ColumnIndexBuilder { valid: bool, } +impl Default for ColumnIndexBuilder { + fn default() -> Self { + Self::new() + } +} + impl ColumnIndexBuilder { pub fn new() -> Self { ColumnIndexBuilder { @@ -887,6 +893,12 @@ pub struct OffsetIndexBuilder { current_first_row_index: i64, } +impl Default for OffsetIndexBuilder { + fn default() -> Self { + Self::new() + } +} + impl OffsetIndexBuilder { pub fn new() -> Self { OffsetIndexBuilder { diff --git a/parquet/src/file/page_index/index.rs b/parquet/src/file/page_index/index.rs index 45381234c027..f29b80accae2 100644 --- a/parquet/src/file/page_index/index.rs +++ b/parquet/src/file/page_index/index.rs @@ -47,6 +47,7 @@ impl<T> PageIndex<T> { } #[derive(Debug, Clone, PartialEq)] +#[allow(non_camel_case_types)] pub enum Index { /// Sometimes reading page index from parquet file /// will only return pageLocations without min_max index, diff --git a/parquet/src/file/page_index/mod.rs b/parquet/src/file/page_index/mod.rs index fc87ef20448f..bb7808f16487 100644 --- a/parquet/src/file/page_index/mod.rs +++ b/parquet/src/file/page_index/mod.rs @@ -17,4 +17,6 @@ pub mod index; pub mod index_reader; + +#[cfg(test)] pub(crate) mod range; diff --git a/parquet/src/file/page_index/range.rs b/parquet/src/file/page_index/range.rs index 06c06553ccd5..e9741ec8e7fd 100644 --- a/parquet/src/file/page_index/range.rs +++ b/parquet/src/file/page_index/range.rs @@ -213,6 +213,7 @@ impl RowRanges { result } + #[allow(unused)] pub fn row_count(&self) -> usize { self.ranges.iter().map(|x| x.count()).sum() } diff --git a/parquet/src/file/properties.rs b/parquet/src/file/properties.rs index 9ca7c4daa597..c96439820262 100644 --- a/parquet/src/file/properties.rs +++ b/parquet/src/file/properties.rs @@ -69,6 +69,7 @@ const DEFAULT_CREATED_BY: &str = env!("PARQUET_CREATED_BY"); /// /// Basic constant, which is not part of the Thrift definition. #[derive(Debug, Clone, Copy, PartialEq)] +#[allow(non_camel_case_types)] pub enum WriterVersion { PARQUET_1_0, PARQUET_2_0, @@ -360,7 +361,7 @@ impl WriterPropertiesBuilder { fn get_mut_props(&mut self, col: ColumnPath) -> &mut ColumnProperties { self.column_properties .entry(col) - .or_insert(ColumnProperties::new()) + .or_insert_with(ColumnProperties::new) } /// Sets encoding for a column. diff --git a/parquet/src/file/serialized_reader.rs b/parquet/src/file/serialized_reader.rs index e0053225d249..045410d03809 100644 --- a/parquet/src/file/serialized_reader.rs +++ b/parquet/src/file/serialized_reader.rs @@ -141,6 +141,7 @@ pub struct SerializedFileReader<R: ChunkReader> { /// A builder for [`ReadOptions`]. /// For the predicates that are added to the builder, /// they will be chained using 'AND' to filter the row groups. +#[derive(Default)] pub struct ReadOptionsBuilder { predicates: Vec<Box<dyn FnMut(&RowGroupMetaData, usize) -> bool>>, enable_page_index: bool, @@ -149,10 +150,7 @@ pub struct ReadOptionsBuilder { impl ReadOptionsBuilder { /// New builder pub fn new() -> Self { - ReadOptionsBuilder { - predicates: vec![], - enable_page_index: false, - } + Self::default() } /// Add a predicate on row group metadata to the reading option, @@ -692,7 +690,7 @@ mod tests { use crate::record::RowAccessor; use crate::schema::parser::parse_message_type; use crate::util::bit_util::from_le_slice; - use crate::util::test_common::{get_test_file, get_test_path}; + use crate::util::test_common::file_util::{get_test_file, get_test_path}; use parquet_format::BoundaryOrder; use std::sync::Arc; diff --git a/parquet/src/lib.rs b/parquet/src/lib.rs index 5ee43f8ad6fb..90fe399e78d7 100644 --- a/parquet/src/lib.rs +++ b/parquet/src/lib.rs @@ -33,14 +33,6 @@ //! //! 3. [arrow::async_reader] for `async` reading and writing parquet //! files to Arrow `RecordBatch`es (requires the `async` feature). -#![allow(dead_code)] -#![allow(non_camel_case_types)] -#![allow( - clippy::from_over_into, - clippy::new_without_default, - clippy::or_fun_call, - clippy::too_many_arguments -)] /// Defines a an item with an experimental public API /// diff --git a/parquet/src/record/reader.rs b/parquet/src/record/reader.rs index 05b63661f09b..0b7e04587354 100644 --- a/parquet/src/record/reader.rs +++ b/parquet/src/record/reader.rs @@ -40,6 +40,12 @@ pub struct TreeBuilder { batch_size: usize, } +impl Default for TreeBuilder { + fn default() -> Self { + Self::new() + } +} + impl TreeBuilder { /// Creates new tree builder with default parameters. pub fn new() -> Self { @@ -822,7 +828,7 @@ mod tests { use crate::file::reader::{FileReader, SerializedFileReader}; use crate::record::api::{Field, Row, RowAccessor, RowFormatter}; use crate::schema::parser::parse_message_type; - use crate::util::test_common::{get_test_file, get_test_path}; + use crate::util::test_common::file_util::{get_test_file, get_test_path}; use std::convert::TryFrom; // Convenient macros to assemble row, list, map, and group. diff --git a/parquet/src/record/triplet.rs b/parquet/src/record/triplet.rs index de566a122e20..5a7e2a0ca74e 100644 --- a/parquet/src/record/triplet.rs +++ b/parquet/src/record/triplet.rs @@ -363,7 +363,7 @@ mod tests { use crate::file::reader::{FileReader, SerializedFileReader}; use crate::schema::types::ColumnPath; - use crate::util::test_common::get_test_file; + use crate::util::test_common::file_util::get_test_file; #[test] #[should_panic(expected = "Expected positive batch size, found: 0")] diff --git a/parquet/src/util/bit_util.rs b/parquet/src/util/bit_util.rs index 1dec9b03f082..c70384e7aa2f 100644 --- a/parquet/src/util/bit_util.rs +++ b/parquet/src/util/bit_util.rs @@ -101,38 +101,6 @@ macro_rules! read_num_bytes { }}; } -/// Converts value `val` of type `T` to a byte vector, by reading `num_bytes` from `val`. -/// NOTE: if `val` is less than the size of `T` then it can be truncated. -#[inline] -pub fn convert_to_bytes<T>(val: &T, num_bytes: usize) -> Vec<u8> -where - T: ?Sized + AsBytes, -{ - let mut bytes: Vec<u8> = vec![0; num_bytes]; - memcpy_value(val.as_bytes(), num_bytes, &mut bytes); - bytes -} - -#[inline] -pub fn memcpy(source: &[u8], target: &mut [u8]) { - assert!(target.len() >= source.len()); - target[..source.len()].copy_from_slice(source) -} - -#[inline] -pub fn memcpy_value<T>(source: &T, num_bytes: usize, target: &mut [u8]) -where - T: ?Sized + AsBytes, -{ - assert!( - target.len() >= num_bytes, - "Not enough space. Only had {} bytes but need to put {} bytes", - target.len(), - num_bytes - ); - memcpy(&source.as_bytes()[..num_bytes], target) -} - /// Returns the ceil of value/divisor. /// /// This function should be removed after @@ -152,16 +120,6 @@ pub fn trailing_bits(v: u64, num_bits: usize) -> u64 { } } -#[inline] -pub fn set_array_bit(bits: &mut [u8], i: usize) { - bits[i / 8] |= 1 << (i % 8); -} - -#[inline] -pub fn unset_array_bit(bits: &mut [u8], i: usize) { - bits[i / 8] &= !(1 << (i % 8)); -} - /// Returns the minimum number of bits needed to represent the value 'x' #[inline] pub fn num_required_bits(x: u64) -> u8 { @@ -728,20 +686,11 @@ impl From<Vec<u8>> for BitReader { } } -/// Returns the nearest multiple of `factor` that is `>=` than `num`. Here `factor` must -/// be a power of 2. -/// -/// Copied from the arrow crate to make arrow optional -pub fn round_upto_power_of_2(num: usize, factor: usize) -> usize { - debug_assert!(factor > 0 && (factor & (factor - 1)) == 0); - (num + (factor - 1)) & !(factor - 1) -} - #[cfg(test)] mod tests { - use super::super::test_common::*; use super::*; + use crate::util::test_common::rand_gen::random_numbers; use rand::distributions::{Distribution, Standard}; use std::fmt::Debug; @@ -874,25 +823,6 @@ mod tests { assert_eq!(bit_reader.get_zigzag_vlq_int(), Some(-2)); } - #[test] - fn test_set_array_bit() { - let mut buffer = vec![0, 0, 0]; - set_array_bit(&mut buffer[..], 1); - assert_eq!(buffer, vec![2, 0, 0]); - set_array_bit(&mut buffer[..], 4); - assert_eq!(buffer, vec![18, 0, 0]); - unset_array_bit(&mut buffer[..], 1); - assert_eq!(buffer, vec![16, 0, 0]); - set_array_bit(&mut buffer[..], 10); - assert_eq!(buffer, vec![16, 4, 0]); - set_array_bit(&mut buffer[..], 10); - assert_eq!(buffer, vec![16, 4, 0]); - set_array_bit(&mut buffer[..], 11); - assert_eq!(buffer, vec![16, 12, 0]); - unset_array_bit(&mut buffer[..], 10); - assert_eq!(buffer, vec![16, 8, 0]); - } - #[test] fn test_num_required_bits() { assert_eq!(num_required_bits(0), 0); diff --git a/parquet/src/util/io.rs b/parquet/src/util/io.rs index 016d45075ee9..1fb92063e27c 100644 --- a/parquet/src/util/io.rs +++ b/parquet/src/util/io.rs @@ -167,7 +167,7 @@ mod tests { use std::iter; - use crate::util::test_common::get_test_file; + use crate::util::test_common::file_util::get_test_file; #[test] fn test_io_read_fully() {
diff --git a/parquet/src/arrow/array_reader/test_util.rs b/parquet/src/arrow/array_reader/test_util.rs index da9b8d3bf9b2..ca1aabfd4aa1 100644 --- a/parquet/src/arrow/array_reader/test_util.rs +++ b/parquet/src/arrow/array_reader/test_util.rs @@ -48,8 +48,7 @@ pub fn utf8_column() -> ColumnDescPtr { /// Encode `data` with the provided `encoding` pub fn encode_byte_array(encoding: Encoding, data: &[ByteArray]) -> ByteBufferPtr { - let descriptor = utf8_column(); - let mut encoder = get_encoder::<ByteArrayType>(descriptor, encoding).unwrap(); + let mut encoder = get_encoder::<ByteArrayType>(encoding).unwrap(); encoder.put(data).unwrap(); encoder.flush_buffer().unwrap() diff --git a/parquet/src/util/test_common/mod.rs b/parquet/src/util/test_common/mod.rs index f0beb16ca954..504219ecae19 100644 --- a/parquet/src/util/test_common/mod.rs +++ b/parquet/src/util/test_common/mod.rs @@ -15,17 +15,10 @@ // specific language governing permissions and limitations // under the License. -pub mod file_util; pub mod page_util; -pub mod rand_gen; - -pub use self::rand_gen::random_bools; -pub use self::rand_gen::random_bytes; -pub use self::rand_gen::random_numbers; -pub use self::rand_gen::random_numbers_range; -pub use self::rand_gen::RandGen; -pub use self::file_util::get_test_file; -pub use self::file_util::get_test_path; +#[cfg(test)] +pub mod file_util; -pub use self::page_util::make_pages; +#[cfg(test)] +pub mod rand_gen; \ No newline at end of file diff --git a/parquet/src/util/test_common/page_util.rs b/parquet/src/util/test_common/page_util.rs index bc197d00e00d..dffcb2a44e87 100644 --- a/parquet/src/util/test_common/page_util.rs +++ b/parquet/src/util/test_common/page_util.rs @@ -19,14 +19,11 @@ use crate::basic::Encoding; use crate::column::page::{Page, PageIterator}; use crate::column::page::{PageMetadata, PageReader}; use crate::data_type::DataType; -use crate::encodings::encoding::{get_encoder, DictEncoder, Encoder}; +use crate::encodings::encoding::{get_encoder, Encoder}; use crate::encodings::levels::LevelEncoder; use crate::errors::Result; use crate::schema::types::{ColumnDescPtr, SchemaDescPtr}; use crate::util::memory::ByteBufferPtr; -use crate::util::test_common::random_numbers_range; -use rand::distributions::uniform::SampleUniform; -use std::collections::VecDeque; use std::mem; pub trait DataPageBuilder { @@ -44,7 +41,6 @@ pub trait DataPageBuilder { /// - consume() /// in order to populate and obtain a data page. pub struct DataPageBuilderImpl { - desc: ColumnDescPtr, encoding: Option<Encoding>, num_values: u32, buffer: Vec<u8>, @@ -57,9 +53,8 @@ impl DataPageBuilderImpl { // `num_values` is the number of non-null values to put in the data page. // `datapage_v2` flag is used to indicate if the generated data page should use V2 // format or not. - pub fn new(desc: ColumnDescPtr, num_values: u32, datapage_v2: bool) -> Self { + pub fn new(_desc: ColumnDescPtr, num_values: u32, datapage_v2: bool) -> Self { DataPageBuilderImpl { - desc, encoding: None, num_values, buffer: vec![], @@ -111,8 +106,7 @@ impl DataPageBuilder for DataPageBuilderImpl { ); self.encoding = Some(encoding); let mut encoder: Box<dyn Encoder<T>> = - get_encoder::<T>(self.desc.clone(), encoding) - .expect("get_encoder() should be OK"); + get_encoder::<T>(encoding).expect("get_encoder() should be OK"); encoder.put(values).expect("put() should be OK"); let encoded_values = encoder .flush_buffer() @@ -229,88 +223,3 @@ impl<I: Iterator<Item = Vec<Page>> + Send> PageIterator for InMemoryPageIterator Ok(self.column_desc.clone()) } } - -pub fn make_pages<T: DataType>( - desc: ColumnDescPtr, - encoding: Encoding, - num_pages: usize, - levels_per_page: usize, - min: T::T, - max: T::T, - def_levels: &mut Vec<i16>, - rep_levels: &mut Vec<i16>, - values: &mut Vec<T::T>, - pages: &mut VecDeque<Page>, - use_v2: bool, -) where - T::T: PartialOrd + SampleUniform + Copy, -{ - let mut num_values = 0; - let max_def_level = desc.max_def_level(); - let max_rep_level = desc.max_rep_level(); - - let mut dict_encoder = DictEncoder::<T>::new(desc.clone()); - - for i in 0..num_pages { - let mut num_values_cur_page = 0; - let level_range = i * levels_per_page..(i + 1) * levels_per_page; - - if max_def_level > 0 { - random_numbers_range(levels_per_page, 0, max_def_level + 1, def_levels); - for dl in &def_levels[level_range.clone()] { - if *dl == max_def_level { - num_values_cur_page += 1; - } - } - } else { - num_values_cur_page = levels_per_page; - } - if max_rep_level > 0 { - random_numbers_range(levels_per_page, 0, max_rep_level + 1, rep_levels); - } - random_numbers_range(num_values_cur_page, min, max, values); - - // Generate the current page - - let mut pb = - DataPageBuilderImpl::new(desc.clone(), num_values_cur_page as u32, use_v2); - if max_rep_level > 0 { - pb.add_rep_levels(max_rep_level, &rep_levels[level_range.clone()]); - } - if max_def_level > 0 { - pb.add_def_levels(max_def_level, &def_levels[level_range]); - } - - let value_range = num_values..num_values + num_values_cur_page; - match encoding { - Encoding::PLAIN_DICTIONARY | Encoding::RLE_DICTIONARY => { - let _ = dict_encoder.put(&values[value_range.clone()]); - let indices = dict_encoder - .write_indices() - .expect("write_indices() should be OK"); - pb.add_indices(indices); - } - Encoding::PLAIN => { - pb.add_values::<T>(encoding, &values[value_range]); - } - enc => panic!("Unexpected encoding {}", enc), - } - - let data_page = pb.consume(); - pages.push_back(data_page); - num_values += num_values_cur_page; - } - - if encoding == Encoding::PLAIN_DICTIONARY || encoding == Encoding::RLE_DICTIONARY { - let dict = dict_encoder - .write_dict() - .expect("write_dict() should be OK"); - let dict_page = Page::DictionaryPage { - buf: dict, - num_values: dict_encoder.num_entries() as u32, - encoding: Encoding::RLE_DICTIONARY, - is_sorted: false, - }; - pages.push_front(dict_page); - } -} diff --git a/parquet/src/util/test_common/rand_gen.rs b/parquet/src/util/test_common/rand_gen.rs index d9c256577684..4e54aa7999cf 100644 --- a/parquet/src/util/test_common/rand_gen.rs +++ b/parquet/src/util/test_common/rand_gen.rs @@ -15,13 +15,19 @@ // specific language governing permissions and limitations // under the License. +use crate::basic::Encoding; +use crate::column::page::Page; use rand::{ distributions::{uniform::SampleUniform, Distribution, Standard}, thread_rng, Rng, }; +use std::collections::VecDeque; use crate::data_type::*; +use crate::encodings::encoding::{DictEncoder, Encoder}; +use crate::schema::types::ColumnDescPtr; use crate::util::memory::ByteBufferPtr; +use crate::util::{DataPageBuilder, DataPageBuilderImpl}; /// Random generator of data type `T` values and sequences. pub trait RandGen<T: DataType> { @@ -106,15 +112,6 @@ pub fn random_bytes(n: usize) -> Vec<u8> { result } -pub fn random_bools(n: usize) -> Vec<bool> { - let mut result = vec![]; - let mut rng = thread_rng(); - for _ in 0..n { - result.push(rng.gen::<bool>()); - } - result -} - pub fn random_numbers<T>(n: usize) -> Vec<T> where Standard: Distribution<T>, @@ -132,3 +129,89 @@ where result.push(rng.gen_range(low..high)); } } + +#[allow(clippy::too_many_arguments)] +pub fn make_pages<T: DataType>( + desc: ColumnDescPtr, + encoding: Encoding, + num_pages: usize, + levels_per_page: usize, + min: T::T, + max: T::T, + def_levels: &mut Vec<i16>, + rep_levels: &mut Vec<i16>, + values: &mut Vec<T::T>, + pages: &mut VecDeque<Page>, + use_v2: bool, +) where + T::T: PartialOrd + SampleUniform + Copy, +{ + let mut num_values = 0; + let max_def_level = desc.max_def_level(); + let max_rep_level = desc.max_rep_level(); + + let mut dict_encoder = DictEncoder::<T>::new(desc.clone()); + + for i in 0..num_pages { + let mut num_values_cur_page = 0; + let level_range = i * levels_per_page..(i + 1) * levels_per_page; + + if max_def_level > 0 { + random_numbers_range(levels_per_page, 0, max_def_level + 1, def_levels); + for dl in &def_levels[level_range.clone()] { + if *dl == max_def_level { + num_values_cur_page += 1; + } + } + } else { + num_values_cur_page = levels_per_page; + } + if max_rep_level > 0 { + random_numbers_range(levels_per_page, 0, max_rep_level + 1, rep_levels); + } + random_numbers_range(num_values_cur_page, min, max, values); + + // Generate the current page + + let mut pb = + DataPageBuilderImpl::new(desc.clone(), num_values_cur_page as u32, use_v2); + if max_rep_level > 0 { + pb.add_rep_levels(max_rep_level, &rep_levels[level_range.clone()]); + } + if max_def_level > 0 { + pb.add_def_levels(max_def_level, &def_levels[level_range]); + } + + let value_range = num_values..num_values + num_values_cur_page; + match encoding { + Encoding::PLAIN_DICTIONARY | Encoding::RLE_DICTIONARY => { + let _ = dict_encoder.put(&values[value_range.clone()]); + let indices = dict_encoder + .write_indices() + .expect("write_indices() should be OK"); + pb.add_indices(indices); + } + Encoding::PLAIN => { + pb.add_values::<T>(encoding, &values[value_range]); + } + enc => panic!("Unexpected encoding {}", enc), + } + + let data_page = pb.consume(); + pages.push_back(data_page); + num_values += num_values_cur_page; + } + + if encoding == Encoding::PLAIN_DICTIONARY || encoding == Encoding::RLE_DICTIONARY { + let dict = dict_encoder + .write_dict() + .expect("write_dict() should be OK"); + let dict_page = Page::DictionaryPage { + buf: dict, + num_values: dict_encoder.num_entries() as u32, + encoding: Encoding::RLE_DICTIONARY, + is_sorted: false, + }; + pages.push_front(dict_page); + } +}
Fix all clippy lints in parquet crate **Describe the bug** Due to "historical reasons" there are several clippy lints that are disabled in the parquet crate https://github.com/apache/arrow-rs/blob/master/parquet/src/lib.rs#L18-L36 ```rust #![allow(incomplete_features)] #![allow(dead_code)] #![allow(non_camel_case_types)] #![allow( clippy::approx_constant, clippy::cast_ptr_alignment, clippy::float_cmp, clippy::float_equality_without_abs, clippy::from_over_into, clippy::many_single_char_names, clippy::needless_range_loop, clippy::new_without_default, clippy::or_fun_call, clippy::same_item_push, clippy::too_many_arguments, clippy::transmute_ptr_to_ptr, clippy::upper_case_acronyms, clippy::vec_init_then_push )] ``` It would be great to clean up the code to pass these lints for tidiness **To Reproduce** Remove one of the `#[allow]` lines above, run `clippy` **Expected behavior** Clippy runs cleanly without blank `#allow` across the whole crate **Additional context** Add any other context about the problem here.
I'd like to have a try if no one else has been doing it! Rust Clippy is really interesting! There are many dead code and unused public functions. I am not sure whether to clean them up. > There are many dead code and unused public functions. I am not sure whether to clean them up. I recommend doing this issue in a few PRs -- in the first take care of the easier lints, and then in follow ons we can sort out dead code / public function nonsense together Lots of `pub` members are detected as dead code. I am not sure whether to clean them up. For example: ```rust warning: enum is never used: `LevelDecoder` --> parquet/src/encodings/levels.rs:151:10 | 151 | pub enum LevelDecoder { | ^^^^^^^^^^^^ warning: associated function is never used: `v1` --> parquet/src/encodings/levels.rs:165:12 | 165 | pub fn v1(encoding: Encoding, max_level: i16) -> Self { | ^^ warning: associated function is never used: `v2` --> parquet/src/encodings/levels.rs:180:12 | 180 | pub fn v2(max_level: i16) -> Self { | ^^ warning: associated function is never used: `set_data` --> parquet/src/encodings/levels.rs:194:12 | 194 | pub fn set_data(&mut self, num_buffered_values: usize, data: ByteBufferPtr) -> usize { | ^^^^^^^^ warning: associated function is never used: `set_data_range` --> parquet/src/encodings/levels.rs:221:12 | 221 | pub fn set_data_range( | ^^^^^^^^^^^^^^ warning: associated function is never used: `is_data_set` --> parquet/src/encodings/levels.rs:242:12 | 242 | pub fn is_data_set(&self) -> bool { | ^^^^^^^^^^^ warning: associated function is never used: `get` --> parquet/src/encodings/levels.rs:254:12 | 254 | pub fn get(&mut self, buffer: &mut [i16]) -> Result<usize> { | ^^^ warning: associated function is never used: `buffer` --> parquet/src/encodings/rle.rs:171:12 | 171 | pub fn buffer(&self) -> &[u8] { | ^^^^^^ warning: associated function is never used: `get` --> parquet/src/encodings/rle.rs:358:12 | 358 | pub fn get<T: FromBytes>(&mut self) -> Result<Option<T>> { ``` Sorry for the late reply @HaoYang670 > Lots of pub members are detected as dead code. I am not sure whether to clean them up. For example: If the code is dead I think we should remove it. One way for `pub` functions to be dead is if the module they are defined in is not `pub`. I am not sure how you are running clippy, but it may also be that some of these structs are only used when certain features of the `parquet` crate are enabled. I believe our CI system has good coverage so feel free to try removing them and if the CI passes I think it is a good change > but it may also be that some of these structs are only used when certain features of the `parquet` crate are enabled. Thank you @alamb. There are some experimental mods under `parquet`. And I have to run `cargo clippy --features experimental` to make them public. But I am not sure whether our CI adds this flag. Clippy is run like this: https://github.com/apache/arrow-rs/blob/master/.github/workflows/rust.yml#L211-L250 ``` cargo clippy --features test_common --features prettyprint --features=async --all-targets --workspace -- -D warnings ``` Perhaps we can also add the `experimental` features to this list? After https://github.com/apache/arrow-rs/pull/2190 clippy is run just for the parquet crate (which now includes the `--experimental` flag) So once that is merged, the first order of business will be to make this command run cleanly: ```shell cargo clippy -p parquet --all-targets --all-features -- -D warnings ``` And then we can move on to removing the additional lints
2022-08-08T19:09:34Z
20.0
27f4762c8794ef1c5d042933562185980eb85ae5
[ "parquet/src/schema/types.rs - schema::types::ColumnPath::append (line 674)" ]
[ "parquet/src/file/mod.rs - file (line 64) - compile", "parquet/src/file/mod.rs - file (line 81) - compile", "parquet/src/file/mod.rs - file (line 29) - compile", "parquet/src/record/api.rs - record::api::Row::get_column_iter (line 62) - compile", "parquet/src/column/mod.rs - column (line 38) - compile", "parquet/src/schema/printer.rs - schema::printer (line 23)", "parquet/src/file/statistics.rs - file::statistics (line 23)", "parquet/src/arrow/mod.rs - arrow (line 55)", "parquet/src/schema/parser.rs - schema::parser (line 24)", "parquet/src/schema/mod.rs - schema (line 22)", "parquet/src/arrow/mod.rs - arrow (line 68)", "parquet/src/arrow/mod.rs - arrow (line 27)", "parquet/src/file/properties.rs - file::properties (line 22)", "parquet/src/schema/types.rs - schema::types::ColumnPath::string (line 663)", "parquet/src/record/api.rs - record::api::RowFormatter (line 140)" ]
[]
[ "parquet/src/arrow/arrow_writer/mod.rs - arrow::arrow_writer::ArrowWriter (line 55)" ]
apache/arrow-rs
5,092
apache__arrow-rs-5092
[ "5091" ]
481652a4f8d972b633063158903dbdb0adcf094d
diff --git a/arrow-data/src/transform/mod.rs b/arrow-data/src/transform/mod.rs index af25e9c7e3dc..268cf10f2326 100644 --- a/arrow-data/src/transform/mod.rs +++ b/arrow-data/src/transform/mod.rs @@ -354,6 +354,14 @@ impl<'a> MutableArrayData<'a> { ) -> Self { let data_type = arrays[0].data_type(); + for a in arrays.iter().skip(1) { + assert_eq!( + data_type, + a.data_type(), + "Arrays with inconsistent types passed to MutableArrayData" + ) + } + // if any of the arrays has nulls, insertions from any array requires setting bits // as there is at least one array with nulls. let use_nulls = use_nulls | arrays.iter().any(|array| array.null_count() > 0);
diff --git a/arrow/tests/array_transform.rs b/arrow/tests/array_transform.rs index ccf66e1c30ad..74e2a212736a 100644 --- a/arrow/tests/array_transform.rs +++ b/arrow/tests/array_transform.rs @@ -975,6 +975,14 @@ fn test_extend_nulls_panic() { mutable.extend_nulls(2); } +#[test] +#[should_panic(expected = "Arrays with inconsistent types passed to MutableArrayData")] +fn test_mixed_types() { + let a = StringArray::from(vec!["abc", "def"]).to_data(); + let b = Int32Array::from(vec![1, 2, 3]).to_data(); + MutableArrayData::new(vec![&a, &b], false, 4); +} + /* // this is an old test used on a meanwhile removed dead code // that is still useful when `MutableArrayData` supports fixed-size lists.
Unsound MutableArrayData Constructor **Describe the bug** <!-- A clear and concise description of what the bug is. --> I want to use `MutableArrayData` to construct an array, but if the input array sequence is different, the output will be different. This is because `MutableArrayData::new_with_capacities` will use the first array's data type. https://github.com/apache/arrow-rs/blob/master/arrow-data/src/transform/mod.rs#L350-L356 **To Reproduce** <!-- Steps to reproduce the behavior: --> Such as ```rust use arrow::array::{ArrayRef, Int64Array, MutableArrayData, NullArray, Capacities}; use std::sync::Arc; fn main() { let x = Arc::new(Int64Array::from(vec![1, 2, 3])) as ArrayRef; let x_data = x.to_data(); let y = Arc::new(NullArray::new(3)) as ArrayRef; let y_data = y.to_data(); let arr1 = vec![&x_data, &y_data]; let mut m1 = MutableArrayData::new(arr1, true, 1000); m1.extend(0, 0, 3); let ret = Int64Array::from(m1.freeze()); // works just fine let arr2 = vec![&y_data, &x_data]; let mut m2 = MutableArrayData::new(arr2, true, 100); m2.extend(1, 0, 3); let ret = Int64Array::from(m2.freeze()); // This will panic because ArrayData data type is null } ``` **Expected behavior** <!-- A clear and concise description of what you expected to happen. --> maybe we need a method to specify the ArrayData DataType, so whatever sequence of arrays we put in, we can get the excepted result. maybe we can have a method like ``` pub fn with_capacities( arrays: Vec<&'a ArrayData>, use_nulls: bool, capacities: Capacities, data_type: DataType ) -> Self { ``` @tustvold @alamb how do you think? **Additional context** <!-- Add any other context about the problem here. -->
I think it is probably a bug that MutableArrayData lets you extend with a mixture of types, this is not what it is intended to do and is highly unlikely to behave correctly... I was sure it checked this Edit: it would appear this does is not only incorrect but is unsound, will prioritize fixing this Thanks for your answer! I'm refactoring `array_array` in `arrow-datafusion`, and I want to simplify macro by using `MutableArrayData`. So I use it like https://github.com/apache/arrow-datafusion/pull/8252/files#diff-48cc9cf1bfdb0214a9f625b384d1c4fd5967a9da61e8f22a5dc1c4c5800563b4R395-R403 it can handle `make_array(1, NULL, 2)` but when it comes `make_array(NULL, 1)`, this will be failed to construct. Because in the later case, this first array is `NullArray` > it can handle make_array(1, NULL, 2) but when it comes make_array(NULL, 1), this will be failed to construct. Because in the later case, this first array is NullArray It is only handling this by accident and incorrectly. You need to coerce the types passed to make_array to a consistent type signature
2023-11-17T15:11:14Z
49.0
a9470d3eb083303350fc109f94865666fd0f062f
[ "test_mixed_types - should panic" ]
[ "arrow/src/lib.rs - (line 108)", "arrow/src/lib.rs - (line 89)", "arrow/src/lib.rs - (line 221)", "arrow/src/lib.rs - (line 65)", "arrow/src/lib.rs - (line 31)", "arrow/src/lib.rs - (line 46)", "arrow/src/lib.rs - (line 129)", "arrow/src/lib.rs - (line 250)", "arrow/src/lib.rs - (line 195)", "arrow/src/lib.rs - (line 166)", "arrow/src/util/string_writer.rs - util::string_writer (line 25)", "test_bool", "test_binary_fixed_sized_offsets", "test_decimal_null_offset_nulls", "test_decimal", "test_dictionary", "test_decimal_offset", "test_extend_nulls", "test_extend_nulls_panic - should panic", "test_fixed_size_binary_append", "test_list_append", "test_list_null_offset", "test_list_nulls_append", "test_list_of_strings_append", "test_multiple_with_nulls", "test_null", "test_map_nulls_append", "test_primitive", "test_primitive_null_offset", "test_primitive_null_offset_nulls", "test_primitive_offset", "test_string_null_offset_nulls", "test_string_offsets", "test_struct", "test_struct_many", "test_struct_nulls", "test_struct_offset", "test_union_dense", "test_variable_sized_offsets", "test_variable_sized_nulls" ]
[]
[]
apache/arrow-rs
5,076
apache__arrow-rs-5076
[ "5037" ]
7ba36b012322e08b06184c806f8ba339181cebc1
diff --git a/parquet/src/column/writer/mod.rs b/parquet/src/column/writer/mod.rs index a917c4864988..11c39685911c 100644 --- a/parquet/src/column/writer/mod.rs +++ b/parquet/src/column/writer/mod.rs @@ -636,8 +636,16 @@ impl<'a, E: ColumnValueEncoder> GenericColumnWriter<'a, E> { Type::BYTE_ARRAY | Type::FIXED_LEN_BYTE_ARRAY => { self.column_index_builder.append( null_page, - self.truncate_min_value(stat.min_bytes()), - self.truncate_max_value(stat.max_bytes()), + self.truncate_min_value( + self.props.column_index_truncate_length(), + stat.min_bytes(), + ) + .0, + self.truncate_max_value( + self.props.column_index_truncate_length(), + stat.max_bytes(), + ) + .0, self.page_metrics.num_page_nulls as i64, ); } @@ -658,26 +666,26 @@ impl<'a, E: ColumnValueEncoder> GenericColumnWriter<'a, E> { .append_row_count(self.page_metrics.num_buffered_rows as i64); } - fn truncate_min_value(&self, data: &[u8]) -> Vec<u8> { - self.props - .column_index_truncate_length() + fn truncate_min_value(&self, truncation_length: Option<usize>, data: &[u8]) -> (Vec<u8>, bool) { + truncation_length .filter(|l| data.len() > *l) .and_then(|l| match str::from_utf8(data) { Ok(str_data) => truncate_utf8(str_data, l), Err(_) => Some(data[..l].to_vec()), }) - .unwrap_or_else(|| data.to_vec()) + .map(|truncated| (truncated, true)) + .unwrap_or_else(|| (data.to_vec(), false)) } - fn truncate_max_value(&self, data: &[u8]) -> Vec<u8> { - self.props - .column_index_truncate_length() + fn truncate_max_value(&self, truncation_length: Option<usize>, data: &[u8]) -> (Vec<u8>, bool) { + truncation_length .filter(|l| data.len() > *l) .and_then(|l| match str::from_utf8(data) { Ok(str_data) => truncate_utf8(str_data, l).and_then(increment_utf8), Err(_) => increment(data[..l].to_vec()), }) - .unwrap_or_else(|| data.to_vec()) + .map(|truncated| (truncated, true)) + .unwrap_or_else(|| (data.to_vec(), false)) } /// Adds data page. @@ -856,20 +864,64 @@ impl<'a, E: ColumnValueEncoder> GenericColumnWriter<'a, E> { .set_dictionary_page_offset(dict_page_offset); if self.statistics_enabled != EnabledStatistics::None { + let backwards_compatible_min_max = self.descr.sort_order().is_signed(); + let statistics = ValueStatistics::<E::T>::new( self.column_metrics.min_column_value.clone(), self.column_metrics.max_column_value.clone(), self.column_metrics.column_distinct_count, self.column_metrics.num_column_nulls, false, - ); + ) + .with_backwards_compatible_min_max(backwards_compatible_min_max) + .into(); + + let statistics = match statistics { + Statistics::ByteArray(stats) if stats.has_min_max_set() => { + let (min, did_truncate_min) = self.truncate_min_value( + self.props.statistics_truncate_length(), + stats.min_bytes(), + ); + let (max, did_truncate_max) = self.truncate_max_value( + self.props.statistics_truncate_length(), + stats.max_bytes(), + ); + Statistics::ByteArray( + ValueStatistics::new( + Some(min.into()), + Some(max.into()), + stats.distinct_count(), + stats.null_count(), + backwards_compatible_min_max, + ) + .with_max_is_exact(!did_truncate_max) + .with_min_is_exact(!did_truncate_min), + ) + } + Statistics::FixedLenByteArray(stats) if stats.has_min_max_set() => { + let (min, did_truncate_min) = self.truncate_min_value( + self.props.statistics_truncate_length(), + stats.min_bytes(), + ); + let (max, did_truncate_max) = self.truncate_max_value( + self.props.statistics_truncate_length(), + stats.max_bytes(), + ); + Statistics::FixedLenByteArray( + ValueStatistics::new( + Some(min.into()), + Some(max.into()), + stats.distinct_count(), + stats.null_count(), + backwards_compatible_min_max, + ) + .with_max_is_exact(!did_truncate_max) + .with_min_is_exact(!did_truncate_min), + ) + } + stats => stats, + }; - // Some common readers only support the deprecated statistics - // format so we also write them out if possible - // See https://github.com/apache/arrow-rs/issues/799 - let statistics = statistics - .with_backwards_compatible_min_max(self.descr.sort_order().is_signed()) - .into(); builder = builder.set_statistics(statistics); } @@ -2612,6 +2664,148 @@ mod tests { } } + #[test] + fn test_statistics_truncating_byte_array() { + let page_writer = get_test_page_writer(); + + const TEST_TRUNCATE_LENGTH: usize = 1; + + // Truncate values at 1 byte + let builder = + WriterProperties::builder().set_statistics_truncate_length(Some(TEST_TRUNCATE_LENGTH)); + let props = Arc::new(builder.build()); + let mut writer = get_test_column_writer::<ByteArrayType>(page_writer, 0, 0, props); + + let mut data = vec![ByteArray::default(); 1]; + // This is the expected min value + data[0].set_data(Bytes::from(String::from("Blart Versenwald III"))); + + writer.write_batch(&data, None, None).unwrap(); + + writer.flush_data_pages().unwrap(); + + let r = writer.close().unwrap(); + + assert_eq!(1, r.rows_written); + + let stats = r.metadata.statistics().expect("statistics"); + assert!(stats.has_min_max_set()); + assert_eq!(stats.null_count(), 0); + assert_eq!(stats.distinct_count(), None); + if let Statistics::ByteArray(_stats) = stats { + let min_value = _stats.min(); + let max_value = _stats.max(); + + assert!(!_stats.min_is_exact()); + assert!(!_stats.max_is_exact()); + + assert_eq!(min_value.len(), TEST_TRUNCATE_LENGTH); + assert_eq!(max_value.len(), TEST_TRUNCATE_LENGTH); + + assert_eq!("B".as_bytes(), min_value.as_bytes()); + assert_eq!("C".as_bytes(), max_value.as_bytes()); + } else { + panic!("expecting Statistics::ByteArray"); + } + } + + #[test] + fn test_statistics_truncating_fixed_len_byte_array() { + let page_writer = get_test_page_writer(); + + const TEST_TRUNCATE_LENGTH: usize = 1; + + // Truncate values at 1 byte + let builder = + WriterProperties::builder().set_statistics_truncate_length(Some(TEST_TRUNCATE_LENGTH)); + let props = Arc::new(builder.build()); + let mut writer = get_test_column_writer::<FixedLenByteArrayType>(page_writer, 0, 0, props); + + let mut data = vec![FixedLenByteArray::default(); 1]; + + const PSEUDO_DECIMAL_VALUE: i128 = 6541894651216648486512564456564654; + const PSEUDO_DECIMAL_BYTES: [u8; 16] = PSEUDO_DECIMAL_VALUE.to_be_bytes(); + + const EXPECTED_MIN: [u8; TEST_TRUNCATE_LENGTH] = [PSEUDO_DECIMAL_BYTES[0]]; // parquet specifies big-endian order for decimals + const EXPECTED_MAX: [u8; TEST_TRUNCATE_LENGTH] = + [PSEUDO_DECIMAL_BYTES[0].overflowing_add(1).0]; + + // This is the expected min value + data[0].set_data(Bytes::from(PSEUDO_DECIMAL_BYTES.as_slice())); + + writer.write_batch(&data, None, None).unwrap(); + + writer.flush_data_pages().unwrap(); + + let r = writer.close().unwrap(); + + assert_eq!(1, r.rows_written); + + let stats = r.metadata.statistics().expect("statistics"); + assert!(stats.has_min_max_set()); + assert_eq!(stats.null_count(), 0); + assert_eq!(stats.distinct_count(), None); + if let Statistics::FixedLenByteArray(_stats) = stats { + let min_value = _stats.min(); + let max_value = _stats.max(); + + assert!(!_stats.min_is_exact()); + assert!(!_stats.max_is_exact()); + + assert_eq!(min_value.len(), TEST_TRUNCATE_LENGTH); + assert_eq!(max_value.len(), TEST_TRUNCATE_LENGTH); + + assert_eq!(EXPECTED_MIN.as_slice(), min_value.as_bytes()); + assert_eq!(EXPECTED_MAX.as_slice(), max_value.as_bytes()); + + let reconstructed_min = i128::from_be_bytes([ + min_value.as_bytes()[0], + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + ]); + + let reconstructed_max = i128::from_be_bytes([ + max_value.as_bytes()[0], + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + ]); + + // check that the inner value is correctly bounded by the min/max + println!("min: {reconstructed_min} {PSEUDO_DECIMAL_VALUE}"); + assert!(reconstructed_min <= PSEUDO_DECIMAL_VALUE); + println!("max {reconstructed_max} {PSEUDO_DECIMAL_VALUE}"); + assert!(reconstructed_max >= PSEUDO_DECIMAL_VALUE); + } else { + panic!("expecting Statistics::FixedLenByteArray"); + } + } + #[test] fn test_send() { fn test<T: Send>() {} diff --git a/parquet/src/file/properties.rs b/parquet/src/file/properties.rs index ea71763a0101..287e73c9906a 100644 --- a/parquet/src/file/properties.rs +++ b/parquet/src/file/properties.rs @@ -51,6 +51,8 @@ pub const DEFAULT_COLUMN_INDEX_TRUNCATE_LENGTH: Option<usize> = Some(64); pub const DEFAULT_BLOOM_FILTER_FPP: f64 = 0.05; /// Default value for [`BloomFilterProperties::ndv`] pub const DEFAULT_BLOOM_FILTER_NDV: u64 = 1_000_000_u64; +/// Default values for [`WriterProperties::statistics_truncate_length`] +pub const DEFAULT_STATISTICS_TRUNCATE_LENGTH: Option<usize> = None; /// Parquet writer version. /// @@ -136,6 +138,7 @@ pub struct WriterProperties { column_properties: HashMap<ColumnPath, ColumnProperties>, sorting_columns: Option<Vec<SortingColumn>>, column_index_truncate_length: Option<usize>, + statistics_truncate_length: Option<usize>, } impl Default for WriterProperties { @@ -241,6 +244,13 @@ impl WriterProperties { self.column_index_truncate_length } + /// Returns the maximum length of truncated min/max values in statistics. + /// + /// `None` if truncation is disabled, must be greater than 0 otherwise. + pub fn statistics_truncate_length(&self) -> Option<usize> { + self.statistics_truncate_length + } + /// Returns encoding for a data page, when dictionary encoding is enabled. /// This is not configurable. #[inline] @@ -334,6 +344,7 @@ pub struct WriterPropertiesBuilder { column_properties: HashMap<ColumnPath, ColumnProperties>, sorting_columns: Option<Vec<SortingColumn>>, column_index_truncate_length: Option<usize>, + statistics_truncate_length: Option<usize>, } impl WriterPropertiesBuilder { @@ -352,6 +363,7 @@ impl WriterPropertiesBuilder { column_properties: HashMap::new(), sorting_columns: None, column_index_truncate_length: DEFAULT_COLUMN_INDEX_TRUNCATE_LENGTH, + statistics_truncate_length: DEFAULT_STATISTICS_TRUNCATE_LENGTH, } } @@ -370,6 +382,7 @@ impl WriterPropertiesBuilder { column_properties: self.column_properties, sorting_columns: self.sorting_columns, column_index_truncate_length: self.column_index_truncate_length, + statistics_truncate_length: self.statistics_truncate_length, } } @@ -643,6 +656,17 @@ impl WriterPropertiesBuilder { self.column_index_truncate_length = max_length; self } + + /// Sets the max length of min/max value fields in statistics. Must be greater than 0. + /// If set to `None` - there's no effective limit. + pub fn set_statistics_truncate_length(mut self, max_length: Option<usize>) -> Self { + if let Some(value) = max_length { + assert!(value > 0, "Cannot have a 0 statistics truncate length. If you wish to disable min/max value truncation, set it to `None`."); + } + + self.statistics_truncate_length = max_length; + self + } } /// Controls the level of statistics to be computed by the writer diff --git a/parquet/src/file/statistics.rs b/parquet/src/file/statistics.rs index 345fe7dd2615..1bc003d48854 100644 --- a/parquet/src/file/statistics.rs +++ b/parquet/src/file/statistics.rs @@ -27,6 +27,8 @@ //! assert_eq!(stats.null_count(), 3); //! assert!(stats.has_min_max_set()); //! assert!(stats.is_min_max_deprecated()); +//! assert!(stats.min_is_exact()); +//! assert!(stats.max_is_exact()); //! //! match stats { //! Statistics::Int32(ref typed) => { @@ -206,19 +208,27 @@ pub fn from_thrift( null_count, old_format, ), - Type::BYTE_ARRAY => Statistics::byte_array( - min.map(ByteArray::from), - max.map(ByteArray::from), - distinct_count, - null_count, - old_format, + Type::BYTE_ARRAY => Statistics::ByteArray( + ValueStatistics::new( + min.map(ByteArray::from), + max.map(ByteArray::from), + distinct_count, + null_count, + old_format, + ) + .with_max_is_exact(stats.is_max_value_exact.unwrap_or(false)) + .with_min_is_exact(stats.is_min_value_exact.unwrap_or(false)), ), - Type::FIXED_LEN_BYTE_ARRAY => Statistics::fixed_len_byte_array( - min.map(ByteArray::from).map(FixedLenByteArray::from), - max.map(ByteArray::from).map(FixedLenByteArray::from), - distinct_count, - null_count, - old_format, + Type::FIXED_LEN_BYTE_ARRAY => Statistics::FixedLenByteArray( + ValueStatistics::new( + min.map(ByteArray::from).map(FixedLenByteArray::from), + max.map(ByteArray::from).map(FixedLenByteArray::from), + distinct_count, + null_count, + old_format, + ) + .with_max_is_exact(stats.is_max_value_exact.unwrap_or(false)) + .with_min_is_exact(stats.is_min_value_exact.unwrap_or(false)), ), }; @@ -248,13 +258,15 @@ pub fn to_thrift(stats: Option<&Statistics>) -> Option<TStatistics> { }; // Get min/max if set. - let (min, max) = if stats.has_min_max_set() { + let (min, max, min_exact, max_exact) = if stats.has_min_max_set() { ( Some(stats.min_bytes().to_vec()), Some(stats.max_bytes().to_vec()), + Some(stats.min_is_exact()), + Some(stats.max_is_exact()), ) } else { - (None, None) + (None, None, None, None) }; if stats.is_min_max_backwards_compatible() { @@ -268,6 +280,9 @@ pub fn to_thrift(stats: Option<&Statistics>) -> Option<TStatistics> { thrift_stats.max_value = max; } + thrift_stats.is_min_value_exact = min_exact; + thrift_stats.is_max_value_exact = max_exact; + Some(thrift_stats) } @@ -374,6 +389,16 @@ impl Statistics { statistics_enum_func![self, has_min_max_set] } + /// Returns `true` if the min value is set, and is an exact min value. + pub fn min_is_exact(&self) -> bool { + statistics_enum_func![self, min_is_exact] + } + + /// Returns `true` if the max value is set, and is an exact max value. + pub fn max_is_exact(&self) -> bool { + statistics_enum_func![self, max_is_exact] + } + /// Returns slice of bytes that represent min value. /// Panics if min value is not set. pub fn min_bytes(&self) -> &[u8] { @@ -428,6 +453,10 @@ pub struct ValueStatistics<T> { distinct_count: Option<u64>, null_count: u64, + // Whether or not the min or max values are exact, or truncated. + is_max_value_exact: bool, + is_min_value_exact: bool, + /// If `true` populate the deprecated `min` and `max` fields instead of /// `min_value` and `max_value` is_min_max_deprecated: bool, @@ -447,6 +476,8 @@ impl<T: ParquetValueType> ValueStatistics<T> { is_min_max_deprecated: bool, ) -> Self { Self { + is_max_value_exact: max.is_some(), + is_min_value_exact: min.is_some(), min, max, distinct_count, @@ -456,6 +487,28 @@ impl<T: ParquetValueType> ValueStatistics<T> { } } + /// Set whether the stored `min` field represents the exact + /// minimum, or just a bound on the minimum value. + /// + /// see [`Self::min_is_exact`] + pub fn with_min_is_exact(self, is_min_value_exact: bool) -> Self { + Self { + is_min_value_exact, + ..self + } + } + + /// Set whether the stored `max` field represents the exact + /// maximum, or just a bound on the maximum value. + /// + /// see [`Self::max_is_exact`] + pub fn with_max_is_exact(self, is_max_value_exact: bool) -> Self { + Self { + is_max_value_exact, + ..self + } + } + /// Set whether to write the deprecated `min` and `max` fields /// for compatibility with older parquet writers /// @@ -506,13 +559,23 @@ impl<T: ParquetValueType> ValueStatistics<T> { self.min.is_some() && self.max.is_some() } + /// Whether or not max value is set, and is an exact value. + pub fn max_is_exact(&self) -> bool { + self.max.is_some() && self.is_max_value_exact + } + + /// Whether or not min value is set, and is an exact value. + pub fn min_is_exact(&self) -> bool { + self.min.is_some() && self.is_min_value_exact + } + /// Returns optional value of number of distinct values occurring. - fn distinct_count(&self) -> Option<u64> { + pub fn distinct_count(&self) -> Option<u64> { self.distinct_count } /// Returns null count. - fn null_count(&self) -> u64 { + pub fn null_count(&self) -> u64 { self.null_count } @@ -556,6 +619,8 @@ impl<T: ParquetValueType> fmt::Display for ValueStatistics<T> { } write!(f, ", null_count: {}", self.null_count)?; write!(f, ", min_max_deprecated: {}", self.is_min_max_deprecated)?; + write!(f, ", max_value_exact: {}", self.is_max_value_exact)?; + write!(f, ", min_value_exact: {}", self.is_min_value_exact)?; write!(f, "}}") } } @@ -565,13 +630,15 @@ impl<T: ParquetValueType> fmt::Debug for ValueStatistics<T> { write!( f, "{{min: {:?}, max: {:?}, distinct_count: {:?}, null_count: {}, \ - min_max_deprecated: {}, min_max_backwards_compatible: {}}}", + min_max_deprecated: {}, min_max_backwards_compatible: {}, max_value_exact: {}, min_value_exact: {}}}", self.min, self.max, self.distinct_count, self.null_count, self.is_min_max_deprecated, - self.is_min_max_backwards_compatible + self.is_min_max_backwards_compatible, + self.is_max_value_exact, + self.is_min_value_exact ) } } @@ -628,14 +695,14 @@ mod tests { assert_eq!( format!("{stats:?}"), "Int32({min: Some(1), max: Some(12), distinct_count: None, null_count: 12, \ - min_max_deprecated: true, min_max_backwards_compatible: true})" + min_max_deprecated: true, min_max_backwards_compatible: true, max_value_exact: true, min_value_exact: true})" ); let stats = Statistics::int32(None, None, None, 7, false); assert_eq!( format!("{stats:?}"), "Int32({min: None, max: None, distinct_count: None, null_count: 7, \ - min_max_deprecated: false, min_max_backwards_compatible: false})" + min_max_deprecated: false, min_max_backwards_compatible: false, max_value_exact: false, min_value_exact: false})" ) } @@ -644,14 +711,14 @@ mod tests { let stats = Statistics::int32(Some(1), Some(12), None, 12, true); assert_eq!( format!("{stats}"), - "{min: 1, max: 12, distinct_count: N/A, null_count: 12, min_max_deprecated: true}" + "{min: 1, max: 12, distinct_count: N/A, null_count: 12, min_max_deprecated: true, max_value_exact: true, min_value_exact: true}" ); let stats = Statistics::int64(None, None, None, 7, false); assert_eq!( format!("{stats}"), "{min: N/A, max: N/A, distinct_count: N/A, null_count: 7, min_max_deprecated: \ - false}" + false, max_value_exact: false, min_value_exact: false}" ); let stats = Statistics::int96( @@ -664,19 +731,23 @@ mod tests { assert_eq!( format!("{stats}"), "{min: [1, 0, 0], max: [2, 3, 4], distinct_count: N/A, null_count: 3, \ - min_max_deprecated: true}" + min_max_deprecated: true, max_value_exact: true, min_value_exact: true}" ); - let stats = Statistics::byte_array( - Some(ByteArray::from(vec![1u8])), - Some(ByteArray::from(vec![2u8])), - Some(5), - 7, - false, + let stats = Statistics::ByteArray( + ValueStatistics::new( + Some(ByteArray::from(vec![1u8])), + Some(ByteArray::from(vec![2u8])), + Some(5), + 7, + false, + ) + .with_max_is_exact(false) + .with_min_is_exact(false), ); assert_eq!( format!("{stats}"), - "{min: [1], max: [2], distinct_count: 5, null_count: 7, min_max_deprecated: false}" + "{min: [1], max: [2], distinct_count: 5, null_count: 7, min_max_deprecated: false, max_value_exact: false, min_value_exact: false}" ); } @@ -712,7 +783,45 @@ mod tests { Some(ByteArray::from(vec![1, 2, 3]).into()), None, 0, - true + true, + ) + ); + + assert!( + Statistics::byte_array( + Some(ByteArray::from(vec![1, 2, 3])), + Some(ByteArray::from(vec![1, 2, 3])), + None, + 0, + true, + ) != Statistics::ByteArray( + ValueStatistics::new( + Some(ByteArray::from(vec![1, 2, 3])), + Some(ByteArray::from(vec![1, 2, 3])), + None, + 0, + true, + ) + .with_max_is_exact(false) + ) + ); + + assert!( + Statistics::fixed_len_byte_array( + Some(FixedLenByteArray::from(vec![1, 2, 3])), + Some(FixedLenByteArray::from(vec![1, 2, 3])), + None, + 0, + true, + ) != Statistics::FixedLenByteArray( + ValueStatistics::new( + Some(FixedLenByteArray::from(vec![1, 2, 3])), + Some(FixedLenByteArray::from(vec![1, 2, 3])), + None, + 0, + true, + ) + .with_min_is_exact(false) ) ); }
diff --git a/parquet/tests/arrow_writer_layout.rs b/parquet/tests/arrow_writer_layout.rs index fab87f32f5c4..cd124031cfdc 100644 --- a/parquet/tests/arrow_writer_layout.rs +++ b/parquet/tests/arrow_writer_layout.rs @@ -185,7 +185,7 @@ fn test_primitive() { pages: (0..8) .map(|_| Page { rows: 250, - page_header_size: 34, + page_header_size: 36, compressed_size: 1000, encoding: Encoding::PLAIN, page_type: PageType::DATA_PAGE, @@ -214,14 +214,14 @@ fn test_primitive() { pages: vec![ Page { rows: 250, - page_header_size: 34, + page_header_size: 36, compressed_size: 258, encoding: Encoding::RLE_DICTIONARY, page_type: PageType::DATA_PAGE, }, Page { rows: 1750, - page_header_size: 34, + page_header_size: 36, compressed_size: 7000, encoding: Encoding::PLAIN, page_type: PageType::DATA_PAGE, @@ -229,7 +229,7 @@ fn test_primitive() { ], dictionary_page: Some(Page { rows: 250, - page_header_size: 34, + page_header_size: 36, compressed_size: 1000, encoding: Encoding::PLAIN, page_type: PageType::DICTIONARY_PAGE, @@ -256,42 +256,42 @@ fn test_primitive() { pages: vec![ Page { rows: 400, - page_header_size: 34, + page_header_size: 36, compressed_size: 452, encoding: Encoding::RLE_DICTIONARY, page_type: PageType::DATA_PAGE, }, Page { rows: 370, - page_header_size: 34, + page_header_size: 36, compressed_size: 472, encoding: Encoding::RLE_DICTIONARY, page_type: PageType::DATA_PAGE, }, Page { rows: 330, - page_header_size: 34, + page_header_size: 36, compressed_size: 464, encoding: Encoding::RLE_DICTIONARY, page_type: PageType::DATA_PAGE, }, Page { rows: 330, - page_header_size: 34, + page_header_size: 36, compressed_size: 464, encoding: Encoding::RLE_DICTIONARY, page_type: PageType::DATA_PAGE, }, Page { rows: 330, - page_header_size: 34, + page_header_size: 36, compressed_size: 464, encoding: Encoding::RLE_DICTIONARY, page_type: PageType::DATA_PAGE, }, Page { rows: 240, - page_header_size: 34, + page_header_size: 36, compressed_size: 332, encoding: Encoding::RLE_DICTIONARY, page_type: PageType::DATA_PAGE, @@ -299,7 +299,7 @@ fn test_primitive() { ], dictionary_page: Some(Page { rows: 2000, - page_header_size: 34, + page_header_size: 36, compressed_size: 8000, encoding: Encoding::PLAIN, page_type: PageType::DICTIONARY_PAGE, @@ -325,7 +325,7 @@ fn test_primitive() { pages: (0..20) .map(|_| Page { rows: 100, - page_header_size: 34, + page_header_size: 36, compressed_size: 400, encoding: Encoding::PLAIN, page_type: PageType::DATA_PAGE, @@ -360,14 +360,14 @@ fn test_string() { pages: (0..15) .map(|_| Page { rows: 130, - page_header_size: 34, + page_header_size: 36, compressed_size: 1040, encoding: Encoding::PLAIN, page_type: PageType::DATA_PAGE, }) .chain(std::iter::once(Page { rows: 50, - page_header_size: 33, + page_header_size: 35, compressed_size: 400, encoding: Encoding::PLAIN, page_type: PageType::DATA_PAGE, @@ -396,21 +396,21 @@ fn test_string() { pages: vec![ Page { rows: 130, - page_header_size: 34, + page_header_size: 36, compressed_size: 138, encoding: Encoding::RLE_DICTIONARY, page_type: PageType::DATA_PAGE, }, Page { rows: 1250, - page_header_size: 36, + page_header_size: 38, compressed_size: 10000, encoding: Encoding::PLAIN, page_type: PageType::DATA_PAGE, }, Page { rows: 620, - page_header_size: 34, + page_header_size: 36, compressed_size: 4960, encoding: Encoding::PLAIN, page_type: PageType::DATA_PAGE, @@ -418,7 +418,7 @@ fn test_string() { ], dictionary_page: Some(Page { rows: 130, - page_header_size: 34, + page_header_size: 36, compressed_size: 1040, encoding: Encoding::PLAIN, page_type: PageType::DICTIONARY_PAGE, @@ -445,42 +445,42 @@ fn test_string() { pages: vec![ Page { rows: 400, - page_header_size: 34, + page_header_size: 36, compressed_size: 452, encoding: Encoding::RLE_DICTIONARY, page_type: PageType::DATA_PAGE, }, Page { rows: 370, - page_header_size: 34, + page_header_size: 36, compressed_size: 472, encoding: Encoding::RLE_DICTIONARY, page_type: PageType::DATA_PAGE, }, Page { rows: 330, - page_header_size: 34, + page_header_size: 36, compressed_size: 464, encoding: Encoding::RLE_DICTIONARY, page_type: PageType::DATA_PAGE, }, Page { rows: 330, - page_header_size: 34, + page_header_size: 36, compressed_size: 464, encoding: Encoding::RLE_DICTIONARY, page_type: PageType::DATA_PAGE, }, Page { rows: 330, - page_header_size: 34, + page_header_size: 36, compressed_size: 464, encoding: Encoding::RLE_DICTIONARY, page_type: PageType::DATA_PAGE, }, Page { rows: 240, - page_header_size: 34, + page_header_size: 36, compressed_size: 332, encoding: Encoding::RLE_DICTIONARY, page_type: PageType::DATA_PAGE, @@ -488,7 +488,7 @@ fn test_string() { ], dictionary_page: Some(Page { rows: 2000, - page_header_size: 34, + page_header_size: 36, compressed_size: 16000, encoding: Encoding::PLAIN, page_type: PageType::DICTIONARY_PAGE, @@ -528,7 +528,7 @@ fn test_list() { pages: (0..10) .map(|_| Page { rows: 20, - page_header_size: 34, + page_header_size: 36, compressed_size: 672, encoding: Encoding::PLAIN, page_type: PageType::DATA_PAGE,
Binary columns do not receive truncated statistics **Describe the bug** #4389 introduced truncation on column indices for binary columns, where the min/max values for a binary column may be arbitrarily large. As noted, this matches the behaviour in parquet-mr for shortening columns. However, the value in the statistics is written un-truncated. This differs from the behaviour of parquet-mr where the statistics are truncated too: https://github.com/apache/parquet-mr/blob/master/parquet-hadoop/src/main/java/org/apache/parquet/format/converter/ParquetMetadataConverter.java#L715 **To Reproduce** There is a test in https://github.com/delta-io/delta-rs/issues/1805 which demonstrates this, but in general write a parquet file with a long binary column and observe that the stats for that column are not truncated. **Expected behavior** Matching parquet-mr, the statistics should be truncated as well. **Additional context** Found this when looking into https://github.com/delta-io/delta-rs/issues/1805. delta-rs uses the column stats to serialize into the delta log, which leads to very bloated entries. I think it is sufficient to just call truncate_min_value/truncate_max_value when creating the column metadata here: https://github.com/apache/arrow-rs/blob/master/parquet/src/column/writer/mod.rs#L858-L859 but I don't know enough about the internals of arrow to know if that change is correct.
Support for this was only added to the parquet standard 3 weeks ago - https://github.com/apache/parquet-format/pull/216 TBC this will be a breaking API change, as it will break workloads expecting the statistics to not be truncated Got it. It looks like the change to enable statistics truncation was done to parquet-mr in 2019, but without the flag: https://github.com/apache/parquet-mr/pull/696 So in principle, you couldn’t trust the completeness of binary column stats before then as there was no indication as to whether truncation had occurred or not. Hmm... I also note that it is disabled by default, is this still the case? Regardless I think we should probably only perform this in the context of https://github.com/apache/parquet-format/pull/216 as whilst parquet-mr would appear to be configurable to perform binary truncation, I'm fairly confident there are applications that have implicit assumptions that this would break. FYI @alamb my memory is hazy as to what forms of aggregate pushdown DF performs, and if we might need to introduce some notion of inexact statistics (if it doesn't already exist). I'm happy to work up a PR that implements this in the same way, also disabled by default, for parquet-rs. Thank you, that would be great > FYI @alamb my memory is hazy as to what forms of aggregate pushdown DF performs, and if we might need to introduce some notion of inexact statistics (if it doesn't already exist). I think the recent work by @berkaysynnada to add https://github.com/apache/arrow-datafusion/blob/e95e3f89c97ae27149c1dd8093f91a5574210fe6/datafusion/common/src/stats.rs#L29-L36 might be relevant However, I think it is likely we will/should eventually add another variant like ``` enum Precision { // The value is known to be within the range (it is at at most this large for Max, or at least this large for Min) // but the actual values may be lower/higher. Bounded(ScalarValue) } ``` I believe we have a similar usecase in IOx for when we want to ensure the bound includes the actual range, but could be larger (cc @NGA-TRAN ) > > FYI @alamb my memory is hazy as to what forms of aggregate pushdown DF performs, and if we might need to introduce some notion of inexact statistics (if it doesn't already exist). > > I think the recent work by @berkaysynnada to add https://github.com/apache/arrow-datafusion/blob/e95e3f89c97ae27149c1dd8093f91a5574210fe6/datafusion/common/src/stats.rs#L29-L36 might be relevant > > However, I think it is likely we will/should eventually add another variant like > > ``` > enum Precision { > // The value is known to be within the range (it is at at most this large for Max, or at least this large for Min) > // but the actual values may be lower/higher. > Bounded(ScalarValue) > } > ``` > > I believe we have a similar usecase in IOx for when we want to ensure the bound includes the actual range, but could be larger (cc @NGA-TRAN ) I think so too, adding a range-specifying variant will pave the way for many things. While I have other high-priority tasks to address shortly, I'm always available to offer support if someone wishes to take this on. The variant I have in mind is as follows: ``` enum Precision { ... InBetween(Interval) } ``` It will also be easier to use after updating intervals (planning to open the related PR in a few days). I filed https://github.com/apache/arrow-datafusion/issues/8078 with a proposal of a more precise way to represent inexact statistics
2023-11-14T13:24:14Z
49.0
a9470d3eb083303350fc109f94865666fd0f062f
[ "test_list", "test_primitive", "test_string" ]
[ "parquet/src/file/mod.rs - file (line 80) - compile", "parquet/src/record/api.rs - record::api::Row::get_column_iter (line 64) - compile", "parquet/src/file/mod.rs - file (line 29) - compile", "parquet/src/file/mod.rs - file (line 63) - compile", "parquet/src/column/mod.rs - column (line 38) - compile", "parquet/src/file/statistics.rs - file::statistics (line 23)", "parquet/src/schema/parser.rs - schema::parser (line 24)", "parquet/src/schema/types.rs - schema::types::ColumnPath::append (line 689)", "parquet/src/schema/types.rs - schema::types::ColumnPath::string (line 678)", "parquet/src/schema/printer.rs - schema::printer (line 23)", "parquet/src/arrow/arrow_reader/selection.rs - arrow::arrow_reader::selection::RowSelection (line 63)", "parquet/src/schema/mod.rs - schema (line 22)", "parquet/src/record/api.rs - record::api::RowFormatter (line 143)", "parquet/src/arrow/mod.rs - arrow (line 27)", "parquet/src/arrow/arrow_writer/mod.rs - arrow::arrow_writer::ArrowColumnWriter (line 388)", "parquet/src/arrow/arrow_writer/mod.rs - arrow::arrow_writer::ArrowWriter (line 63)", "parquet/src/arrow/arrow_reader/mod.rs - arrow::arrow_reader::ParquetRecordBatchReaderBuilder<T>::new_with_metadata (line 354)", "parquet/src/arrow/arrow_reader/mod.rs - arrow::arrow_reader::ParquetRecordBatchReaderBuilder<T>::try_new (line 313)", "parquet/src/arrow/mod.rs - arrow (line 59)" ]
[]
[]
apache/arrow-rs
2,890
apache__arrow-rs-2890
[ "2889" ]
17d1aade3572d1609cf6ed0e3db15f3d68511460
diff --git a/parquet/Cargo.toml b/parquet/Cargo.toml index 819f41bca32a..9c7da94f9dd7 100644 --- a/parquet/Cargo.toml +++ b/parquet/Cargo.toml @@ -81,6 +81,10 @@ experimental = [] # Enable async APIs async = ["futures", "tokio"] +[[test]] +name = "arrow_writer_layout" +required-features = ["arrow"] + [[bin]] name = "parquet-read" required-features = ["cli"] diff --git a/parquet/src/arrow/arrow_writer/byte_array.rs b/parquet/src/arrow/arrow_writer/byte_array.rs index 9ea3767a28ed..7070cecacf2b 100644 --- a/parquet/src/arrow/arrow_writer/byte_array.rs +++ b/parquet/src/arrow/arrow_writer/byte_array.rs @@ -379,8 +379,7 @@ impl DictEncoder { fn estimated_data_page_size(&self) -> usize { let bit_width = self.bit_width(); - 1 + RleEncoder::min_buffer_size(bit_width) - + RleEncoder::max_buffer_size(bit_width, self.indices.len()) + 1 + RleEncoder::max_buffer_size(bit_width, self.indices.len()) } fn estimated_dict_page_size(&self) -> usize { @@ -427,7 +426,6 @@ impl DictEncoder { struct ByteArrayEncoder { fallback: FallbackEncoder, dict_encoder: Option<DictEncoder>, - num_values: usize, min_value: Option<ByteArray>, max_value: Option<ByteArray>, } @@ -466,7 +464,6 @@ impl ColumnValueEncoder for ByteArrayEncoder { Ok(Self { fallback, dict_encoder: dictionary, - num_values: 0, min_value: None, max_value: None, }) @@ -487,7 +484,10 @@ impl ColumnValueEncoder for ByteArrayEncoder { } fn num_values(&self) -> usize { - self.num_values + match &self.dict_encoder { + Some(encoder) => encoder.indices.len(), + None => self.fallback.num_values, + } } fn has_dictionary(&self) -> bool { @@ -508,7 +508,7 @@ impl ColumnValueEncoder for ByteArrayEncoder { fn flush_dict_page(&mut self) -> Result<Option<DictionaryPage>> { match self.dict_encoder.take() { Some(encoder) => { - if self.num_values != 0 { + if !encoder.indices.is_empty() { return Err(general_err!( "Must flush data pages before flushing dictionary" )); @@ -551,10 +551,7 @@ where match &mut encoder.dict_encoder { Some(dict_encoder) => dict_encoder.encode(values, indices), - None => { - encoder.num_values += indices.len(); - encoder.fallback.encode(values, indices) - } + None => encoder.fallback.encode(values, indices), } } diff --git a/parquet/src/column/writer/encoder.rs b/parquet/src/column/writer/encoder.rs index 4fb4f210e146..9227c4ba1ce8 100644 --- a/parquet/src/column/writer/encoder.rs +++ b/parquet/src/column/writer/encoder.rs @@ -201,6 +201,7 @@ impl<T: DataType> ColumnValueEncoder for ColumnValueEncoderImpl<T> { } fn write_gather(&mut self, values: &Self::Values, indices: &[usize]) -> Result<()> { + self.num_values += indices.len(); let slice: Vec<_> = indices.iter().map(|idx| values[*idx].clone()).collect(); self.write_slice(&slice) } diff --git a/parquet/src/column/writer/mod.rs b/parquet/src/column/writer/mod.rs index 55e667043d35..0f96b6fd78e5 100644 --- a/parquet/src/column/writer/mod.rs +++ b/parquet/src/column/writer/mod.rs @@ -1825,7 +1825,7 @@ mod tests { let page_writer = Box::new(SerializedPageWriter::new(&mut writer)); let props = Arc::new( WriterProperties::builder() - .set_data_pagesize_limit(15) // actually each page will have size 15-18 bytes + .set_data_pagesize_limit(10) .set_write_batch_size(3) // write 3 values at a time .build(), ); @@ -1846,16 +1846,14 @@ mod tests { ); let mut res = Vec::new(); while let Some(page) = page_reader.get_next_page().unwrap() { - res.push((page.page_type(), page.num_values())); + res.push((page.page_type(), page.num_values(), page.buffer().len())); } assert_eq!( res, vec![ - (PageType::DICTIONARY_PAGE, 10), - (PageType::DATA_PAGE, 3), - (PageType::DATA_PAGE, 3), - (PageType::DATA_PAGE, 3), - (PageType::DATA_PAGE, 1) + (PageType::DICTIONARY_PAGE, 10, 40), + (PageType::DATA_PAGE, 9, 10), + (PageType::DATA_PAGE, 1, 3), ] ); } diff --git a/parquet/src/encodings/encoding/dict_encoder.rs b/parquet/src/encodings/encoding/dict_encoder.rs index 18deba65e687..1b516452083c 100644 --- a/parquet/src/encodings/encoding/dict_encoder.rs +++ b/parquet/src/encodings/encoding/dict_encoder.rs @@ -162,8 +162,7 @@ impl<T: DataType> Encoder<T> for DictEncoder<T> { fn estimated_data_encoded_size(&self) -> usize { let bit_width = self.bit_width(); - 1 + RleEncoder::min_buffer_size(bit_width) - + RleEncoder::max_buffer_size(bit_width, self.indices.len()) + RleEncoder::max_buffer_size(bit_width, self.indices.len()) } fn flush_buffer(&mut self) -> Result<ByteBufferPtr> { diff --git a/parquet/src/encodings/encoding/mod.rs b/parquet/src/encodings/encoding/mod.rs index 34d3bb3d4c75..78f4a8b97b33 100644 --- a/parquet/src/encodings/encoding/mod.rs +++ b/parquet/src/encodings/encoding/mod.rs @@ -888,7 +888,7 @@ mod tests { // DICTIONARY // NOTE: The final size is almost the same because the dictionary entries are // preserved after encoded values have been written. - run_test::<Int32Type>(Encoding::RLE_DICTIONARY, -1, &[123, 1024], 11, 68, 66); + run_test::<Int32Type>(Encoding::RLE_DICTIONARY, -1, &[123, 1024], 0, 2, 0); // DELTA_BINARY_PACKED run_test::<Int32Type>(Encoding::DELTA_BINARY_PACKED, -1, &[123; 1024], 0, 35, 0); diff --git a/parquet/src/encodings/levels.rs b/parquet/src/encodings/levels.rs index 95384926ddba..cf1da20b6842 100644 --- a/parquet/src/encodings/levels.rs +++ b/parquet/src/encodings/levels.rs @@ -38,13 +38,8 @@ pub fn max_buffer_size( ) -> usize { let bit_width = num_required_bits(max_level as u64); match encoding { - Encoding::RLE => { - RleEncoder::max_buffer_size(bit_width, num_buffered_values) - + RleEncoder::min_buffer_size(bit_width) - } - Encoding::BIT_PACKED => { - ceil((num_buffered_values * bit_width as usize) as i64, 8) as usize - } + Encoding::RLE => RleEncoder::max_buffer_size(bit_width, num_buffered_values), + Encoding::BIT_PACKED => ceil(num_buffered_values * bit_width as usize, 8), _ => panic!("Unsupported encoding type {}", encoding), } } diff --git a/parquet/src/encodings/rle.rs b/parquet/src/encodings/rle.rs index 93dd4ab565ca..9475275cb625 100644 --- a/parquet/src/encodings/rle.rs +++ b/parquet/src/encodings/rle.rs @@ -42,9 +42,8 @@ use crate::util::{ /// repeated-value := value that is repeated, using a fixed-width of /// round-up-to-next-byte(bit-width) -/// Maximum groups per bit-packed run. Current value is 64. +/// Maximum groups of 8 values per bit-packed run. Current value is 64. const MAX_GROUPS_PER_BIT_PACKED_RUN: usize = 1 << 6; -const MAX_VALUES_PER_BIT_PACKED_RUN: usize = MAX_GROUPS_PER_BIT_PACKED_RUN * 8; /// A RLE/Bit-Packing hybrid encoder. // TODO: tracking memory usage @@ -99,31 +98,28 @@ impl RleEncoder { } } - /// Returns the minimum buffer size needed to use the encoder for `bit_width`. - /// This is the maximum length of a single run for `bit_width`. - pub fn min_buffer_size(bit_width: u8) -> usize { - let max_bit_packed_run_size = 1 + bit_util::ceil( - (MAX_VALUES_PER_BIT_PACKED_RUN * bit_width as usize) as i64, - 8, - ); - let max_rle_run_size = - bit_util::MAX_VLQ_BYTE_LEN + bit_util::ceil(bit_width as i64, 8) as usize; - std::cmp::max(max_bit_packed_run_size as usize, max_rle_run_size) - } - - /// Returns the maximum buffer size takes to encode `num_values` values with + /// Returns the maximum buffer size to encode `num_values` values with /// `bit_width`. pub fn max_buffer_size(bit_width: u8, num_values: usize) -> usize { - // First the maximum size for bit-packed run - let bytes_per_run = bit_width; - let num_runs = bit_util::ceil(num_values as i64, 8) as usize; - let bit_packed_max_size = num_runs + num_runs * bytes_per_run as usize; + // The maximum size occurs with the shortest possible runs of 8 + let num_runs = bit_util::ceil(num_values, 8); + + // The number of bytes in a run of 8 + let bytes_per_run = bit_width as usize; + + // The maximum size if stored as shortest possible bit packed runs of 8 + let bit_packed_max_size = num_runs + num_runs * bytes_per_run; + + // The length of `8` VLQ encoded + let rle_len_prefix = 1; + + // The length of an RLE run of 8 + let min_rle_run_size = rle_len_prefix + bit_util::ceil(bit_width as usize, 8); + + // The maximum size if stored as shortest possible RLE runs of 8 + let rle_max_size = num_runs * min_rle_run_size; - // Second the maximum size for RLE run - let min_rle_run_size = 1 + bit_util::ceil(bit_width as i64, 8) as usize; - let rle_max_size = - bit_util::ceil(num_values as i64, 8) as usize * min_rle_run_size; - std::cmp::max(bit_packed_max_size, rle_max_size) as usize + bit_packed_max_size.max(rle_max_size) } /// Encodes `value`, which must be representable with `bit_width` bits. @@ -905,8 +901,8 @@ mod tests { #[test] fn test_rle_specific_roundtrip() { let bit_width = 1; - let buffer_len = RleEncoder::min_buffer_size(bit_width); let values: Vec<i16> = vec![0, 1, 1, 1, 1, 0, 0, 0, 0, 1]; + let buffer_len = RleEncoder::max_buffer_size(bit_width, values.len()); let mut encoder = RleEncoder::new(bit_width, buffer_len); for v in &values { encoder.put(*v as u64)
diff --git a/parquet/tests/arrow_writer_layout.rs b/parquet/tests/arrow_writer_layout.rs new file mode 100644 index 000000000000..40076add325a --- /dev/null +++ b/parquet/tests/arrow_writer_layout.rs @@ -0,0 +1,472 @@ +// 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. + +//! Tests that the ArrowWriter correctly lays out values into multiple pages + +use arrow::array::{Int32Array, StringArray}; +use arrow::record_batch::RecordBatch; +use bytes::Bytes; +use parquet::arrow::arrow_reader::{ArrowReaderOptions, ParquetRecordBatchReaderBuilder}; +use parquet::arrow::ArrowWriter; +use parquet::basic::{Encoding, PageType}; +use parquet::file::metadata::ParquetMetaData; +use parquet::file::properties::WriterProperties; +use parquet::file::reader::SerializedPageReader; +use std::sync::Arc; + +struct Layout { + row_groups: Vec<RowGroup>, +} + +struct RowGroup { + columns: Vec<ColumnChunk>, +} + +struct ColumnChunk { + pages: Vec<Page>, + dictionary_page: Option<Page>, +} + +struct Page { + rows: usize, + compressed_size: usize, + page_header_size: usize, + encoding: Encoding, + page_type: PageType, +} + +struct LayoutTest { + props: WriterProperties, + batches: Vec<RecordBatch>, + layout: Layout, +} + +fn do_test(test: LayoutTest) { + let mut buf = Vec::with_capacity(1024); + + let mut writer = + ArrowWriter::try_new(&mut buf, test.batches[0].schema(), Some(test.props)) + .unwrap(); + for batch in test.batches { + writer.write(&batch).unwrap(); + } + writer.close().unwrap(); + let b = Bytes::from(buf); + + // Re-read file to decode column index + let read_options = ArrowReaderOptions::new().with_page_index(true); + let reader = + ParquetRecordBatchReaderBuilder::try_new_with_options(b.clone(), read_options) + .unwrap(); + + assert_layout(&b, reader.metadata().as_ref(), &test.layout); +} + +fn assert_layout(file_reader: &Bytes, meta: &ParquetMetaData, layout: &Layout) { + assert_eq!(meta.row_groups().len(), layout.row_groups.len()); + for (row_group, row_group_layout) in meta.row_groups().iter().zip(&layout.row_groups) + { + // Check against offset index + let offset_index = row_group.page_offset_index().as_ref().unwrap(); + assert_eq!(offset_index.len(), row_group_layout.columns.len()); + + for (column_index, column_layout) in + offset_index.iter().zip(&row_group_layout.columns) + { + assert_eq!( + column_index.len(), + column_layout.pages.len(), + "index page count mismatch" + ); + for (idx, (page, page_layout)) in + column_index.iter().zip(&column_layout.pages).enumerate() + { + assert_eq!( + page.compressed_page_size as usize, + page_layout.compressed_size + page_layout.page_header_size, + "index page {} size mismatch", + idx + ); + let next_first_row_index = column_index + .get(idx + 1) + .map(|x| x.first_row_index) + .unwrap_or_else(|| row_group.num_rows()); + + let num_rows = next_first_row_index - page.first_row_index; + assert_eq!( + num_rows as usize, page_layout.rows, + "index page {} row count", + idx + ); + } + } + + // Check against page data + assert_eq!( + row_group.columns().len(), + row_group_layout.columns.len(), + "column count mismatch" + ); + + let iter = row_group + .columns() + .iter() + .zip(&row_group_layout.columns) + .enumerate(); + + for (idx, (column, column_layout)) in iter { + let page_reader = SerializedPageReader::new( + Arc::new(file_reader.clone()), + column, + row_group.num_rows() as usize, + None, + ) + .unwrap(); + + let pages = page_reader.collect::<Result<Vec<_>, _>>().unwrap(); + assert_eq!( + pages.len(), + column_layout.pages.len() + + column_layout.dictionary_page.is_some() as usize, + "page {} count mismatch", + idx + ); + + let page_layouts = column_layout + .dictionary_page + .iter() + .chain(&column_layout.pages); + + for (page, page_layout) in pages.iter().zip(page_layouts) { + assert_eq!(page.encoding(), page_layout.encoding); + assert_eq!( + page.buffer().len(), + page_layout.compressed_size, + "page {} size mismatch", + idx + ); + assert_eq!(page.page_type(), page_layout.page_type); + } + } + } +} + +#[test] +fn test_primitive() { + let array = Arc::new(Int32Array::from_iter_values(0..2000)) as _; + let batch = RecordBatch::try_from_iter([("col", array)]).unwrap(); + let props = WriterProperties::builder() + .set_dictionary_enabled(false) + .set_data_pagesize_limit(1000) + .set_write_batch_size(10) + .build(); + + // Test spill plain encoding pages + do_test(LayoutTest { + props, + batches: vec![batch.clone()], + layout: Layout { + row_groups: vec![RowGroup { + columns: vec![ColumnChunk { + pages: (0..8) + .map(|_| Page { + rows: 250, + page_header_size: 34, + compressed_size: 1000, + encoding: Encoding::PLAIN, + page_type: PageType::DATA_PAGE, + }) + .collect(), + dictionary_page: None, + }], + }], + }, + }); + + // Test spill dictionary + let props = WriterProperties::builder() + .set_dictionary_enabled(true) + .set_dictionary_pagesize_limit(1000) + .set_data_pagesize_limit(10000) + .set_write_batch_size(10) + .build(); + + do_test(LayoutTest { + props, + batches: vec![batch.clone()], + layout: Layout { + row_groups: vec![RowGroup { + columns: vec![ColumnChunk { + pages: vec![ + Page { + rows: 250, + page_header_size: 34, + compressed_size: 258, + encoding: Encoding::RLE_DICTIONARY, + page_type: PageType::DATA_PAGE, + }, + Page { + rows: 1750, + page_header_size: 34, + compressed_size: 7000, + encoding: Encoding::PLAIN, + page_type: PageType::DATA_PAGE, + }, + ], + dictionary_page: Some(Page { + rows: 250, + page_header_size: 34, + compressed_size: 1000, + encoding: Encoding::PLAIN, + page_type: PageType::DICTIONARY_PAGE, + }), + }], + }], + }, + }); + + // Test spill dictionary encoded pages + let props = WriterProperties::builder() + .set_dictionary_enabled(true) + .set_dictionary_pagesize_limit(10000) + .set_data_pagesize_limit(500) + .set_write_batch_size(10) + .build(); + + do_test(LayoutTest { + props, + batches: vec![batch], + layout: Layout { + row_groups: vec![RowGroup { + columns: vec![ColumnChunk { + pages: vec![ + Page { + rows: 400, + page_header_size: 34, + compressed_size: 452, + encoding: Encoding::RLE_DICTIONARY, + page_type: PageType::DATA_PAGE, + }, + Page { + rows: 370, + page_header_size: 34, + compressed_size: 472, + encoding: Encoding::RLE_DICTIONARY, + page_type: PageType::DATA_PAGE, + }, + Page { + rows: 330, + page_header_size: 34, + compressed_size: 464, + encoding: Encoding::RLE_DICTIONARY, + page_type: PageType::DATA_PAGE, + }, + Page { + rows: 330, + page_header_size: 34, + compressed_size: 464, + encoding: Encoding::RLE_DICTIONARY, + page_type: PageType::DATA_PAGE, + }, + Page { + rows: 330, + page_header_size: 34, + compressed_size: 464, + encoding: Encoding::RLE_DICTIONARY, + page_type: PageType::DATA_PAGE, + }, + Page { + rows: 240, + page_header_size: 34, + compressed_size: 332, + encoding: Encoding::RLE_DICTIONARY, + page_type: PageType::DATA_PAGE, + }, + ], + dictionary_page: Some(Page { + rows: 2000, + page_header_size: 34, + compressed_size: 8000, + encoding: Encoding::PLAIN, + page_type: PageType::DICTIONARY_PAGE, + }), + }], + }], + }, + }); +} + +#[test] +fn test_string() { + let array = Arc::new(StringArray::from_iter_values( + (0..2000).map(|x| format!("{:04}", x)), + )) as _; + let batch = RecordBatch::try_from_iter([("col", array)]).unwrap(); + let props = WriterProperties::builder() + .set_dictionary_enabled(false) + .set_data_pagesize_limit(1000) + .set_write_batch_size(10) + .build(); + + // Test spill plain encoding pages + do_test(LayoutTest { + props, + batches: vec![batch.clone()], + layout: Layout { + row_groups: vec![RowGroup { + columns: vec![ColumnChunk { + pages: (0..15) + .map(|_| Page { + rows: 130, + page_header_size: 34, + compressed_size: 1040, + encoding: Encoding::PLAIN, + page_type: PageType::DATA_PAGE, + }) + .chain(std::iter::once(Page { + rows: 50, + page_header_size: 33, + compressed_size: 400, + encoding: Encoding::PLAIN, + page_type: PageType::DATA_PAGE, + })) + .collect(), + dictionary_page: None, + }], + }], + }, + }); + + // Test spill dictionary + let props = WriterProperties::builder() + .set_dictionary_enabled(true) + .set_dictionary_pagesize_limit(1000) + .set_data_pagesize_limit(10000) + .set_write_batch_size(10) + .build(); + + do_test(LayoutTest { + props, + batches: vec![batch.clone()], + layout: Layout { + row_groups: vec![RowGroup { + columns: vec![ColumnChunk { + pages: vec![ + Page { + rows: 130, + page_header_size: 34, + compressed_size: 138, + encoding: Encoding::RLE_DICTIONARY, + page_type: PageType::DATA_PAGE, + }, + Page { + rows: 1250, + page_header_size: 36, + compressed_size: 10000, + encoding: Encoding::PLAIN, + page_type: PageType::DATA_PAGE, + }, + Page { + rows: 620, + page_header_size: 34, + compressed_size: 4960, + encoding: Encoding::PLAIN, + page_type: PageType::DATA_PAGE, + }, + ], + dictionary_page: Some(Page { + rows: 130, + page_header_size: 34, + compressed_size: 1040, + encoding: Encoding::PLAIN, + page_type: PageType::DICTIONARY_PAGE, + }), + }], + }], + }, + }); + + // Test spill dictionary encoded pages + let props = WriterProperties::builder() + .set_dictionary_enabled(true) + .set_dictionary_pagesize_limit(20000) + .set_data_pagesize_limit(500) + .set_write_batch_size(10) + .build(); + + do_test(LayoutTest { + props, + batches: vec![batch], + layout: Layout { + row_groups: vec![RowGroup { + columns: vec![ColumnChunk { + pages: vec![ + Page { + rows: 400, + page_header_size: 34, + compressed_size: 452, + encoding: Encoding::RLE_DICTIONARY, + page_type: PageType::DATA_PAGE, + }, + Page { + rows: 370, + page_header_size: 34, + compressed_size: 472, + encoding: Encoding::RLE_DICTIONARY, + page_type: PageType::DATA_PAGE, + }, + Page { + rows: 330, + page_header_size: 34, + compressed_size: 464, + encoding: Encoding::RLE_DICTIONARY, + page_type: PageType::DATA_PAGE, + }, + Page { + rows: 330, + page_header_size: 34, + compressed_size: 464, + encoding: Encoding::RLE_DICTIONARY, + page_type: PageType::DATA_PAGE, + }, + Page { + rows: 330, + page_header_size: 34, + compressed_size: 464, + encoding: Encoding::RLE_DICTIONARY, + page_type: PageType::DATA_PAGE, + }, + Page { + rows: 240, + page_header_size: 34, + compressed_size: 332, + encoding: Encoding::RLE_DICTIONARY, + page_type: PageType::DATA_PAGE, + }, + ], + dictionary_page: Some(Page { + rows: 2000, + page_header_size: 34, + compressed_size: 16000, + encoding: Encoding::PLAIN, + page_type: PageType::DICTIONARY_PAGE, + }), + }], + }], + }, + }); +}
Overly Pessimistic RLE Size Estimation **Describe the bug** <!-- A clear and concise description of what the bug is. --> The size of RLE encoded data is routinely estimated as ``` RleEncoder::min_buffer_size(bit_width) + RleEncoder::max_buffer_size(bit_width, self.indices.len()) ``` Where `RleEncoder::min_buffer_size` is defined as ``` let max_bit_packed_run_size = 1 + bit_util::ceil( (MAX_VALUES_PER_BIT_PACKED_RUN * bit_width as usize) as i64, 8, ); let max_rle_run_size = bit_util::MAX_VLQ_BYTE_LEN + bit_util::ceil(bit_width as i64, 8) as usize; std::cmp::max(max_bit_packed_run_size as usize, max_rle_run_size) ``` In practice this will almost always be `64 * bit_width`. ``` let bytes_per_run = bit_width; let num_runs = bit_util::ceil(num_values as i64, 8) as usize; let bit_packed_max_size = num_runs + num_runs * bytes_per_run as usize; let min_rle_run_size = 1 + bit_util::ceil(bit_width as i64, 8) as usize; let rle_max_size = bit_util::ceil(num_values as i64, 8) as usize * min_rle_run_size; std::cmp::max(bit_packed_max_size, rle_max_size) as usize ``` **To Reproduce** <!-- Steps to reproduce the behavior: --> It is unclear why min_buffer_size is included in the size estimation at all **Expected behavior** <!-- A clear and concise description of what you expected to happen. --> A more accurate size estimation of written RLE encoded data **Additional context** <!-- Add any other context about the problem here. -->
2022-10-18T01:56:17Z
25.0
a9f632c1bd04410c2528543d74151a91f78643cf
[ "test_primitive", "test_string" ]
[ "parquet/src/file/mod.rs - file (line 64) - compile", "parquet/src/record/api.rs - record::api::Row::get_column_iter (line 62) - compile", "parquet/src/file/mod.rs - file (line 29) - compile", "parquet/src/file/mod.rs - file (line 81) - compile", "parquet/src/arrow/arrow_reader/mod.rs - arrow::arrow_reader::ParquetFileArrowReader::try_new (line 315) - compile", "parquet/src/column/mod.rs - column (line 38) - compile", "parquet/src/schema/types.rs - schema::types::ColumnPath::append (line 686)", "parquet/src/schema/types.rs - schema::types::ColumnPath::string (line 675)", "parquet/src/file/statistics.rs - file::statistics (line 23)", "parquet/src/schema/mod.rs - schema (line 22)", "parquet/src/arrow/mod.rs - arrow (line 55)", "parquet/src/schema/parser.rs - schema::parser (line 24)", "parquet/src/file/properties.rs - file::properties (line 22)", "parquet/src/schema/printer.rs - schema::printer (line 23)", "parquet/src/record/api.rs - record::api::RowFormatter (line 140)", "parquet/src/arrow/mod.rs - arrow (line 68)", "parquet/src/arrow/mod.rs - arrow (line 27)", "parquet/src/arrow/arrow_writer/mod.rs - arrow::arrow_writer::ArrowWriter (line 54)" ]
[]
[]
apache/arrow-rs
4,681
apache__arrow-rs-4681
[ "4255" ]
c6184389241a0c85823aa494e8b5d93343771666
diff --git a/arrow-array/src/array/list_array.rs b/arrow-array/src/array/list_array.rs index 05628084c844..e50f2eb0941d 100644 --- a/arrow-array/src/array/list_array.rs +++ b/arrow-array/src/array/list_array.rs @@ -1037,13 +1037,17 @@ mod tests { #[should_panic( expected = "Memory pointer is not aligned with the specified scalar type" )] + // Different error messages, so skip for now + // https://github.com/apache/arrow-rs/issues/1545 + #[cfg(not(feature = "force_validate"))] fn test_primitive_array_alignment() { let buf = Buffer::from_slice_ref([0_u64]); let buf2 = buf.slice(1); - let array_data = ArrayData::builder(DataType::Int32) - .add_buffer(buf2) - .build() - .unwrap(); + let array_data = unsafe { + ArrayData::builder(DataType::Int32) + .add_buffer(buf2) + .build_unchecked() + }; drop(Int32Array::from(array_data)); } diff --git a/arrow-array/src/types.rs b/arrow-array/src/types.rs index 769dbf974b93..d79b32a991ed 100644 --- a/arrow-array/src/types.rs +++ b/arrow-array/src/types.rs @@ -1494,7 +1494,6 @@ pub type LargeBinaryType = GenericBinaryType<i64>; mod tests { use super::*; use arrow_data::{layout, BufferSpec}; - use std::mem::size_of; #[test] fn month_day_nano_should_roundtrip() { @@ -1541,7 +1540,8 @@ mod tests { assert_eq!( spec, &BufferSpec::FixedWidth { - byte_width: size_of::<T::Native>() + byte_width: std::mem::size_of::<T::Native>(), + alignment: std::mem::align_of::<T::Native>(), } ); } diff --git a/arrow-data/src/data.rs b/arrow-data/src/data.rs index 6ff8a824b2ff..0417e1d357c7 100644 --- a/arrow-data/src/data.rs +++ b/arrow-data/src/data.rs @@ -20,7 +20,7 @@ use crate::bit_iterator::BitSliceIterator; use arrow_buffer::buffer::{BooleanBuffer, NullBuffer}; -use arrow_buffer::{bit_util, ArrowNativeType, Buffer, MutableBuffer}; +use arrow_buffer::{bit_util, i256, ArrowNativeType, Buffer, MutableBuffer}; use arrow_schema::{ArrowError, DataType, UnionMode}; use std::convert::TryInto; use std::mem; @@ -451,7 +451,7 @@ impl ArrayData { for spec in layout.buffers.iter() { match spec { - BufferSpec::FixedWidth { byte_width } => { + BufferSpec::FixedWidth { byte_width, .. } => { let buffer_size = self.len.checked_mul(*byte_width).ok_or_else(|| { ArrowError::ComputeError( @@ -699,6 +699,23 @@ impl ArrayData { Self::new_null(data_type, 0) } + /// Verifies that the buffers meet the minimum alignment requirements for the data type + /// + /// Buffers that are not adequately aligned will be copied to a new aligned allocation + /// + /// This can be useful for when interacting with data sent over IPC or FFI, that may + /// not meet the minimum alignment requirements + fn align_buffers(&mut self) { + let layout = layout(&self.data_type); + for (buffer, spec) in self.buffers.iter_mut().zip(&layout.buffers) { + if let BufferSpec::FixedWidth { alignment, .. } = spec { + if buffer.as_ptr().align_offset(*alignment) != 0 { + *buffer = Buffer::from_slice_ref(buffer.as_ref()) + } + } + } + } + /// "cheap" validation of an `ArrayData`. Ensures buffers are /// sufficiently sized to store `len` + `offset` total elements of /// `data_type` and performs other inexpensive consistency checks. @@ -736,10 +753,11 @@ impl ArrayData { self.buffers.iter().zip(layout.buffers.iter()).enumerate() { match spec { - BufferSpec::FixedWidth { byte_width } => { - let min_buffer_size = len_plus_offset - .checked_mul(*byte_width) - .expect("integer overflow computing min buffer size"); + BufferSpec::FixedWidth { + byte_width, + alignment, + } => { + let min_buffer_size = len_plus_offset.saturating_mul(*byte_width); if buffer.len() < min_buffer_size { return Err(ArrowError::InvalidArgumentError(format!( @@ -747,6 +765,14 @@ impl ArrayData { min_buffer_size, i, self.data_type, buffer.len() ))); } + + let align_offset = buffer.as_ptr().align_offset(*alignment); + if align_offset != 0 { + return Err(ArrowError::InvalidArgumentError(format!( + "Misaligned buffers[{i}] in array of type {:?}, offset from expected alignment of {alignment} by {}", + self.data_type, align_offset.min(alignment - align_offset) + ))); + } } BufferSpec::VariableWidth => { // not cheap to validate (need to look at the @@ -1493,7 +1519,8 @@ impl ArrayData { pub fn layout(data_type: &DataType) -> DataTypeLayout { // based on C/C++ implementation in // https://github.com/apache/arrow/blob/661c7d749150905a63dd3b52e0a04dac39030d95/cpp/src/arrow/type.h (and .cc) - use std::mem::size_of; + use arrow_schema::IntervalUnit::*; + match data_type { DataType::Null => DataTypeLayout { buffers: vec![], @@ -1503,44 +1530,52 @@ pub fn layout(data_type: &DataType) -> DataTypeLayout { buffers: vec![BufferSpec::BitMap], can_contain_null_mask: true, }, - DataType::Int8 - | DataType::Int16 - | DataType::Int32 - | DataType::Int64 - | DataType::UInt8 - | DataType::UInt16 - | DataType::UInt32 - | DataType::UInt64 - | DataType::Float16 - | DataType::Float32 - | DataType::Float64 - | DataType::Timestamp(_, _) - | DataType::Date32 - | DataType::Date64 - | DataType::Time32(_) - | DataType::Time64(_) - | DataType::Interval(_) => { - DataTypeLayout::new_fixed_width(data_type.primitive_width().unwrap()) - } - DataType::Duration(_) => DataTypeLayout::new_fixed_width(size_of::<i64>()), - DataType::Binary => DataTypeLayout::new_binary(size_of::<i32>()), - DataType::FixedSizeBinary(bytes_per_value) => { - let bytes_per_value: usize = (*bytes_per_value) - .try_into() - .expect("negative size for fixed size binary"); - DataTypeLayout::new_fixed_width(bytes_per_value) + DataType::Int8 => DataTypeLayout::new_fixed_width::<i8>(), + DataType::Int16 => DataTypeLayout::new_fixed_width::<i16>(), + DataType::Int32 => DataTypeLayout::new_fixed_width::<i32>(), + DataType::Int64 => DataTypeLayout::new_fixed_width::<i64>(), + DataType::UInt8 => DataTypeLayout::new_fixed_width::<u8>(), + DataType::UInt16 => DataTypeLayout::new_fixed_width::<u16>(), + DataType::UInt32 => DataTypeLayout::new_fixed_width::<u32>(), + DataType::UInt64 => DataTypeLayout::new_fixed_width::<u64>(), + DataType::Float16 => DataTypeLayout::new_fixed_width::<half::f16>(), + DataType::Float32 => DataTypeLayout::new_fixed_width::<f32>(), + DataType::Float64 => DataTypeLayout::new_fixed_width::<f64>(), + DataType::Timestamp(_, _) => DataTypeLayout::new_fixed_width::<i64>(), + DataType::Date32 => DataTypeLayout::new_fixed_width::<i32>(), + DataType::Date64 => DataTypeLayout::new_fixed_width::<i64>(), + DataType::Time32(_) => DataTypeLayout::new_fixed_width::<i32>(), + DataType::Time64(_) => DataTypeLayout::new_fixed_width::<i64>(), + DataType::Interval(YearMonth) => DataTypeLayout::new_fixed_width::<i32>(), + DataType::Interval(DayTime) => DataTypeLayout::new_fixed_width::<i64>(), + DataType::Interval(MonthDayNano) => DataTypeLayout::new_fixed_width::<i128>(), + DataType::Duration(_) => DataTypeLayout::new_fixed_width::<i64>(), + DataType::Decimal128(_, _) => DataTypeLayout::new_fixed_width::<i128>(), + DataType::Decimal256(_, _) => DataTypeLayout::new_fixed_width::<i256>(), + DataType::FixedSizeBinary(size) => { + let spec = BufferSpec::FixedWidth { + byte_width: (*size).try_into().unwrap(), + alignment: mem::align_of::<u8>(), + }; + DataTypeLayout { + buffers: vec![spec], + can_contain_null_mask: true, + } } - DataType::LargeBinary => DataTypeLayout::new_binary(size_of::<i64>()), - DataType::Utf8 => DataTypeLayout::new_binary(size_of::<i32>()), - DataType::LargeUtf8 => DataTypeLayout::new_binary(size_of::<i64>()), - DataType::List(_) => DataTypeLayout::new_fixed_width(size_of::<i32>()), + DataType::Binary => DataTypeLayout::new_binary::<i32>(), + DataType::LargeBinary => DataTypeLayout::new_binary::<i64>(), + DataType::Utf8 => DataTypeLayout::new_binary::<i32>(), + DataType::LargeUtf8 => DataTypeLayout::new_binary::<i64>(), DataType::FixedSizeList(_, _) => DataTypeLayout::new_empty(), // all in child data - DataType::LargeList(_) => DataTypeLayout::new_fixed_width(size_of::<i64>()), + DataType::List(_) => DataTypeLayout::new_fixed_width::<i32>(), + DataType::LargeList(_) => DataTypeLayout::new_fixed_width::<i64>(), + DataType::Map(_, _) => DataTypeLayout::new_fixed_width::<i32>(), DataType::Struct(_) => DataTypeLayout::new_empty(), // all in child data, DataType::RunEndEncoded(_, _) => DataTypeLayout::new_empty(), // all in child data, DataType::Union(_, mode) => { let type_ids = BufferSpec::FixedWidth { - byte_width: size_of::<i8>(), + byte_width: mem::size_of::<i8>(), + alignment: mem::align_of::<i8>(), }; DataTypeLayout { @@ -1552,7 +1587,8 @@ pub fn layout(data_type: &DataType) -> DataTypeLayout { vec![ type_ids, BufferSpec::FixedWidth { - byte_width: size_of::<i32>(), + byte_width: mem::size_of::<i32>(), + alignment: mem::align_of::<i32>(), }, ] } @@ -1561,19 +1597,6 @@ pub fn layout(data_type: &DataType) -> DataTypeLayout { } } DataType::Dictionary(key_type, _value_type) => layout(key_type), - DataType::Decimal128(_, _) => { - // Decimals are always some fixed width; The rust implementation - // always uses 16 bytes / size of i128 - DataTypeLayout::new_fixed_width(size_of::<i128>()) - } - DataType::Decimal256(_, _) => { - // Decimals are always some fixed width. - DataTypeLayout::new_fixed_width(32) - } - DataType::Map(_, _) => { - // same as ListType - DataTypeLayout::new_fixed_width(size_of::<i32>()) - } } } @@ -1589,10 +1612,13 @@ pub struct DataTypeLayout { } impl DataTypeLayout { - /// Describes a basic numeric array where each element has a fixed width - pub fn new_fixed_width(byte_width: usize) -> Self { + /// Describes a basic numeric array where each element has type `T` + pub fn new_fixed_width<T>() -> Self { Self { - buffers: vec![BufferSpec::FixedWidth { byte_width }], + buffers: vec![BufferSpec::FixedWidth { + byte_width: mem::size_of::<T>(), + alignment: mem::align_of::<T>(), + }], can_contain_null_mask: true, } } @@ -1608,14 +1634,15 @@ impl DataTypeLayout { } /// Describes a basic numeric array where each element has a fixed - /// with offset buffer of `offset_byte_width` bytes, followed by a + /// with offset buffer of type `T`, followed by a /// variable width data buffer - pub fn new_binary(offset_byte_width: usize) -> Self { + pub fn new_binary<T>() -> Self { Self { buffers: vec![ // offsets BufferSpec::FixedWidth { - byte_width: offset_byte_width, + byte_width: mem::size_of::<T>(), + alignment: mem::align_of::<T>(), }, // values BufferSpec::VariableWidth, @@ -1628,8 +1655,18 @@ impl DataTypeLayout { /// Layout specification for a single data type buffer #[derive(Debug, PartialEq, Eq)] pub enum BufferSpec { - /// each element has a fixed width - FixedWidth { byte_width: usize }, + /// Each element is a fixed width primitive, with the given `byte_width` and `alignment` + /// + /// `alignment` is the alignment required by Rust for an array of the corresponding primitive, + /// see [`Layout::array`](std::alloc::Layout::array) and [`std::mem::align_of`]. + /// + /// Arrow-rs requires that all buffers are have at least this alignment, to allow for + /// [slice](std::slice) based APIs. We do not require alignment in excess of this to allow + /// for array slicing, and interoperability with `Vec` which in the absence of support + /// for custom allocators, cannot be over-aligned. + /// + /// Note that these alignment requirements will vary between architectures + FixedWidth { byte_width: usize, alignment: usize }, /// Variable width, such as string data for utf8 data VariableWidth, /// Buffer holds a bitmap. @@ -1741,6 +1778,15 @@ impl ArrayDataBuilder { /// apply. #[allow(clippy::let_and_return)] pub unsafe fn build_unchecked(self) -> ArrayData { + let data = self.build_impl(); + // Provide a force_validate mode + #[cfg(feature = "force_validate")] + data.validate_data().unwrap(); + data + } + + /// Same as [`Self::build_unchecked`] but ignoring `force_validate` feature flag + unsafe fn build_impl(self) -> ArrayData { let nulls = self.nulls.or_else(|| { let buffer = self.null_bit_buffer?; let buffer = BooleanBuffer::new(buffer, self.offset, self.len); @@ -1750,26 +1796,41 @@ impl ArrayDataBuilder { }) }); - let data = ArrayData { + ArrayData { data_type: self.data_type, len: self.len, offset: self.offset, buffers: self.buffers, child_data: self.child_data, nulls: nulls.filter(|b| b.null_count() != 0), - }; - - // Provide a force_validate mode - #[cfg(feature = "force_validate")] - data.validate_data().unwrap(); - data + } } /// Creates an array data, validating all inputs - #[allow(clippy::let_and_return)] pub fn build(self) -> Result<ArrayData, ArrowError> { - let data = unsafe { self.build_unchecked() }; - #[cfg(not(feature = "force_validate"))] + let data = unsafe { self.build_impl() }; + data.validate_data()?; + Ok(data) + } + + /// Creates an array data, validating all inputs, and aligning any buffers + /// + /// Rust requires that arrays are aligned to their corresponding primitive, + /// see [`Layout::array`](std::alloc::Layout::array) and [`std::mem::align_of`]. + /// + /// [`ArrayData`] therefore requires that all buffers are have at least this alignment, + /// to allow for [slice](std::slice) based APIs. See [`BufferSpec::FixedWidth`]. + /// + /// As this alignment is architecture specific, and not guaranteed by all arrow implementations, + /// this method is provided to automatically copy buffers to a new correctly aligned allocation + /// when necessary, making it useful when interacting with buffers produced by other systems, + /// e.g. IPC or FFI. + /// + /// This is unlike `[Self::build`] which will instead return an error on encountering + /// insufficiently aligned buffers. + pub fn build_aligned(self) -> Result<ArrayData, ArrowError> { + let mut data = unsafe { self.build_impl() }; + data.align_buffers(); data.validate_data()?; Ok(data) } @@ -2057,4 +2118,31 @@ mod tests { assert_eq!(buffers.len(), layout.buffers.len()); } } + + #[test] + fn test_alignment() { + let buffer = Buffer::from_vec(vec![1_i32, 2_i32, 3_i32]); + let sliced = buffer.slice(1); + + let mut data = ArrayData { + data_type: DataType::Int32, + len: 0, + offset: 0, + buffers: vec![buffer], + child_data: vec![], + nulls: None, + }; + data.validate_full().unwrap(); + + data.buffers[0] = sliced; + let err = data.validate().unwrap_err(); + + assert_eq!( + err.to_string(), + "Invalid argument error: Misaligned buffers[0] in array of type Int32, offset from expected alignment of 4 by 1" + ); + + data.align_buffers(); + data.validate_full().unwrap(); + } } diff --git a/arrow-ipc/src/reader.rs b/arrow-ipc/src/reader.rs index 0908d580d59a..b7d328977d1c 100644 --- a/arrow-ipc/src/reader.rs +++ b/arrow-ipc/src/reader.rs @@ -20,7 +20,6 @@ //! The `FileReader` and `StreamReader` have similar interfaces, //! however the `FileReader` expects a reader that supports `Seek`ing -use arrow_buffer::i256; use flatbuffers::VectorIter; use std::collections::HashMap; use std::fmt; @@ -129,7 +128,7 @@ fn create_array(reader: &mut ArrayReader, field: &Field) -> Result<ArrayRef, Arr .offset(0) .add_child_data(run_ends.into_data()) .add_child_data(values.into_data()) - .build()?; + .build_aligned()?; Ok(make_array(data)) } @@ -202,7 +201,7 @@ fn create_array(reader: &mut ArrayReader, field: &Field) -> Result<ArrayRef, Arr let data = ArrayData::builder(data_type.clone()) .len(length as usize) .offset(0) - .build() + .build_aligned() .unwrap(); // no buffer increases Ok(Arc::new(NullArray::from(data))) @@ -231,54 +230,17 @@ fn create_primitive_array( .len(length) .buffers(buffers[1..3].to_vec()) .null_bit_buffer(null_buffer) - .build()? + .build_aligned()? } - Int8 - | Int16 - | Int32 - | UInt8 - | UInt16 - | UInt32 - | Time32(_) - | Date32 - | Interval(IntervalUnit::YearMonth) - | Interval(IntervalUnit::DayTime) - | FixedSizeBinary(_) - | Boolean - | Int64 - | UInt64 - | Float32 - | Float64 - | Time64(_) - | Timestamp(_, _) - | Date64 - | Duration(_) => { + _ if data_type.is_primitive() + || matches!(data_type, Boolean | FixedSizeBinary(_)) => + { // read 2 buffers: null buffer (optional) and data buffer ArrayData::builder(data_type.clone()) .len(length) .add_buffer(buffers[1].clone()) .null_bit_buffer(null_buffer) - .build()? - } - Interval(IntervalUnit::MonthDayNano) | Decimal128(_, _) => { - let buffer = get_aligned_buffer::<i128>(&buffers[1], length); - - // read 2 buffers: null buffer (optional) and data buffer - ArrayData::builder(data_type.clone()) - .len(length) - .add_buffer(buffer) - .null_bit_buffer(null_buffer) - .build()? - } - Decimal256(_, _) => { - let buffer = get_aligned_buffer::<i256>(&buffers[1], length); - - // read 2 buffers: null buffer (optional) and data buffer - ArrayData::builder(data_type.clone()) - .len(length) - .add_buffer(buffer) - .null_bit_buffer(null_buffer) - .build()? + .build_aligned()? } t => unreachable!("Data type {:?} either unsupported or not primitive", t), }; @@ -286,28 +248,10 @@ fn create_primitive_array( Ok(make_array(array_data)) } -/// Checks if given `Buffer` is properly aligned with `T`. -/// If not, copying the data and padded it for alignment. -fn get_aligned_buffer<T>(buffer: &Buffer, length: usize) -> Buffer { - let ptr = buffer.as_ptr(); - let align_req = std::mem::align_of::<T>(); - let align_offset = ptr.align_offset(align_req); - // The buffer is not aligned properly. The writer might use a smaller alignment - // e.g. 8 bytes, but on some platform (e.g. ARM) i128 requires 16 bytes alignment. - // We need to copy the buffer as fallback. - if align_offset != 0 { - let len_in_bytes = (length * std::mem::size_of::<T>()).min(buffer.len()); - let slice = &buffer.as_slice()[0..len_in_bytes]; - Buffer::from_slice_ref(slice) - } else { - buffer.clone() - } -} - /// Reads the correct number of buffers based on list type and null_count, and creates a /// list array ref fn create_list_array( - field_node: &crate::FieldNode, + field_node: &FieldNode, data_type: &DataType, buffers: &[Buffer], child_array: ArrayRef, @@ -329,13 +273,13 @@ fn create_list_array( _ => unreachable!("Cannot create list or map array from {:?}", data_type), }; - Ok(make_array(builder.build()?)) + Ok(make_array(builder.build_aligned()?)) } /// Reads the correct number of buffers based on list type and null_count, and creates a /// list array ref fn create_dictionary_array( - field_node: &crate::FieldNode, + field_node: &FieldNode, data_type: &DataType, buffers: &[Buffer], value_array: ArrayRef, @@ -348,7 +292,7 @@ fn create_dictionary_array( .add_child_data(value_array.into_data()) .null_bit_buffer(null_buffer); - Ok(make_array(builder.build()?)) + Ok(make_array(builder.build_aligned()?)) } else { unreachable!("Cannot create dictionary array from {:?}", data_type) } @@ -1097,10 +1041,11 @@ impl<R: Read> RecordBatchReader for StreamReader<R> { #[cfg(test)] mod tests { - use crate::writer::unslice_run_array; + use crate::writer::{unslice_run_array, DictionaryTracker, IpcDataGenerator}; use super::*; + use crate::root_as_message; use arrow_array::builder::{PrimitiveRunBuilder, UnionBuilder}; use arrow_array::types::*; use arrow_buffer::ArrowNativeType; @@ -1357,8 +1302,7 @@ mod tests { writer.finish().unwrap(); drop(writer); - let mut reader = - crate::reader::FileReader::try_new(std::io::Cursor::new(buf), None).unwrap(); + let mut reader = FileReader::try_new(std::io::Cursor::new(buf), None).unwrap(); reader.next().unwrap().unwrap() } @@ -1704,4 +1648,40 @@ mod tests { let output_batch = roundtrip_ipc_stream(&input_batch); assert_eq!(input_batch, output_batch); } + + #[test] + fn test_unaligned() { + let batch = RecordBatch::try_from_iter(vec![( + "i32", + Arc::new(Int32Array::from(vec![1, 2, 3, 4])) as _, + )]) + .unwrap(); + + let gen = IpcDataGenerator {}; + let mut dict_tracker = DictionaryTracker::new(false); + let (_, encoded) = gen + .encoded_batch(&batch, &mut dict_tracker, &Default::default()) + .unwrap(); + + let message = root_as_message(&encoded.ipc_message).unwrap(); + + // Construct an unaligned buffer + let mut buffer = MutableBuffer::with_capacity(encoded.arrow_data.len() + 1); + buffer.push(0_u8); + buffer.extend_from_slice(&encoded.arrow_data); + let b = Buffer::from(buffer).slice(1); + assert_ne!(b.as_ptr().align_offset(8), 0); + + let ipc_batch = message.header_as_record_batch().unwrap(); + let roundtrip = read_record_batch( + &b, + ipc_batch, + batch.schema(), + &Default::default(), + None, + &message.version(), + ) + .unwrap(); + assert_eq!(batch, roundtrip); + } } diff --git a/arrow-ipc/src/writer.rs b/arrow-ipc/src/writer.rs index 59657bc4be09..1c56613d8f24 100644 --- a/arrow-ipc/src/writer.rs +++ b/arrow-ipc/src/writer.rs @@ -1146,7 +1146,7 @@ fn buffer_need_truncate( #[inline] fn get_buffer_element_width(spec: &BufferSpec) -> usize { match spec { - BufferSpec::FixedWidth { byte_width } => *byte_width, + BufferSpec::FixedWidth { byte_width, .. } => *byte_width, _ => 0, } }
diff --git a/arrow/tests/array_validation.rs b/arrow/tests/array_validation.rs index 0d3652a0473a..fa80db1860cd 100644 --- a/arrow/tests/array_validation.rs +++ b/arrow/tests/array_validation.rs @@ -56,7 +56,9 @@ fn test_bad_number_of_buffers() { } #[test] -#[should_panic(expected = "integer overflow computing min buffer size")] +#[should_panic( + expected = "Need at least 18446744073709551615 bytes in buffers[0] in array of type Int64, but got 8" +)] fn test_fixed_width_overflow() { let buffer = Buffer::from_slice_ref([0i32, 2i32]); ArrayData::try_new(DataType::Int64, usize::MAX, None, 0, vec![buffer], vec![])
Handle Misaligned IPC Buffers **Is your feature request related to a problem or challenge? Please describe what you are trying to do.** <!-- A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] (This section helps Arrow developers understand the context and *why* for this feature, in addition to the *what*) --> The flatbuffer specification recommends that buffers are aligned to 64-bit boundaries, however, this is not mandated. Additionally when loading a flatbuffer from an in-memory source, it is possible the source buffer itself isn't aligned. We already re-align interval buffers, we should do this consistently **Describe the solution you'd like** <!-- A clear and concise description of what you want to happen. --> We should automatically re-align mis-aligned IPC buffers **Describe alternatives you've considered** <!-- A clear and concise description of any alternative solutions or features you've considered. --> **Additional context** <!-- Add any other context or screenshots about the feature request here. --> Relates to #4254 which would likely produce mis-aligned buffers
2023-08-11T11:00:40Z
45.0
c6184389241a0c85823aa494e8b5d93343771666
[ "test_fixed_width_overflow - should panic" ]
[ "arrow/src/lib.rs - (line 108)", "arrow/src/lib.rs - (line 89)", "arrow/src/lib.rs - (line 221)", "arrow/src/lib.rs - (line 65)", "arrow/src/lib.rs - (line 31)", "arrow/src/lib.rs - (line 195)", "arrow/src/lib.rs - (line 250)", "arrow/src/lib.rs - (line 46)", "arrow/src/lib.rs - (line 129)", "arrow/src/util/string_writer.rs - util::string_writer (line 25)", "arrow/src/lib.rs - (line 166)", "test_bad_number_of_buffers - should panic", "test_bitmap_too_small - should panic", "test_buffer_too_small - should panic", "test_buffer_too_small_offset - should panic", "test_decimal_full_validation", "test_decimal_validation", "test_empty_large_utf8_array_with_wrong_type_offsets - should panic", "test_empty_utf8_array_with_empty_offsets_buffer", "test_empty_utf8_array_with_invalid_offset - should panic", "test_empty_utf8_array_with_non_zero_offset", "test_empty_utf8_array_with_single_zero_offset", "test_mismatched_dictionary_types - should panic", "test_non_int_dictionary - should panic", "test_sliced_array_child", "test_string_data_from_foreign", "test_try_new_sliced_struct", "test_validate_binary_out_of_bounds - should panic", "test_validate_binary_index_backwards - should panic", "test_validate_dictionary_index_giant_negative - should panic", "test_validate_dictionary_index_negative_but_not_referenced", "test_validate_dictionary_index_negative - should panic", "test_validate_fixed_size_list - should panic", "test_validate_dictionary_index_too_large - should panic", "test_validate_large_binary_index_backwards - should panic", "test_validate_large_binary_out_of_bounds - should panic", "test_validate_large_list_offsets - should panic", "test_validate_large_utf8_char_boundary - should panic", "test_validate_large_utf8_content - should panic", "test_validate_large_utf8_index_backwards - should panic", "test_validate_large_utf8_out_of_bounds - should panic", "test_validate_list_negative_offsets - should panic", "test_validate_list_offsets - should panic", "test_validate_offsets_first_too_large - should panic", "test_validate_offsets_first_too_large_skipped", "test_validate_offsets_i32 - should panic", "test_validate_offsets_i64 - should panic", "test_validate_offsets_last_too_large - should panic", "test_validate_offsets_negative_first_i32 - should panic", "test_validate_offsets_negative_last_i32 - should panic", "test_validate_offsets_range_too_large - should panic", "test_validate_offsets_range_too_small - should panic", "test_validate_struct_child_length - should panic", "test_validate_struct_child_type - should panic", "test_validate_union_dense_with_bad_len - should panic", "test_validate_union_dense_without_offsets - should panic", "test_validate_union_different_types - should panic", "test_validate_union_sparse_different_child_len - should panic", "test_validate_utf8_char_boundary - should panic", "test_validate_utf8_content - should panic", "test_validate_utf8_index_backwards - should panic", "test_validate_utf8_out_of_bounds - should panic" ]
[]
[]
apache/arrow-rs
4,670
apache__arrow-rs-4670
[ "4637" ]
5023ea8438e3143bf711a89a3a2ffb8838a18e9e
diff --git a/arrow-data/src/equal/fixed_binary.rs b/arrow-data/src/equal/fixed_binary.rs index 9e0e77ff7eca..40dacdddd3a0 100644 --- a/arrow-data/src/equal/fixed_binary.rs +++ b/arrow-data/src/equal/fixed_binary.rs @@ -80,7 +80,7 @@ pub(super) fn fixed_binary_equal( lhs_start + lhs_nulls.offset(), len, ); - let rhs_nulls = lhs.nulls().unwrap(); + let rhs_nulls = rhs.nulls().unwrap(); let rhs_slices_iter = BitSliceIterator::new( rhs_nulls.validity(), rhs_start + rhs_nulls.offset(),
diff --git a/arrow/tests/array_equal.rs b/arrow/tests/array_equal.rs index 83a280db67b8..4abe31a36cf5 100644 --- a/arrow/tests/array_equal.rs +++ b/arrow/tests/array_equal.rs @@ -1295,3 +1295,25 @@ fn test_struct_equal_slice() { test_equal(&a, &b, true); } + +#[test] +fn test_list_excess_children_equal() { + let mut a = ListBuilder::new(FixedSizeBinaryBuilder::new(5)); + a.values().append_value(b"11111").unwrap(); // Masked value + a.append_null(); + a.values().append_value(b"22222").unwrap(); + a.values().append_null(); + a.append(true); + let a = a.finish(); + + let mut b = ListBuilder::new(FixedSizeBinaryBuilder::new(5)); + b.append_null(); + b.values().append_value(b"22222").unwrap(); + b.values().append_null(); + b.append(true); + let b = b.finish(); + + assert_eq!(a.value_offsets(), &[0, 1, 3]); + assert_eq!(b.value_offsets(), &[0, 0, 2]); + assert_eq!(a, b); +}
`List(FixedSizeBinary)` array equality check may return wrong result **Describe the bug** `<ListArray as PartialEq>::eq` returns `false` for two arrays of datatype `List(FixedSizeBinary(5))` containing identical values but physically differ. **To Reproduce** ```rust #[test] fn test_list_excess_children_equal() { let a_values = create_fixed_size_binary_array([Some(b"11111"), Some(b"22222"), None]); // ^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^^^ // a[0] a[1] let a: ListArray = ArrayDataBuilder::new(DataType::List(Arc::new(Field::new( "item", a_values.data_type().clone(), true, )))) .len(2) .add_buffer(Buffer::from(vec![0i32, 1, 3].to_byte_slice())) .add_child_data(a_values.into_data()) .null_bit_buffer(Some(Buffer::from(&[0b00000010]))) .build() .unwrap() .into(); let b_values = create_fixed_size_binary_array([Some(b"22222"), None]); // ^^^^^^^^^^^^^^^^^^^^ // a[1] let b: ListArray = ArrayDataBuilder::new(DataType::List(Arc::new(Field::new( "item", b_values.data_type().clone(), true, )))) .len(2) .add_buffer(Buffer::from(vec![0i32, 0, 2].to_byte_slice())) .add_child_data(b_values.into_data()) .null_bit_buffer(Some(Buffer::from(&[0b00000010]))) .build() .unwrap() .into(); a.to_data().validate_full().unwrap(); b.to_data().validate_full().unwrap(); assert_eq!(a, b); } // from `arrow/tests/array_equal.rs` fn create_fixed_size_binary_array<U: AsRef<[u8]>, T: AsRef<[Option<U>]>>( data: T, ) -> FixedSizeBinaryArray { let mut builder = FixedSizeBinaryBuilder::with_capacity(data.as_ref().len(), 5); for d in data.as_ref() { if let Some(v) = d { builder.append_value(v.as_ref()).unwrap(); } else { builder.append_null(); } } builder.finish() } ``` ``` thread 'test_list_excess_children_equal' panicked at 'assertion failed: `(left == right)` left: `ListArray [ null, FixedSizeBinaryArray<5> [ [50, 50, 50, 50, 50], null, ], ]`, right: `ListArray [ null, FixedSizeBinaryArray<5> [ [50, 50, 50, 50, 50], null, ], ]`', arrow\tests\array_equal.rs:399:5 note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace ``` **Expected behavior** Returning `true` because they both contain `[null, [[50, 50, 50, 50, 50], null]]` as shown by the debug printing **Additional context** <!-- Add any other context about the problem here. -->
These two array isn't equal in fact. ``` values: [ [49, 49, 49, 49, 49], [50, 50, 50, 50, 50], null, ] value_offsets: [0, 1, 3] values [ [50, 50, 50, 50, 50], null, ] value_offsets [0, 0, 2] ```
2023-08-09T15:59:12Z
45.0
c6184389241a0c85823aa494e8b5d93343771666
[ "test_list_excess_children_equal" ]
[ "arrow/src/lib.rs - (line 108)", "arrow/src/lib.rs - (line 89)", "arrow/src/lib.rs - (line 221)", "arrow/src/lib.rs - (line 65)", "arrow/src/lib.rs - (line 31)", "arrow/src/lib.rs - (line 195)", "arrow/src/lib.rs - (line 46)", "arrow/src/lib.rs - (line 250)", "arrow/src/lib.rs - (line 129)", "arrow/src/util/string_writer.rs - util::string_writer (line 25)", "arrow/src/lib.rs - (line 166)", "test_binary_equal", "list_array_non_zero_nulls", "test_boolean_equal_nulls", "test_boolean_slice", "test_boolean_equal_offset", "test_boolean_equal", "test_decimal_offsets", "test_decimal_null", "test_decimal_equal", "test_dictionary_equal", "test_empty_offsets_list_equal", "test_dictionary_equal_null", "test_fixed_list_null", "test_fixed_size_binary_equal", "test_fixed_size_binary_array", "test_fixed_size_binary_null", "test_fixed_size_binary_offsets", "test_fixed_list_offsets", "test_fixed_size_list_equal", "test_large_binary_equal", "test_large_string_equal", "test_list_different_offsets", "test_list_equal", "test_list_null", "test_non_null_empty_strings", "test_list_offsets", "test_null", "test_null_empty_strings", "test_null_equal", "test_primitive", "test_primitive_slice", "test_sliced_nullable_boolean_array", "test_string_equal", "test_string_offset", "test_string_offset_larger", "test_struct_equal", "test_struct_equal_slice", "test_struct_equal_null_variable_size", "test_struct_equal_null", "test_union_equal_sparse_slice", "test_union_equal_sparse", "test_union_equal_dense" ]
[]
[]
apache/arrow-rs
4,598
apache__arrow-rs-4598
[ "4578" ]
95683439fa4108c036e48b334f8bed898b87a9b9
diff --git a/arrow-data/src/transform/union.rs b/arrow-data/src/transform/union.rs index 8d1ea34c314d..d7083588d782 100644 --- a/arrow-data/src/transform/union.rs +++ b/arrow-data/src/transform/union.rs @@ -39,6 +39,9 @@ pub(super) fn build_extend_sparse(array: &ArrayData) -> Extend { pub(super) fn build_extend_dense(array: &ArrayData) -> Extend { let type_ids = array.buffer::<i8>(0); let offsets = array.buffer::<i32>(1); + let arrow_schema::DataType::Union(src_fields, _) = array.data_type() else { + unreachable!(); + }; Box::new( move |mutable: &mut _MutableArrayData, index: usize, start: usize, len: usize| { @@ -48,14 +51,18 @@ pub(super) fn build_extend_dense(array: &ArrayData) -> Extend { .extend_from_slice(&type_ids[start..start + len]); (start..start + len).for_each(|i| { - let type_id = type_ids[i] as usize; + let type_id = type_ids[i]; + let child_index = src_fields + .iter() + .position(|(r, _)| r == type_id) + .expect("invalid union type ID"); let src_offset = offsets[i] as usize; - let child_data = &mut mutable.child_data[type_id]; + let child_data = &mut mutable.child_data[child_index]; let dst_offset = child_data.len(); // Extend offsets mutable.buffer2.push(dst_offset as i32); - mutable.child_data[type_id].extend(index, src_offset, src_offset + 1) + mutable.child_data[child_index].extend(index, src_offset, src_offset + 1) }) }, )
diff --git a/arrow/tests/array_transform.rs b/arrow/tests/array_transform.rs index ebbadc00aecd..15141eb208e4 100644 --- a/arrow/tests/array_transform.rs +++ b/arrow/tests/array_transform.rs @@ -19,7 +19,7 @@ use arrow::array::{ Array, ArrayRef, BooleanArray, Decimal128Array, DictionaryArray, FixedSizeBinaryArray, Int16Array, Int32Array, Int64Array, Int64Builder, ListArray, ListBuilder, MapBuilder, NullArray, StringArray, StringBuilder, - StringDictionaryBuilder, StructArray, UInt8Array, + StringDictionaryBuilder, StructArray, UInt8Array, UnionArray, }; use arrow::datatypes::Int16Type; use arrow_buffer::Buffer; @@ -488,6 +488,63 @@ fn test_struct_many() { assert_eq!(array, expected) } +#[test] +fn test_union_dense() { + // Input data + let strings: ArrayRef = Arc::new(StringArray::from(vec![ + Some("joe"), + Some("mark"), + Some("doe"), + ])); + let ints: ArrayRef = Arc::new(Int32Array::from(vec![ + Some(1), + Some(2), + Some(3), + Some(4), + Some(5), + ])); + let offsets = Buffer::from_slice_ref([0, 0, 1, 1, 2, 2, 3, 4i32]); + let type_ids = Buffer::from_slice_ref([42, 84, 42, 84, 84, 42, 84, 84i8]); + + let array = UnionArray::try_new( + &[84, 42], + type_ids, + Some(offsets), + vec![ + (Field::new("int", DataType::Int32, false), ints), + (Field::new("string", DataType::Utf8, false), strings), + ], + ) + .unwrap() + .into_data(); + let arrays = vec![&array]; + let mut mutable = MutableArrayData::new(arrays, false, 0); + + // Slice it by `MutableArrayData` + mutable.extend(0, 4, 7); + let data = mutable.freeze(); + let array = UnionArray::from(data); + + // Expected data + let strings: ArrayRef = Arc::new(StringArray::from(vec![Some("doe")])); + let ints: ArrayRef = Arc::new(Int32Array::from(vec![Some(3), Some(4)])); + let offsets = Buffer::from_slice_ref([0, 0, 1i32]); + let type_ids = Buffer::from_slice_ref([84, 42, 84i8]); + + let expected = UnionArray::try_new( + &[84, 42], + type_ids, + Some(offsets), + vec![ + (Field::new("int", DataType::Int32, false), ints), + (Field::new("string", DataType::Utf8, false), strings), + ], + ) + .unwrap(); + + assert_eq!(array.to_data(), expected.to_data()); +} + #[test] fn test_binary_fixed_sized_offsets() { let array = FixedSizeBinaryArray::try_from_iter(
`arrow::compute::concat` panics for dense union arrays with non-trivial type IDs **Describe the bug** `arrow::compute::concat` panics when called with dense union arrays with type IDs that don't start at zero. ``` thread 'proptest::tests::qc_row' panicked at 'index out of bounds: the len is 1 but the index is 35', ...\.cargo\registry\src\index.crates.io-6f17d22bba15001f\arrow-data-43.0.0\src\transform\union.rs:53:39 stack backtrace: ... 3: arrow_data::transform::union::build_extend_dense::{{closure}}::{{closure}} 4: core::iter::traits::iterator::Iterator::for_each::call::{{closure}} at /rustc/864bdf7843e1ceabc824ed86d97006acad6af643\library\core\src\iter\traits/iterator.rs:853:29 5: core::iter::traits::iterator::Iterator::fold at /rustc/864bdf7843e1ceabc824ed86d97006acad6af643\library\core\src\iter\traits/iterator.rs:2481:21 6: core::iter::traits::iterator::Iterator::for_each at /rustc/864bdf7843e1ceabc824ed86d97006acad6af643\library\core\src\iter\traits/iterator.rs:856:9 7: arrow_data::transform::union::build_extend_dense::{{closure}} at ...\.cargo\registry\src\index.crates.io-6f17d22bba15001f\arrow-data-43.0.0\src\transform\union.rs:50:13 8: <alloc::boxed::Box<F,A> as core::ops::function::Fn<Args>>::call at /rustc/864bdf7843e1ceabc824ed86d97006acad6af643\library\alloc\src/boxed.rs:2021:9 9: arrow_data::transform::MutableArrayData::extend at ...\.cargo\registry\src\index.crates.io-6f17d22bba15001f\arrow-data-43.0.0\src\transform\mod.rs:631:9 10: arrow_select::concat::concat at ...\.cargo\registry\src\index.crates.io-6f17d22bba15001f\arrow-select-43.0.0\src\concat.rs:89:9 ``` **To Reproduce** Call `arrow::compute::concat` and pass the following arrays: [ UnionArray(Dense) [ -- type id buffer: ScalarBuffer([35]) -- offsets buffer: ScalarBuffer([0]) -- child 35: "" (Null) NullArray(1) ], UnionArray(Dense) [ -- type id buffer: ScalarBuffer([35]) -- offsets buffer: ScalarBuffer([0]) -- child 35: "" (Null) NullArray(1) ], ] of the following data type: ``` Union( [ ( 35, Field { name: "", data_type: Null, nullable: false, dict_id: 0, dict_is_ordered: false, metadata: {}, }, ), ], Dense, ) ``` **Expected behavior** Producing the following array: ``` UnionArray(Dense) [ -- type id buffer: ScalarBuffer([35, 35]) -- offsets buffer: ScalarBuffer([0, 1]) -- child 35: "" (Null) NullArray(2) ] ``` **Additional context** <!-- Add any other context about the problem here. -->
MutableArrayData likely needs to be updated to properly understand UnionArray with non-trivial type ids
2023-07-31T04:27:18Z
45.0
c6184389241a0c85823aa494e8b5d93343771666
[ "test_union_dense" ]
[ "arrow/src/lib.rs - (line 108)", "arrow/src/lib.rs - (line 89)", "arrow/src/lib.rs - (line 221)", "arrow/src/lib.rs - (line 65)", "arrow/src/lib.rs - (line 31)", "arrow/src/lib.rs - (line 195)", "arrow/src/lib.rs - (line 46)", "arrow/src/lib.rs - (line 250)", "arrow/src/util/string_writer.rs - util::string_writer (line 25)", "arrow/src/lib.rs - (line 129)", "arrow/src/lib.rs - (line 166)", "test_binary_fixed_sized_offsets", "test_bool", "test_decimal_null_offset_nulls", "test_decimal_offset", "test_decimal", "test_extend_nulls", "test_dictionary", "test_extend_nulls_panic - should panic", "test_fixed_size_binary_append", "test_list_append", "test_list_null_offset", "test_list_nulls_append", "test_list_of_strings_append", "test_multiple_with_nulls", "test_null", "test_map_nulls_append", "test_primitive", "test_primitive_null_offset", "test_primitive_null_offset_nulls", "test_primitive_offset", "test_string_offsets", "test_string_null_offset_nulls", "test_struct", "test_struct_many", "test_struct_nulls", "test_struct_offset", "test_variable_sized_nulls", "test_variable_sized_offsets" ]
[]
[]
apache/arrow-rs
6,368
apache__arrow-rs-6368
[ "6366" ]
0491294828a6480959ba3983355b415abbaf1174
diff --git a/.github/workflows/integration.yml b/.github/workflows/integration.yml index 1937fafe3a62..41edc1bb194e 100644 --- a/.github/workflows/integration.yml +++ b/.github/workflows/integration.yml @@ -48,7 +48,6 @@ on: - arrow/** jobs: - integration: name: Archery test With other arrows runs-on: ubuntu-latest @@ -118,9 +117,9 @@ jobs: runs-on: ubuntu-latest strategy: matrix: - rust: [ stable ] - # PyArrow 13 was the last version prior to introduction to Arrow PyCapsules - pyarrow: [ "13", "14" ] + rust: [stable] + # PyArrow 15 was the first version to introduce StringView/BinaryView support + pyarrow: ["15", "16", "17"] steps: - uses: actions/checkout@v4 with: diff --git a/arrow-array/src/ffi.rs b/arrow-array/src/ffi.rs index 1d76ed62d365..a28b3f746115 100644 --- a/arrow-array/src/ffi.rs +++ b/arrow-array/src/ffi.rs @@ -193,6 +193,13 @@ fn bit_width(data_type: &DataType, i: usize) -> Result<usize> { "The datatype \"{data_type:?}\" expects 3 buffers, but requested {i}. Please verify that the C data interface is correctly implemented." ))) } + // Variable-sized views: have 3 or more buffers. + // Buffer 1 are the u128 views + // Buffers 2...N-1 are u8 byte buffers + (DataType::Utf8View, 1) | (DataType::BinaryView,1) => u128::BITS as _, + (DataType::Utf8View, _) | (DataType::BinaryView, _) => { + u8::BITS as _ + } // type ids. UnionArray doesn't have null bitmap so buffer index begins with 0. (DataType::Union(_, _), 0) => i8::BITS as _, // Only DenseUnion has 2nd buffer @@ -300,7 +307,7 @@ impl<'a> ImportedArrowArray<'a> { }; let data_layout = layout(&self.data_type); - let buffers = self.buffers(data_layout.can_contain_null_mask)?; + let buffers = self.buffers(data_layout.can_contain_null_mask, data_layout.variadic)?; let null_bit_buffer = if data_layout.can_contain_null_mask { self.null_bit_buffer() @@ -373,13 +380,30 @@ impl<'a> ImportedArrowArray<'a> { /// returns all buffers, as organized by Rust (i.e. null buffer is skipped if it's present /// in the spec of the type) - fn buffers(&self, can_contain_null_mask: bool) -> Result<Vec<Buffer>> { + fn buffers(&self, can_contain_null_mask: bool, variadic: bool) -> Result<Vec<Buffer>> { // + 1: skip null buffer let buffer_begin = can_contain_null_mask as usize; - (buffer_begin..self.array.num_buffers()) - .map(|index| { - let len = self.buffer_len(index, &self.data_type)?; + let buffer_end = self.array.num_buffers() - usize::from(variadic); + + let variadic_buffer_lens = if variadic { + // Each views array has 1 (optional) null buffer, 1 views buffer, 1 lengths buffer. + // Rest are variadic. + let num_variadic_buffers = + self.array.num_buffers() - (2 + usize::from(can_contain_null_mask)); + if num_variadic_buffers == 0 { + &[] + } else { + let lengths = self.array.buffer(self.array.num_buffers() - 1); + // SAFETY: is lengths is non-null, then it must be valid for up to num_variadic_buffers. + unsafe { std::slice::from_raw_parts(lengths.cast::<i64>(), num_variadic_buffers) } + } + } else { + &[] + }; + (buffer_begin..buffer_end) + .map(|index| { + let len = self.buffer_len(index, variadic_buffer_lens, &self.data_type)?; match unsafe { create_buffer(self.owner.clone(), self.array, index, len) } { Some(buf) => Ok(buf), None if len == 0 => { @@ -399,7 +423,12 @@ impl<'a> ImportedArrowArray<'a> { /// Rust implementation uses fixed-sized buffers, which require knowledge of their `len`. /// for variable-sized buffers, such as the second buffer of a stringArray, we need /// to fetch offset buffer's len to build the second buffer. - fn buffer_len(&self, i: usize, dt: &DataType) -> Result<usize> { + fn buffer_len( + &self, + i: usize, + variadic_buffer_lengths: &[i64], + dt: &DataType, + ) -> Result<usize> { // Special handling for dictionary type as we only care about the key type in the case. let data_type = match dt { DataType::Dictionary(key_data_type, _) => key_data_type.as_ref(), @@ -430,7 +459,7 @@ impl<'a> ImportedArrowArray<'a> { } // the len of the data buffer (buffer 2) equals the last value of the offset buffer (buffer 1) - let len = self.buffer_len(1, dt)?; + let len = self.buffer_len(1, variadic_buffer_lengths, dt)?; // first buffer is the null buffer => add(1) // we assume that pointer is aligned for `i32`, as Utf8 uses `i32` offsets. #[allow(clippy::cast_ptr_alignment)] @@ -444,7 +473,7 @@ impl<'a> ImportedArrowArray<'a> { } // the len of the data buffer (buffer 2) equals the last value of the offset buffer (buffer 1) - let len = self.buffer_len(1, dt)?; + let len = self.buffer_len(1, variadic_buffer_lengths, dt)?; // first buffer is the null buffer => add(1) // we assume that pointer is aligned for `i64`, as Large uses `i64` offsets. #[allow(clippy::cast_ptr_alignment)] @@ -452,6 +481,16 @@ impl<'a> ImportedArrowArray<'a> { // get last offset (unsafe { *offset_buffer.add(len / size_of::<i64>() - 1) }) as usize } + // View types: these have variadic buffers. + // Buffer 1 is the views buffer, which stores 1 u128 per length of the array. + // Buffers 2..N-1 are the buffers holding the byte data. Their lengths are variable. + // Buffer N is of length (N - 2) and stores i64 containing the lengths of buffers 2..N-1 + (DataType::Utf8View, 1) | (DataType::BinaryView, 1) => { + std::mem::size_of::<u128>() * length + } + (DataType::Utf8View, i) | (DataType::BinaryView, i) => { + variadic_buffer_lengths[i - 2] as usize + } // buffer len of primitive types _ => { let bits = bit_width(data_type, i)?; @@ -1229,18 +1268,18 @@ mod tests_from_ffi { use arrow_data::ArrayData; use arrow_schema::{DataType, Field}; - use crate::types::Int32Type; + use super::{ImportedArrowArray, Result}; + use crate::builder::GenericByteViewBuilder; + use crate::types::{BinaryViewType, ByteViewType, Int32Type, StringViewType}; use crate::{ array::{ Array, BooleanArray, DictionaryArray, FixedSizeBinaryArray, FixedSizeListArray, Int32Array, Int64Array, StringArray, StructArray, UInt32Array, UInt64Array, }, ffi::{from_ffi, FFI_ArrowArray, FFI_ArrowSchema}, - make_array, ArrayRef, ListArray, + make_array, ArrayRef, GenericByteViewArray, ListArray, }; - use super::{ImportedArrowArray, Result}; - fn test_round_trip(expected: &ArrayData) -> Result<()> { // here we export the array let array = FFI_ArrowArray::new(expected); @@ -1453,8 +1492,8 @@ mod tests_from_ffi { owner: &array, }; - let offset_buf_len = imported_array.buffer_len(1, &imported_array.data_type)?; - let data_buf_len = imported_array.buffer_len(2, &imported_array.data_type)?; + let offset_buf_len = imported_array.buffer_len(1, &[], &imported_array.data_type)?; + let data_buf_len = imported_array.buffer_len(2, &[], &imported_array.data_type)?; assert_eq!(offset_buf_len, 4); assert_eq!(data_buf_len, 0); @@ -1472,6 +1511,18 @@ mod tests_from_ffi { StringArray::from(array) } + fn roundtrip_byte_view_array<T: ByteViewType>( + array: GenericByteViewArray<T>, + ) -> GenericByteViewArray<T> { + let data = array.into_data(); + + let array = FFI_ArrowArray::new(&data); + let schema = FFI_ArrowSchema::try_from(data.data_type()).unwrap(); + + let array = unsafe { from_ffi(array, &schema) }.unwrap(); + GenericByteViewArray::<T>::from(array) + } + fn extend_array(array: &dyn Array) -> ArrayRef { let len = array.len(); let data = array.to_data(); @@ -1551,4 +1602,93 @@ mod tests_from_ffi { &imported ); } + + /// Helper trait to allow us to use easily strings as either BinaryViewType::Native or + /// StringViewType::Native scalars. + trait NativeFromStr { + fn from_str(value: &str) -> &Self; + } + + impl NativeFromStr for str { + fn from_str(value: &str) -> &Self { + value + } + } + + impl NativeFromStr for [u8] { + fn from_str(value: &str) -> &Self { + value.as_bytes() + } + } + + #[test] + fn test_round_trip_byte_view() { + fn test_case<T>() + where + T: ByteViewType, + T::Native: NativeFromStr, + { + macro_rules! run_test_case { + ($array:expr) => {{ + // round-trip through C Data Interface + let len = $array.len(); + let imported = roundtrip_byte_view_array($array); + assert_eq!(imported.len(), len); + + let copied = extend_array(&imported); + assert_eq!( + copied + .as_any() + .downcast_ref::<GenericByteViewArray<T>>() + .unwrap(), + &imported + ); + }}; + } + + // Empty test case. + let empty = GenericByteViewBuilder::<T>::new().finish(); + run_test_case!(empty); + + // All inlined strings test case. + let mut all_inlined = GenericByteViewBuilder::<T>::new(); + all_inlined.append_value(T::Native::from_str("inlined1")); + all_inlined.append_value(T::Native::from_str("inlined2")); + all_inlined.append_value(T::Native::from_str("inlined3")); + let all_inlined = all_inlined.finish(); + assert_eq!(all_inlined.data_buffers().len(), 0); + run_test_case!(all_inlined); + + // some inlined + non-inlined, 1 variadic buffer. + let mixed_one_variadic = { + let mut builder = GenericByteViewBuilder::<T>::new(); + builder.append_value(T::Native::from_str("inlined")); + let block_id = + builder.append_block(Buffer::from("non-inlined-string-buffer".as_bytes())); + builder.try_append_view(block_id, 0, 25).unwrap(); + builder.finish() + }; + assert_eq!(mixed_one_variadic.data_buffers().len(), 1); + run_test_case!(mixed_one_variadic); + + // inlined + non-inlined, 2 variadic buffers. + let mixed_two_variadic = { + let mut builder = GenericByteViewBuilder::<T>::new(); + builder.append_value(T::Native::from_str("inlined")); + let block_id = + builder.append_block(Buffer::from("non-inlined-string-buffer".as_bytes())); + builder.try_append_view(block_id, 0, 25).unwrap(); + + let block_id = builder + .append_block(Buffer::from("another-non-inlined-string-buffer".as_bytes())); + builder.try_append_view(block_id, 0, 33).unwrap(); + builder.finish() + }; + assert_eq!(mixed_two_variadic.data_buffers().len(), 2); + run_test_case!(mixed_two_variadic); + } + + test_case::<StringViewType>(); + test_case::<BinaryViewType>(); + } } diff --git a/arrow-buffer/src/buffer/immutable.rs b/arrow-buffer/src/buffer/immutable.rs index 7cd3552215f8..fef2f8008b2a 100644 --- a/arrow-buffer/src/buffer/immutable.rs +++ b/arrow-buffer/src/buffer/immutable.rs @@ -203,7 +203,9 @@ impl Buffer { pub fn advance(&mut self, offset: usize) { assert!( offset <= self.length, - "the offset of the new Buffer cannot exceed the existing length" + "the offset of the new Buffer cannot exceed the existing length: offset={} length={}", + offset, + self.length ); self.length -= offset; // Safety: @@ -221,7 +223,8 @@ impl Buffer { pub fn slice_with_length(&self, offset: usize, length: usize) -> Self { assert!( offset.saturating_add(length) <= self.length, - "the offset of the new Buffer cannot exceed the existing length" + "the offset of the new Buffer cannot exceed the existing length: slice offset={offset} length={length} selflen={}", + self.length ); // Safety: // offset + length <= self.length diff --git a/arrow-data/src/ffi.rs b/arrow-data/src/ffi.rs index 3345595fac19..cd283d32662f 100644 --- a/arrow-data/src/ffi.rs +++ b/arrow-data/src/ffi.rs @@ -20,7 +20,7 @@ use crate::bit_mask::set_bits; use crate::{layout, ArrayData}; use arrow_buffer::buffer::NullBuffer; -use arrow_buffer::{Buffer, MutableBuffer}; +use arrow_buffer::{Buffer, MutableBuffer, ScalarBuffer}; use arrow_schema::DataType; use std::ffi::c_void; @@ -121,7 +121,7 @@ impl FFI_ArrowArray { pub fn new(data: &ArrayData) -> Self { let data_layout = layout(data.data_type()); - let buffers = if data_layout.can_contain_null_mask { + let mut buffers = if data_layout.can_contain_null_mask { // * insert the null buffer at the start // * make all others `Option<Buffer>`. std::iter::once(align_nulls(data.offset(), data.nulls())) @@ -132,7 +132,7 @@ impl FFI_ArrowArray { }; // `n_buffers` is the number of buffers by the spec. - let n_buffers = { + let mut n_buffers = { data_layout.buffers.len() + { // If the layout has a null buffer by Arrow spec. // Note that even the array doesn't have a null buffer because it has @@ -141,10 +141,22 @@ impl FFI_ArrowArray { } } as i64; + if data_layout.variadic { + // Save the lengths of all variadic buffers into a new buffer. + // The first buffer is `views`, and the rest are variadic. + let mut data_buffers_lengths = Vec::new(); + for buffer in data.buffers().iter().skip(1) { + data_buffers_lengths.push(buffer.len() as i64); + n_buffers += 1; + } + + buffers.push(Some(ScalarBuffer::from(data_buffers_lengths).into_inner())); + n_buffers += 1; + } + let buffers_ptr = buffers .iter() .flat_map(|maybe_buffer| match maybe_buffer { - // note that `raw_data` takes into account the buffer's offset Some(b) => Some(b.as_ptr() as *const c_void), // This is for null buffer. We only put a null pointer for // null buffer if by spec it can contain null mask. diff --git a/arrow/src/pyarrow.rs b/arrow/src/pyarrow.rs index 336398cbf22f..a7b593799835 100644 --- a/arrow/src/pyarrow.rs +++ b/arrow/src/pyarrow.rs @@ -354,7 +354,7 @@ impl FromPyArrow for RecordBatch { validate_pycapsule(array_capsule, "arrow_array")?; let schema_ptr = unsafe { schema_capsule.reference::<FFI_ArrowSchema>() }; - let ffi_array = unsafe { FFI_ArrowArray::from_raw(array_capsule.pointer() as _) }; + let ffi_array = unsafe { FFI_ArrowArray::from_raw(array_capsule.pointer().cast()) }; let array_data = unsafe { ffi::from_ffi(ffi_array, schema_ptr) }.map_err(to_py_err)?; if !matches!(array_data.data_type(), DataType::Struct(_)) { return Err(PyTypeError::new_err(
diff --git a/arrow/tests/pyarrow.rs b/arrow/tests/pyarrow.rs index a1c365c31798..d9ebd0daa1cd 100644 --- a/arrow/tests/pyarrow.rs +++ b/arrow/tests/pyarrow.rs @@ -18,6 +18,8 @@ use arrow::array::{ArrayRef, Int32Array, StringArray}; use arrow::pyarrow::{FromPyArrow, ToPyArrow}; use arrow::record_batch::RecordBatch; +use arrow_array::builder::{BinaryViewBuilder, StringViewBuilder}; +use arrow_array::{Array, BinaryViewArray, StringViewArray}; use pyo3::Python; use std::sync::Arc; @@ -27,7 +29,9 @@ fn test_to_pyarrow() { let a: ArrayRef = Arc::new(Int32Array::from(vec![1, 2])); let b: ArrayRef = Arc::new(StringArray::from(vec!["a", "b"])); - let input = RecordBatch::try_from_iter(vec![("a", a), ("b", b)]).unwrap(); + // The "very long string" will not be inlined, and force the creation of a data buffer. + let c: ArrayRef = Arc::new(StringViewArray::from(vec!["short", "a very long string"])); + let input = RecordBatch::try_from_iter(vec![("a", a), ("b", b), ("c", c)]).unwrap(); println!("input: {:?}", input); let res = Python::with_gil(|py| { @@ -40,3 +44,66 @@ fn test_to_pyarrow() { assert_eq!(input, res); } + +#[test] +fn test_to_pyarrow_byte_view() { + pyo3::prepare_freethreaded_python(); + + for num_variadic_buffers in 0..=2 { + let string_view: ArrayRef = Arc::new(string_view_column(num_variadic_buffers)); + let binary_view: ArrayRef = Arc::new(binary_view_column(num_variadic_buffers)); + + let input = RecordBatch::try_from_iter(vec![ + ("string_view", string_view), + ("binary_view", binary_view), + ]) + .unwrap(); + + println!("input: {:?}", input); + let res = Python::with_gil(|py| { + let py_input = input.to_pyarrow(py)?; + let records = RecordBatch::from_pyarrow_bound(py_input.bind(py))?; + let py_records = records.to_pyarrow(py)?; + RecordBatch::from_pyarrow_bound(py_records.bind(py)) + }) + .unwrap(); + + assert_eq!(input, res); + } +} + +fn binary_view_column(num_variadic_buffers: usize) -> BinaryViewArray { + let long_scalar = b"but soft what light through yonder window breaks".as_slice(); + let mut builder = BinaryViewBuilder::new().with_fixed_block_size(long_scalar.len() as u32); + // Make sure there is at least one non-inlined value. + builder.append_value("inlined".as_bytes()); + + for _ in 0..num_variadic_buffers { + builder.append_value(long_scalar); + } + + let result = builder.finish(); + + assert_eq!(result.data_buffers().len(), num_variadic_buffers); + assert_eq!(result.len(), num_variadic_buffers + 1); + + result +} + +fn string_view_column(num_variadic_buffers: usize) -> StringViewArray { + let long_scalar = "but soft what light through yonder window breaks"; + let mut builder = StringViewBuilder::new().with_fixed_block_size(long_scalar.len() as u32); + // Make sure there is at least one non-inlined value. + builder.append_value("inlined"); + + for _ in 0..num_variadic_buffers { + builder.append_value(long_scalar); + } + + let result = builder.finish(); + + assert_eq!(result.data_buffers().len(), num_variadic_buffers); + assert_eq!(result.len(), num_variadic_buffers + 1); + + result +}
Exporting Binary/Utf8View from arrow-rs to pyarrow fails **Describe the bug** Exporting binaryview arrow to pyarrow fails with `Expected at least 3 buffers for imported type binary_view, ArrowArray struct has 2` **To Reproduce** Construct binaryview array and export it over c data interface to pyarrow **Expected behavior** Export should succeed without error **Additional context** I think there's ambiguity in the spec https://github.com/apache/arrow/issues/43989. However, regardless of that issue it seems that export binaryview array has to do a bit extra work to produce buffer lengths
2024-09-06T21:16:12Z
53.0
f41c258246cd4bd9d89228cded9ed54dbd00faff
[ "test_to_pyarrow", "test_to_pyarrow_byte_view" ]
[ "arrow/src/lib.rs - (line 118)", "arrow/src/lib.rs - (line 95)", "arrow/src/lib.rs - (line 235)", "arrow/src/lib.rs - (line 31)", "arrow/src/lib.rs - (line 70)", "arrow/src/lib.rs - (line 205)", "arrow/src/lib.rs - (line 48)", "arrow/src/lib.rs - (line 139)", "arrow/src/lib.rs - (line 264)", "arrow/src/lib.rs - (line 176)", "arrow/src/util/string_writer.rs - util::string_writer (line 25)" ]
[]
[]
apache/arrow-rs
4,909
apache__arrow-rs-4909
[ "4735" ]
ed58e767d7607e954085842a57a680b6807794e0
diff --git a/arrow-csv/src/writer.rs b/arrow-csv/src/writer.rs index 840e8e8a93cc..1ca956e2c73f 100644 --- a/arrow-csv/src/writer.rs +++ b/arrow-csv/src/writer.rs @@ -70,11 +70,6 @@ use csv::ByteRecord; use std::io::Write; use crate::map_csv_error; - -const DEFAULT_DATE_FORMAT: &str = "%F"; -const DEFAULT_TIME_FORMAT: &str = "%T"; -const DEFAULT_TIMESTAMP_FORMAT: &str = "%FT%H:%M:%S.%9f"; -const DEFAULT_TIMESTAMP_TZ_FORMAT: &str = "%FT%H:%M:%S.%9f%:z"; const DEFAULT_NULL_VALUE: &str = ""; /// A CSV writer @@ -82,41 +77,29 @@ const DEFAULT_NULL_VALUE: &str = ""; pub struct Writer<W: Write> { /// The object to write to writer: csv::Writer<W>, - /// Whether file should be written with headers. Defaults to `true` + /// Whether file should be written with headers, defaults to `true` has_headers: bool, - /// The date format for date arrays + /// The date format for date arrays, defaults to RFC3339 date_format: Option<String>, - /// The datetime format for datetime arrays + /// The datetime format for datetime arrays, defaults to RFC3339 datetime_format: Option<String>, - /// The timestamp format for timestamp arrays + /// The timestamp format for timestamp arrays, defaults to RFC3339 timestamp_format: Option<String>, - /// The timestamp format for timestamp (with timezone) arrays + /// The timestamp format for timestamp (with timezone) arrays, defaults to RFC3339 timestamp_tz_format: Option<String>, - /// The time format for time arrays + /// The time format for time arrays, defaults to RFC3339 time_format: Option<String>, /// Is the beginning-of-writer beginning: bool, - /// The value to represent null entries - null_value: String, + /// The value to represent null entries, defaults to [`DEFAULT_NULL_VALUE`] + null_value: Option<String>, } impl<W: Write> Writer<W> { /// Create a new CsvWriter from a writable object, with default options pub fn new(writer: W) -> Self { let delimiter = b','; - let mut builder = csv::WriterBuilder::new(); - let writer = builder.delimiter(delimiter).from_writer(writer); - Writer { - writer, - has_headers: true, - date_format: Some(DEFAULT_DATE_FORMAT.to_string()), - datetime_format: Some(DEFAULT_TIMESTAMP_FORMAT.to_string()), - time_format: Some(DEFAULT_TIME_FORMAT.to_string()), - timestamp_format: Some(DEFAULT_TIMESTAMP_FORMAT.to_string()), - timestamp_tz_format: Some(DEFAULT_TIMESTAMP_TZ_FORMAT.to_string()), - beginning: true, - null_value: DEFAULT_NULL_VALUE.to_string(), - } + WriterBuilder::new().with_delimiter(delimiter).build(writer) } /// Write a vector of record batches to a writable object @@ -138,7 +121,7 @@ impl<W: Write> Writer<W> { } let options = FormatOptions::default() - .with_null(&self.null_value) + .with_null(self.null_value.as_deref().unwrap_or(DEFAULT_NULL_VALUE)) .with_date_format(self.date_format.as_deref()) .with_datetime_format(self.datetime_format.as_deref()) .with_timestamp_format(self.timestamp_format.as_deref()) @@ -207,9 +190,9 @@ impl<W: Write> RecordBatchWriter for Writer<W> { #[derive(Clone, Debug)] pub struct WriterBuilder { /// Optional column delimiter. Defaults to `b','` - delimiter: Option<u8>, + delimiter: u8, /// Whether to write column names as file headers. Defaults to `true` - has_headers: bool, + has_header: bool, /// Optional date format for date arrays date_format: Option<String>, /// Optional datetime format for datetime arrays @@ -227,14 +210,14 @@ pub struct WriterBuilder { impl Default for WriterBuilder { fn default() -> Self { Self { - has_headers: true, - delimiter: None, - date_format: Some(DEFAULT_DATE_FORMAT.to_string()), - datetime_format: Some(DEFAULT_TIMESTAMP_FORMAT.to_string()), - time_format: Some(DEFAULT_TIME_FORMAT.to_string()), - timestamp_format: Some(DEFAULT_TIMESTAMP_FORMAT.to_string()), - timestamp_tz_format: Some(DEFAULT_TIMESTAMP_TZ_FORMAT.to_string()), - null_value: Some(DEFAULT_NULL_VALUE.to_string()), + has_header: true, + delimiter: b',', + date_format: None, + datetime_format: None, + time_format: None, + timestamp_format: None, + timestamp_tz_format: None, + null_value: None, } } } @@ -254,7 +237,7 @@ impl WriterBuilder { /// let file = File::create("target/out.csv").unwrap(); /// /// // create a builder that doesn't write headers - /// let builder = WriterBuilder::new().has_headers(false); + /// let builder = WriterBuilder::new().with_header(false); /// let writer = builder.build(file); /// /// writer @@ -265,48 +248,92 @@ impl WriterBuilder { } /// Set whether to write headers + #[deprecated(note = "Use Self::with_header")] + #[doc(hidden)] pub fn has_headers(mut self, has_headers: bool) -> Self { - self.has_headers = has_headers; + self.has_header = has_headers; + self + } + + /// Set whether to write the CSV file with a header + pub fn with_header(mut self, header: bool) -> Self { + self.has_header = header; self } + /// Returns `true` if this writer is configured to write a header + pub fn header(&self) -> bool { + self.has_header + } + /// Set the CSV file's column delimiter as a byte character pub fn with_delimiter(mut self, delimiter: u8) -> Self { - self.delimiter = Some(delimiter); + self.delimiter = delimiter; self } + /// Get the CSV file's column delimiter as a byte character + pub fn delimiter(&self) -> u8 { + self.delimiter + } + /// Set the CSV file's date format pub fn with_date_format(mut self, format: String) -> Self { self.date_format = Some(format); self } + /// Get the CSV file's date format if set, defaults to RFC3339 + pub fn date_format(&self) -> Option<&str> { + self.date_format.as_deref() + } + /// Set the CSV file's datetime format pub fn with_datetime_format(mut self, format: String) -> Self { self.datetime_format = Some(format); self } + /// Get the CSV file's datetime format if set, defaults to RFC3339 + pub fn datetime_format(&self) -> Option<&str> { + self.datetime_format.as_deref() + } + /// Set the CSV file's time format pub fn with_time_format(mut self, format: String) -> Self { self.time_format = Some(format); self } + /// Get the CSV file's datetime time if set, defaults to RFC3339 + pub fn time_format(&self) -> Option<&str> { + self.time_format.as_deref() + } + /// Set the CSV file's timestamp format pub fn with_timestamp_format(mut self, format: String) -> Self { self.timestamp_format = Some(format); self } + /// Get the CSV file's timestamp format if set, defaults to RFC3339 + pub fn timestamp_format(&self) -> Option<&str> { + self.timestamp_format.as_deref() + } + /// Set the value to represent null in output pub fn with_null(mut self, null_value: String) -> Self { self.null_value = Some(null_value); self } - /// Use RFC3339 format for date/time/timestamps + /// Get the value to represent null in output + pub fn null(&self) -> &str { + self.null_value.as_deref().unwrap_or(DEFAULT_NULL_VALUE) + } + + /// Use RFC3339 format for date/time/timestamps (default) + #[deprecated(note = "Use WriterBuilder::default()")] pub fn with_rfc3339(mut self) -> Self { self.date_format = None; self.datetime_format = None; @@ -318,21 +345,18 @@ impl WriterBuilder { /// Create a new `Writer` pub fn build<W: Write>(self, writer: W) -> Writer<W> { - let delimiter = self.delimiter.unwrap_or(b','); let mut builder = csv::WriterBuilder::new(); - let writer = builder.delimiter(delimiter).from_writer(writer); + let writer = builder.delimiter(self.delimiter).from_writer(writer); Writer { writer, - has_headers: self.has_headers, + beginning: true, + has_headers: self.has_header, date_format: self.date_format, datetime_format: self.datetime_format, time_format: self.time_format, timestamp_format: self.timestamp_format, timestamp_tz_format: self.timestamp_tz_format, - beginning: true, - null_value: self - .null_value - .unwrap_or_else(|| DEFAULT_NULL_VALUE.to_string()), + null_value: self.null_value, } } } @@ -411,11 +435,11 @@ mod tests { let expected = r#"c1,c2,c3,c4,c5,c6,c7 Lorem ipsum dolor sit amet,123.564532,3,true,,00:20:34,cupcakes -consectetur adipiscing elit,,2,false,2019-04-18T10:54:47.378000000,06:51:20,cupcakes -sed do eiusmod tempor,-556132.25,1,,2019-04-18T02:45:55.555000000,23:46:03,foo +consectetur adipiscing elit,,2,false,2019-04-18T10:54:47.378,06:51:20,cupcakes +sed do eiusmod tempor,-556132.25,1,,2019-04-18T02:45:55.555,23:46:03,foo Lorem ipsum dolor sit amet,123.564532,3,true,,00:20:34,cupcakes -consectetur adipiscing elit,,2,false,2019-04-18T10:54:47.378000000,06:51:20,cupcakes -sed do eiusmod tempor,-556132.25,1,,2019-04-18T02:45:55.555000000,23:46:03,foo +consectetur adipiscing elit,,2,false,2019-04-18T10:54:47.378,06:51:20,cupcakes +sed do eiusmod tempor,-556132.25,1,,2019-04-18T02:45:55.555,23:46:03,foo "#; assert_eq!(expected.to_string(), String::from_utf8(buffer).unwrap()); } @@ -512,7 +536,7 @@ sed do eiusmod tempor,-556132.25,1,,2019-04-18T02:45:55.555000000,23:46:03,foo let mut file = tempfile::tempfile().unwrap(); let builder = WriterBuilder::new() - .has_headers(false) + .with_header(false) .with_delimiter(b'|') .with_null("NULL".to_string()) .with_time_format("%r".to_string()); @@ -560,7 +584,7 @@ sed do eiusmod tempor,-556132.25,1,,2019-04-18T02:45:55.555000000,23:46:03,foo ) .unwrap(); - let builder = WriterBuilder::new().has_headers(false); + let builder = WriterBuilder::new().with_header(false); let mut buf: Cursor<Vec<u8>> = Default::default(); // drop the writer early to release the borrow. @@ -652,7 +676,7 @@ sed do eiusmod tempor,-556132.25,1,,2019-04-18T02:45:55.555000000,23:46:03,foo let mut file = tempfile::tempfile().unwrap(); - let builder = WriterBuilder::new().with_rfc3339(); + let builder = WriterBuilder::new(); let mut writer = builder.build(&mut file); let batches = vec![&batch]; for batch in batches {
diff --git a/arrow/tests/csv.rs b/arrow/tests/csv.rs index 3ee319101757..a79b6b44c2d3 100644 --- a/arrow/tests/csv.rs +++ b/arrow/tests/csv.rs @@ -53,48 +53,6 @@ fn test_export_csv_timestamps() { } drop(writer); - let left = "c1,c2 -2019-04-18T20:54:47.378000000+10:00,2019-04-18T10:54:47.378000000 -2021-10-30T17:59:07.000000000+11:00,2021-10-30T06:59:07.000000000\n"; - let right = String::from_utf8(sw).unwrap(); - assert_eq!(left, right); -} - -#[test] -fn test_export_csv_timestamps_using_rfc3339() { - let schema = Schema::new(vec![ - Field::new( - "c1", - DataType::Timestamp(TimeUnit::Millisecond, Some("Australia/Sydney".into())), - true, - ), - Field::new("c2", DataType::Timestamp(TimeUnit::Millisecond, None), true), - ]); - - let c1 = TimestampMillisecondArray::from( - // 1555584887 converts to 2019-04-18, 20:54:47 in time zone Australia/Sydney (AEST). - // The offset (difference to UTC) is +10:00. - // 1635577147 converts to 2021-10-30 17:59:07 in time zone Australia/Sydney (AEDT) - // The offset (difference to UTC) is +11:00. Note that daylight savings is in effect on 2021-10-30. - // - vec![Some(1555584887378), Some(1635577147000)], - ) - .with_timezone("Australia/Sydney"); - let c2 = - TimestampMillisecondArray::from(vec![Some(1555584887378), Some(1635577147000)]); - let batch = - RecordBatch::try_new(Arc::new(schema), vec![Arc::new(c1), Arc::new(c2)]).unwrap(); - - let mut sw = Vec::new(); - let mut writer = arrow_csv::WriterBuilder::new() - .with_rfc3339() - .build(&mut sw); - let batches = vec![&batch]; - for batch in batches { - writer.write(batch).unwrap(); - } - drop(writer); - let left = "c1,c2 2019-04-18T20:54:47.378+10:00,2019-04-18T10:54:47.378 2021-10-30T17:59:07+11:00,2021-10-30T06:59:07\n";
Add read access to settings in `csv::WriterBuilder` **Is your feature request related to a problem or challenge? Please describe what you are trying to do.** While implementing CSV writing in DataFusion (see https://github.com/apache/arrow-datafusion/pull/7390/files), we would like to be able to check the value of `has_headers` before actually constructing a csv writer. However, the current API has no way to do read the current values (only modify them): https://docs.rs/arrow-csv/45.0.0/arrow_csv/writer/struct.WriterBuilder.html **Describe the solution you'd like** It would be nice to have read only access to the fields. Maybe something like ```rust let builder = WriterBuilder::new().has_headers(false); let has_headers = builder.get_has_headers() ``` It is somewhat unfortunate that the builder already uses `has_headers` to set the field names rather than `with_has_headers` **Describe alternatives you've considered** We can keep a copy of has_headers around as @devinjdangelo has done in https://github.com/apache/arrow-datafusion/pull/7390/files **Additional context** <!-- Add any other context or screenshots about the feature request here. -->
Looks it is easy.
2023-10-09T16:11:31Z
47.0
fa7a61a4b074ca4ec9bf429cc84b6c325057d96e
[ "test_export_csv_timestamps" ]
[ "arrow/src/lib.rs - (line 89)", "arrow/src/lib.rs - (line 108)", "arrow/src/lib.rs - (line 221)", "arrow/src/lib.rs - (line 65)", "arrow/src/lib.rs - (line 31)", "arrow/src/lib.rs - (line 129)", "arrow/src/lib.rs - (line 46)", "arrow/src/lib.rs - (line 250)", "arrow/src/util/string_writer.rs - util::string_writer (line 25)", "arrow/src/lib.rs - (line 195)", "arrow/src/lib.rs - (line 166)" ]
[]
[]
apache/arrow-rs
2,044
apache__arrow-rs-2044
[ "2043" ]
ca5fe7df5ca0bdcfd6f732cc3f10da511b753c5f
diff --git a/parquet/src/arrow/async_reader.rs b/parquet/src/arrow/async_reader.rs index b251c2a827e7..923f329eff20 100644 --- a/parquet/src/arrow/async_reader.rs +++ b/parquet/src/arrow/async_reader.rs @@ -552,7 +552,7 @@ impl PageReader for InMemoryColumnChunkReader { Ok(None) } - fn peek_next_page(&self) -> Result<Option<PageMetadata>> { + fn peek_next_page(&mut self) -> Result<Option<PageMetadata>> { Err(nyi_err!("https://github.com/apache/arrow-rs/issues/1792")) } diff --git a/parquet/src/column/page.rs b/parquet/src/column/page.rs index d667af7120a5..78890f36a47f 100644 --- a/parquet/src/column/page.rs +++ b/parquet/src/column/page.rs @@ -205,7 +205,7 @@ pub trait PageReader: Iterator<Item = Result<Page>> + Send { /// Gets metadata about the next page, returns an error if no /// column index information - fn peek_next_page(&self) -> Result<Option<PageMetadata>>; + fn peek_next_page(&mut self) -> Result<Option<PageMetadata>>; /// Skips reading the next page, returns an error if no /// column index information diff --git a/parquet/src/file/metadata.rs b/parquet/src/file/metadata.rs index ad8fe16ad8be..bffe538cc72f 100644 --- a/parquet/src/file/metadata.rs +++ b/parquet/src/file/metadata.rs @@ -228,7 +228,7 @@ pub struct RowGroupMetaData { num_rows: i64, total_byte_size: i64, schema_descr: SchemaDescPtr, - // Todo add filter result -> row range + page_offset_index: Option<Vec<Vec<PageLocation>>>, } impl RowGroupMetaData { @@ -267,6 +267,11 @@ impl RowGroupMetaData { self.columns.iter().map(|c| c.total_compressed_size).sum() } + /// Returns reference of page offset index of all column in this row group. + pub fn page_offset_index(&self) -> &Option<Vec<Vec<PageLocation>>> { + &self.page_offset_index + } + /// Returns reference to a schema descriptor. pub fn schema_descr(&self) -> &SchemaDescriptor { self.schema_descr.as_ref() @@ -277,6 +282,11 @@ impl RowGroupMetaData { self.schema_descr.clone() } + /// Sets page offset index for this row group. + pub fn set_page_offset(&mut self, page_offset: Vec<Vec<PageLocation>>) { + self.page_offset_index = Some(page_offset); + } + /// Method to convert from Thrift. pub fn from_thrift( schema_descr: SchemaDescPtr, @@ -295,6 +305,7 @@ impl RowGroupMetaData { num_rows, total_byte_size, schema_descr, + page_offset_index: None, }) } @@ -318,6 +329,7 @@ pub struct RowGroupMetaDataBuilder { schema_descr: SchemaDescPtr, num_rows: i64, total_byte_size: i64, + page_offset_index: Option<Vec<Vec<PageLocation>>>, } impl RowGroupMetaDataBuilder { @@ -328,6 +340,7 @@ impl RowGroupMetaDataBuilder { schema_descr, num_rows: 0, total_byte_size: 0, + page_offset_index: None, } } @@ -349,6 +362,12 @@ impl RowGroupMetaDataBuilder { self } + /// Sets page offset index for this row group. + pub fn set_page_offset(mut self, page_offset: Vec<Vec<PageLocation>>) -> Self { + self.page_offset_index = Some(page_offset); + self + } + /// Builds row group metadata. pub fn build(self) -> Result<RowGroupMetaData> { if self.schema_descr.num_columns() != self.columns.len() { @@ -364,6 +383,7 @@ impl RowGroupMetaDataBuilder { num_rows: self.num_rows, total_byte_size: self.total_byte_size, schema_descr: self.schema_descr, + page_offset_index: self.page_offset_index, }) } } diff --git a/parquet/src/file/serialized_reader.rs b/parquet/src/file/serialized_reader.rs index c0f7c3926a5d..766813f11aee 100644 --- a/parquet/src/file/serialized_reader.rs +++ b/parquet/src/file/serialized_reader.rs @@ -19,9 +19,10 @@ //! Also contains implementations of the ChunkReader for files (with buffering) and byte arrays (RAM) use bytes::{Buf, Bytes}; +use std::collections::VecDeque; use std::{convert::TryFrom, fs::File, io::Read, path::Path, sync::Arc}; -use parquet_format::{PageHeader, PageType}; +use parquet_format::{PageHeader, PageLocation, PageType}; use thrift::protocol::TCompactInputProtocol; use crate::basic::{Compression, Encoding, Type}; @@ -33,6 +34,7 @@ use crate::file::{footer, metadata::*, reader::*, statistics}; use crate::record::reader::RowIter; use crate::record::Row; use crate::schema::types::Type as SchemaType; +use crate::util::page_util::{calculate_row_count, get_pages_readable_slices}; use crate::util::{io::TryClone, memory::ByteBufferPtr}; // export `SliceableCursor` and `FileSource` publically so clients can @@ -251,11 +253,12 @@ impl<R: 'static + ChunkReader> SerializedFileReader<R> { let mut columns_indexes = vec![]; let mut offset_indexes = vec![]; - for rg in &filtered_row_groups { + for rg in &mut filtered_row_groups { let column_index = index_reader::read_columns_indexes(&chunk_reader, rg.columns())?; let offset_index = index_reader::read_pages_locations(&chunk_reader, rg.columns())?; + rg.set_page_offset(offset_index.clone()); columns_indexes.push(column_index); offset_indexes.push(offset_index); } @@ -346,14 +349,31 @@ impl<'a, R: 'static + ChunkReader> RowGroupReader for SerializedRowGroupReader<' fn get_column_page_reader(&self, i: usize) -> Result<Box<dyn PageReader>> { let col = self.metadata.column(i); let (col_start, col_length) = col.byte_range(); - //Todo filter with multi row range - let file_chunk = self.chunk_reader.get_read(col_start, col_length as usize)?; - let page_reader = SerializedPageReader::new( - file_chunk, - col.num_values(), - col.compression(), - col.column_descr().physical_type(), - )?; + let page_reader = if let Some(offset_index) = self.metadata.page_offset_index() { + let col_chunk_offset_index = &offset_index[i]; + let (page_bufs, has_dict) = get_pages_readable_slices( + col_chunk_offset_index, + col_start, + self.chunk_reader.clone(), + )?; + SerializedPageReader::new_with_page_offsets( + col.num_values(), + col.compression(), + col.column_descr().physical_type(), + col_chunk_offset_index.clone(), + has_dict, + page_bufs, + )? + } else { + let file_chunk = + self.chunk_reader.get_read(col_start, col_length as usize)?; + SerializedPageReader::new( + file_chunk, + col.num_values(), + col.compression(), + col.column_descr().physical_type(), + )? + }; Ok(Box::new(page_reader)) } @@ -464,11 +484,23 @@ pub(crate) fn decode_page( Ok(result) } +enum SerializedPages<T: Read> { + /// Read entire chunk + Chunk { buf: T }, + /// Read operate pages which can skip. + Pages { + offset_index: Vec<PageLocation>, + seen_num_data_pages: usize, + has_dictionary_page_to_read: bool, + page_bufs: VecDeque<T>, + }, +} + /// A serialized implementation for Parquet [`PageReader`]. pub struct SerializedPageReader<T: Read> { // The file source buffer which references exactly the bytes for the column trunk // to be read by this page reader. - buf: T, + buf: SerializedPages<T>, // The compression codec for this column chunk. Only set for non-PLAIN codec. decompressor: Option<Box<dyn Codec>>, @@ -493,7 +525,32 @@ impl<T: Read> SerializedPageReader<T> { ) -> Result<Self> { let decompressor = create_codec(compression)?; let result = Self { - buf, + buf: SerializedPages::Chunk { buf }, + total_num_values, + seen_num_values: 0, + decompressor, + physical_type, + }; + Ok(result) + } + + /// Creates a new serialized page reader from file source. + pub fn new_with_page_offsets( + total_num_values: i64, + compression: Compression, + physical_type: Type, + offset_index: Vec<PageLocation>, + has_dictionary_page_to_read: bool, + page_bufs: VecDeque<T>, + ) -> Result<Self> { + let decompressor = create_codec(compression)?; + let result = Self { + buf: SerializedPages::Pages { + offset_index, + seen_num_data_pages: 0, + has_dictionary_page_to_read, + page_bufs, + }, total_num_values, seen_num_values: 0, decompressor, @@ -513,14 +570,35 @@ impl<T: Read + Send> Iterator for SerializedPageReader<T> { impl<T: Read + Send> PageReader for SerializedPageReader<T> { fn get_next_page(&mut self) -> Result<Option<Page>> { + let mut cursor; + let mut dictionary_cursor; while self.seen_num_values < self.total_num_values { - let page_header = read_page_header(&mut self.buf)?; + match &mut self.buf { + SerializedPages::Chunk { buf } => { + cursor = buf; + } + SerializedPages::Pages { + offset_index, + seen_num_data_pages, + has_dictionary_page_to_read, + page_bufs, + } => { + if offset_index.len() <= *seen_num_data_pages { + return Ok(None); + } else if *seen_num_data_pages == 0 && *has_dictionary_page_to_read { + dictionary_cursor = page_bufs.pop_front().unwrap(); + cursor = &mut dictionary_cursor; + } else { + cursor = page_bufs.get_mut(*seen_num_data_pages).unwrap(); + } + } + } + + let page_header = read_page_header(cursor)?; let to_read = page_header.compressed_page_size as usize; let mut buffer = Vec::with_capacity(to_read); - let read = (&mut self.buf) - .take(to_read as u64) - .read_to_end(&mut buffer)?; + let read = cursor.take(to_read as u64).read_to_end(&mut buffer)?; if read != to_read { return Err(eof_err!( @@ -540,14 +618,30 @@ impl<T: Read + Send> PageReader for SerializedPageReader<T> { self.decompressor.as_mut(), )?; self.seen_num_values += decoded.num_values() as i64; + if let SerializedPages::Pages { + seen_num_data_pages, + .. + } = &mut self.buf + { + *seen_num_data_pages += 1; + } decoded } - PageType::DictionaryPage => decode_page( - page_header, - buffer, - self.physical_type, - self.decompressor.as_mut(), - )?, + PageType::DictionaryPage => { + if let SerializedPages::Pages { + has_dictionary_page_to_read, + .. + } = &mut self.buf + { + *has_dictionary_page_to_read = false; + } + decode_page( + page_header, + buffer, + self.physical_type, + self.decompressor.as_mut(), + )? + } _ => { // For unknown page type (e.g., INDEX_PAGE), skip and read next. continue; @@ -560,12 +654,49 @@ impl<T: Read + Send> PageReader for SerializedPageReader<T> { Ok(None) } - fn peek_next_page(&self) -> Result<Option<PageMetadata>> { - Err(nyi_err!("https://github.com/apache/arrow-rs/issues/1792")) + fn peek_next_page(&mut self) -> Result<Option<PageMetadata>> { + match &mut self.buf { + SerializedPages::Chunk { .. } => { Err(general_err!("Must set page_offset_index when using peek_next_page in SerializedPageReader.")) } + SerializedPages::Pages { offset_index, seen_num_data_pages, has_dictionary_page_to_read, .. } => { + if *seen_num_data_pages >= offset_index.len() { + Ok(None) + } else if *seen_num_data_pages == 0 && *has_dictionary_page_to_read { + // Will set `has_dictionary_page_to_read` false in `get_next_page`, + // assume dictionary page must be read and cannot be skipped. + Ok(Some(PageMetadata { + num_rows: usize::MIN, + is_dict: true, + })) + } else { + let row_count = calculate_row_count( + offset_index, + *seen_num_data_pages, + self.total_num_values, + )?; + Ok(Some(PageMetadata { + num_rows: row_count, + is_dict: false, + })) + } + } + } } fn skip_next_page(&mut self) -> Result<()> { - Err(nyi_err!("https://github.com/apache/arrow-rs/issues/1792")) + match &mut self.buf { + SerializedPages::Chunk { .. } => { Err(general_err!("Must set page_offset_index when using skip_next_page in SerializedPageReader.")) } + SerializedPages::Pages { offset_index, seen_num_data_pages, .. } => { + if offset_index.len() <= *seen_num_data_pages { + Err(general_err!( + "seen_num_data_pages is out of bound in SerializedPageReader." + )) + } else { + *seen_num_data_pages += 1; + // Notice: maybe need 'self.seen_num_values += xxx', for now we can not get skip values in skip_next_page. + Ok(()) + } + } + } } } @@ -1323,4 +1454,76 @@ mod tests { let statistics = r.column(col_num).statistics().unwrap(); (statistics.min_bytes(), statistics.max_bytes()) } + + #[test] + fn test_skip_page_with_offset_index() { + let test_file = get_test_file("alltypes_tiny_pages_plain.parquet"); + let builder = ReadOptionsBuilder::new(); + //enable read page index + let options = builder.with_page_index().build(); + let reader_result = SerializedFileReader::new_with_options(test_file, options); + let reader = reader_result.unwrap(); + + let row_group_reader = reader.get_row_group(0).unwrap(); + + //use 'int_col', Boundary order: ASCENDING, total 325 pages. + let mut column_page_reader = row_group_reader.get_column_page_reader(4).unwrap(); + + let mut vec = vec![]; + + for i in 0..325 { + if i % 2 == 0 { + vec.push(column_page_reader.get_next_page().unwrap().unwrap()); + } else { + column_page_reader.skip_next_page().unwrap(); + } + } + //check read all pages. + assert!(column_page_reader.peek_next_page().unwrap().is_none()); + assert!(column_page_reader.get_next_page().unwrap().is_none()); + + assert_eq!(vec.len(), 163); + } + + #[test] + fn test_peek_page_with_dictionary_page() { + let test_file = get_test_file("alltypes_tiny_pages.parquet"); + let builder = ReadOptionsBuilder::new(); + //enable read page index + let options = builder.with_page_index().build(); + let reader_result = SerializedFileReader::new_with_options(test_file, options); + let reader = reader_result.unwrap(); + let row_group_reader = reader.get_row_group(0).unwrap(); + + //use 'string_col', Boundary order: UNORDERED, total 352 data ages and 1 dictionary page. + let mut column_page_reader = row_group_reader.get_column_page_reader(9).unwrap(); + + let mut vec = vec![]; + + let meta = column_page_reader.peek_next_page().unwrap().unwrap(); + assert!(meta.is_dict); + let page = column_page_reader.get_next_page().unwrap().unwrap(); + assert!(matches!(page.page_type(), basic::PageType::DICTIONARY_PAGE)); + + for i in 0..352 { + let meta = column_page_reader.peek_next_page().unwrap().unwrap(); + // have checked with `parquet-tools column-index -c string_col ./alltypes_tiny_pages.parquet` + // page meta has two scenarios(21, 20) of num_rows expect last page has 11 rows. + if i != 351 { + assert!((meta.num_rows == 21) || (meta.num_rows == 20)); + } else { + assert_eq!(meta.num_rows, 11); + } + assert!(!meta.is_dict); + vec.push(meta); + let page = column_page_reader.get_next_page().unwrap().unwrap(); + assert!(matches!(page.page_type(), basic::PageType::DATA_PAGE)); + } + + //check read all pages. + assert!(column_page_reader.peek_next_page().unwrap().is_none()); + assert!(column_page_reader.get_next_page().unwrap().is_none()); + + assert_eq!(vec.len(), 352); + } } diff --git a/parquet/src/util/mod.rs b/parquet/src/util/mod.rs index 3a69df4360b2..b49e32516921 100644 --- a/parquet/src/util/mod.rs +++ b/parquet/src/util/mod.rs @@ -24,6 +24,8 @@ pub mod cursor; pub mod hash_util; #[cfg(any(test, feature = "test_common"))] pub(crate) mod test_common; +pub(crate)mod page_util; + #[cfg(any(test, feature = "test_common"))] pub use self::test_common::page_util::{ DataPageBuilder, DataPageBuilderImpl, InMemoryPageIterator, diff --git a/parquet/src/util/page_util.rs b/parquet/src/util/page_util.rs new file mode 100644 index 000000000000..5cdcf7535c63 --- /dev/null +++ b/parquet/src/util/page_util.rs @@ -0,0 +1,54 @@ +// 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. + +use std::collections::VecDeque; +use std::io::Read; +use std::sync::Arc; +use crate::errors::Result; +use parquet_format::PageLocation; +use crate::file::reader::ChunkReader; + +/// Use column chunk's offset index to get the `page_num` page row count. +pub(crate) fn calculate_row_count(indexes: &[PageLocation], page_num: usize, total_row_count: i64) -> Result<usize> { + if page_num == indexes.len() - 1 { + Ok((total_row_count - indexes[page_num].first_row_index + 1) as usize) + } else { + Ok((indexes[page_num + 1].first_row_index - indexes[page_num].first_row_index) as usize) + } +} + +/// Use column chunk's offset index to get each page serially readable slice +/// and a flag indicates whether having one dictionary page in this column chunk. +pub(crate) fn get_pages_readable_slices<T: Read + Send, R: ChunkReader<T=T>>(col_chunk_offset_index: &[PageLocation], col_start: u64, chunk_reader: Arc<R>) -> Result<(VecDeque<T>, bool)> { + let first_data_page_offset = col_chunk_offset_index[0].offset as u64; + let has_dictionary_page = first_data_page_offset != col_start; + let mut page_readers = VecDeque::with_capacity(col_chunk_offset_index.len() + 1); + + if has_dictionary_page { + let length = (first_data_page_offset - col_start) as usize; + let reader: T = chunk_reader.get_read(col_start, length)?; + page_readers.push_back(reader); + } + + for index in col_chunk_offset_index { + let start = index.offset as u64; + let length = index.compressed_page_size as usize; + let reader: T = chunk_reader.get_read(start, length)?; + page_readers.push_back(reader) + } + Ok((page_readers, has_dictionary_page)) +}
diff --git a/parquet/src/util/test_common/page_util.rs b/parquet/src/util/test_common/page_util.rs index 0b70c38ad0e6..f56eaf85e636 100644 --- a/parquet/src/util/test_common/page_util.rs +++ b/parquet/src/util/test_common/page_util.rs @@ -173,7 +173,7 @@ impl<P: Iterator<Item = Page> + Send> PageReader for InMemoryPageReader<P> { Ok(self.page_iter.next()) } - fn peek_next_page(&self) -> Result<Option<PageMetadata>> { + fn peek_next_page(&mut self) -> Result<Option<PageMetadata>> { unimplemented!() }
Support `peek_next_page()` and `skip_next_page` in `SerializedPageReader` **Is your feature request related to a problem or challenge? Please describe what you are trying to do.** Add `skip_next_page` and `peek_next_page` function to SerializedPageReader that uses the column index to skip the next page without reading it. related #1792 **Describe the solution you'd like** A clear and concise description of what you want to happen. **Describe alternatives you've considered** A clear and concise description of any alternative solutions or features you've considered. **Additional context** Add any other context or screenshots about the feature request here.
2022-07-11T15:00:53Z
18.0
2541e2c88913d115cbe85312d1dc0202457c050c
[ "parquet/src/arrow/mod.rs - arrow (line 55)" ]
[ "parquet/src/arrow/arrow_reader.rs - arrow::arrow_reader::ParquetFileArrowReader::try_new (line 199) - compile", "parquet/src/file/mod.rs - file (line 81) - compile", "parquet/src/record/api.rs - record::api::Row::get_column_iter (line 62) - compile", "parquet/src/file/mod.rs - file (line 64) - compile", "parquet/src/file/mod.rs - file (line 29) - compile", "parquet/src/column/mod.rs - column (line 38) - compile", "parquet/src/arrow/mod.rs - arrow (line 68)", "parquet/src/arrow/arrow_writer/mod.rs - arrow::arrow_writer::ArrowWriter (line 53)", "parquet/src/arrow/mod.rs - arrow (line 27)", "parquet/src/schema/mod.rs - schema (line 22)", "parquet/src/schema/printer.rs - schema::printer (line 23)", "parquet/src/schema/parser.rs - schema::parser (line 24)", "parquet/src/schema/types.rs - schema::types::ColumnPath::append (line 674)", "parquet/src/schema/types.rs - schema::types::ColumnPath::string (line 663)", "parquet/src/file/properties.rs - file::properties (line 22)", "parquet/src/file/statistics.rs - file::statistics (line 23)", "parquet/src/record/api.rs - record::api::RowFormatter (line 140)" ]
[]
[]
apache/arrow-rs
3,222
apache__arrow-rs-3222
[ "3221" ]
1a8e6ed957e483ec27b88fce54a48b8176be3179
diff --git a/arrow-cast/src/cast.rs b/arrow-cast/src/cast.rs index 23be8839593c..ad9f08388326 100644 --- a/arrow-cast/src/cast.rs +++ b/arrow-cast/src/cast.rs @@ -160,7 +160,7 @@ pub fn can_cast_types(from_type: &DataType, to_type: &DataType) -> bool { | Time64(TimeUnit::Nanosecond) | Timestamp(TimeUnit::Nanosecond, None) ) => true, - (Utf8, _) => DataType::is_numeric(to_type), + (Utf8, _) => DataType::is_numeric(to_type) && to_type != &Float16, (LargeUtf8, LargeBinary | Date32 @@ -171,11 +171,11 @@ pub fn can_cast_types(from_type: &DataType, to_type: &DataType) -> bool { | Time64(TimeUnit::Nanosecond) | Timestamp(TimeUnit::Nanosecond, None) ) => true, - (LargeUtf8, _) => DataType::is_numeric(to_type), + (LargeUtf8, _) => DataType::is_numeric(to_type) && to_type != &Float16, (Timestamp(_, _), Utf8) | (Timestamp(_, _), LargeUtf8) => true, (Date32, Utf8) | (Date32, LargeUtf8) => true, (Date64, Utf8) | (Date64, LargeUtf8) => true, - (_, Utf8 | LargeUtf8) => DataType::is_numeric(from_type) || from_type == &Binary, + (_, Utf8 | LargeUtf8) => (DataType::is_numeric(from_type) && from_type != &Float16) || from_type == &Binary, // start numeric casts ( @@ -972,6 +972,7 @@ pub fn cast_with_options( Int16 => cast_numeric_to_bool::<Int16Type>(array), Int32 => cast_numeric_to_bool::<Int32Type>(array), Int64 => cast_numeric_to_bool::<Int64Type>(array), + Float16 => cast_numeric_to_bool::<Float16Type>(array), Float32 => cast_numeric_to_bool::<Float32Type>(array), Float64 => cast_numeric_to_bool::<Float64Type>(array), Utf8 => cast_utf8_to_boolean(array, cast_options), @@ -989,6 +990,7 @@ pub fn cast_with_options( Int16 => cast_bool_to_numeric::<Int16Type>(array, cast_options), Int32 => cast_bool_to_numeric::<Int32Type>(array, cast_options), Int64 => cast_bool_to_numeric::<Int64Type>(array, cast_options), + Float16 => cast_bool_to_numeric::<Float16Type>(array, cast_options), Float32 => cast_bool_to_numeric::<Float32Type>(array, cast_options), Float64 => cast_bool_to_numeric::<Float64Type>(array, cast_options), Utf8 => { @@ -3614,7 +3616,6 @@ mod tests { } #[test] - #[cfg(not(feature = "force_validate"))] fn test_cast_decimal_to_decimal_round() { let array = vec![ Some(1123454), @@ -3733,7 +3734,6 @@ mod tests { } #[test] - #[cfg(not(feature = "force_validate"))] fn test_cast_decimal128_to_decimal128() { let input_type = DataType::Decimal128(20, 3); let output_type = DataType::Decimal128(20, 4); @@ -4124,7 +4124,6 @@ mod tests { } #[test] - #[cfg(not(feature = "force_validate"))] fn test_cast_numeric_to_decimal128() { let decimal_type = DataType::Decimal128(38, 6); // u8, u16, u32, u64 @@ -4296,7 +4295,6 @@ mod tests { } #[test] - #[cfg(not(feature = "force_validate"))] fn test_cast_numeric_to_decimal256() { // test negative cast type let decimal_type = DataType::Decimal256(58, 6); @@ -5274,25 +5272,6 @@ mod tests { assert!(c.is_null(2)); } - #[test] - #[cfg(feature = "chrono-tz")] - fn test_cast_timestamp_to_string() { - let a = TimestampMillisecondArray::from(vec![ - Some(864000000005), - Some(1545696000001), - None, - ]) - .with_timezone("UTC".to_string()); - let array = Arc::new(a) as ArrayRef; - dbg!(&array); - let b = cast(&array, &DataType::Utf8).unwrap(); - let c = b.as_any().downcast_ref::<StringArray>().unwrap(); - assert_eq!(&DataType::Utf8, c.data_type()); - assert_eq!("1997-05-19 00:00:00.005 +00:00", c.value(0)); - assert_eq!("2018-12-25 00:00:00.001 +00:00", c.value(1)); - assert!(c.is_null(2)); - } - #[test] fn test_cast_date32_to_string() { let a = Date32Array::from(vec![10000, 17890]); @@ -6799,41 +6778,6 @@ mod tests { assert!(!c.is_valid(5)); // "2000-01-01" } - #[test] - #[cfg_attr(miri, ignore)] // running forever - #[cfg(feature = "chrono-tz")] - fn test_can_cast_types() { - // this function attempts to ensure that can_cast_types stays - // in sync with cast. It simply tries all combinations of - // types and makes sure that if `can_cast_types` returns - // true, so does `cast` - - let all_types = get_all_types(); - - for array in get_arrays_of_all_types() { - for to_type in &all_types { - println!("Test casting {:?} --> {:?}", array.data_type(), to_type); - let cast_result = cast(&array, to_type); - let reported_cast_ability = can_cast_types(array.data_type(), to_type); - - // check for mismatch - match (cast_result, reported_cast_ability) { - (Ok(_), false) => { - panic!("Was able to cast array {:?} from {:?} to {:?} but can_cast_types reported false", - array, array.data_type(), to_type) - } - (Err(e), true) => { - panic!("Was not able to cast array {:?} from {:?} to {:?} but can_cast_types reported true. \ - Error was {:?}", - array, array.data_type(), to_type, e) - } - // otherwise it was a match - _ => {} - }; - } - } - } - #[test] fn test_cast_list_containers() { // large-list to list @@ -6868,99 +6812,6 @@ mod tests { assert_eq!(&expected.value(2), &actual.value(2)); } - /// Create instances of arrays with varying types for cast tests - #[cfg(feature = "chrono-tz")] - fn get_arrays_of_all_types() -> Vec<ArrayRef> { - let tz_name = String::from("America/New_York"); - let binary_data: Vec<&[u8]> = vec![b"foo", b"bar"]; - vec![ - Arc::new(BinaryArray::from(binary_data.clone())), - Arc::new(LargeBinaryArray::from(binary_data.clone())), - make_dictionary_primitive::<Int8Type>(), - make_dictionary_primitive::<Int16Type>(), - make_dictionary_primitive::<Int32Type>(), - make_dictionary_primitive::<Int64Type>(), - make_dictionary_primitive::<UInt8Type>(), - make_dictionary_primitive::<UInt16Type>(), - make_dictionary_primitive::<UInt32Type>(), - make_dictionary_primitive::<UInt64Type>(), - make_dictionary_utf8::<Int8Type>(), - make_dictionary_utf8::<Int16Type>(), - make_dictionary_utf8::<Int32Type>(), - make_dictionary_utf8::<Int64Type>(), - make_dictionary_utf8::<UInt8Type>(), - make_dictionary_utf8::<UInt16Type>(), - make_dictionary_utf8::<UInt32Type>(), - make_dictionary_utf8::<UInt64Type>(), - Arc::new(make_list_array()), - Arc::new(make_large_list_array()), - Arc::new(make_fixed_size_list_array()), - Arc::new(make_fixed_size_binary_array()), - Arc::new(StructArray::from(vec![ - ( - Field::new("a", DataType::Boolean, false), - Arc::new(BooleanArray::from(vec![false, false, true, true])) - as Arc<dyn Array>, - ), - ( - Field::new("b", DataType::Int32, false), - Arc::new(Int32Array::from(vec![42, 28, 19, 31])), - ), - ])), - Arc::new(make_union_array()), - Arc::new(NullArray::new(10)), - Arc::new(StringArray::from(vec!["foo", "bar"])), - Arc::new(LargeStringArray::from(vec!["foo", "bar"])), - Arc::new(BooleanArray::from(vec![true, false])), - Arc::new(Int8Array::from(vec![1, 2])), - Arc::new(Int16Array::from(vec![1, 2])), - Arc::new(Int32Array::from(vec![1, 2])), - Arc::new(Int64Array::from(vec![1, 2])), - Arc::new(UInt8Array::from(vec![1, 2])), - Arc::new(UInt16Array::from(vec![1, 2])), - Arc::new(UInt32Array::from(vec![1, 2])), - Arc::new(UInt64Array::from(vec![1, 2])), - Arc::new(Float32Array::from(vec![1.0, 2.0])), - Arc::new(Float64Array::from(vec![1.0, 2.0])), - Arc::new(TimestampSecondArray::from(vec![1000, 2000])), - Arc::new(TimestampMillisecondArray::from(vec![1000, 2000])), - Arc::new(TimestampMicrosecondArray::from(vec![1000, 2000])), - Arc::new(TimestampNanosecondArray::from(vec![1000, 2000])), - Arc::new( - TimestampSecondArray::from(vec![1000, 2000]) - .with_timezone(tz_name.clone()), - ), - Arc::new( - TimestampMillisecondArray::from(vec![1000, 2000]) - .with_timezone(tz_name.clone()), - ), - Arc::new( - TimestampMicrosecondArray::from(vec![1000, 2000]) - .with_timezone(tz_name.clone()), - ), - Arc::new( - TimestampNanosecondArray::from(vec![1000, 2000]).with_timezone(tz_name), - ), - Arc::new(Date32Array::from(vec![1000, 2000])), - Arc::new(Date64Array::from(vec![1000, 2000])), - Arc::new(Time32SecondArray::from(vec![1000, 2000])), - Arc::new(Time32MillisecondArray::from(vec![1000, 2000])), - Arc::new(Time64MicrosecondArray::from(vec![1000, 2000])), - Arc::new(Time64NanosecondArray::from(vec![1000, 2000])), - Arc::new(IntervalYearMonthArray::from(vec![1000, 2000])), - Arc::new(IntervalDayTimeArray::from(vec![1000, 2000])), - Arc::new(IntervalMonthDayNanoArray::from(vec![1000, 2000])), - Arc::new(DurationSecondArray::from(vec![1000, 2000])), - Arc::new(DurationMillisecondArray::from(vec![1000, 2000])), - Arc::new(DurationMicrosecondArray::from(vec![1000, 2000])), - Arc::new(DurationNanosecondArray::from(vec![1000, 2000])), - Arc::new( - create_decimal_array(vec![Some(1), Some(2), Some(3), None], 38, 0) - .unwrap(), - ), - ] - } - fn make_list_array() -> ListArray { // Construct a value array let value_data = ArrayData::builder(DataType::Int32) @@ -7009,140 +6860,6 @@ mod tests { LargeListArray::from(list_data) } - #[cfg(feature = "chrono-tz")] - fn make_fixed_size_list_array() -> FixedSizeListArray { - // Construct a value array - let value_data = ArrayData::builder(DataType::Int32) - .len(10) - .add_buffer(Buffer::from_slice_ref(&[0, 1, 2, 3, 4, 5, 6, 7, 8, 9])) - .build() - .unwrap(); - - // Construct a fixed size list array from the above two - let list_data_type = DataType::FixedSizeList( - Box::new(Field::new("item", DataType::Int32, true)), - 2, - ); - let list_data = ArrayData::builder(list_data_type) - .len(5) - .add_child_data(value_data) - .build() - .unwrap(); - FixedSizeListArray::from(list_data) - } - - #[cfg(feature = "chrono-tz")] - fn make_fixed_size_binary_array() -> FixedSizeBinaryArray { - let values: [u8; 15] = *b"hellotherearrow"; - - let array_data = ArrayData::builder(DataType::FixedSizeBinary(5)) - .len(3) - .add_buffer(Buffer::from(&values[..])) - .build() - .unwrap(); - FixedSizeBinaryArray::from(array_data) - } - - #[cfg(feature = "chrono-tz")] - fn make_union_array() -> UnionArray { - let mut builder = UnionBuilder::with_capacity_dense(7); - builder.append::<Int32Type>("a", 1).unwrap(); - builder.append::<Int64Type>("b", 2).unwrap(); - builder.build().unwrap() - } - - /// Creates a dictionary with primitive dictionary values, and keys of type K - #[cfg(feature = "chrono-tz")] - fn make_dictionary_primitive<K: ArrowDictionaryKeyType>() -> ArrayRef { - // Pick Int32 arbitrarily for dictionary values - let mut b: PrimitiveDictionaryBuilder<K, Int32Type> = - PrimitiveDictionaryBuilder::new(); - b.append(1).unwrap(); - b.append(2).unwrap(); - Arc::new(b.finish()) - } - - /// Creates a dictionary with utf8 values, and keys of type K - #[cfg(feature = "chrono-tz")] - fn make_dictionary_utf8<K: ArrowDictionaryKeyType>() -> ArrayRef { - // Pick Int32 arbitrarily for dictionary values - let mut b: StringDictionaryBuilder<K> = StringDictionaryBuilder::new(); - b.append("foo").unwrap(); - b.append("bar").unwrap(); - Arc::new(b.finish()) - } - - // Get a selection of datatypes to try and cast to - #[cfg(feature = "chrono-tz")] - fn get_all_types() -> Vec<DataType> { - use DataType::*; - let tz_name = String::from("America/New_York"); - - vec![ - Null, - Boolean, - Int8, - Int16, - Int32, - UInt64, - UInt8, - UInt16, - UInt32, - UInt64, - Float16, - Float32, - Float64, - Timestamp(TimeUnit::Second, None), - Timestamp(TimeUnit::Millisecond, None), - Timestamp(TimeUnit::Microsecond, None), - Timestamp(TimeUnit::Nanosecond, None), - Timestamp(TimeUnit::Second, Some(tz_name.clone())), - Timestamp(TimeUnit::Millisecond, Some(tz_name.clone())), - Timestamp(TimeUnit::Microsecond, Some(tz_name.clone())), - Timestamp(TimeUnit::Nanosecond, Some(tz_name)), - Date32, - Date64, - Time32(TimeUnit::Second), - Time32(TimeUnit::Millisecond), - Time64(TimeUnit::Microsecond), - Time64(TimeUnit::Nanosecond), - Duration(TimeUnit::Second), - Duration(TimeUnit::Millisecond), - Duration(TimeUnit::Microsecond), - Duration(TimeUnit::Nanosecond), - Interval(IntervalUnit::YearMonth), - Interval(IntervalUnit::DayTime), - Interval(IntervalUnit::MonthDayNano), - Binary, - FixedSizeBinary(10), - LargeBinary, - Utf8, - LargeUtf8, - List(Box::new(Field::new("item", DataType::Int8, true))), - List(Box::new(Field::new("item", DataType::Utf8, true))), - FixedSizeList(Box::new(Field::new("item", DataType::Int8, true)), 10), - FixedSizeList(Box::new(Field::new("item", DataType::Utf8, false)), 10), - LargeList(Box::new(Field::new("item", DataType::Int8, true))), - LargeList(Box::new(Field::new("item", DataType::Utf8, false))), - Struct(vec![ - Field::new("f1", DataType::Int32, false), - Field::new("f2", DataType::Utf8, true), - ]), - Union( - vec![ - Field::new("f1", DataType::Int32, false), - Field::new("f2", DataType::Utf8, true), - ], - vec![0, 1], - UnionMode::Dense, - ), - Dictionary(Box::new(DataType::Int8), Box::new(DataType::Int32)), - Dictionary(Box::new(DataType::Int16), Box::new(DataType::Utf8)), - Dictionary(Box::new(DataType::UInt32), Box::new(DataType::Utf8)), - Decimal128(38, 0), - ] - } - #[test] fn test_utf8_cast_offsets() { // test if offset of the array is taken into account during cast @@ -7169,41 +6886,6 @@ mod tests { assert_eq!(&out1, &out2.slice(1, 2)) } - #[test] - #[cfg(feature = "chrono-tz")] - fn test_timestamp_cast_utf8() { - let array: PrimitiveArray<TimestampMicrosecondType> = - vec![Some(37800000000), None, Some(86339000000)].into(); - let out = cast(&(Arc::new(array) as ArrayRef), &DataType::Utf8).unwrap(); - - let expected = StringArray::from(vec![ - Some("1970-01-01 10:30:00"), - None, - Some("1970-01-01 23:58:59"), - ]); - - assert_eq!( - out.as_any().downcast_ref::<StringArray>().unwrap(), - &expected - ); - - let array: PrimitiveArray<TimestampMicrosecondType> = - vec![Some(37800000000), None, Some(86339000000)].into(); - let array = array.with_timezone("Australia/Sydney".to_string()); - let out = cast(&(Arc::new(array) as ArrayRef), &DataType::Utf8).unwrap(); - - let expected = StringArray::from(vec![ - Some("1970-01-01 20:30:00 +10:00"), - None, - Some("1970-01-02 09:58:59 +10:00"), - ]); - - assert_eq!( - out.as_any().downcast_ref::<StringArray>().unwrap(), - &expected - ); - } - #[test] fn test_list_to_string() { let str_array = StringArray::from(vec!["a", "b", "c", "d", "e", "f", "g", "h"]); @@ -7268,7 +6950,6 @@ mod tests { } #[test] - #[cfg(not(feature = "force_validate"))] fn test_cast_f64_to_decimal128() { // to reproduce https://github.com/apache/arrow-rs/issues/2997 diff --git a/arrow/Cargo.toml b/arrow/Cargo.toml index a97ec1ac123f..876d0d65084e 100644 --- a/arrow/Cargo.toml +++ b/arrow/Cargo.toml @@ -273,3 +273,7 @@ required-features = ["csv", "chrono-tz"] [[test]] name = "pyarrow" required-features = ["pyarrow"] + +[[test]] +name = "array_cast" +required-features = ["chrono-tz"]
diff --git a/arrow/tests/array_cast.rs b/arrow/tests/array_cast.rs new file mode 100644 index 000000000000..95fb973289a5 --- /dev/null +++ b/arrow/tests/array_cast.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. + +use arrow_array::builder::{ + PrimitiveDictionaryBuilder, StringDictionaryBuilder, UnionBuilder, +}; +use arrow_array::types::{ + ArrowDictionaryKeyType, Int16Type, Int32Type, Int64Type, Int8Type, + TimestampMicrosecondType, UInt16Type, UInt32Type, UInt64Type, UInt8Type, +}; +use arrow_array::{ + Array, ArrayRef, BinaryArray, BooleanArray, Date32Array, Date64Array, + Decimal128Array, DurationMicrosecondArray, DurationMillisecondArray, + DurationNanosecondArray, DurationSecondArray, FixedSizeBinaryArray, + FixedSizeListArray, Float16Array, Float32Array, Float64Array, Int16Array, Int32Array, + Int64Array, Int8Array, IntervalDayTimeArray, IntervalMonthDayNanoArray, + IntervalYearMonthArray, LargeBinaryArray, LargeListArray, LargeStringArray, + ListArray, NullArray, PrimitiveArray, StringArray, StructArray, + Time32MillisecondArray, Time32SecondArray, Time64MicrosecondArray, + Time64NanosecondArray, TimestampMicrosecondArray, TimestampMillisecondArray, + TimestampNanosecondArray, TimestampSecondArray, UInt16Array, UInt32Array, + UInt64Array, UInt8Array, UnionArray, +}; +use arrow_buffer::Buffer; +use arrow_cast::{can_cast_types, cast}; +use arrow_data::ArrayData; +use arrow_schema::{ArrowError, DataType, Field, IntervalUnit, TimeUnit, UnionMode}; +use half::f16; +use std::sync::Arc; + +#[test] +fn test_cast_timestamp_to_string() { + let a = TimestampMillisecondArray::from(vec![ + Some(864000000005), + Some(1545696000001), + None, + ]) + .with_timezone("UTC".to_string()); + let array = Arc::new(a) as ArrayRef; + dbg!(&array); + let b = cast(&array, &DataType::Utf8).unwrap(); + let c = b.as_any().downcast_ref::<StringArray>().unwrap(); + assert_eq!(&DataType::Utf8, c.data_type()); + assert_eq!("1997-05-19 00:00:00.005 +00:00", c.value(0)); + assert_eq!("2018-12-25 00:00:00.001 +00:00", c.value(1)); + assert!(c.is_null(2)); +} + +#[test] +#[cfg_attr(miri, ignore)] // running forever +fn test_can_cast_types() { + // this function attempts to ensure that can_cast_types stays + // in sync with cast. It simply tries all combinations of + // types and makes sure that if `can_cast_types` returns + // true, so does `cast` + + let all_types = get_all_types(); + + for array in get_arrays_of_all_types() { + for to_type in &all_types { + println!("Test casting {:?} --> {:?}", array.data_type(), to_type); + let cast_result = cast(&array, to_type); + let reported_cast_ability = can_cast_types(array.data_type(), to_type); + + // check for mismatch + match (cast_result, reported_cast_ability) { + (Ok(_), false) => { + panic!("Was able to cast array {:?} from {:?} to {:?} but can_cast_types reported false", + array, array.data_type(), to_type) + } + (Err(e), true) => { + panic!("Was not able to cast array {:?} from {:?} to {:?} but can_cast_types reported true. \ + Error was {:?}", + array, array.data_type(), to_type, e) + } + // otherwise it was a match + _ => {} + }; + } + } +} + +/// Create instances of arrays with varying types for cast tests +fn get_arrays_of_all_types() -> Vec<ArrayRef> { + let tz_name = String::from("America/New_York"); + let binary_data: Vec<&[u8]> = vec![b"foo", b"bar"]; + vec![ + Arc::new(BinaryArray::from(binary_data.clone())), + Arc::new(LargeBinaryArray::from(binary_data.clone())), + make_dictionary_primitive::<Int8Type>(), + make_dictionary_primitive::<Int16Type>(), + make_dictionary_primitive::<Int32Type>(), + make_dictionary_primitive::<Int64Type>(), + make_dictionary_primitive::<UInt8Type>(), + make_dictionary_primitive::<UInt16Type>(), + make_dictionary_primitive::<UInt32Type>(), + make_dictionary_primitive::<UInt64Type>(), + make_dictionary_utf8::<Int8Type>(), + make_dictionary_utf8::<Int16Type>(), + make_dictionary_utf8::<Int32Type>(), + make_dictionary_utf8::<Int64Type>(), + make_dictionary_utf8::<UInt8Type>(), + make_dictionary_utf8::<UInt16Type>(), + make_dictionary_utf8::<UInt32Type>(), + make_dictionary_utf8::<UInt64Type>(), + Arc::new(make_list_array()), + Arc::new(make_large_list_array()), + Arc::new(make_fixed_size_list_array()), + Arc::new(make_fixed_size_binary_array()), + Arc::new(StructArray::from(vec![ + ( + Field::new("a", DataType::Boolean, false), + Arc::new(BooleanArray::from(vec![false, false, true, true])) + as Arc<dyn Array>, + ), + ( + Field::new("b", DataType::Int32, false), + Arc::new(Int32Array::from(vec![42, 28, 19, 31])), + ), + ])), + Arc::new(make_union_array()), + Arc::new(NullArray::new(10)), + Arc::new(StringArray::from(vec!["foo", "bar"])), + Arc::new(LargeStringArray::from(vec!["foo", "bar"])), + Arc::new(BooleanArray::from(vec![true, false])), + Arc::new(Int8Array::from(vec![1, 2])), + Arc::new(Int16Array::from(vec![1, 2])), + Arc::new(Int32Array::from(vec![1, 2])), + Arc::new(Int64Array::from(vec![1, 2])), + Arc::new(UInt8Array::from(vec![1, 2])), + Arc::new(UInt16Array::from(vec![1, 2])), + Arc::new(UInt32Array::from(vec![1, 2])), + Arc::new(UInt64Array::from(vec![1, 2])), + Arc::new( + [Some(f16::from_f64(1.0)), Some(f16::from_f64(2.0))] + .into_iter() + .collect::<Float16Array>(), + ), + Arc::new(Float32Array::from(vec![1.0, 2.0])), + Arc::new(Float64Array::from(vec![1.0, 2.0])), + Arc::new(TimestampSecondArray::from(vec![1000, 2000])), + Arc::new(TimestampMillisecondArray::from(vec![1000, 2000])), + Arc::new(TimestampMicrosecondArray::from(vec![1000, 2000])), + Arc::new(TimestampNanosecondArray::from(vec![1000, 2000])), + Arc::new( + TimestampSecondArray::from(vec![1000, 2000]).with_timezone(tz_name.clone()), + ), + Arc::new( + TimestampMillisecondArray::from(vec![1000, 2000]) + .with_timezone(tz_name.clone()), + ), + Arc::new( + TimestampMicrosecondArray::from(vec![1000, 2000]) + .with_timezone(tz_name.clone()), + ), + Arc::new(TimestampNanosecondArray::from(vec![1000, 2000]).with_timezone(tz_name)), + Arc::new(Date32Array::from(vec![1000, 2000])), + Arc::new(Date64Array::from(vec![1000, 2000])), + Arc::new(Time32SecondArray::from(vec![1000, 2000])), + Arc::new(Time32MillisecondArray::from(vec![1000, 2000])), + Arc::new(Time64MicrosecondArray::from(vec![1000, 2000])), + Arc::new(Time64NanosecondArray::from(vec![1000, 2000])), + Arc::new(IntervalYearMonthArray::from(vec![1000, 2000])), + Arc::new(IntervalDayTimeArray::from(vec![1000, 2000])), + Arc::new(IntervalMonthDayNanoArray::from(vec![1000, 2000])), + Arc::new(DurationSecondArray::from(vec![1000, 2000])), + Arc::new(DurationMillisecondArray::from(vec![1000, 2000])), + Arc::new(DurationMicrosecondArray::from(vec![1000, 2000])), + Arc::new(DurationNanosecondArray::from(vec![1000, 2000])), + Arc::new( + create_decimal_array(vec![Some(1), Some(2), Some(3), None], 38, 0).unwrap(), + ), + ] +} + +fn make_fixed_size_list_array() -> FixedSizeListArray { + // Construct a value array + let value_data = ArrayData::builder(DataType::Int32) + .len(10) + .add_buffer(Buffer::from_slice_ref([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])) + .build() + .unwrap(); + + // Construct a fixed size list array from the above two + let list_data_type = + DataType::FixedSizeList(Box::new(Field::new("item", DataType::Int32, true)), 2); + let list_data = ArrayData::builder(list_data_type) + .len(5) + .add_child_data(value_data) + .build() + .unwrap(); + FixedSizeListArray::from(list_data) +} + +fn make_fixed_size_binary_array() -> FixedSizeBinaryArray { + let values: [u8; 15] = *b"hellotherearrow"; + + let array_data = ArrayData::builder(DataType::FixedSizeBinary(5)) + .len(3) + .add_buffer(Buffer::from(&values[..])) + .build() + .unwrap(); + FixedSizeBinaryArray::from(array_data) +} + +fn make_list_array() -> ListArray { + // Construct a value array + let value_data = ArrayData::builder(DataType::Int32) + .len(8) + .add_buffer(Buffer::from_slice_ref([0, 1, 2, 3, 4, 5, 6, 7])) + .build() + .unwrap(); + + // Construct a buffer for value offsets, for the nested array: + // [[0, 1, 2], [3, 4, 5], [6, 7]] + let value_offsets = Buffer::from_slice_ref([0, 3, 6, 8]); + + // Construct a list array from the above two + let list_data_type = + DataType::List(Box::new(Field::new("item", DataType::Int32, true))); + let list_data = ArrayData::builder(list_data_type) + .len(3) + .add_buffer(value_offsets) + .add_child_data(value_data) + .build() + .unwrap(); + ListArray::from(list_data) +} + +fn make_large_list_array() -> LargeListArray { + // Construct a value array + let value_data = ArrayData::builder(DataType::Int32) + .len(8) + .add_buffer(Buffer::from_slice_ref([0, 1, 2, 3, 4, 5, 6, 7])) + .build() + .unwrap(); + + // Construct a buffer for value offsets, for the nested array: + // [[0, 1, 2], [3, 4, 5], [6, 7]] + let value_offsets = Buffer::from_slice_ref([0i64, 3, 6, 8]); + + // Construct a list array from the above two + let list_data_type = + DataType::LargeList(Box::new(Field::new("item", DataType::Int32, true))); + let list_data = ArrayData::builder(list_data_type) + .len(3) + .add_buffer(value_offsets) + .add_child_data(value_data) + .build() + .unwrap(); + LargeListArray::from(list_data) +} + +fn make_union_array() -> UnionArray { + let mut builder = UnionBuilder::with_capacity_dense(7); + builder.append::<Int32Type>("a", 1).unwrap(); + builder.append::<Int64Type>("b", 2).unwrap(); + builder.build().unwrap() +} + +/// Creates a dictionary with primitive dictionary values, and keys of type K +fn make_dictionary_primitive<K: ArrowDictionaryKeyType>() -> ArrayRef { + // Pick Int32 arbitrarily for dictionary values + let mut b: PrimitiveDictionaryBuilder<K, Int32Type> = + PrimitiveDictionaryBuilder::new(); + b.append(1).unwrap(); + b.append(2).unwrap(); + Arc::new(b.finish()) +} + +/// Creates a dictionary with utf8 values, and keys of type K +fn make_dictionary_utf8<K: ArrowDictionaryKeyType>() -> ArrayRef { + // Pick Int32 arbitrarily for dictionary values + let mut b: StringDictionaryBuilder<K> = StringDictionaryBuilder::new(); + b.append("foo").unwrap(); + b.append("bar").unwrap(); + Arc::new(b.finish()) +} + +fn create_decimal_array( + array: Vec<Option<i128>>, + precision: u8, + scale: i8, +) -> Result<Decimal128Array, ArrowError> { + array + .into_iter() + .collect::<Decimal128Array>() + .with_precision_and_scale(precision, scale) +} + +// Get a selection of datatypes to try and cast to +fn get_all_types() -> Vec<DataType> { + use DataType::*; + let tz_name = String::from("America/New_York"); + + vec![ + Null, + Boolean, + Int8, + Int16, + Int32, + UInt64, + UInt8, + UInt16, + UInt32, + UInt64, + Float16, + Float32, + Float64, + Timestamp(TimeUnit::Second, None), + Timestamp(TimeUnit::Millisecond, None), + Timestamp(TimeUnit::Microsecond, None), + Timestamp(TimeUnit::Nanosecond, None), + Timestamp(TimeUnit::Second, Some(tz_name.clone())), + Timestamp(TimeUnit::Millisecond, Some(tz_name.clone())), + Timestamp(TimeUnit::Microsecond, Some(tz_name.clone())), + Timestamp(TimeUnit::Nanosecond, Some(tz_name)), + Date32, + Date64, + Time32(TimeUnit::Second), + Time32(TimeUnit::Millisecond), + Time64(TimeUnit::Microsecond), + Time64(TimeUnit::Nanosecond), + Duration(TimeUnit::Second), + Duration(TimeUnit::Millisecond), + Duration(TimeUnit::Microsecond), + Duration(TimeUnit::Nanosecond), + Interval(IntervalUnit::YearMonth), + Interval(IntervalUnit::DayTime), + Interval(IntervalUnit::MonthDayNano), + Binary, + FixedSizeBinary(10), + LargeBinary, + Utf8, + LargeUtf8, + List(Box::new(Field::new("item", DataType::Int8, true))), + List(Box::new(Field::new("item", DataType::Utf8, true))), + FixedSizeList(Box::new(Field::new("item", DataType::Int8, true)), 10), + FixedSizeList(Box::new(Field::new("item", DataType::Utf8, false)), 10), + LargeList(Box::new(Field::new("item", DataType::Int8, true))), + LargeList(Box::new(Field::new("item", DataType::Utf8, false))), + Struct(vec![ + Field::new("f1", DataType::Int32, true), + Field::new("f2", DataType::Utf8, true), + ]), + Union( + vec![ + Field::new("f1", DataType::Int32, false), + Field::new("f2", DataType::Utf8, true), + ], + vec![0, 1], + UnionMode::Dense, + ), + Dictionary(Box::new(DataType::Int8), Box::new(DataType::Int32)), + Dictionary(Box::new(DataType::Int16), Box::new(DataType::Utf8)), + Dictionary(Box::new(DataType::UInt32), Box::new(DataType::Utf8)), + Decimal128(38, 0), + ] +} + +#[test] +fn test_timestamp_cast_utf8() { + let array: PrimitiveArray<TimestampMicrosecondType> = + vec![Some(37800000000), None, Some(86339000000)].into(); + let out = cast(&(Arc::new(array) as ArrayRef), &DataType::Utf8).unwrap(); + + let expected = StringArray::from(vec![ + Some("1970-01-01 10:30:00"), + None, + Some("1970-01-01 23:58:59"), + ]); + + assert_eq!( + out.as_any().downcast_ref::<StringArray>().unwrap(), + &expected + ); + + let array: PrimitiveArray<TimestampMicrosecondType> = + vec![Some(37800000000), None, Some(86339000000)].into(); + let array = array.with_timezone("Australia/Sydney".to_string()); + let out = cast(&(Arc::new(array) as ArrayRef), &DataType::Utf8).unwrap(); + + let expected = StringArray::from(vec![ + Some("1970-01-01 20:30:00 +10:00"), + None, + Some("1970-01-02 09:58:59 +10:00"), + ]); + + assert_eq!( + out.as_any().downcast_ref::<StringArray>().unwrap(), + &expected + ); +}
bool should cast from/to Float16Type as `can_cast_types` returns true **Describe the bug** <!-- A clear and concise description of what the bug is. --> `can_cast_types` returns true for casting between bool and Float16, but actually cast kernel doesn't cast them. **To Reproduce** <!-- Steps to reproduce the behavior: --> **Expected behavior** <!-- A clear and concise description of what you expected to happen. --> **Additional context** <!-- Add any other context about the problem here. -->
2022-11-29T08:03:42Z
28.0
26438feb7a59aa156563ed8c6e8b0e6579b2e028
[ "test_can_cast_types" ]
[ "arrow/src/compute/kernels/aggregate.rs - compute::kernels::aggregate::max_boolean (line 90)", "arrow/src/compute/kernels/aggregate.rs - compute::kernels::aggregate::min_boolean (line 65)", "arrow/src/compute/kernels/boolean.rs - compute::kernels::boolean::is_not_null (line 435)", "arrow/src/array/ord.rs - array::ord::build_compare (line 162)", "arrow/src/compute/kernels/boolean.rs - compute::kernels::boolean::is_null (line 394)", "arrow/src/compute/kernels/boolean.rs - compute::kernels::boolean::and (line 230)", "arrow/src/compute/kernels/boolean.rs - compute::kernels::boolean::and_kleene (line 264)", "arrow/src/compute/kernels/boolean.rs - compute::kernels::boolean::not (line 353)", "arrow/src/compute/kernels/boolean.rs - compute::kernels::boolean::or_kleene (line 328)", "arrow/src/compute/kernels/boolean.rs - compute::kernels::boolean::or (line 294)", "arrow/src/compute/kernels/comparison.rs - compute::kernels::comparison::gt_dyn (line 3380)", "arrow/src/compute/kernels/comparison.rs - compute::kernels::comparison::like_utf8 (line 205)", "arrow/src/compute/kernels/comparison.rs - compute::kernels::comparison::lt_dyn (line 3291)", "arrow/src/compute/kernels/comparison.rs - compute::kernels::comparison::gt_eq_dyn (line 3424)", "arrow/src/compute/kernels/comparison.rs - compute::kernels::comparison::eq_dyn (line 3203)", "arrow/src/compute/kernels/comparison.rs - compute::kernels::comparison::lt_eq_dyn (line 3336)", "arrow/src/lib.rs - (line 116)", "arrow/src/lib.rs - (line 137)", "arrow/src/compute/kernels/comparison.rs - compute::kernels::comparison::neq_dyn (line 3246)", "arrow/src/compute/kernels/sort.rs - compute::kernels::sort::lexsort (line 859)", "arrow/src/compute/kernels/substring.rs - compute::kernels::substring::substring (line 47)", "arrow/src/compute/kernels/sort.rs - compute::kernels::sort::sort (line 42)", "arrow/src/compute/kernels/sort.rs - compute::kernels::sort::sort_limit (line 70)", "arrow/src/compute/kernels/substring.rs - compute::kernels::substring::substring_by_char (line 173)", "arrow/src/compute/kernels/substring.rs - compute::kernels::substring::substring (line 63)", "arrow/src/row/mod.rs - row (line 104)", "arrow/src/lib.rs - (line 229)", "arrow/src/lib.rs - (line 174)", "arrow/src/lib.rs - (line 58)", "arrow/src/lib.rs - (line 92)", "arrow/src/lib.rs - (line 203)", "arrow/src/lib.rs - (line 73)", "arrow/src/row/mod.rs - row (line 51)", "arrow/src/util/string_writer.rs - util::string_writer (line 25)", "test_timestamp_cast_utf8", "test_cast_timestamp_to_string" ]
[]
[]
apache/arrow-rs
3,238
apache__arrow-rs-3238
[ "3250" ]
26438feb7a59aa156563ed8c6e8b0e6579b2e028
diff --git a/arrow-cast/src/cast.rs b/arrow-cast/src/cast.rs index be767f137cd8..0e420674b2ab 100644 --- a/arrow-cast/src/cast.rs +++ b/arrow-cast/src/cast.rs @@ -71,24 +71,7 @@ pub fn can_cast_types(from_type: &DataType, to_type: &DataType) -> bool { } match (from_type, to_type) { - // TODO UTF8 to decimal - // cast one decimal type to another decimal type - (Decimal128(_, _), Decimal128(_, _)) => true, - (Decimal256(_, _), Decimal256(_, _)) => true, - (Decimal128(_, _), Decimal256(_, _)) => true, - (Decimal256(_, _), Decimal128(_, _)) => true, - // unsigned integer to decimal - (UInt8 | UInt16 | UInt32 | UInt64, Decimal128(_, _)) | - // signed numeric to decimal - (Null | Int8 | Int16 | Int32 | Int64 | Float32 | Float64, Decimal128(_, _)) | - (Null | Int8 | Int16 | Int32 | Int64 | Float32 | Float64, Decimal256(_, _)) | - // decimal to unsigned numeric - (Decimal128(_, _), UInt8 | UInt16 | UInt32 | UInt64) | - (Decimal256(_, _), UInt8 | UInt16 | UInt32 | UInt64) | - // decimal to signed numeric - (Decimal128(_, _), Null | Int8 | Int16 | Int32 | Int64 | Float32 | Float64) | - (Decimal256(_, _), Null | Int8 | Int16 | Int32 | Int64) - | ( + ( Null, Boolean | Int8 @@ -120,10 +103,12 @@ pub fn can_cast_types(from_type: &DataType, to_type: &DataType) -> bool { | Map(_, _) | Dictionary(_, _) ) => true, - (Decimal128(_, _), _) => false, - (_, Decimal128(_, _)) => false, - (Struct(_), _) => false, - (_, Struct(_)) => false, + // Dictionary/List conditions should be put in front of others + (Dictionary(_, from_value_type), Dictionary(_, to_value_type)) => { + can_cast_types(from_value_type, to_value_type) + } + (Dictionary(_, value_type), _) => can_cast_types(value_type, to_type), + (_, Dictionary(_, value_type)) => can_cast_types(from_type, value_type), (LargeList(list_from), LargeList(list_to)) => { can_cast_types(list_from.data_type(), list_to.data_type()) } @@ -140,12 +125,29 @@ pub fn can_cast_types(from_type: &DataType, to_type: &DataType) -> bool { (List(_), _) => false, (_, List(list_to)) => can_cast_types(from_type, list_to.data_type()), (_, LargeList(list_to)) => can_cast_types(from_type, list_to.data_type()), - (Dictionary(_, from_value_type), Dictionary(_, to_value_type)) => { - can_cast_types(from_value_type, to_value_type) - } - (Dictionary(_, value_type), _) => can_cast_types(value_type, to_type), - (_, Dictionary(_, value_type)) => can_cast_types(from_type, value_type), - + // TODO UTF8 to decimal + // cast one decimal type to another decimal type + (Decimal128(_, _), Decimal128(_, _)) => true, + (Decimal256(_, _), Decimal256(_, _)) => true, + (Decimal128(_, _), Decimal256(_, _)) => true, + (Decimal256(_, _), Decimal128(_, _)) => true, + // unsigned integer to decimal + (UInt8 | UInt16 | UInt32 | UInt64, Decimal128(_, _)) | + // signed numeric to decimal + (Null | Int8 | Int16 | Int32 | Int64 | Float32 | Float64, Decimal128(_, _)) | + (Null | Int8 | Int16 | Int32 | Int64 | Float32 | Float64, Decimal256(_, _)) | + // decimal to unsigned numeric + (Decimal128(_, _), UInt8 | UInt16 | UInt32 | UInt64) | + (Decimal256(_, _), UInt8 | UInt16 | UInt32 | UInt64) | + // decimal to signed numeric + (Decimal128(_, _), Null | Int8 | Int16 | Int32 | Int64 | Float32 | Float64) | + (Decimal256(_, _), Null | Int8 | Int16 | Int32 | Int64) => true, + (Decimal128(_, _), _) => false, + (_, Decimal128(_, _)) => false, + (Decimal256(_, _), _) => false, + (_, Decimal256(_, _)) => false, + (Struct(_), _) => false, + (_, Struct(_)) => false, (_, Boolean) => DataType::is_numeric(from_type) || from_type == &Utf8, (Boolean, _) => DataType::is_numeric(to_type) || to_type == &Utf8, @@ -624,6 +626,103 @@ pub fn cast_with_options( return Ok(array.clone()); } match (from_type, to_type) { + ( + Null, + Boolean + | Int8 + | UInt8 + | Int16 + | UInt16 + | Int32 + | UInt32 + | Float32 + | Date32 + | Time32(_) + | Int64 + | UInt64 + | Float64 + | Date64 + | Timestamp(_, _) + | Time64(_) + | Duration(_) + | Interval(_) + | FixedSizeBinary(_) + | Binary + | Utf8 + | LargeBinary + | LargeUtf8 + | List(_) + | LargeList(_) + | FixedSizeList(_, _) + | Struct(_) + | Map(_, _) + | Dictionary(_, _), + ) => Ok(new_null_array(to_type, array.len())), + (Dictionary(index_type, _), _) => match **index_type { + Int8 => dictionary_cast::<Int8Type>(array, to_type, cast_options), + Int16 => dictionary_cast::<Int16Type>(array, to_type, cast_options), + Int32 => dictionary_cast::<Int32Type>(array, to_type, cast_options), + Int64 => dictionary_cast::<Int64Type>(array, to_type, cast_options), + UInt8 => dictionary_cast::<UInt8Type>(array, to_type, cast_options), + UInt16 => dictionary_cast::<UInt16Type>(array, to_type, cast_options), + UInt32 => dictionary_cast::<UInt32Type>(array, to_type, cast_options), + UInt64 => dictionary_cast::<UInt64Type>(array, to_type, cast_options), + _ => Err(ArrowError::CastError(format!( + "Casting from dictionary type {:?} to {:?} not supported", + from_type, to_type, + ))), + }, + (_, Dictionary(index_type, value_type)) => match **index_type { + Int8 => cast_to_dictionary::<Int8Type>(array, value_type, cast_options), + Int16 => cast_to_dictionary::<Int16Type>(array, value_type, cast_options), + Int32 => cast_to_dictionary::<Int32Type>(array, value_type, cast_options), + Int64 => cast_to_dictionary::<Int64Type>(array, value_type, cast_options), + UInt8 => cast_to_dictionary::<UInt8Type>(array, value_type, cast_options), + UInt16 => cast_to_dictionary::<UInt16Type>(array, value_type, cast_options), + UInt32 => cast_to_dictionary::<UInt32Type>(array, value_type, cast_options), + UInt64 => cast_to_dictionary::<UInt64Type>(array, value_type, cast_options), + _ => Err(ArrowError::CastError(format!( + "Casting from type {:?} to dictionary type {:?} not supported", + from_type, to_type, + ))), + }, + (List(_), List(ref to)) => { + cast_list_inner::<i32>(array, to, to_type, cast_options) + } + (LargeList(_), LargeList(ref to)) => { + cast_list_inner::<i64>(array, to, to_type, cast_options) + } + (List(list_from), LargeList(list_to)) => { + if list_to.data_type() != list_from.data_type() { + Err(ArrowError::CastError( + "cannot cast list to large-list with different child data".into(), + )) + } else { + cast_list_container::<i32, i64>(&**array, cast_options) + } + } + (LargeList(list_from), List(list_to)) => { + if list_to.data_type() != list_from.data_type() { + Err(ArrowError::CastError( + "cannot cast large-list to list with different child data".into(), + )) + } else { + cast_list_container::<i64, i32>(&**array, cast_options) + } + } + (List(_) | LargeList(_), _) => match to_type { + Utf8 => cast_list_to_string!(array, i32), + LargeUtf8 => cast_list_to_string!(array, i64), + _ => Err(ArrowError::CastError( + "Cannot cast list to non-list data types".to_string(), + )), + }, + (_, List(ref to)) => { + cast_primitive_to_list::<i32>(array, to, to_type, cast_options) + } + (_, LargeList(ref to)) => { + cast_primitive_to_list::<i64>(array, to, to_type, cast_options) + } (Decimal128(_, s1), Decimal128(p2, s2)) => { cast_decimal_to_decimal_with_option::<16, 16>(array, s1, p2, s2, cast_options) } @@ -887,107 +986,12 @@ pub fn cast_with_options( ))), } } - ( - Null, - Boolean - | Int8 - | UInt8 - | Int16 - | UInt16 - | Int32 - | UInt32 - | Float32 - | Date32 - | Time32(_) - | Int64 - | UInt64 - | Float64 - | Date64 - | Timestamp(_, _) - | Time64(_) - | Duration(_) - | Interval(_) - | FixedSizeBinary(_) - | Binary - | Utf8 - | LargeBinary - | LargeUtf8 - | List(_) - | LargeList(_) - | FixedSizeList(_, _) - | Struct(_) - | Map(_, _) - | Dictionary(_, _), - ) => Ok(new_null_array(to_type, array.len())), (Struct(_), _) => Err(ArrowError::CastError( "Cannot cast from struct to other types".to_string(), )), (_, Struct(_)) => Err(ArrowError::CastError( "Cannot cast to struct from other types".to_string(), )), - (List(_), List(ref to)) => { - cast_list_inner::<i32>(array, to, to_type, cast_options) - } - (LargeList(_), LargeList(ref to)) => { - cast_list_inner::<i64>(array, to, to_type, cast_options) - } - (List(list_from), LargeList(list_to)) => { - if list_to.data_type() != list_from.data_type() { - Err(ArrowError::CastError( - "cannot cast list to large-list with different child data".into(), - )) - } else { - cast_list_container::<i32, i64>(&**array, cast_options) - } - } - (LargeList(list_from), List(list_to)) => { - if list_to.data_type() != list_from.data_type() { - Err(ArrowError::CastError( - "cannot cast large-list to list with different child data".into(), - )) - } else { - cast_list_container::<i64, i32>(&**array, cast_options) - } - } - (List(_) | LargeList(_), Utf8) => cast_list_to_string!(array, i32), - (List(_) | LargeList(_), LargeUtf8) => cast_list_to_string!(array, i64), - (List(_), _) => Err(ArrowError::CastError( - "Cannot cast list to non-list data types".to_string(), - )), - (_, List(ref to)) => { - cast_primitive_to_list::<i32>(array, to, to_type, cast_options) - } - (_, LargeList(ref to)) => { - cast_primitive_to_list::<i64>(array, to, to_type, cast_options) - } - (Dictionary(index_type, _), _) => match **index_type { - Int8 => dictionary_cast::<Int8Type>(array, to_type, cast_options), - Int16 => dictionary_cast::<Int16Type>(array, to_type, cast_options), - Int32 => dictionary_cast::<Int32Type>(array, to_type, cast_options), - Int64 => dictionary_cast::<Int64Type>(array, to_type, cast_options), - UInt8 => dictionary_cast::<UInt8Type>(array, to_type, cast_options), - UInt16 => dictionary_cast::<UInt16Type>(array, to_type, cast_options), - UInt32 => dictionary_cast::<UInt32Type>(array, to_type, cast_options), - UInt64 => dictionary_cast::<UInt64Type>(array, to_type, cast_options), - _ => Err(ArrowError::CastError(format!( - "Casting from dictionary type {:?} to {:?} not supported", - from_type, to_type, - ))), - }, - (_, Dictionary(index_type, value_type)) => match **index_type { - Int8 => cast_to_dictionary::<Int8Type>(array, value_type, cast_options), - Int16 => cast_to_dictionary::<Int16Type>(array, value_type, cast_options), - Int32 => cast_to_dictionary::<Int32Type>(array, value_type, cast_options), - Int64 => cast_to_dictionary::<Int64Type>(array, value_type, cast_options), - UInt8 => cast_to_dictionary::<UInt8Type>(array, value_type, cast_options), - UInt16 => cast_to_dictionary::<UInt16Type>(array, value_type, cast_options), - UInt32 => cast_to_dictionary::<UInt32Type>(array, value_type, cast_options), - UInt64 => cast_to_dictionary::<UInt64Type>(array, value_type, cast_options), - _ => Err(ArrowError::CastError(format!( - "Casting from type {:?} to dictionary type {:?} not supported", - from_type, to_type, - ))), - }, (_, Boolean) => match from_type { UInt8 => cast_numeric_to_bool::<UInt8Type>(array), UInt16 => cast_numeric_to_bool::<UInt16Type>(array), @@ -3341,7 +3345,18 @@ fn cast_to_dictionary<K: ArrowDictionaryKeyType>( dict_value_type, cast_options, ), + Decimal128(_, _) => pack_numeric_to_dictionary::<K, Decimal128Type>( + array, + dict_value_type, + cast_options, + ), + Decimal256(_, _) => pack_numeric_to_dictionary::<K, Decimal256Type>( + array, + dict_value_type, + cast_options, + ), Utf8 => pack_string_to_dictionary::<K>(array, cast_options), + LargeUtf8 => pack_string_to_dictionary::<K>(array, cast_options), _ => Err(ArrowError::CastError(format!( "Unsupported output type for dictionary packing: {:?}", dict_value_type
diff --git a/arrow/tests/array_cast.rs b/arrow/tests/array_cast.rs index 95fb973289a5..be37a7636b63 100644 --- a/arrow/tests/array_cast.rs +++ b/arrow/tests/array_cast.rs @@ -19,12 +19,13 @@ use arrow_array::builder::{ PrimitiveDictionaryBuilder, StringDictionaryBuilder, UnionBuilder, }; use arrow_array::types::{ - ArrowDictionaryKeyType, Int16Type, Int32Type, Int64Type, Int8Type, - TimestampMicrosecondType, UInt16Type, UInt32Type, UInt64Type, UInt8Type, + ArrowDictionaryKeyType, Decimal128Type, Decimal256Type, Int16Type, Int32Type, + Int64Type, Int8Type, TimestampMicrosecondType, UInt16Type, UInt32Type, UInt64Type, + UInt8Type, }; use arrow_array::{ - Array, ArrayRef, BinaryArray, BooleanArray, Date32Array, Date64Array, - Decimal128Array, DurationMicrosecondArray, DurationMillisecondArray, + Array, ArrayRef, ArrowPrimitiveType, BinaryArray, BooleanArray, Date32Array, + Date64Array, Decimal128Array, DurationMicrosecondArray, DurationMillisecondArray, DurationNanosecondArray, DurationSecondArray, FixedSizeBinaryArray, FixedSizeListArray, Float16Array, Float32Array, Float64Array, Int16Array, Int32Array, Int64Array, Int8Array, IntervalDayTimeArray, IntervalMonthDayNanoArray, @@ -35,7 +36,7 @@ use arrow_array::{ TimestampNanosecondArray, TimestampSecondArray, UInt16Array, UInt32Array, UInt64Array, UInt8Array, UnionArray, }; -use arrow_buffer::Buffer; +use arrow_buffer::{i256, Buffer}; use arrow_cast::{can_cast_types, cast}; use arrow_data::ArrayData; use arrow_schema::{ArrowError, DataType, Field, IntervalUnit, TimeUnit, UnionMode}; @@ -101,14 +102,14 @@ fn get_arrays_of_all_types() -> Vec<ArrayRef> { vec![ Arc::new(BinaryArray::from(binary_data.clone())), Arc::new(LargeBinaryArray::from(binary_data.clone())), - make_dictionary_primitive::<Int8Type>(), - make_dictionary_primitive::<Int16Type>(), - make_dictionary_primitive::<Int32Type>(), - make_dictionary_primitive::<Int64Type>(), - make_dictionary_primitive::<UInt8Type>(), - make_dictionary_primitive::<UInt16Type>(), - make_dictionary_primitive::<UInt32Type>(), - make_dictionary_primitive::<UInt64Type>(), + make_dictionary_primitive::<Int8Type, Int32Type>(vec![1, 2]), + make_dictionary_primitive::<Int16Type, Int32Type>(vec![1, 2]), + make_dictionary_primitive::<Int32Type, Int32Type>(vec![1, 2]), + make_dictionary_primitive::<Int64Type, Int32Type>(vec![1, 2]), + make_dictionary_primitive::<UInt8Type, Int32Type>(vec![1, 2]), + make_dictionary_primitive::<UInt16Type, Int32Type>(vec![1, 2]), + make_dictionary_primitive::<UInt32Type, Int32Type>(vec![1, 2]), + make_dictionary_primitive::<UInt64Type, Int32Type>(vec![1, 2]), make_dictionary_utf8::<Int8Type>(), make_dictionary_utf8::<Int16Type>(), make_dictionary_utf8::<Int32Type>(), @@ -184,6 +185,46 @@ fn get_arrays_of_all_types() -> Vec<ArrayRef> { Arc::new( create_decimal_array(vec![Some(1), Some(2), Some(3), None], 38, 0).unwrap(), ), + make_dictionary_primitive::<Int8Type, Decimal128Type>(vec![1, 2]), + make_dictionary_primitive::<Int16Type, Decimal128Type>(vec![1, 2]), + make_dictionary_primitive::<Int32Type, Decimal128Type>(vec![1, 2]), + make_dictionary_primitive::<Int64Type, Decimal128Type>(vec![1, 2]), + make_dictionary_primitive::<UInt8Type, Decimal128Type>(vec![1, 2]), + make_dictionary_primitive::<UInt16Type, Decimal128Type>(vec![1, 2]), + make_dictionary_primitive::<UInt32Type, Decimal128Type>(vec![1, 2]), + make_dictionary_primitive::<UInt64Type, Decimal128Type>(vec![1, 2]), + make_dictionary_primitive::<Int8Type, Decimal256Type>(vec![ + i256::from_i128(1), + i256::from_i128(2), + ]), + make_dictionary_primitive::<Int16Type, Decimal256Type>(vec![ + i256::from_i128(1), + i256::from_i128(2), + ]), + make_dictionary_primitive::<Int32Type, Decimal256Type>(vec![ + i256::from_i128(1), + i256::from_i128(2), + ]), + make_dictionary_primitive::<Int64Type, Decimal256Type>(vec![ + i256::from_i128(1), + i256::from_i128(2), + ]), + make_dictionary_primitive::<UInt8Type, Decimal256Type>(vec![ + i256::from_i128(1), + i256::from_i128(2), + ]), + make_dictionary_primitive::<UInt16Type, Decimal256Type>(vec![ + i256::from_i128(1), + i256::from_i128(2), + ]), + make_dictionary_primitive::<UInt32Type, Decimal256Type>(vec![ + i256::from_i128(1), + i256::from_i128(2), + ]), + make_dictionary_primitive::<UInt64Type, Decimal256Type>(vec![ + i256::from_i128(1), + i256::from_i128(2), + ]), ] } @@ -273,12 +314,15 @@ fn make_union_array() -> UnionArray { } /// Creates a dictionary with primitive dictionary values, and keys of type K -fn make_dictionary_primitive<K: ArrowDictionaryKeyType>() -> ArrayRef { +/// and values of type V +fn make_dictionary_primitive<K: ArrowDictionaryKeyType, V: ArrowPrimitiveType>( + values: Vec<V::Native>, +) -> ArrayRef { // Pick Int32 arbitrarily for dictionary values - let mut b: PrimitiveDictionaryBuilder<K, Int32Type> = - PrimitiveDictionaryBuilder::new(); - b.append(1).unwrap(); - b.append(2).unwrap(); + let mut b: PrimitiveDictionaryBuilder<K, V> = PrimitiveDictionaryBuilder::new(); + values.iter().for_each(|v| { + b.append(*v).unwrap(); + }); Arc::new(b.finish()) } @@ -369,6 +413,12 @@ fn get_all_types() -> Vec<DataType> { Dictionary(Box::new(DataType::Int16), Box::new(DataType::Utf8)), Dictionary(Box::new(DataType::UInt32), Box::new(DataType::Utf8)), Decimal128(38, 0), + Dictionary(Box::new(DataType::Int8), Box::new(Decimal128(38, 0))), + Dictionary(Box::new(DataType::Int16), Box::new(Decimal128(38, 0))), + Dictionary(Box::new(DataType::UInt32), Box::new(Decimal128(38, 0))), + Dictionary(Box::new(DataType::Int8), Box::new(Decimal256(76, 0))), + Dictionary(Box::new(DataType::Int16), Box::new(Decimal256(76, 0))), + Dictionary(Box::new(DataType::UInt32), Box::new(Decimal256(76, 0))), ] }
Some more inconsistency between can_cast_types and cast_with_options **Describe the bug** <!-- A clear and concise description of what the bug is. --> There are more inconsistency between `can_cast_types` and `cast_with_options` that is `cast_with_options` can cast but `can_cast_types` reports `false`. For example, 1. Casting from Dictionary of Integer to DecimalArray ``` thread 'test_can_cast_types' panicked at 'Was able to cast array DictionaryArray {keys: PrimitiveArray<Int8> [ 0, 1, ] values: PrimitiveArray<Int32> [ 1, 2, ]} from Dictionary(Int8, Int32) to Decimal128(38, 0) but can_cast_types reported false', arrow/tests/array_cast.rs:83:21 ``` 2. Casting from List of some type (e.g., Integer) to Dictionary of Utf8 ``` thread 'test_can_cast_types' panicked at 'Was not able to cast array ListArray [ PrimitiveArray<Int32> [ 0, 1, 2, ], PrimitiveArray<Int32> [ 3, 4, 5, ], PrimitiveArray<Int32> [ 6, 7, ], ] from List(Field { name: "item", data_type: Int32, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }) to Dictionary(Int16, Utf8) but can_cast_types reported true. Error was CastError("Cannot cast list to non-list data types")', arrow/tests/array_cast.rs:87:21 ``` **To Reproduce** <!-- Steps to reproduce the behavior: --> **Expected behavior** <!-- A clear and concise description of what you expected to happen. --> **Additional context** <!-- Add any other context about the problem here. -->
2022-11-30T08:02:16Z
28.0
26438feb7a59aa156563ed8c6e8b0e6579b2e028
[ "test_can_cast_types" ]
[ "arrow/src/compute/kernels/boolean.rs - compute::kernels::boolean::and_kleene (line 263)", "arrow/src/array/ord.rs - array::ord::build_compare (line 162)", "arrow/src/compute/kernels/boolean.rs - compute::kernels::boolean::is_null (line 393)", "arrow/src/compute/kernels/boolean.rs - compute::kernels::boolean::not (line 352)", "arrow/src/compute/kernels/aggregate.rs - compute::kernels::aggregate::min_boolean (line 65)", "arrow/src/compute/kernels/boolean.rs - compute::kernels::boolean::is_not_null (line 434)", "arrow/src/compute/kernels/aggregate.rs - compute::kernels::aggregate::max_boolean (line 90)", "arrow/src/compute/kernels/boolean.rs - compute::kernels::boolean::and (line 229)", "arrow/src/compute/kernels/boolean.rs - compute::kernels::boolean::or (line 293)", "arrow/src/compute/kernels/comparison.rs - compute::kernels::comparison::eq_dyn (line 3203)", "arrow/src/compute/kernels/boolean.rs - compute::kernels::boolean::or_kleene (line 327)", "arrow/src/compute/kernels/comparison.rs - compute::kernels::comparison::gt_eq_dyn (line 3424)", "arrow/src/compute/kernels/comparison.rs - compute::kernels::comparison::gt_dyn (line 3380)", "arrow/src/compute/kernels/comparison.rs - compute::kernels::comparison::lt_eq_dyn (line 3336)", "arrow/src/compute/kernels/comparison.rs - compute::kernels::comparison::lt_dyn (line 3291)", "arrow/src/compute/kernels/comparison.rs - compute::kernels::comparison::like_utf8 (line 205)", "arrow/src/lib.rs - (line 116)", "arrow/src/compute/kernels/comparison.rs - compute::kernels::comparison::neq_dyn (line 3246)", "arrow/src/lib.rs - (line 137)", "arrow/src/compute/kernels/sort.rs - compute::kernels::sort::lexsort (line 859)", "arrow/src/compute/kernels/substring.rs - compute::kernels::substring::substring (line 47)", "arrow/src/compute/kernels/substring.rs - compute::kernels::substring::substring_by_char (line 173)", "arrow/src/compute/kernels/sort.rs - compute::kernels::sort::sort (line 42)", "arrow/src/compute/kernels/substring.rs - compute::kernels::substring::substring (line 63)", "arrow/src/row/mod.rs - row (line 104)", "arrow/src/compute/kernels/sort.rs - compute::kernels::sort::sort_limit (line 70)", "arrow/src/lib.rs - (line 229)", "arrow/src/lib.rs - (line 58)", "arrow/src/lib.rs - (line 174)", "arrow/src/lib.rs - (line 92)", "arrow/src/lib.rs - (line 203)", "arrow/src/lib.rs - (line 73)", "arrow/src/row/mod.rs - row (line 51)", "arrow/src/util/string_writer.rs - util::string_writer (line 25)", "test_timestamp_cast_utf8", "test_cast_timestamp_to_string" ]
[]
[]
apache/arrow-rs
3,188
apache__arrow-rs-3188
[ "3136" ]
fd08c31a2cd37342d261f67e999b2be2d5a4ba6b
diff --git a/.github/workflows/integration.yml b/.github/workflows/integration.yml index 3ece06b29238..656e56a652ca 100644 --- a/.github/workflows/integration.yml +++ b/.github/workflows/integration.yml @@ -149,13 +149,13 @@ jobs: virtualenv venv source venv/bin/activate pip install maturin toml pytest pytz pyarrow>=5.0 + - name: Run Rust tests + run: | + source venv/bin/activate + cargo test -p arrow --test pyarrow --features pyarrow - name: Run tests - env: - CARGO_HOME: "/home/runner/.cargo" - CARGO_TARGET_DIR: "/home/runner/target" run: | source venv/bin/activate - pushd arrow-pyarrow-integration-testing + cd arrow-pyarrow-integration-testing maturin develop pytest -v . - popd diff --git a/arrow/Cargo.toml b/arrow/Cargo.toml index ab8963b9c300..7ab5720296cd 100644 --- a/arrow/Cargo.toml +++ b/arrow/Cargo.toml @@ -268,3 +268,7 @@ required-features = ["test_utils", "ipc"] [[test]] name = "csv" required-features = ["csv", "chrono-tz"] + +[[test]] +name = "pyarrow" +required-features = ["pyarrow"] diff --git a/arrow/src/pyarrow.rs b/arrow/src/pyarrow.rs index 7c365a4344a5..5ddc3105a4ad 100644 --- a/arrow/src/pyarrow.rs +++ b/arrow/src/pyarrow.rs @@ -184,20 +184,19 @@ impl PyArrowConvert for RecordBatch { fn to_pyarrow(&self, py: Python) -> PyResult<PyObject> { let mut py_arrays = vec![]; - let mut py_names = vec![]; let schema = self.schema(); - let fields = schema.fields().iter(); let columns = self.columns().iter(); - for (array, field) in columns.zip(fields) { + for array in columns { py_arrays.push(array.data().to_pyarrow(py)?); - py_names.push(field.name()); } + let py_schema = schema.to_pyarrow(py)?; + let module = py.import("pyarrow")?; let class = module.getattr("RecordBatch")?; - let record = class.call_method1("from_arrays", (py_arrays, py_names))?; + let record = class.call_method1("from_arrays", (py_arrays, py_schema))?; Ok(PyObject::from(record)) }
diff --git a/arrow/tests/pyarrow.rs b/arrow/tests/pyarrow.rs new file mode 100644 index 000000000000..4b1226c738f5 --- /dev/null +++ b/arrow/tests/pyarrow.rs @@ -0,0 +1,42 @@ +// 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. + +use arrow::array::{ArrayRef, Int32Array, StringArray}; +use arrow::pyarrow::PyArrowConvert; +use arrow::record_batch::RecordBatch; +use pyo3::Python; +use std::sync::Arc; + +#[test] +fn test_to_pyarrow() { + pyo3::prepare_freethreaded_python(); + + let a: ArrayRef = Arc::new(Int32Array::from(vec![1, 2])); + let b: ArrayRef = Arc::new(StringArray::from(vec!["a", "b"])); + let input = RecordBatch::try_from_iter(vec![("a", a), ("b", b)]).unwrap(); + println!("input: {:?}", input); + + let res = Python::with_gil(|py| { + let py_input = input.to_pyarrow(py)?; + let records = RecordBatch::from_pyarrow(py_input.as_ref(py))?; + let py_records = records.to_pyarrow(py)?; + RecordBatch::from_pyarrow(py_records.as_ref(py)) + }) + .unwrap(); + + assert_eq!(input, res); +}
arrow to and from pyarrow conversion results in changes in schema **Describe the bug** <!-- A clear and concise description of what the bug is. --> Converting a RecordBatch to pyarrow RecordBatch and converting it back to rust RecordBatch results in inconsistent schema. **To Reproduce** <!-- Steps to reproduce the behavior: --> ``` #[pyfunction] fn lookup(py: Python<'_>, keys: PyObject) -> PyResult<PyObject> { // Input is Arrow RecordBatch let keys = RecordBatch::from_pyarrow(keys.as_ref(py))?; println!("keys: {:?}", keys); keys.to_pyarrow(py) } #[test] fn test_conversion() { let a: ArrayRef = Arc::new(Int32Array::from(vec![1, 2])); let b: ArrayRef = Arc::new(StringArray::from(vec!["a", "b"])); let input = RecordBatch::try_from_iter(vec![("a", a), ("b", b)]).unwrap(); println!("input: {:?}", input); let res = pyo3::Python::with_gil(|py| { let x = lookup(py, input.to_pyarrow(py).unwrap()).unwrap(); RecordBatch::from_pyarrow(x.as_ref(py)).unwrap() }); assert_eq!(input, res); } ``` output - ``` input: RecordBatch { schema: Schema { fields: [Field { name: "a", data_type: Int32, nullable: false, dict_id: 0, dict_is_ordered: false, metadata: None }, Field { name: "b", data_type: Utf8, nullable: false, dict_id: 0, dict_is_ordered: false, metadata: None }], metadata: {} }, columns: [PrimitiveArray<Int32> [ 1, 2, ], StringArray [ "a", "b", ]], row_count: 2 } keys: RecordBatch { schema: Schema { fields: [Field { name: "a", data_type: Int32, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: None }, Field { name: "b", data_type: Utf8, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: None }], metadata: {} }, columns: [PrimitiveArray<Int32> [ 1, 2, ], StringArray [ "a", "b", ]], row_count: 2 } ``` `nullable: false` is what is different b/w the types. **Expected behavior** <!-- A clear and concise description of what you expected to happen. --> **Additional context** <!-- Add any other context about the problem here. --> Versions of the packages used - ``` arrow = { version = "25.0.0", features = ["pyarrow"] } pyo3 = { version = "0.17.1" } ```
Yes, we may need pass the schema to the pyarrow's `from_arrays` in [to_pyarrow](https://github.com/apache/arrow-rs/blob/2460c7b5da2ba22c7fb0ef0df6ac84984e3aed12/arrow/src/pyarrow.rs#L200)
2022-11-25T04:08:06Z
28.0
26438feb7a59aa156563ed8c6e8b0e6579b2e028
[ "test_to_pyarrow" ]
[ "arrow/src/compute/kernels/aggregate.rs - compute::kernels::aggregate::min_boolean (line 65)", "arrow/src/compute/kernels/boolean.rs - compute::kernels::boolean::and (line 230)", "arrow/src/compute/kernels/boolean.rs - compute::kernels::boolean::not (line 353)", "arrow/src/compute/kernels/boolean.rs - compute::kernels::boolean::is_null (line 394)", "arrow/src/array/ord.rs - array::ord::build_compare (line 162)", "arrow/src/compute/kernels/aggregate.rs - compute::kernels::aggregate::max_boolean (line 90)", "arrow/src/compute/kernels/boolean.rs - compute::kernels::boolean::and_kleene (line 264)", "arrow/src/compute/kernels/boolean.rs - compute::kernels::boolean::is_not_null (line 435)", "arrow/src/compute/kernels/comparison.rs - compute::kernels::comparison::gt_dyn (line 2965)", "arrow/src/compute/kernels/comparison.rs - compute::kernels::comparison::eq_dyn (line 2788)", "arrow/src/compute/kernels/boolean.rs - compute::kernels::boolean::or_kleene (line 328)", "arrow/src/compute/kernels/boolean.rs - compute::kernels::boolean::or (line 294)", "arrow/src/compute/kernels/comparison.rs - compute::kernels::comparison::like_utf8 (line 206)", "arrow/src/compute/kernels/comparison.rs - compute::kernels::comparison::lt_eq_dyn (line 2921)", "arrow/src/compute/kernels/comparison.rs - compute::kernels::comparison::lt_dyn (line 2876)", "arrow/src/compute/kernels/comparison.rs - compute::kernels::comparison::gt_eq_dyn (line 3009)", "arrow/src/compute/kernels/window.rs - compute::kernels::window::shift (line 32)", "arrow/src/lib.rs - (line 116)", "arrow/src/compute/kernels/comparison.rs - compute::kernels::comparison::neq_dyn (line 2831)", "arrow/src/compute/kernels/sort.rs - compute::kernels::sort::lexsort (line 859)", "arrow/src/compute/kernels/sort.rs - compute::kernels::sort::sort (line 42)", "arrow/src/compute/kernels/sort.rs - compute::kernels::sort::sort_limit (line 70)", "arrow/src/compute/kernels/substring.rs - compute::kernels::substring::substring (line 47)", "arrow/src/compute/kernels/substring.rs - compute::kernels::substring::substring (line 63)", "arrow/src/compute/kernels/substring.rs - compute::kernels::substring::substring_by_char (line 173)", "arrow/src/row/mod.rs - row (line 104)", "arrow/src/lib.rs - (line 229)", "arrow/src/lib.rs - (line 137)", "arrow/src/lib.rs - (line 58)", "arrow/src/lib.rs - (line 174)", "arrow/src/lib.rs - (line 92)", "arrow/src/lib.rs - (line 203)", "arrow/src/lib.rs - (line 73)", "arrow/src/row/mod.rs - row (line 51)", "arrow/src/util/string_writer.rs - util::string_writer (line 25)" ]
[]
[]
apache/arrow-rs
4,045
apache__arrow-rs-4045
[ "4044" ]
fec282fd43add7df97ca8f58eb5eaa42eb9c928d
diff --git a/arrow-data/src/equal/union.rs b/arrow-data/src/equal/union.rs index 4f04bc287aa8..5869afc30dbe 100644 --- a/arrow-data/src/equal/union.rs +++ b/arrow-data/src/equal/union.rs @@ -70,7 +70,13 @@ fn equal_sparse( .iter() .zip(rhs.child_data()) .all(|(lhs_values, rhs_values)| { - equal_range(lhs_values, rhs_values, lhs_start, rhs_start, len) + equal_range( + lhs_values, + rhs_values, + lhs_start + lhs.offset(), + rhs_start + rhs.offset(), + len, + ) }) }
diff --git a/arrow/tests/array_equal.rs b/arrow/tests/array_equal.rs index 93296c3b0e43..83a280db67b8 100644 --- a/arrow/tests/array_equal.rs +++ b/arrow/tests/array_equal.rs @@ -1155,6 +1155,22 @@ fn test_union_equal_sparse() { test_equal(&union1, &union4, false); } +#[test] +fn test_union_equal_sparse_slice() { + let mut builder = UnionBuilder::new_sparse(); + builder.append::<Int32Type>("a", 1).unwrap(); + builder.append::<Int32Type>("a", 2).unwrap(); + builder.append::<Int32Type>("b", 3).unwrap(); + let a1 = builder.build().unwrap(); + + let mut builder = UnionBuilder::new_sparse(); + builder.append::<Int32Type>("a", 2).unwrap(); + builder.append::<Int32Type>("b", 3).unwrap(); + let a2 = builder.build().unwrap(); + + test_equal(&a1.slice(1, 2), &a2, true) +} + #[test] fn test_boolean_slice() { let array = BooleanArray::from(vec![true; 32]);
Sparse UnionArray Equality Incorrect Offset Handling **Describe the bug** <!-- A clear and concise description of what the bug is. --> **To Reproduce** <!-- Steps to reproduce the behavior: --> ``` #[test] fn test_union_equal_sparse_slice() { let mut builder = UnionBuilder::new_sparse(); builder.append::<Int32Type>("a", 1).unwrap(); builder.append::<Int32Type>("a", 2).unwrap(); builder.append::<Int32Type>("b", 3).unwrap(); let a1 = builder.build().unwrap(); let mut builder = UnionBuilder::new_sparse(); builder.append::<Int32Type>("a", 2).unwrap(); builder.append::<Int32Type>("b", 3).unwrap(); let a2 = builder.build().unwrap(); test_equal(&a1.slice(1, 2), &a2, true) } ``` The above should pass, it currently does not **Expected behavior** <!-- A clear and concise description of what you expected to happen. --> **Additional context** <!-- Add any other context about the problem here. -->
2023-04-10T14:51:17Z
37.0
a35c6c5f4309787a9a2f523920af2efd9b1682b9
[ "test_union_equal_sparse_slice" ]
[ "arrow/src/lib.rs - (line 121)", "arrow/src/lib.rs - (line 140)", "arrow/src/lib.rs - (line 253)", "arrow/src/lib.rs - (line 78)", "arrow/src/lib.rs - (line 63)", "arrow/src/lib.rs - (line 282)", "arrow/src/lib.rs - (line 161)", "arrow/src/lib.rs - (line 198)", "arrow/src/lib.rs - (line 227)", "arrow/src/lib.rs - (line 97)", "arrow/src/util/string_writer.rs - util::string_writer (line 25)", "test_boolean_equal_offset", "test_binary_equal", "test_boolean_equal", "test_boolean_equal_nulls", "list_array_non_zero_nulls", "test_decimal_equal", "test_decimal_null", "test_boolean_slice", "test_decimal_offsets", "test_empty_offsets_list_equal", "test_dictionary_equal", "test_dictionary_equal_null", "test_fixed_list_null", "test_fixed_size_binary_array", "test_fixed_list_offsets", "test_fixed_size_binary_equal", "test_fixed_size_binary_null", "test_fixed_size_binary_offsets", "test_fixed_size_list_equal", "test_large_binary_equal", "test_large_string_equal", "test_list_different_offsets", "test_list_equal", "test_list_offsets", "test_list_null", "test_non_null_empty_strings", "test_null", "test_null_empty_strings", "test_null_equal", "test_primitive", "test_sliced_nullable_boolean_array", "test_primitive_slice", "test_string_equal", "test_string_offset", "test_string_offset_larger", "test_struct_equal", "test_struct_equal_null_variable_size", "test_struct_equal_slice", "test_struct_equal_null", "test_union_equal_dense", "test_union_equal_sparse" ]
[]
[]
apache/arrow-rs
3,811
apache__arrow-rs-3811
[ "3779" ]
3df7c00a358cff34da8bacd819e791892755d3a9
diff --git a/arrow-flight/src/encode.rs b/arrow-flight/src/encode.rs index 2e93acb0931c..557663922121 100644 --- a/arrow-flight/src/encode.rs +++ b/arrow-flight/src/encode.rs @@ -323,7 +323,7 @@ fn prepare_schema_for_flight(schema: &Schema) -> Schema { }) .collect(); - Schema::new(fields) + Schema::new(fields).with_metadata(schema.metadata().clone()) } /// Split [`RecordBatch`] so it hopefully fits into a gRPC response. @@ -461,6 +461,7 @@ mod tests { use arrow_array::{ DictionaryArray, Int16Array, Int32Array, Int64Array, StringArray, UInt64Array, }; + use std::collections::HashMap; use super::*; @@ -502,6 +503,17 @@ mod tests { ); } + #[test] + fn test_schema_metadata_encoded() { + let schema = + Schema::new(vec![Field::new("data", DataType::Int32, false)]).with_metadata( + HashMap::from([("some_key".to_owned(), "some_value".to_owned())]), + ); + + let got = prepare_schema_for_flight(&schema); + assert!(got.metadata().contains_key("some_key")); + } + #[test] fn test_encode_no_column_batch() { let batch = RecordBatch::try_new_with_options(
diff --git a/arrow-flight/tests/encode_decode.rs b/arrow-flight/tests/encode_decode.rs index 25e74cb3b6bc..8c73a516b2b0 100644 --- a/arrow-flight/tests/encode_decode.rs +++ b/arrow-flight/tests/encode_decode.rs @@ -17,7 +17,7 @@ //! Tests for round trip encoding / decoding -use std::sync::Arc; +use std::{collections::HashMap, sync::Arc}; use arrow::{compute::concat_batches, datatypes::Int32Type}; use arrow_array::{ArrayRef, DictionaryArray, Float64Array, RecordBatch, UInt8Array}; @@ -62,6 +62,18 @@ async fn test_primative_one() { roundtrip(vec![make_primative_batch(5)]).await; } +#[tokio::test] +async fn test_schema_metadata() { + let batch = make_primative_batch(5); + let metadata = HashMap::from([("some_key".to_owned(), "some_value".to_owned())]); + + // create a batch that has schema level metadata + let schema = Arc::new(batch.schema().as_ref().clone().with_metadata(metadata)); + let batch = RecordBatch::try_new(schema, batch.columns().to_vec()).unwrap(); + + roundtrip(vec![batch]).await; +} + #[tokio::test] async fn test_primative_many() { roundtrip(vec![
Schema-level metadata is not encoded in Flight responses **Describe the bug** When preparing schema for encoding into a Flight response, the schema-level metadata from the source schema is dropped: https://github.com/apache/arrow-rs/blob/e7eb304dac442a943c434f8ea248de909f82aa88/arrow-flight/src/encode.rs#L326 **To Reproduce** ```patch Index: arrow-flight/src/encode.rs IDEA additional info: Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP <+>UTF-8 =================================================================== diff --git a/arrow-flight/src/encode.rs b/arrow-flight/src/encode.rs --- a/arrow-flight/src/encode.rs (revision e7eb304dac442a943c434f8ea248de909f82aa88) +++ b/arrow-flight/src/encode.rs (date 1677611826249) @@ -453,6 +453,7 @@ #[cfg(test)] mod tests { + use std::collections::HashMap; use arrow::{ array::{UInt32Array, UInt8Array}, compute::concat_batches, @@ -502,6 +503,16 @@ ); } + #[test] + fn test_schema_metadata_encoded() { + let schema = Schema::new(vec![ + Field::new("data", DataType::Int32, false), + ]).with_metadata(HashMap::from([("some_key".to_owned(), "some_value".to_owned())])); + + let got = prepare_schema_for_flight(&schema); + assert!(got.metadata().contains_key("some_key")); + } + #[test] fn test_encode_no_column_batch() { let batch = RecordBatch::try_new_with_options( ``` **Expected behavior** Schema-level metadata should be included permitting test to pass. **Additional context** <!-- Add any other context about the problem here. -->
@alamb I can confirm that with this patch: ```patch Index: arrow-flight/src/encode.rs IDEA additional info: Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP <+>UTF-8 =================================================================== diff --git a/arrow-flight/src/encode.rs b/arrow-flight/src/encode.rs --- a/arrow-flight/src/encode.rs (revision bbc1469077e13ba2e5a61f130917ad7eccfcb569) +++ b/arrow-flight/src/encode.rs (date 1677712010122) @@ -323,7 +323,7 @@ }) .collect(); - Schema::new(fields) + Schema::new(fields).with_metadata(schema.metadata().clone()) } /// Split [`RecordBatch`] so it hopefully fits into a gRPC response. @@ -453,6 +453,7 @@ #[cfg(test)] mod tests { + use std::collections::HashMap; use arrow::{ array::{UInt32Array, UInt8Array}, compute::concat_batches, @@ -502,6 +503,16 @@ ); } + #[test] + fn test_schema_metadata_encoded() { + let schema = Schema::new(vec![ + Field::new("data", DataType::Int32, false), + ]).with_metadata(HashMap::from([("some_key".to_owned(), "some_value".to_owned())])); + + let got = prepare_schema_for_flight(&schema); + assert!(got.metadata().contains_key("some_key")); + } + #[test] fn test_encode_no_column_batch() { let batch = RecordBatch::try_new_with_options( ``` and minor fixes in IOx, the schema metadata propagates across RPC requests
2023-03-07T05:35:13Z
34.0
495682aa72ffe92bbd0d6d8d93e0c00b5483ff7d
[ "test_schema_metadata" ]
[ "arrow-flight/src/client.rs - client::FlightClient::do_action (line 512) - compile", "arrow-flight/src/client.rs - client::FlightClient::do_get (line 178) - compile", "arrow-flight/src/client.rs - client::FlightClient (line 45) - compile", "arrow-flight/src/client.rs - client::FlightClient::get_flight_info (line 225) - compile", "arrow-flight/src/client.rs - client::FlightClient::list_actions (line 475) - compile", "arrow-flight/src/client.rs - client::FlightClient::do_put (line 278) - compile", "arrow-flight/src/client.rs - client::FlightClient::get_schema (line 440) - compile", "arrow-flight/src/encode.rs - encode::FlightDataEncoderBuilder (line 39) - compile", "arrow-flight/src/client.rs - client::FlightClient::list_flights (line 397) - compile", "arrow-flight/src/client.rs - client::FlightClient::do_exchange (line 347) - compile", "arrow-flight/src/decode.rs - decode::FlightRecordBatchStream (line 39) - compile", "test_empty", "test_error", "test_empty_batch", "test_app_metadata", "test_primative_empty", "test_dictionary_one", "test_chained_streams_batch_decoder", "test_chained_streams_data_decoder", "test_mismatched_record_batch_schema", "test_zero_batches_dictonary_schema_specified", "test_max_message_size", "test_dictionary_many", "test_zero_batches_no_schema", "test_mismatched_schema_message", "test_primative_many", "test_primative_one", "test_zero_batches_schema_specified", "test_max_message_size_fuzz" ]
[]
[]