diff --git a/crates/data/src/source/mod.rs b/crates/data/src/source/mod.rs index edb3505f48..4a64d8a113 100644 --- a/crates/data/src/source/mod.rs +++ b/crates/data/src/source/mod.rs @@ -728,7 +728,7 @@ pub fn open_path(path: &Path, layer: Option<&str>) -> Result, saved: &[crate::Field]) -> Result> { 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), "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"))] @@ -768,7 +768,7 @@ pub fn open_shared(file_name: &str, bytes: std::sync::Arc>, 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 diff --git a/crates/data/src/source/parquet.rs b/crates/data/src/source/parquet.rs index fbb99f3a2e..82bb826ac7 100644 --- a/crates/data/src/source/parquet.rs +++ b/crates/data/src/source/parquet.rs @@ -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}; @@ -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> { + 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> { + 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) -> Result> { diff --git a/crates/data/src/source/parquet/declared.rs b/crates/data/src/source/parquet/declared.rs index adbb1371da..d53dc6319f 100644 --- a/crates/data/src/source/parquet/declared.rs +++ b/crates/data/src/source/parquet/declared.rs @@ -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"]; @@ -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", diff --git a/crates/data/src/source/parquet/table.rs b/crates/data/src/source/parquet/table.rs new file mode 100644 index 0000000000..aa41243c6d --- /dev/null +++ b/crates/data/src/source/parquet/table.rs @@ -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, + info: SourceInfo, + reader: Arc, + /// Leaf column index of each field, in `info.fields` order. + field_cols: Vec, + /// 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, 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) { + 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 } + } +} + +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 { + 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() { + crate::progress::check()?; + let rows = whole_group(g, md.row_group(g).num_rows(), super::MAX_GROUP_ROWS)?; + 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 = (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 = + self.field_cols.iter().map(|&c| read_values(rg.as_ref(), c, &take, &budget)).collect::>()?; + 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 { + 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))); + } +} diff --git a/crates/data/src/source/tests.rs b/crates/data/src/source/tests.rs index 5efb02bcff..f7dbf65d33 100644 --- a/crates/data/src/source/tests.rs +++ b/crates/data/src/source/tests.rs @@ -6841,3 +6841,76 @@ fn a_streamed_geopackage_loads_its_index_in_runs() { assert_eq!(rows.iter().map(|r| r.0).collect::>(), 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() { + 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> = table.features.iter().map(|f| &f.attrs).collect(); + assert_eq!(rows, ds.features.iter().map(|f| &f.attrs).collect::>()); + 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::().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()); +} diff --git a/crates/engine/src/cmd/layer.rs b/crates/engine/src/cmd/layer.rs index 2e0256d0e8..f86327b482 100644 --- a/crates/engine/src/cmd/layer.rs +++ b/crates/engine/src/cmd/layer.rs @@ -2109,6 +2109,13 @@ fn add_data(s: &mut Session, p: &Value) -> CmdResult { return add_layer_file(s, path); } if rustgis_data::source::is_source_name(path) { + // A Parquet file opened ahead in the desktop app, a table read whole there ([`in_place_ahead`]). + #[cfg(not(target_arch = "wasm32"))] + if is_parquet_name(path) + && let Some(Opened { source, whole, .. }) = take_opened(s, path, None) + { + return add_source_read(s, p, Origin::Path(path), Some(source.map_err(|e| format!("{path}: {e}"))?), whole, None); + } return add_source(s, p, Origin::Path(path), None); } // Only a possible city model is read whole; ordinary GeoJSON keeps its streaming path. @@ -2611,6 +2618,10 @@ fn link_choice(path: &str, tables: &[String]) -> Option { rustgis_data::progress::check().ok()?; let src = rustgis_data::source::open_path(Path::new(path), table).ok()?; // One table read in place links them all, so those after it aren't opened. + // A Parquet file with no geometry column is a table, always read whole: nothing to ask (#3539). + if src.info().format == rustgis_data::source::parquet::TABLE_FORMAT { + return None; + } if streams_by_count(src.info().count) { linked = true; break; @@ -2623,7 +2634,8 @@ fn link_choice(path: &str, tables: &[String]) -> Option { Some(json!({"linked": linked, "copy": copy})) } -/// A large Shapefile or GeoJSON file, read in place, as Add Data opens it ahead (#2446). +/// A large Shapefile or GeoJSON file, read in place, or a Parquet file, as Add Data opens it ahead +/// (#2446, #3539). #[cfg(not(target_arch = "wasm32"))] pub(crate) struct Opened { /// The size and modification time of the file and those beside it of its name (a @@ -2661,6 +2673,13 @@ impl Opened { } } +/// Whether `path` names a Parquet file, which Add Data opens ahead ([`in_place_ahead`]). +#[cfg(not(target_arch = "wasm32"))] +fn is_parquet_name(path: &str) -> bool { + let lower = path.to_ascii_lowercase(); + lower.ends_with(".parquet") || lower.ends_with(".geoparquet") +} + /// The size and modification time (where the file system keeps one) of `path` and of the files /// beside it with the same name before the extension, in any case (a Shapefile's parts), by name. /// One that names no file (a dangling link) is left out, as the opening can't read it either; @@ -2718,6 +2737,22 @@ fn in_place_ahead(p: &Value, path: &str) -> Option { let lower = path.to_ascii_lowercase(); let name = Path::new(path).file_stem().and_then(|n| n.to_str()).unwrap_or("layer").to_string(); let given = |k: &str| ps(p, k).is_some_and(|v| !v.trim().is_empty()); + // A Parquet file: one with no geometry column is a standalone table, read whole here (#3539); + // a GeoParquet is only opened, and add_data reads it as before. + if is_parquet_name(path) { + let path = path.to_string(); + return Some(super::reads::ahead(NAME, in_place_key(&path, None), move || { + let stamp = file_stamp(&path); + let source = rustgis_data::source::open_path(Path::new(&path), None); + let whole = match &source { + Ok(src) if src.info().format == rustgis_data::source::parquet::TABLE_FORMAT => { + Some(rustgis_data::source::materialize(src.as_ref())) + } + _ => None, + }; + Opened { stamp, source, whole } + })); + } if is_geojson(path) && !rustgis_data::cityjson::is_cityjson_name(path) // Match add_data's bounded city-model probe before opening GeoJSON in place. @@ -3556,6 +3591,13 @@ fn add_source_read( })?, }; let info = src.info().clone(); + // A Parquet file with no geometry column is a standalone table, read whole (#3539). + if info.format == source::parquet::TABLE_FORMAT { + let (mut ds, report) = whole.take().unwrap_or_else(|| source::materialize(src.as_ref())).map_err(err)?; + // Kept, so a tool's output can't write over the file the table was read from. + ds.source = Some(label.clone()); + return add_read(s, p, (ds, report), zoom); + } // A point cloud is always read in place, so a project keeps its file's path, not millions // of points; its colours come from a sample of it. let lidar = info.format == "LiDAR"; @@ -9357,4 +9399,24 @@ mod geodatabase_tests { assert!(super::asks_link(path) && super::link_choice(path, &[]).is_some(), "{path:?}"); } } + + /// A Parquet file with no geometry column is a table, always read whole (#3539): Add Data asks + /// nothing about it, however many rows it has, as an answer of Link would go unheard. + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn link_choice_asks_nothing_about_a_parquet_table() { + use rustgis_data::{Dataset, Feature, Field, FieldType, GeometryType, Value}; + let mut ds = Dataset::new("t", GeometryType::None, vec![Field::new("n", FieldType::Integer)]); + let rows = rustgis_map::source::STREAM_ABOVE + 1; + ds.features = (1..=rows).map(|id| Feature { id, geometry: None, attrs: vec![Value::Int(id as i64)] }).collect(); + let dir = std::env::temp_dir().join(format!("rustgis-link-parquet-table-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("t.parquet"); + std::fs::write(&path, rustgis_data::source::parquet::write(&ds).unwrap()).unwrap(); + let path = path.to_str().unwrap(); + // The tables as Add Data's listing gives them: the file's one layer. + let tables = ["t".to_string()]; + assert!(super::asks_link(path) && super::link_choice(path, &tables).is_none(), "{:?}", super::link_choice(path, &tables)); + let _ = std::fs::remove_dir_all(&dir); + } } diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 1dacd58ac3..cd55a9c977 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -66963,3 +66963,65 @@ fn gp_batch_says_special_files_in_a_folder_apart_from_unreadable_entries() { assert!(!said.iter().any(|n| n.contains("unreadable")), "{said:?}"); let _ = std::fs::remove_dir_all(&root); } + +/// `layer.addData` adds a Parquet file without a geometry column as a standalone table, with its +/// columns' types and every row, and a GeoParquet still as a layer (#3539). +#[test] +fn parquet_without_geometry_is_added_as_a_standalone_table() { + use rustgis_data::{Dataset, Feature, Field, FieldType, Geometry, GeometryType, Value as Cell}; + let fields = vec![ + Field::new("CO_MUN_RES", 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", GeometryType::None, fields.clone()); + for i in 0..4i64 { + let attrs = vec![ + Cell::Int(3_106_200 + i), + Cell::Float(0.25 * i as f64), + Cell::Text(format!("m{i}")), + Cell::Bool(i % 2 == 1), + Cell::Date(rustgis_data::Date::from_days(20_727 + i).unwrap()), + Cell::DateTime(rustgis_data::DateTime::local(1_790_856_000_000_000 + i).unwrap()), + ]; + ds.features.push(Feature { id: i as u64 + 1, geometry: None, attrs }); + } + let dir = std::env::temp_dir().join(format!("rustgis-parquet-table-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("INFLUD26.parquet"); + std::fs::write(&path, rustgis_data::source::parquet::write(&ds).unwrap()).unwrap(); + let mut s = Session::new(Project::default()); + let r = s.run("layer.addData", &json!({"path": path})).unwrap(); + assert_eq!(r["table"], "INFLUD26", "{r}"); + let id = r["id"].as_u64().and_then(|i| u32::try_from(i).ok()).expect("a table id"); + assert!(r.get("layer").is_none() && s.map().layers.is_empty(), "{r}"); + let table = &s.project.table(id).expect("the table").dataset; + assert_eq!(table.geometry_type, GeometryType::None); + assert_eq!(table.fields, fields); + let rows: Vec<&Vec> = table.features.iter().map(|f| &f.attrs).collect(); + assert_eq!(rows, ds.features.iter().map(|f| &f.attrs).collect::>()); + // Its file is kept, which a tool's output may not write over. + assert_eq!(table.source.as_deref(), Some(path.to_str().unwrap())); + + // The desktop app reads the table ahead, on a thread of its own, and lands it as the command. + let mut app = Session::new(Project::default()); + let p = json!({"path": path.display().to_string()}); + let ahead = crate::cmd::reads::read_ahead(&mut app, "layer.addData", &p).unwrap(); + assert!(ahead.reads(), "read ahead"); + let read = ahead.run(&rustgis_analysis::control::Control::new()).unwrap(); + let r = crate::cmd::reads::read_land(&mut app, read).unwrap(); + let id = r["id"].as_u64().and_then(|i| u32::try_from(i).ok()).expect("a table id"); + assert_eq!(app.project.table(id).expect("the table").dataset.features.len(), 4, "{r}"); + assert!(app.read_ahead.is_none() && app.map().layers.is_empty(), "{r}"); + + let mut points = Dataset::new("pts", GeometryType::Point, vec![Field::new("n", FieldType::Integer)]); + points.features.push(Feature { id: 1, geometry: Some(Geometry::Point(rustgis_geom::Coord::new(1.0, 2.0))), attrs: vec![Cell::Int(7)] }); + let geo = dir.join("pts.parquet"); + std::fs::write(&geo, rustgis_data::source::parquet::write(&points).unwrap()).unwrap(); + let r = s.run("layer.addData", &json!({"path": geo})).unwrap(); + assert!(r.get("layer").is_some() && r.get("table").is_none(), "{r}"); + std::fs::remove_dir_all(&dir).ok(); +}