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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions datafusion/core/tests/parquet/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ mod row_group_pruning;
mod schema;
mod schema_coercion;
mod string_in_list_pruning;
mod struct_field_pruning;
mod utils;

#[cfg(test)]
Expand Down
106 changes: 106 additions & 0 deletions datafusion/core/tests/parquet/struct_field_pruning.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: See the NOTICE file distributed with this work for additional information regarding copyright ownership
// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements

//! Pruning on struct fields, for files that SQL cannot write.

use std::io::Write;
use std::sync::Arc;

use arrow::array::{ArrayRef, Int64Array, RecordBatch, StructArray};
use arrow::datatypes::{DataType, Field, Fields, Schema};
use datafusion::prelude::{ParquetReadOptions, SessionContext};
use datafusion_common::ScalarValue;
use parquet::arrow::ArrowWriter;
use parquet::file::metadata::{ParquetMetaData, ParquetMetaDataWriter};
use parquet::file::statistics::Statistics;
use parquet::file::writer::TrackedWrite;
use tempfile::NamedTempFile;

/// Writes `s: {a: Int64}` with rows `{a: 1}` and `{a: null}` in one row
/// group. The footer keeps the min and max of `s.a`, but not its null count.
///
/// The null count is optional in the Parquet format, and some writers omit
/// it. A scan that reads a missing null count as zero prunes this row group
/// for `s['a'] IS NULL` and loses a row.
///
/// The Arrow writer always writes the null count. So this function writes the
/// file with the Arrow writer, then writes the footer again without the null
/// count.
fn struct_file_without_null_count() -> NamedTempFile {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

what is the purpose of hand constructing a file without null statistics?

It might be easier to understand if the test wrote a file with null statistics and then updated the statistics and rewrite the file (not sure if this is possible with the parquet API today)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Also in theory we could add this setup file to the slt harness runner (or check it in) so that the tests could be entirely .slt

let a = Field::new("a", DataType::Int64, true);
let schema = Arc::new(Schema::new(vec![Field::new(
"s",
DataType::Struct(Fields::from(vec![a.clone()])),
true,
)]));
let values: ArrayRef = Arc::new(Int64Array::from(vec![Some(1), None]));
let s = StructArray::new(Fields::from(vec![a]), vec![values], None);
let batch = RecordBatch::try_new(Arc::clone(&schema), vec![Arc::new(s)]).unwrap();
let mut bytes = Vec::new();
let mut writer = ArrowWriter::try_new(&mut bytes, schema, None).unwrap();
writer.write(&batch).unwrap();
let metadata = writer.close().unwrap();

let group = &metadata.row_groups()[0];
let column = group.column(0).clone();
let Statistics::Int64(stats) = column.statistics().unwrap() else {
panic!("expected Int64 statistics");
};
let stats = Statistics::int64(
stats.min_opt().copied(),
stats.max_opt().copied(),
None,
None,
false,
);
let column = column.into_builder().set_statistics(stats).build().unwrap();
let group = group
.clone()
.into_builder()
.set_column_metadata(vec![column])
.build()
.unwrap();
let metadata = ParquetMetaData::new(metadata.file_metadata().clone(), vec![group]);

// Replace the footer. The encoded rows and their offsets do not change.
let footer_len =
u32::from_le_bytes(bytes[bytes.len() - 8..bytes.len() - 4].try_into().unwrap());
bytes.truncate(bytes.len() - 8 - footer_len as usize);
let mut file = tempfile::Builder::new()
.suffix(".parquet")
.tempfile()
.unwrap();
let mut output = TrackedWrite::new(file.as_file_mut());
output.write_all(&bytes).unwrap();
ParquetMetaDataWriter::new_with_tracked(output, &metadata)
.finish()
.unwrap();
file
}

#[tokio::test]
async fn missing_struct_field_null_count_keeps_row_group() {
// A missing null count is unknown, not zero. `s['a'] IS NULL` must not
// prune the row group.
let file = struct_file_without_null_count();
let ctx = SessionContext::new();
ctx.register_parquet(
"t",
file.path().to_str().unwrap(),
ParquetReadOptions::default(),
)
.await
.unwrap();
let batches = ctx
.sql("SELECT count(*) FROM t WHERE s['a'] IS NULL")
.await
.unwrap()
.collect()
.await
.unwrap();
assert_eq!(
ScalarValue::try_from_array(batches[0].column(0), 0).unwrap(),
ScalarValue::Int64(Some(1)),
);
}
Loading