Skip to content
10 changes: 10 additions & 0 deletions crates/data/src/source/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -485,6 +485,12 @@ pub trait FeatureSource: Send + Sync {
fn skipped_at_open(&self) -> usize {
0
}
/// The smallest and largest value of a numeric field across the whole source, when the source
/// states them without being read (GeoParquet column statistics); `None` when any part of it
/// doesn't, or the field has no value.
fn field_range(&self, _field: &str) -> Option<(f64, f64)> {
None
}
/// Whether the source's notes ([`SourceInfo::notes`]) already count the features it keeps
/// with a place that can't be given in longitude/latitude, so a whole read doesn't count them
/// again.
Expand Down Expand Up @@ -754,6 +760,10 @@ impl FeatureSource for Fetching {
self.0.skipped_at_open()
}

fn field_range(&self, field: &str) -> Option<(f64, f64)> {
self.0.field_range(field)
}

fn says_unplaced_at_open(&self) -> bool {
self.0.says_unplaced_at_open()
}
Expand Down
53 changes: 53 additions & 0 deletions crates/data/src/source/parquet.rs
Original file line number Diff line number Diff line change
Expand Up @@ -489,6 +489,42 @@ impl FeatureSource for ParquetSource {
&self.info
}

/// From every row group's statistics of the field's column, which the footer holds: no byte of
Comment thread
elpidioassinaturas marked this conversation as resolved.
Resolved
/// the data is read. A row group without a statistics object, or whose statistics give no
/// bounds while it has values, or bounds that aren't finite and in order, leaves the range
/// unknown (`None`); one whose statistics count only nulls adds nothing. The field is named exactly
/// as the source lists it.
fn field_range(&self, field: &str) -> Option<(f64, f64)> {
Comment thread
elpidioassinaturas marked this conversation as resolved.
Resolved
let i = self.info.fields.iter().position(|f| f.name == field && f.ty.is_numeric())?;
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
let col = *self.field_cols.get(i)?;
let md = self.reader.metadata();
let desc = md.file_metadata().schema_descr().column(col);
// Unsigned integers are ordered as unsigned in the statistics, not as the values are read.
if matches!(desc.logical_type_ref(), Some(LogicalType::Integer(t)) if !t.is_signed)
|| matches!(
desc.converted_type(),
ConvertedType::UINT_8 | ConvertedType::UINT_16 | ConvertedType::UINT_32 | ConvertedType::UINT_64
)
{
return None;
}
let scale = decimal_scale(&desc).map_or(1.0, |s| 10f64.powi(-s));
let (lo, hi) = (0..md.num_row_groups()).try_fold((f64::INFINITY, f64::NEG_INFINITY), |(lo, hi), g| {
let rg = md.row_group(g);
let s = rg.columns().get(col)?.statistics()?;
match (number_stat(s, false), number_stat(s, true)) {
(Some(a), Some(b)) => {
let (a, b) = (a * scale, b * scale);
(a.is_finite() && b.is_finite() && a <= b).then(|| (lo.min(a), hi.max(b)))
}
// A row group of nulls only has no bounds.
_ if s.null_count_opt() == Some(u64::try_from(rg.num_rows()).ok()?) => Some((lo, hi)),
_ => None,
}
})?;
(lo.is_finite() && hi.is_finite() && lo <= hi).then_some((lo, hi))
}

fn reads_own_box(&self) -> bool {
true
}
Expand Down Expand Up @@ -1071,6 +1107,23 @@ fn stat(s: Option<&Statistics>, max: bool) -> Option<f64> {
}
}

/// A numeric column's smallest or largest value in a row group's statistics.
fn number_stat(s: &Statistics, max: bool) -> Option<f64> {
match s {
Statistics::Int32(v) => (if max { v.max_opt() } else { v.min_opt() }).map(|x| f64::from(*x)),
// Past 2^53, the next double out, so the bound still holds every value.
Statistics::Int64(v) => (if max { v.max_opt() } else { v.min_opt() }).map(|&x| {
let y = x as f64;
match (y as i128).cmp(&i128::from(x)) {
std::cmp::Ordering::Less if max => y.next_up(),
std::cmp::Ordering::Greater if !max => y.next_down(),
_ => y,
}
}),
_ => stat(Some(s), max),
}
}

