Skip to content
Merged
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
4 changes: 2 additions & 2 deletions crates/data/src/source/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -728,7 +728,7 @@ pub fn open_path(path: &Path, layer: Option<&str>) -> Result<Box<dyn FeatureSour
pub fn open_path_for_fields(path: &Path, layer: Option<&str>, saved: &[crate::Field]) -> Result<Box<dyn FeatureSource>> {
let name = path.file_stem().and_then(|s| s.to_str()).unwrap_or("layer").to_string();
match ext(path).as_str() {
"parquet" | "geoparquet" => Ok(Box::new(parquet::ParquetSource::open_path(path, &name)?)),
"parquet" | "geoparquet" => parquet::open_any_path(path, &name),
Comment thread
elpidioassinaturas marked this conversation as resolved.
Resolved
Comment thread
elpidioassinaturas marked this conversation as resolved.
Resolved
"fgb" => Ok(Box::new(fgb::FgbSource::open_path(path, &name)?)),
"las" | "laz" => Ok(Box::new(lidar::LidarSource::open_path(path, &name)?)),
#[cfg(not(target_arch = "wasm32"))]
Expand Down Expand Up @@ -768,7 +768,7 @@ pub fn open_shared(file_name: &str, bytes: std::sync::Arc<Vec<u8>>, layer: Optio
let name = path.file_stem().and_then(|s| s.to_str()).unwrap_or("layer").to_string();
let bytes = Shared(bytes);
match ext(path).as_str() {
"parquet" | "geoparquet" => Ok(Box::new(parquet::ParquetSource::open_shared(bytes, &name)?)),
"parquet" | "geoparquet" => parquet::open_any_shared(bytes, &name),
"fgb" => Ok(Box::new(fgb::FgbSource::open_shared(bytes, &name)?)),
"las" | "laz" => Ok(Box::new(lidar::LidarSource::open_bytes(bytes.as_ref(), &name)?)),
// The desktop reads GeoPackages with SQLite (and its R-tree); the browser, which has no
Expand Down
26 changes: 26 additions & 0 deletions crates/data/src/source/parquet.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,9 @@
//! downloaded whole instead.

mod declared;
mod table;

pub use table::{ParquetTable, TABLE_FORMAT};

use super::remote::{self, Remote};
use super::{Batch, FeatureSource, Reproject, Request, Sampler, SourceInfo, clamp_limit};
Expand Down Expand Up @@ -249,6 +252,29 @@ impl ParquetSource {
}
}

/// Opens a Parquet file: a GeoParquet as a layer's source, and one with no geometry column at all
/// as a standalone table's ([`ParquetTable`], #3539).
pub fn open_any_path(path: &Path, name: &str) -> Result<Box<dyn FeatureSource>> {
match ParquetSource::open_path(path, name) {
Err(e) if declared::no_geometry(&e) => {
let reader = SerializedFileReader::new(crate::provenance::open(path)?).map_err(err)?;
Ok(Box::new(ParquetTable::new(Arc::new(reader), name, Some(path))))
}
opened => Ok(Box::new(opened?)),
}
}

/// [`open_any_path`], for a file held in memory.
pub fn open_any_shared(bytes: super::Shared, name: &str) -> Result<Box<dyn FeatureSource>> {
match ParquetSource::open_shared(bytes.clone(), name) {
Err(e) if declared::no_geometry(&e) => {
let reader = SerializedFileReader::new(Bytes::from_owner(bytes)).map_err(err)?;
Ok(Box::new(ParquetTable::new(Arc::new(reader), name, None)))
}
opened => Ok(Box::new(opened?)),
}
}

/// The metadata of a file by its web address, from its footer: fails with [`remote::NEED`] until
/// the footer is fetched.
fn remote_reader(file: &Arc<Remote>) -> Result<Arc<RemoteFile>> {
Expand Down
10 changes: 9 additions & 1 deletion crates/data/src/source/parquet/declared.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,14 @@ use crate::raster::wkt::clip;
use parquet::basic::LogicalType;
use serde_json::{Value, json};

/// The error of a file with no geometry column at all, which opens as a standalone table (#3539).
const NO_GEOMETRY: &str = "not a GeoParquet file: no geometry column";

/// Whether `e` says the file has no geometry column at all ([`NO_GEOMETRY`]).
pub(super) fn no_geometry(e: &DataError) -> bool {
matches!(e, DataError::Format(m) if m == NO_GEOMETRY)
}

/// The names taken for a geometry column's when nothing says which column it is.
const USUAL_NAMES: [&str; 5] = ["geometry", "geom", "wkb_geometry", "the_geom", "wkb"];

Expand Down Expand Up @@ -87,7 +95,7 @@ impl Column {
let found = usual(&natives)
.or_else(|| natives.first().copied())
.or_else(|| usual(&named))
.ok_or_else(|| DataError::Format("not a GeoParquet file: no geometry column".into()))?;
.ok_or_else(|| DataError::Format(NO_GEOMETRY.into()))?;
if natives.len() > 1 {
notes.push(format!(
"it has {} geometry columns and nothing says which is the main one: '{}' is read",
Expand Down
165 changes: 165 additions & 0 deletions crates/data/src/source/parquet/table.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,165 @@
//! A Parquet file with no geometry column, read as a standalone table (#3539): its top-level
//! columns with the types the GeoParquet reader gives attribute columns, and every row, within the
//! limits of a GeoParquet's row groups.

use super::{Budget, ColumnValues, FileReader, column_kind, err, field_type, max_decoded_bytes, read_values, whole_group};
use crate::source::{Batch, FeatureSource, MAX_READ_BYTES, Request, SourceInfo, clamp_limit};
use crate::{DataError, Feature, Field, GeometryType, Result};
use rustgis_geom::Extent;
use std::collections::HashSet;
use std::sync::Arc;

/// The format a [`ParquetTable`]'s [`SourceInfo`] gives, which tells it from a GeoParquet.
pub const TABLE_FORMAT: &str = "Parquet";

/// A Parquet file with no geometry column, whose rows have no place.
pub struct ParquetTable {
/// The local file, observed again at each read.
path: Option<std::path::PathBuf>,
info: SourceInfo,
reader: Arc<dyn FileReader>,
/// Leaf column index of each field, in `info.fields` order.
field_cols: Vec<usize>,
/// Most bytes the rows read may hold, across all row groups: [`MAX_READ_BYTES`], lowered by tests.
read_bytes: u64,
}

impl ParquetTable {
pub(super) fn new(reader: Arc<dyn FileReader>, name: &str, path: Option<&std::path::Path>) -> Self {
let md = reader.metadata();
let schema = md.file_metadata().schema_descr();
let (mut fields, mut field_cols) = (Vec::new(), Vec::new());
for i in 0..schema.num_columns() {
let c = schema.column(i);
if c.path().parts().len() != 1 || c.max_rep_level() != 0 {
continue;
}
if let Some(ty) = field_type(&c) {
Comment thread
elpidioassinaturas marked this conversation as resolved.
Resolved
fields.push(Field::new(c.name().to_string(), ty));
field_cols.push(i);
}
}
let read: HashSet<&str> = fields.iter().map(|f| f.name.as_str()).collect();
let left_out: Vec<(String, String)> = schema
.root_schema()
.get_fields()
.iter()
.filter(|t| !read.contains(t.name()))
.map(|t| (t.name().to_string(), column_kind(t).to_string()))
.collect();
let mut info = SourceInfo {
name: name.to_string(),
format: TABLE_FORMAT,
geometry_type: GeometryType::None,
fields,
extent: Extent::EMPTY,
count: u64::try_from(md.file_metadata().num_rows()).ok(),
crs: String::new(),
indexed: false,
notes: Default::default(),
zm_dropped: false,
};
info.note_columns(
&left_out,
["of a type RustGIS has no field for was left out", "of types RustGIS has no field for were left out"],
);
ParquetTable { path: path.map(std::path::Path::to_path_buf), info, reader, field_cols, read_bytes: MAX_READ_BYTES }
Comment thread
elpidioassinaturas marked this conversation as resolved.
Resolved
}
}

impl FeatureSource for ParquetTable {
fn info(&self) -> &SourceInfo {
&self.info
}

/// The first rows up to the request's limit, in the file's order; a read by place meets none.
/// A table whose rows would hold more than [`MAX_READ_BYTES`] is refused as it passes them.
fn read(&self, req: &Request) -> Result<Batch> {
if let Some(path) = &self.path {
crate::provenance::path(path);
}
let mut batch = Batch { complete: true, ..Batch::default() };
if req.extent.is_some() || req.own.is_some() {
return Ok(batch);
}
let limit = clamp_limit(req.limit);
let md = self.reader.metadata();
let (mut base, mut held) = (0u64, 0u64);
for g in 0..md.num_row_groups() {
Comment thread
elpidioassinaturas marked this conversation as resolved.
Resolved
crate::progress::check()?;
Comment thread
elpidioassinaturas marked this conversation as resolved.
Resolved
let rows = whole_group(g, md.row_group(g).num_rows(), super::MAX_GROUP_ROWS)?;
Comment thread
elpidioassinaturas marked this conversation as resolved.
Resolved
batch.matched = batch.matched.saturating_add(rows as u64);
let wanted = rows.min(limit.saturating_sub(batch.features.len()));
if wanted > 0 {
let take: Vec<bool> = (0..rows).map(|r| r < wanted).collect();
let rg = self.reader.get_row_group(g).map_err(err)?;
let budget = Budget::new(max_decoded_bytes(), g);
let attrs: Vec<ColumnValues> =
self.field_cols.iter().map(|&c| read_values(rg.as_ref(), c, &take, &budget)).collect::<Result<_>>()?;
if attrs.iter().any(|a| a.values.len() != wanted) {
return Err(DataError::Format(format!("Parquet: row group {g} has columns shorter than its rows")));
}
for k in 0..wanted {
let attrs = attrs
.iter()
.enumerate()
.map(|(field, col)| col.value(k, field, &mut batch.unread_dates, &mut batch.rounded_dates))
.collect();
let feature = Feature { id: base.saturating_add(k as u64 + 1), geometry: None, attrs };
held = held.saturating_add(crate::source::memory::feature_bytes(&feature) as u64);
if held > self.read_bytes {
Comment thread
elpidioassinaturas marked this conversation as resolved.
Resolved
return Err(DataError::Format(format!(
"{}: the table holds more than the {} MiB read at once: add a file with fewer rows or columns",
self.info.name,
self.read_bytes >> 20
)));
}
batch.features.push(feature);
}
}
base = base.saturating_add(rows as u64);
}
batch.complete = batch.features.len() as u64 == batch.matched;
Ok(batch)
}
}

#[cfg(test)]
mod tests {
use super::*;
use crate::{Dataset, FieldType, Value};
use parquet::file::reader::SerializedFileReader;

/// A table whose rows hold more than the budget is refused, saying what to do; one within it is
/// read whole.
#[test]
fn a_table_past_the_read_budget_is_refused() {
let mut ds = Dataset::new("t", GeometryType::None, vec![Field::new("note", FieldType::Text)]);
for i in 0..100u64 {
ds.features.push(Feature { id: i + 1, geometry: None, attrs: vec![Value::Text("x".repeat(1000))] });
}
let bytes = bytes::Bytes::from(super::super::write(&ds).unwrap());
let open = |read_bytes| {
let reader = SerializedFileReader::new(bytes.clone()).unwrap();
ParquetTable { read_bytes, ..ParquetTable::new(Arc::new(reader), "t", None) }
};
let held: u64 = ds.features.iter().map(|f| crate::source::memory::feature_bytes(f) as u64).sum();
let read = open(held).read(&Request::all()).unwrap();
assert_eq!((read.features.len(), read.complete), (100, true));
let error = open(held - 1).read(&Request::all()).unwrap_err().to_string();
assert!(error.contains("t: the table holds more than") && error.contains("fewer rows or columns"), "{error}");
}

/// A read whose run was cancelled stops instead of reading the rows.
#[test]
fn a_cancelled_read_stops() {
let mut ds = Dataset::new("t", GeometryType::None, vec![Field::new("n", FieldType::Integer)]);
ds.features.push(Feature { id: 1, geometry: None, attrs: vec![Value::Int(7)] });
let reader = SerializedFileReader::new(bytes::Bytes::from(super::super::write(&ds).unwrap())).unwrap();
let table = ParquetTable::new(Arc::new(reader), "t", None);
let probe = Arc::new(crate::progress::tests::Counted::default());
probe.cancel.store(true, std::sync::atomic::Ordering::Relaxed);
let _g = crate::progress::install(Some(probe));
assert!(matches!(table.read(&Request::all()), Err(DataError::Cancelled)));
}
}
73 changes: 73 additions & 0 deletions crates/data/src/source/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6841,3 +6841,76 @@ fn a_streamed_geopackage_loads_its_index_in_runs() {
assert_eq!(rows.iter().map(|r| r.0).collect::<Vec<_>>(), placed, "one entry for each feature with a place");
assert_eq!(nodes, read(&files[1]).1, "the same layer builds the same index");
}

/// The plain table of #3539: a code, a rate, a name, a flag, a day and a moment, with no geometry.
fn plain_parquet_table(rows: i64) -> Dataset {
let fields = vec![
Field::new("code", FieldType::Integer),
Field::new("rate", FieldType::Double),
Field::new("name", FieldType::Text),
Field::new("open", FieldType::Boolean),
Field::new("day", FieldType::Date),
Field::new("at", FieldType::DateTime),
];
let mut ds = Dataset::new("srag", crate::GeometryType::None, fields);
for i in 0..rows {
let attrs = vec![
Value::Int(3_106_200 + i),
Value::Float(0.5 * i as f64),
Value::Text(format!("m{i}")),
Value::Bool(i % 2 == 0),
Value::Date(crate::Date::from_days(20_727 + i).unwrap()),
Value::DateTime(crate::DateTime::local(1_790_856_000_000_000 + i * 1_000_000).unwrap()),
];
ds.features.push(crate::Feature { id: i as u64 + 1, geometry: None, attrs });
}
ds
}

/// A Parquet file with no geometry column opens as a standalone table: no geometry, every
/// column with its type and every row (#3539).
#[test]
fn parquet_without_a_geometry_column_opens_as_a_table() {
Comment thread
elpidioassinaturas marked this conversation as resolved.
Resolved
let ds = plain_parquet_table(5);
let bytes = parquet::write(&ds).unwrap();
let src = open_bytes("srag.parquet", bytes, None).unwrap();
assert_eq!(src.info().geometry_type, crate::GeometryType::None);
assert_eq!(src.info().fields, ds.fields);
assert_eq!(src.info().count, Some(5));
let (table, _) = materialize(src.as_ref()).unwrap();
assert_eq!(table.geometry_type, crate::GeometryType::None);
assert_eq!(table.fields, ds.fields);
let rows: Vec<&Vec<Value>> = table.features.iter().map(|f| &f.attrs).collect();
assert_eq!(rows, ds.features.iter().map(|f| &f.attrs).collect::<Vec<_>>());
assert!(table.features.iter().all(|f| f.geometry.is_none()));
}

/// A file whose GeoParquet metadata names a geometry column it hasn't still fails as it did, and a
/// GeoParquet still opens as a layer (#3539).
#[test]
fn parquet_naming_a_missing_geometry_column_still_fails() {
use ::parquet::data_type::Int64Type;
use ::parquet::file::metadata::KeyValue;
use ::parquet::file::{properties::WriterProperties, writer::SerializedFileWriter};
let schema = ::parquet::schema::parser::parse_message_type("message m { REQUIRED INT64 code; }").unwrap();
let geo = r#"{"version":"1.1.0","primary_column":"geom","columns":{"geom":{"encoding":"WKB"}}}"#;
let props = WriterProperties::builder().set_key_value_metadata(Some(vec![KeyValue::new("geo".into(), geo.to_string())])).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 mut col = rg.next_column().unwrap().unwrap();
col.typed::<Int64Type>().write_batch(&[1, 2], None, None).unwrap();
col.close().unwrap();
rg.close().unwrap();
w.close().unwrap();
let error = open_bytes("named.parquet", bytes, None).err().expect("a missing named geometry column is an error").to_string();
assert!(error.contains("no column 'geom'"), "{error}");

let mut points = Dataset::new("pts", crate::GeometryType::Point, vec![Field::new("n", FieldType::Integer)]);
points.features.push(crate::Feature { id: 1, geometry: Some(Geometry::Point(Coord::new(1.0, 2.0))), attrs: vec![Value::Int(7)] });
let src = open_bytes("pts.parquet", parquet::write(&points).unwrap(), None).unwrap();
assert_eq!((src.info().format, src.info().geometry_type), ("GeoParquet", crate::GeometryType::Point));
let batch = src.read(&Request::all()).unwrap();
assert_eq!(batch.features[0].attrs, [Value::Int(7)]);
assert!(batch.features[0].geometry.is_some());
}
Loading
Loading