/// A row group's bounding box from its covering statistics.
fn group_extent(md: &ParquetMetaData, g: usize, c: [usize; 4]) -> Option<Extent> {
let rg = md.row_groups().get(g)?;
Expand Down
121 changes: 121 additions & 0 deletions crates/data/src/source/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5103,6 +5103,127 @@ fn write_projected_parquet_fixture(ds: &Dataset, path: &Path, rows: usize, dicti
writer.close().unwrap();
}

/// A GeoParquet field's range comes from its column statistics; text, missing and all-null
/// fields have none (#2497).
#[test]
fn geoparquet_field_range_comes_from_column_statistics() {
let fields = vec![
Field::new("height", FieldType::Double),
Field::new("floors", FieldType::Integer),
Field::new("name", FieldType::Text),
Field::new("empty", FieldType::Double),
];
let mut ds = Dataset::new("b", crate::GeometryType::Point, fields);
for (i, h) in [3.5, -2.0, 41.25].into_iter().enumerate() {
let floors = if i == 1 { Value::Null } else { Value::Int(i as i64 * 7 - 3) };
ds.push(Some(Geometry::Point(Coord::new(i as f64, 0.0))), vec![Value::Float(h), floors, Value::Text("x".into()), Value::Null]);
}
let source = parquet::ParquetSource::open_bytes(parquet::write(&ds).unwrap(), "b").unwrap();
assert_eq!(source.field_range("height"), Some((-2.0, 41.25)));
assert_eq!(source.field_range("floors"), Some((-3.0, 11.0)));
for none in ["name", "empty", "nope"] {
assert_eq!(source.field_range(none), None, "{none}");
}
// A wrapper says the same.
#[cfg(not(target_arch = "wasm32"))]
assert_eq!(Fetching(Arc::new(source)).field_range("height"), Some((-2.0, 41.25)));
}

/// The column statistics that can't give a field's range, and the ones scaled or rounded to
/// hold every value: unsigned integers, a column without statistics, decimals, and Int64 past
/// 2^53 (#2497).
#[test]
fn geoparquet_field_range_refuses_unsigned_and_missing_statistics() {
use ::parquet::data_type::{ByteArray, ByteArrayType, DoubleType, Int32Type, Int64Type};
use ::parquet::file::properties::{EnabledStatistics, WriterProperties};
use ::parquet::file::writer::SerializedFileWriter;
use ::parquet::schema::types::ColumnPath;
let schema = ::parquet::schema::parser::parse_message_type(
"message m { REQUIRED BINARY geometry; OPTIONAL INT32 count (UINT_32); OPTIONAL INT64 price (DECIMAL(10,2)); OPTIONAL INT64 big; OPTIONAL DOUBLE bare; }",
)
.unwrap();
let props = WriterProperties::builder().set_column_statistics_enabled(ColumnPath::from("bare"), EnabledStatistics::None).build();
let mut bytes = Vec::new();
let mut w = SerializedFileWriter::new(&mut bytes, Arc::new(schema), Arc::new(props)).unwrap();
let mut rg = w.next_row_group().unwrap();
let geom = ByteArray::from(wkb::encode(&Geometry::Point(Coord::new(0.0, 0.0))));
let mut col = rg.next_column().unwrap().unwrap();
col.typed::<ByteArrayType>().write_batch(&[geom.clone(), geom], None, None).unwrap();
col.close().unwrap();
let mut col = rg.next_column().unwrap().unwrap();
col.typed::<Int32Type>().write_batch(&[1, -1], Some(&[1, 1]), None).unwrap();
col.close().unwrap();
let big = (1i64 << 53) + 1;
for values in [[12_345, -50], [-big, big]] {
let mut col = rg.next_column().unwrap().unwrap();
col.typed::<Int64Type>().write_batch(&values, Some(&[1, 1]), None).unwrap();
col.close().unwrap();
}
let mut col = rg.next_column().unwrap().unwrap();
col.typed::<DoubleType>().write_batch(&[1.0, 2.0], Some(&[1, 1]), None).unwrap();
col.close().unwrap();
rg.close().unwrap();
w.close().unwrap();
let source = parquet::ParquetSource::open_bytes(bytes, "m").unwrap();
let kinds: Vec<_> = source.info().fields.iter().map(|f| (f.name.as_str(), f.ty)).collect();
assert!(kinds.contains(&("count", FieldType::Integer)) && kinds.contains(&("bare", FieldType::Double)), "{kinds:?}");
assert_eq!(source.field_range("count"), None);
assert_eq!(source.field_range("bare"), None);
assert_eq!(source.field_range("price"), Some((-50.0 * 10f64.powi(-2), 12_345.0 * 10f64.powi(-2))));
let (lo, hi) = source.field_range("big").unwrap();
assert!(i128::from(big) <= hi as i128 && lo as i128 <= -i128::from(big), "{lo} {hi}");
}

/// Row groups whose statistics hold their smallest and largest value in order are joined; one that
/// gives them reversed leaves the range unknown, whatever the others give.
#[test]
fn geoparquet_field_range_checks_each_row_group() {
use ::parquet::data_type::{ByteArray, ByteArrayType, DoubleType, Int64Type};
use ::parquet::file::statistics::Statistics;
use ::parquet::file::writer::SerializedFileWriter;
let schema = ::parquet::schema::parser::parse_message_type(
"message m { REQUIRED BINARY geometry; REQUIRED INT64 whole; REQUIRED DOUBLE real; }",
)
.unwrap();
let mut bytes = Vec::new();
let mut w = SerializedFileWriter::new(&mut bytes, Arc::new(schema), Arc::default()).unwrap();
let geom = ByteArray::from(wkb::encode(&Geometry::Point(Coord::new(0.0, 0.0))));
for (lo, hi) in [(10, 20), (40, 50)] {
let mut rg = w.next_row_group().unwrap();
let mut col = rg.next_column().unwrap().unwrap();
col.typed::<ByteArrayType>().write_batch(&[geom.clone(), geom.clone()], None, None).unwrap();
col.close().unwrap();
let mut col = rg.next_column().unwrap().unwrap();
col.typed::<Int64Type>().write_batch(&[lo, hi], None, None).unwrap();
col.close().unwrap();
let mut col = rg.next_column().unwrap().unwrap();
col.typed::<DoubleType>().write_batch(&[lo as f64, hi as f64], None, None).unwrap();
col.close().unwrap();
rg.close().unwrap();
}
w.close().unwrap();
let open = |bytes| parquet::ParquetSource::open_bytes(bytes, "m").unwrap();
let source = open(bytes.clone());
assert_eq!((source.field_range("whole"), source.field_range("real")), (Some((10.0, 50.0)), Some((10.0, 50.0))));
// The second group's bounds, swapped where the footer holds them.
let len = u32::from_le_bytes(bytes[bytes.len() - 8..bytes.len() - 4].try_into().unwrap()) as usize;
let footer = bytes.len() - 8 - len;
for (a, b) in [(40i64.to_le_bytes(), 50i64.to_le_bytes()), (40f64.to_le_bytes(), 50f64.to_le_bytes())] {
for at in footer..bytes.len() - 8 {
if bytes[at..at + 8] == a {
bytes[at..at + 8].copy_from_slice(&b);
} else if bytes[at..at + 8] == b {
bytes[at..at + 8].copy_from_slice(&a);
}
}
}
let md = ::parquet::file::metadata::ParquetMetaDataReader::new().parse_and_finish(&bytes::Bytes::from(bytes.clone())).unwrap();
let Some(Statistics::Int64(st)) = md.row_group(1).column(1).statistics() else { panic!() };
assert_eq!((st.min_opt(), st.max_opt()), (Some(&50), Some(&40)));
let source = open(bytes);
assert_eq!((source.field_range("whole"), source.field_range("real")), (None, None));
}

/// The spatial index, loaded after the rows in Hilbert order, holds one entry with the box of
/// each feature that has a place (none for one without), and the same layer gives the same index
/// nodes each time.
Expand Down
Loading
Loading