From 5f168f08daa24149904214049df0971e2da39b70 Mon Sep 17 00:00:00 2001 From: mavrick Date: Tue, 24 Nov 2026 06:00:12 -0600 Subject: [PATCH 1/7] feat(data): readers say features, geometry and values they leave out, and systems they assume, with loss codes (#2371) New codes: dropped.feature, dropped.geometry, dropped.over-limit, approximated.curve and assumed.crs. The CSV reader's extra cells say dropped.extra-attributes, and a streamed Shapefile says the numbers in its .dbf that aren't finite, as a whole read already did. --- crates/data/src/citygml.rs | 2 +- crates/data/src/cityjson.rs | 2 +- crates/data/src/citymodel.rs | 16 +- crates/data/src/dbf.rs | 14 +- crates/data/src/dxf.rs | 55 ++++-- crates/data/src/esripbf.rs | 16 +- crates/data/src/esripbf/tests.rs | 20 ++- crates/data/src/filegdb.rs | 15 +- crates/data/src/georss.rs | 5 +- crates/data/src/gml.rs | 82 +++++---- crates/data/src/gpx.rs | 5 +- crates/data/src/io.rs | 163 ++++++++++++------ crates/data/src/kml.rs | 10 +- crates/data/src/landxml.rs | 26 ++- crates/data/src/lidar.rs | 35 +++- crates/data/src/loss.rs | 25 +++ crates/data/src/mapinfo.rs | 5 +- crates/data/src/ogc.rs | 2 +- crates/data/src/osm.rs | 39 +++-- crates/data/src/photo.rs | 5 +- crates/data/src/publish.rs | 4 +- crates/data/src/source/arcgis.rs | 4 +- crates/data/src/source/fgb.rs | 18 +- crates/data/src/source/gdal.rs | 34 +++- crates/data/src/source/geojson.rs | 20 ++- crates/data/src/source/gpkg.rs | 4 +- crates/data/src/source/gpkg_mem.rs | 4 +- crates/data/src/source/mod.rs | 34 ++-- crates/data/src/source/mysql.rs | 21 ++- crates/data/src/source/own_box_tests.rs | 4 +- crates/data/src/source/parquet.rs | 9 +- crates/data/src/source/postgis.rs | 34 ++-- crates/data/src/source/shp.rs | 49 ++++-- crates/data/src/source/shp/index.rs | 20 +-- crates/data/src/source/shp/tests.rs | 2 +- crates/data/src/source/sqlserver.rs | 48 +++--- crates/data/src/source/tests.rs | 65 +++++-- crates/data/src/topojson.rs | 27 ++- .../tests/integration/never_silent_reading.rs | 12 +- docs/cli.md | 5 + 40 files changed, 653 insertions(+), 307 deletions(-) diff --git a/crates/data/src/citygml.rs b/crates/data/src/citygml.rs index c451a31dbc..aea5948686 100644 --- a/crates/data/src/citygml.rs +++ b/crates/data/src/citygml.rs @@ -341,7 +341,7 @@ fn read_with(file_name: &str, bytes: &[u8], given: Option, keep_named: bool } let Reading { counts, mut built, rows, reach, mut said, relations, .. } = reading; said.object_links += relate(&mut built, relations); - let mut notes = Vec::new(); + let mut notes = crate::loss::Notes::new(); let crs = coordinate_system(file_name, given, named, index.vertical_named, &reach, &mut notes)?; if let Some(other) = &index.other { notes.push(format!( diff --git a/crates/data/src/cityjson.rs b/crates/data/src/cityjson.rs index bb46b7ea2e..23b790fd64 100644 --- a/crates/data/src/cityjson.rs +++ b/crates/data/src/cityjson.rs @@ -305,7 +305,7 @@ fn read_with(file_name: &str, bytes: &[u8], given: Option, keep_named: bool for v in &mut vertices { *v = [v[0] * s[0] + t[0], v[1] * s[1] + t[1], v[2] * s[2] + t[2]]; } - let mut notes = Vec::new(); + let mut notes = crate::loss::Notes::new(); // A compound URN is read by its horizontal part; its vertical part, said when its heights // aren't metres upward, gives the heights' unit. let system = named_system(doc.metadata.as_ref()); diff --git a/crates/data/src/citymodel.rs b/crates/data/src/citymodel.rs index 672a8906c2..d2e5985fef 100644 --- a/crates/data/src/citymodel.rs +++ b/crates/data/src/citymodel.rs @@ -459,7 +459,7 @@ pub(crate) fn coordinate_system( named: Option<&str>, vertical_named: bool, reach: &Reach, - notes: &mut Vec, + notes: &mut crate::loss::Notes, ) -> Result { let crs = match (given, named) { (Some(crs), named) => { @@ -484,7 +484,7 @@ pub(crate) fn coordinate_system( DataError::Format(format!("{file_name}: it names a coordinate system RustGIS doesn't know ({system}); give one with the crs parameter of layer.addData (from the command line, Python or the AI Assistant)")) })?, (None, None) if reach.within(180.0, 90.0) => { - notes.push("the file names no coordinate system: its coordinates are read as longitude/latitude".into()); + notes.push(crate::loss::Note::loss(crate::loss::LossCode::AssumedCrs, "the file names no coordinate system: its coordinates are read as longitude/latitude")); return Ok(Crs::LonLat); } (None, None) => { @@ -497,7 +497,10 @@ pub(crate) fn coordinate_system( return Err(DataError::Format(format!("{file_name}: {} is a geocentric coordinate system, which isn't a map's", crs.label()))); } if crs == Crs::LonLat && !reach.within(180.5, 90.5) { - notes.push("coordinates are not longitude/latitude; RustGIS reads them as WGS 84 and they may draw out of place".into()); + notes.push(crate::loss::Note::loss( + crate::loss::LossCode::AssumedCrs, + "coordinates are not longitude/latitude; RustGIS reads them as WGS 84 and they may draw out of place", + )); } if let Some(unit) = crs.height_unit_not_metre().filter(|_| !vertical_named) { notes.push(format!( @@ -559,7 +562,7 @@ pub(crate) fn finish( mut rows: Vec, mut built: Vec, mut counts: Counts, - notes: Vec, + notes: crate::loss::Notes, crs: Crs, ) -> Result> { // Converted once every object is in: a reader that streams its objects knows its system, and @@ -1071,7 +1074,10 @@ fn layers(stem: &str, rows: Vec, built: &[Built], crs: Crs, counts: &mut Co if total > MAX_LAYERS && let Some((_, report)) = out.first_mut() { - report.messages.push(format!("{} of {total} layers are left out: only the first {MAX_LAYERS} are read", total - MAX_LAYERS)); + report.messages.push(crate::loss::Note::loss( + crate::loss::LossCode::DroppedOverLimit, + format!("{} of {total} layers are left out: only the first {MAX_LAYERS} are read", total - MAX_LAYERS), + )); } out } diff --git a/crates/data/src/dbf.rs b/crates/data/src/dbf.rs index b1bae6922d..d9059172c9 100644 --- a/crates/data/src/dbf.rs +++ b/crates/data/src/dbf.rs @@ -141,14 +141,14 @@ fn ldid_code_page(ldid: u8) -> Option { }) } -pub(crate) fn encoding(cpg: Option<&[u8]>, ldid: u8, notes: &mut Vec) -> DbfEncoding { +pub(crate) fn encoding(cpg: Option<&[u8]>, ldid: u8, notes: &mut crate::loss::Notes) -> DbfEncoding { if let Some(bytes) = cpg { let label = if bytes.len() <= MAX_CPG_BYTES { std::str::from_utf8(bytes).unwrap_or("") } else { "" }; let label = label.trim().trim_start_matches('\u{feff}').trim(); if let Some(encoding) = DbfEncoding::from_name(label) { return encoding; } - notes.push("Shapefile: unsupported or empty .cpg; using the .dbf code page, or UTF-8 if unavailable".into()); + notes.push("Shapefile: unsupported or empty .cpg; using the .dbf code page, or UTF-8 if unavailable"); } // No language driver: UTF-8, as it always was, without a note. if ldid == 0 { @@ -418,7 +418,7 @@ pub(crate) fn date(field: &[u8]) -> std::result::Result) -> Option> { +pub(crate) fn read_cpg(path: &std::path::Path, notes: &mut crate::loss::Notes) -> Option> { match try_read_cpg(path) { Ok(bytes) => bytes, Err(e) => { @@ -583,10 +583,10 @@ mod tests { #[test] fn a_page_rustgis_cant_decode_is_named_in_the_note() { - let mut notes = Vec::new(); + let mut notes = crate::loss::Notes::new(); assert!(matches!(encoding(None, 0x6C, &mut notes), DbfEncoding::Utf8)); assert_eq!(notes, ["Shapefile: unsupported .dbf code page 0x6C (code page 863, DOS French Canadian); using UTF-8"]); - let mut notes = Vec::new(); + let mut notes = crate::loss::Notes::new(); encoding(None, 0xFF, &mut notes); assert_eq!(notes, ["Shapefile: unsupported .dbf code page 0xFF; using UTF-8"]); } @@ -595,7 +595,7 @@ mod tests { /// and with a code page that can't be decoded; a code page that is decoded is named by it. #[test] fn utf8_is_what_text_is_read_as_unless_another_encoding_is_named() { - let read = |cpg: Option<&[u8]>, ldid| encoding(cpg, ldid, &mut Vec::new()).name(); + let read = |cpg: Option<&[u8]>, ldid| encoding(cpg, ldid, &mut crate::loss::Notes::new()).name(); for (cpg, ldid) in [(None, 0), (None, 0xF0), (Some(b"UTF-8".as_slice()), 0x03), (Some(b"65001".as_slice()), 0), (None, 0x6C)] { assert_eq!(read(cpg, ldid), "UTF-8"); } @@ -613,7 +613,7 @@ mod tests { /// aren't. A DOS page gives every byte a character. #[test] fn bytes_that_cant_be_read_are_those_the_declared_decoder_replaces() { - let page = |cpg: &[u8]| encoding(Some(cpg), 0, &mut Vec::new()); + let page = |cpg: &[u8]| encoding(Some(cpg), 0, &mut crate::loss::Notes::new()); let (sjis, big5, utf8) = (page(b"932"), page(b"950"), page(b"UTF-8")); assert!(sjis.malformed(b"X\x82") && sjis.malformed(b"\x82 ") && sjis.malformed(b"\xff")); assert!(!sjis.malformed(b"\x93\x8c\x8b\x9e") && !sjis.malformed(b"plain") && !sjis.malformed(b"")); diff --git a/crates/data/src/dxf.rs b/crates/data/src/dxf.rs index 8aed10c6d9..3b4512601c 100644 --- a/crates/data/src/dxf.rs +++ b/crates/data/src/dxf.rs @@ -1641,21 +1641,30 @@ pub fn read(file_name: &str, bytes: &[u8], opts: &Options) -> Result 0 { - report.messages.push(format!( - "{} entities of the drawing's layouts (paper space) were left out; add the drawing with \"paperSpace\" to draw them", - out.paper + report.messages.push(crate::loss::Note::loss( + crate::loss::LossCode::DroppedFeature, + format!( + "{} entities of the drawing's layouts (paper space) were left out; add the drawing with \"paperSpace\" to draw them", + out.paper + ), )); } if out.blocked > 0 { - report.messages.push(format!( - "{} inserted blocks (图块) were left out; add the drawing with \"blocks\": true to draw their contents", - out.blocked + report.messages.push(crate::loss::Note::loss( + crate::loss::LossCode::DroppedFeature, + format!("{} inserted blocks (图块) were left out; add the drawing with \"blocks\": true to draw their contents", out.blocked), )); } if out.trimmed { @@ -1670,13 +1679,19 @@ pub fn read(file_name: &str, bytes: &[u8], opts: &Options) -> Result = d.unread.iter().map(|(k, n)| format!("{n} {k}")).collect(); - report.messages.push(format!("entities RustGIS doesn't draw were left out: {}", kinds.join(", "))); + report.messages.push(crate::loss::Note::loss( + crate::loss::LossCode::DroppedFeature, + format!("entities RustGIS doesn't draw were left out: {}", kinds.join(", ")), + )); } let skipped = d.bad + out.cut; report.skipped = skipped; if skipped > 0 { - report.messages.push(format!( - "{skipped} entities couldn't be read or placed (missing blocks, blocks nested too deep or in a cycle) and were left out" + report.messages.push(crate::loss::Note::loss( + crate::loss::LossCode::DroppedFeature, + format!( + "{skipped} entities couldn't be read or placed (missing blocks, blocks nested too deep or in a cycle) and were left out" + ), )); } let transformer = match opts.crs.filter(|c| *c != Crs::LonLat) { @@ -1716,7 +1731,10 @@ pub fn read(file_name: &str, bytes: &[u8], opts: &Options) -> Result 0 { - rep.messages.push(format!("{lost} features couldn't be converted from {}", c.label())); + rep.messages.push(crate::loss::Note::loss( + crate::loss::LossCode::DroppedFeature, + format!("{lost} features couldn't be converted from {}", c.label()), + )); } } if transformer.is_none() { @@ -1870,7 +1888,7 @@ mod tests { ]); let layers = read("a.dxf", &bytes, &Options { crs: Some(Crs::LonLat), ..Options::default() }).unwrap(); assert_eq!(layers[0].0.features[0].geometry, Some(Geometry::Line(vec![vec![Coord::new(0., 0.), Coord::new(2., 2.)]]))); - assert_eq!(layers[0].1.messages, ["1 vertex without Y was left out of spline paths"]); + assert_eq!(layers[0].1.messages.texts().collect::>(), ["1 vertex without Y was left out of spline paths"]); assert_eq!(layers[0].1.skipped, 0); } } @@ -1927,7 +1945,10 @@ mod tests { Some(Geometry::Polygon(vec![vec![vec![Coord::new(0., 0.), Coord::new(2., 0.), Coord::new(0., 2.), Coord::new(0., 0.)]]])) ); let subject = if count == 1 { "ring was" } else { "rings were" }; - assert_eq!(layers[0].1.messages, [format!("{count} short HATCH boundary {subject} left out of polygons")]); + assert_eq!( + layers[0].1.messages.texts().collect::>(), + [format!("{count} short HATCH boundary {subject} left out of polygons")] + ); assert_eq!(layers[0].1.skipped, 0); } } @@ -2034,7 +2055,7 @@ mod tests { assert_eq!(layers.iter().map(|(d, _)| d.features.len()).sum::(), 1); assert_eq!(layers[0].1.skipped, 1); assert_eq!( - layers[0].1.messages, + layers[0].1.messages.texts().collect::>(), ["1 entities couldn't be read or placed (missing blocks, blocks nested too deep or in a cycle) and were left out"] ); } @@ -2047,7 +2068,7 @@ mod tests { let layers = read("a.dxf", text.as_bytes(), &Options { layer: Some("keep"), ..opts }).unwrap(); assert_eq!(layers[0].0.features.len(), 2); assert_eq!( - layers[0].1.messages, + layers[0].1.messages.texts().collect::>(), [ "1 entities of the drawing's layouts (paper space) were left out; add the drawing with \"paperSpace\" to draw them", "2 vertices without Y were left out of spline paths", @@ -2955,7 +2976,7 @@ mod tests { let kept = layers[0].0.features.len(); assert_eq!(kept, MAX_TOTAL_VERTICES / 300); assert_eq!( - layers[0].1.messages, + layers[0].1.messages.texts().collect::>(), [ format!("the drawing's features hold more than {MAX_TOTAL_VERTICES} coordinates: the rest are left out"), format!("{kept} unreadable POLYLINE vertices were left out of their lines"), diff --git a/crates/data/src/esripbf.rs b/crates/data/src/esripbf.rs index 5eb31c3f6c..61d6b38b0a 100644 --- a/crates/data/src/esripbf.rs +++ b/crates/data/src/esripbf.rs @@ -186,9 +186,9 @@ pub fn read(bytes: &[u8], name: &str) -> Result<(Dataset, ReadReport)> { let mut page = read_page(bytes, name)?; page.report.messages.extend(page.losses.messages()); if page.exceeded_transfer_limit { - page.report.messages.push(format!( - "the service sent {} features only (its record limit); the rest aren't in this answer", - page.dataset.features.len() + page.report.messages.push(crate::loss::Note::loss( + crate::loss::LossCode::DroppedOverLimit, + format!("the service sent {} features only (its record limit); the rest aren't in this answer", page.dataset.features.len()), )); } Ok((page.dataset, page.report)) @@ -323,7 +323,10 @@ pub fn read_page_within(bytes: &[u8], name: &str, limit: usize) -> Result || esri_wkt_over_code(code, wkt.as_deref()).is_some() || !wkt.as_deref().is_some_and(crate::raster::wkt::parses)) { - report.messages.push("the coordinate system's WKT isn't valid UTF-8; the bytes that can't be read are replaced with U+FFFD"); + report.messages.push(crate::loss::Note::loss( + crate::loss::LossCode::ChangedEncoding, + "the coordinate system's WKT isn't valid UTF-8; the bytes that can't be read are replaced with U+FFFD", + )); } let said_before = report.messages.len(); let (crs, to_lonlat) = crate::filegdb::esri_crs(code, wkt.as_deref(), &mut report)?; @@ -340,7 +343,10 @@ pub fn read_page_within(bytes: &[u8], name: &str, limit: usize) -> Result && crate::filegdb::crs_of_code(code) != Some(crate::raster::Crs::LonLat) { unread_code = true; - report.messages.push(format!("coordinate system {code} can't be used; coordinates are read as longitude/latitude")); + report.messages.push(crate::loss::Note::loss( + crate::loss::LossCode::AssumedCrs, + format!("coordinate system {code} can't be used; coordinates are read as longitude/latitude"), + )); } let layer_type = match shape_kind { diff --git a/crates/data/src/esripbf/tests.rs b/crates/data/src/esripbf/tests.rs index 045da4bb64..b246efe940 100644 --- a/crates/data/src/esripbf/tests.rs +++ b/crates/data/src/esripbf/tests.rs @@ -233,7 +233,10 @@ fn an_unknown_coordinate_system_is_said() { let bytes = answer(&[message(8, &number(1, 999_999)), transform(false, 1.0, 0.0, 0.0), feature(&[geometry(&[], &[1, 2])])]); let (ds, report) = read(&bytes, "t").unwrap(); assert!(ds.crs.is_none()); - assert_eq!(report.messages, ["coordinate system 999999 can't be used; coordinates are read as longitude/latitude"]); + assert_eq!( + report.messages.texts().collect::>(), + ["coordinate system 999999 can't be used; coordinates are read as longitude/latitude"] + ); } #[test] @@ -319,7 +322,10 @@ fn a_page_cut_at_the_record_limit_says_so() { let bytes = answer(&[number(9, 1), field("OBJECTID", OID), feature(&[uint(1)])]); assert!(read_page(&bytes, "t").unwrap().exceeded_transfer_limit); let (_, report) = read(&bytes, "t").unwrap(); - assert_eq!(report.messages, ["the service sent 1 features only (its record limit); the rest aren't in this answer"]); + assert_eq!( + report.messages.texts().collect::>(), + ["the service sent 1 features only (its record limit); the rest aren't in this answer"] + ); } #[test] @@ -487,7 +493,10 @@ fn a_wkts_own_shift_wins_over_its_wkid() { assert!(!crate::raster::wkt::parses(&String::from_utf8_lossy(&broken))); let (p, messages) = at(&page([number(1, 27700), message(5, &broken)].concat())); assert!((p.x - by_code.x).abs() < 1e-9 && (p.y - by_code.y).abs() < 1e-9, "{p:?} {by_code:?}"); - assert_eq!(messages, ["the coordinate system's WKT isn't valid UTF-8; the bytes that can't be read are replaced with U+FFFD"]); + assert_eq!( + messages.texts().collect::>(), + ["the coordinate system's WKT isn't valid UTF-8; the bytes that can't be read are replaced with U+FFFD"] + ); // A non-EPSG Esri code: its WKT is read only for another body's system, so a byte that // breaks the WKT is said, and a byte in a name is not. The WKT's shift (OSGB 1936's) is set // aside for the code's, which is said. @@ -495,7 +504,10 @@ fn a_wkts_own_shift_wins_over_its_wkid() { let albers = crate::filegdb::crs_of_code(102033).unwrap().transformer().unwrap().to_lonlat(xy).unwrap(); let (p, messages) = at(&page([number(1, 102033), message(5, &broken)].concat())); assert!((p.x - albers.x).abs() < 1e-9 && (p.y - albers.y).abs() < 1e-9, "{p:?} {albers:?}"); - assert_eq!(messages, ["the coordinate system's WKT isn't valid UTF-8; the bytes that can't be read are replaced with U+FFFD"]); + assert_eq!( + messages.texts().collect::>(), + ["the coordinate system's WKT isn't valid UTF-8; the bytes that can't be read are replaced with U+FFFD"] + ); let (p, messages) = at(&page([number(1, 102033), message(5, ¬_utf8)].concat())); assert!((p.x - albers.x).abs() < 1e-9 && (p.y - albers.y).abs() < 1e-9, "{p:?} {albers:?}"); assert_eq!( diff --git a/crates/data/src/filegdb.rs b/crates/data/src/filegdb.rs index a21ab43367..080f8b8ad6 100644 --- a/crates/data/src/filegdb.rs +++ b/crates/data/src/filegdb.rs @@ -261,7 +261,10 @@ pub(crate) fn esri_crs(code: Option, wkt: Option<&str>, report: &mut ReadRe Ok(t) if c != Crs::LonLat => (Some(c), Some(t)), Ok(_) => (None, None), Err(e) => { - report.messages.push(format!("coordinate system: {e}; coordinates are read as longitude/latitude")); + report.messages.push(crate::loss::Note::loss( + crate::loss::LossCode::AssumedCrs, + format!("coordinate system: {e}; coordinates are read as longitude/latitude"), + )); (None, None) } } @@ -270,7 +273,10 @@ pub(crate) fn esri_crs(code: Option, wkt: Option<&str>, report: &mut ReadRe if let Some(refused) = planetary::refused_wkt(wkt, &e) { return Err(DataError::Format(format!("coordinate system: {refused}"))); } - report.messages.push(format!("coordinate system: {e}; coordinates are read as longitude/latitude")); + report.messages.push(crate::loss::Note::loss( + crate::loss::LossCode::AssumedCrs, + format!("coordinate system: {e}; coordinates are read as longitude/latitude"), + )); (None, None) } }, @@ -434,7 +440,10 @@ fn read_table(name: &str, t: &[u8], x: &[u8], wkid: Option) -> Result 0 { - report.messages.push(format!("{curves} curved segments are drawn as straight lines")); + report.messages.push(crate::loss::Note::loss( + crate::loss::LossCode::ApproximatedCurve, + format!("{curves} curved segments are drawn as straight lines"), + )); } if unprojected > 0 { report diff --git a/crates/data/src/georss.rs b/crates/data/src/georss.rs index a8c27fdece..5510a079fe 100644 --- a/crates/data/src/georss.rs +++ b/crates/data/src/georss.rs @@ -196,7 +196,10 @@ pub fn read(file_name: &str, bytes: &[u8]) -> Result> report.messages.push(format!("{skipped} items had places that couldn't be read")); } if without > 0 { - report.messages.push(format!("{without} items have no place and were left out")); + report.messages.push(crate::loss::Note::loss( + crate::loss::LossCode::DroppedFeature, + format!("{without} items have no place and were left out"), + )); } if lost_holes > 0 { let what = if lost_holes == 1 { diff --git a/crates/data/src/gml.rs b/crates/data/src/gml.rs index 17642d96a3..7110de14ad 100644 --- a/crates/data/src/gml.rs +++ b/crates/data/src/gml.rs @@ -620,10 +620,16 @@ pub fn read(file_name: &str, bytes: &[u8]) -> Result> } let mut report = ReadReport::default(); if over > 0 { - report.messages.push(format!("{over} features of more than {MAX_LAYERS} feature types were left out")); + report.messages.push(crate::loss::Note::loss( + crate::loss::LossCode::DroppedOverLimit, + format!("{over} features of more than {MAX_LAYERS} feature types were left out"), + )); } if let Some(s) = &unknown_srs { - report.messages.push(format!("unknown coordinate system '{s}': coordinates are read as they are")); + report.messages.push(crate::loss::Note::loss( + crate::loss::LossCode::AssumedCrs, + format!("unknown coordinate system '{s}': coordinates are read as they are"), + )); } let transform = match file_srs { Some((c, swap)) => Some((if c == Crs::LonLat { None } else { Some(c.transformer().map_err(DataError::Format)?) }, swap)), @@ -726,10 +732,10 @@ pub fn read(file_name: &str, bytes: &[u8]) -> Result> if unplaced > 0 { let what = if unplaced == 1 { "feature has" } else { "features have" }; let system = file_srs.map_or_else(String::new, |(c, _)| format!(" in {}", c.label())); - rep.messages.push(format!( + rep.messages.push(crate::loss::Note::loss(crate::loss::LossCode::DroppedGeometry, format!( "{}: {unplaced} {what} places{system} that can't be given in longitude/latitude; they are kept as missing coordinates and don't draw", ds.name - )); + ))); } if file_srs.is_none() && outside { rep.messages.push("the GML doesn't say its coordinate system (srsName) and its coordinates aren't longitude/latitude"); @@ -738,10 +744,10 @@ pub fn read(file_name: &str, bytes: &[u8]) -> Result> if kind.lost > 0 { let what = if kind.lost == 1 { "ring or surface patch of a geometry was" } else { "rings or surface patches of geometries were" }; - rep.messages.push(format!( + rep.messages.push(crate::loss::Note::loss(crate::loss::LossCode::DroppedRing, format!( "{}: {} {what} left out: too few points, unreadable coordinates, a patch with no exterior ring or of a kind not read, or an exterior ring past the first", ds.name, kind.lost - )); + ))); } if zm > 0 { ds.zm_dropped = true; @@ -755,26 +761,32 @@ pub fn read(file_name: &str, bytes: &[u8]) -> Result> } if parts > 0 { let what = if parts == 1 { "part" } else { "parts" }; - rep.messages.push(format!( - "{}: {parts} {what} of multi-geometries not read (a reference, too short, invalid coordinates, or of a kind not read)", - ds.name + rep.messages.push(crate::loss::Note::loss( + crate::loss::LossCode::DroppedGeometry, + format!( + "{}: {parts} {what} of multi-geometries not read (a reference, too short, invalid coordinates, or of a kind not read)", + ds.name + ), )); } if kind.approximated > 0 { let what = if kind.approximated == 1 { "feature" } else { "features" }; - rep.messages.push(format!( - "{}: {} {what} had curve segments approximated by their control points ({})", - ds.name, - kind.approximated, - kind.approximated_names.said() + rep.messages.push(crate::loss::Note::loss( + crate::loss::LossCode::ApproximatedCurve, + format!( + "{}: {} {what} had curve segments approximated by their control points ({})", + ds.name, + kind.approximated, + kind.approximated_names.said() + ), )); } if kind.centred > 0 { let what = if kind.centred == 1 { "feature" } else { "features" }; - rep.messages.push(format!( + rep.messages.push(crate::loss::Note::loss(crate::loss::LossCode::ApproximatedCurve, format!( "{}: {} {what} had curve segments given by a centre point (ArcByCenterPoint or CircleByCenterPoint): the centre was read as a vertex, so the line doesn't follow the curve there", ds.name, kind.centred - )); + ))); } if unread > 0 { let what = if unread == 1 { "property" } else { "properties" }; @@ -785,20 +797,26 @@ pub fn read(file_name: &str, bytes: &[u8]) -> Result> } if kind.repeated > 0 { let what = if kind.repeated == 1 { "value" } else { "values" }; - rep.messages.push(format!( - "{}: {} {what} of repeated properties not read, only the last is kept ({})", - ds.name, - kind.repeated, - kind.repeated_names.said() + rep.messages.push(crate::loss::Note::loss( + crate::loss::LossCode::DroppedValue, + format!( + "{}: {} {what} of repeated properties not read, only the last is kept ({})", + ds.name, + kind.repeated, + kind.repeated_names.said() + ), )); } if kind.capped > 0 { let what = if kind.capped == 1 { "value" } else { "values" }; - rep.messages.push(format!( - "{}: {} {what} of properties past the first {MAX_COLUMNS} names not read ({})", - ds.name, - kind.capped, - kind.capped_names.said() + rep.messages.push(crate::loss::Note::loss( + crate::loss::LossCode::DroppedOverLimit, + format!( + "{}: {} {what} of properties past the first {MAX_COLUMNS} names not read ({})", + ds.name, + kind.capped, + kind.capped_names.said() + ), )); } out.push((ds, rep)); @@ -959,11 +977,8 @@ mod tests { assert!(!layers[0].0.zm_dropped, "{:?}", layers[0].1.messages); // The part left out is said. assert!( - layers[0] - .1 - .messages - .iter() - .any(|m| m == "r: 1 part of multi-geometries not read (a reference, too short, invalid coordinates, or of a kind not read)"), + layers[0].1.messages.iter().any(|m| m.as_str() + == "r: 1 part of multi-geometries not read (a reference, too short, invalid coordinates, or of a kind not read)"), "{:?}", layers[0].1.messages ); @@ -1056,7 +1071,10 @@ mod tests { assert_eq!((ds.features.len(), rep.skipped), (2, 0)); assert!(matches!(&ds.features[1].geometry, Some(Geometry::Line(l)) if l.len() == 2)); let said: Vec<&crate::loss::Note> = rep.messages.iter().filter(|m| m.contains("multi-geometries")).collect(); - assert_eq!(said, ["m: 1 part of multi-geometries not read (a reference, too short, invalid coordinates, or of a kind not read)"]); + assert_eq!( + said.iter().map(|n| n.as_str()).collect::>(), + ["m: 1 part of multi-geometries not read (a reference, too short, invalid coordinates, or of a kind not read)"] + ); } /// Properties that aren't attributes (a nested record, a time, a second shape) are said on diff --git a/crates/data/src/gpx.rs b/crates/data/src/gpx.rs index 074285c670..1b71b3b18a 100644 --- a/crates/data/src/gpx.rs +++ b/crates/data/src/gpx.rs @@ -200,7 +200,10 @@ pub fn read(file_name: &str, bytes: &[u8]) -> Result> } report.skipped = skipped; if skipped > 0 { - report.messages.push(format!("{name}: {skipped} points, routes or tracks without usable geometry were skipped")); + report.messages.push(crate::loss::Note::loss( + crate::loss::LossCode::DroppedFeature, + format!("{name}: {skipped} points, routes or tracks without usable geometry were skipped"), + )); } } if out.is_empty() { diff --git a/crates/data/src/io.rs b/crates/data/src/io.rs index a48832343e..2686c5d0c3 100644 --- a/crates/data/src/io.rs +++ b/crates/data/src/io.rs @@ -517,10 +517,10 @@ pub fn read_path(path: &Path) -> Result<(Dataset, ReadReport)> { } "dbf" => { check_size(path)?; - let mut notes = Vec::new(); + let mut notes = crate::loss::Notes::new(); let cpg = crate::dbf::read_cpg(path, &mut notes); let (ds, mut report) = read_dbf(std::fs::read(path)?, cpg.as_deref(), &name, &mut csv_memory_budget())?; - report.messages.extend(notes.into_iter().map(|n| format!("{name}: {n}"))); + report.messages.extend(notes.prefixed(&name)); (ds, report) } "shp" => read_shapefile_in(path, &name, None)?, @@ -1545,7 +1545,10 @@ fn clip(s: &str) -> String { /// An IAU code (another body's system, as GDAL writes `urn:ogc:def:crs:IAU_2015::49900`) is read /// as longitude/latitude with a notice when it is planetocentric. Any other IAU code is an error, /// because its coordinates would land in the wrong place ([`planetary::declared`]). -pub(crate) fn declared_crs(root: &Map, messages: &mut Vec) -> Result> { +pub(crate) fn declared_crs( + root: &Map, + messages: &mut crate::loss::Notes, +) -> Result> { let Some(decl) = root.get("crs").filter(|v| !v.is_null()) else { return Ok(None) }; if let Some(name) = decl.get("properties").and_then(|p| p.get("name")).and_then(Json::as_str).filter(|n| n.len() <= CRS_NAME_MAX) && let Some((authority, code)) = iau_name(name) @@ -1569,7 +1572,10 @@ pub(crate) fn declared_crs(root: &Map, messages: &mut Vec) None => "of an unknown shape".to_string(), }, }; - messages.push(format!("GeoJSON crs {shown}: {why}; coordinates are read as longitude/latitude")); + messages.push(crate::loss::Note::loss( + crate::loss::LossCode::AssumedCrs, + format!("GeoJSON crs {shown}: {why}; coordinates are read as longitude/latitude"), + )); None } }) @@ -1926,9 +1932,12 @@ impl Collector { let mut ds = Dataset::new(name, GeometryType::None, fields); ds.features.reserve(self.features.len()); if report.skipped > 0 { - report.messages.push(format!("{} features had unreadable geometry", report.skipped)); + report.messages.push(crate::loss::Note::loss( + crate::loss::LossCode::DroppedFeature, + format!("{} features had unreadable geometry", report.skipped), + )); } - let mut said = Vec::new(); + let mut said = crate::loss::Notes::new(); let declared = declared_crs(root, &mut said)?; report.messages.extend(said); let mut unconverted = 0usize; @@ -1969,9 +1978,9 @@ impl Collector { ds.held_in = *crs; if unconverted > 0 { report.skipped += unconverted; - report.messages.push(format!( - "{unconverted} features couldn't be converted from {} to longitude/latitude and were skipped", - crs.label() + report.messages.push(crate::loss::Note::loss( + crate::loss::LossCode::DroppedFeature, + format!("{unconverted} features couldn't be converted from {} to longitude/latitude and were skipped", crs.label()), )); } // What couldn't be converted can't come back by defining the projection again. @@ -2850,7 +2859,9 @@ pub(crate) fn read_rows( report.messages.push(note); } if malformed > 0 { - report.messages.push(format!("{malformed} rows were malformed and skipped")); + report + .messages + .push(crate::loss::Note::loss(crate::loss::LossCode::DroppedFeature, format!("{malformed} rows were malformed and skipped"))); } let gt = if xy.is_some() { GeometryType::Point } else { GeometryType::None }; let mut ds = Dataset::new(name, gt, fields); @@ -2865,10 +2876,14 @@ pub(crate) fn read_rows( let column = headers.get(w).map_or("", |h| h.trim()); match workbook.and_then(|(_, empty)| empty.get(w)).copied().unwrap_or(0) { 0 => {} - 1 => report.messages.push(format!("1 value in '{column}' isn't a date and was read as empty, so its row has no geometry")), - n => report - .messages - .push(format!("{n} values in '{column}' aren't dates and were read as empty, so their rows have no geometry")), + 1 => report.messages.push(crate::loss::Note::loss( + crate::loss::LossCode::DroppedValue, + format!("1 value in '{column}' isn't a date and was read as empty, so its row has no geometry"), + )), + n => report.messages.push(crate::loss::Note::loss( + crate::loss::LossCode::DroppedValue, + format!("{n} values in '{column}' aren't dates and were read as empty, so their rows have no geometry"), + )), } } let (mut bad_wkt, mut zm_rows, mut collection_rows) = (0usize, 0usize, 0usize); @@ -2932,18 +2947,22 @@ pub(crate) fn read_rows( let was = if extra_cells == 1 { "was" } else { "were" }; let rows = if extra_rows == 1 { "row" } else { "rows" }; let columns = if headers.len() == 1 { "column" } else { "columns" }; - report - .messages - .push(format!("{extra_cells} {cells} past the header's {} {columns} {was} omitted in {extra_rows} {rows}", headers.len())); + report.messages.push(crate::loss::Note::loss( + crate::loss::LossCode::DroppedExtraAttributes, + format!("{extra_cells} {cells} past the header's {} {columns} {was} omitted in {extra_rows} {rows}", headers.len()), + )); } ds.drop_zm(&mut report, zm_rows); if collection_rows > 0 { let column = wkt.and_then(|i| headers.get(i)).map_or("", |h| h.trim()); let what = if collection_rows == 1 { "WKT value" } else { "WKT values" }; - report.messages.push(format!("{collection_rows} {what} in '{column}' lost later non-empty geometry-collection members; only the first non-empty member is kept")); + report.messages.push(crate::loss::Note::loss(crate::loss::LossCode::DroppedGeometry, format!("{collection_rows} {what} in '{column}' lost later non-empty geometry-collection members; only the first non-empty member is kept"))); } if report.skipped > malformed { - report.messages.push(format!("{} rows had no usable coordinates", report.skipped - malformed)); + report.messages.push(crate::loss::Note::loss( + crate::loss::LossCode::DroppedFeature, + format!("{} rows had no usable coordinates", report.skipped - malformed), + )); } if bad_wkt > 0 { report.messages.push(format!("{bad_wkt} rows had geometry that isn't readable WKT")); @@ -2965,7 +2984,10 @@ pub(crate) fn read_rows( (None, Some(code)) => match crate::raster::Crs::from_epsg(code) { Some(c) => Some(c), None => { - report.messages.push(format!("unknown coordinate system SRID {code}; coordinates are read as longitude/latitude")); + report.messages.push(crate::loss::Note::loss( + crate::loss::LossCode::AssumedCrs, + format!("unknown coordinate system SRID {code}; coordinates are read as longitude/latitude"), + )); None } }, @@ -2988,7 +3010,10 @@ pub(crate) fn read_rows( } if lost > 0 { report.skipped += lost; - report.messages.push(format!("{lost} rows couldn't be converted from {} to longitude/latitude", c.label())); + report.messages.push(crate::loss::Note::loss( + crate::loss::LossCode::DroppedFeature, + format!("{lost} rows couldn't be converted from {} to longitude/latitude", c.label()), + )); } } let read_as_degrees = crs.is_none_or(Crs::is_geographic); @@ -3344,7 +3369,7 @@ pub fn read_shapefile_in(path: &Path, name: &str, crs: Option) -> Result<(D if shx.is_file() { check_size_with(&shx, shapefile_size_error)?; } - let mut notes = Vec::new(); + let mut notes = crate::loss::Notes::new(); let parts = ShapefileParts { shp: crate::provenance::read(path)?, shx: if shx.is_file() { Some(crate::provenance::read(shx)?) } else { None }, @@ -3353,7 +3378,7 @@ pub fn read_shapefile_in(path: &Path, name: &str, crs: Option) -> Result<(D cpg: crate::dbf::read_cpg(path, &mut notes), }; let (ds, mut report) = read_shapefile_parts(parts, name, crs)?; - report.messages.extend(notes.into_iter().map(|n| format!("{name}: {n}"))); + report.messages.extend(notes.prefixed(name)); Ok((ds, report)) } @@ -3769,9 +3794,9 @@ struct DbfRead { /// `name` is the layer's, for the error of a `.dbf` it can't open. fn dbf_reader(mut bytes: Vec, cpg: Option<&[u8]>, name: &str) -> Result { use std::io::Cursor; - let mut declared = Vec::new(); + let mut declared = crate::loss::Notes::new(); let encoding = crate::dbf::encoding(cpg, bytes.get(29).copied().unwrap_or(0), &mut declared); - let mut encoding_notes = crate::loss::Notes::from(declared); + let mut encoding_notes = declared; // Counted before a date column is marked a character one below: its values aren't text. let (names, not_utf8) = crate::dbf::not_utf8(&bytes, &encoding); encoding_notes.extend(crate::dbf::not_utf8_names_note(&names, encoding.name())); @@ -3861,8 +3886,14 @@ fn read_dbf(bytes: Vec, cpg: Option<&[u8]>, name: &str, budget: &mut usize) integral_numeric_to_integer(&mut ds, &decimals); match report.skipped { 0 => {} - 1 => report.messages.push(format!("{name}: 1 dBASE record was unreadable and left out")), - n => report.messages.push(format!("{name}: {n} dBASE records were unreadable and left out")), + 1 => report.messages.push(crate::loss::Note::loss( + crate::loss::LossCode::DroppedFeature, + format!("{name}: 1 dBASE record was unreadable and left out"), + )), + n => report.messages.push(crate::loss::Note::loss( + crate::loss::LossCode::DroppedFeature, + format!("{name}: {n} dBASE records were unreadable and left out"), + )), } *budget = left; Ok((ds, report)) @@ -3949,6 +3980,21 @@ impl DbfCounts { } } +/// Says the numbers in a `.dbf` that aren't finite (nan or inf), read as empty, with the count for +/// each field in `counts` (by field index). +pub(crate) fn nonfinite_note(fields: &[Field], counts: &[usize]) -> Option { + let total: usize = counts.iter().sum(); + if total == 0 { + return None; + } + let what = if total == 1 { + "1 number isn't finite (nan or inf) and was".to_string() + } else { + format!("{total} numbers aren't finite (nan or inf) and were") + }; + Some(crate::loss::Note::loss(crate::loss::LossCode::DroppedValue, format!("{what} read as empty, in {}", named_fields(fields, counts)))) +} + /// Reports date, numeric and `` cells read as null, and text that isn't UTF-8, identically /// for tables and Shapefiles. fn dbf_notices(ds: &Dataset, report: &mut ReadReport, counts: &DbfCounts) { @@ -3956,18 +4002,7 @@ fn dbf_notices(ds: &Dataset, report: &mut ReadReport, counts: &DbfCounts) { let name = &ds.name; report.unread_dates = crate::source::unread_dates_note(&ds.fields, unread_dates); report.messages.extend(report.unread_dates.iter().map(|n| n.clone().prefixed(name))); - let nonfinite_total: usize = nonfinite.iter().sum(); - if nonfinite_total > 0 { - let what = if nonfinite_total == 1 { - "1 number isn't finite (nan or inf) and was".to_string() - } else { - format!("{nonfinite_total} numbers aren't finite (nan or inf) and were") - }; - report.messages.push(crate::loss::Note::loss( - crate::loss::LossCode::DroppedValue, - format!("{name}: {what} read as empty, in {}", named_fields(&ds.fields, nonfinite)), - )); - } + report.messages.extend(nonfinite_note(&ds.fields, nonfinite).map(|n| n.prefixed(name))); report.messages.extend(crate::source::null_text_note(&ds.fields, null_text).map(|n| n.prefixed(name))); report.messages.extend(crate::source::not_utf8_note(&ds.fields, not_utf8, encoding).map(|n| n.prefixed(name))); } @@ -4136,10 +4171,10 @@ pub(crate) fn read_shapefile_parts(parts: ShapefileParts, name: &str, crs: Optio .push(format!("{name}: {extra_shapes} shape(s) past the .dbf's last record have no attributes and were left out{unreadable}")); } if lost_track && records > pairs { - report.messages.push(format!( + report.messages.push(crate::loss::Note::loss(crate::loss::LossCode::DroppedFeature, format!( "{name}: shape {pairs} can't be read and the Shapefile has no .shx to find the next one by: the {} record(s) after it were left out", records.saturating_sub(pairs) - )); + ))); } else if records > pairs && extra_shapes == 0 && !lost_track { report .messages @@ -4162,25 +4197,28 @@ pub(crate) fn read_shapefile_parts(parts: ShapefileParts, name: &str, crs: Optio // doesn't match the coordinates), or as they are without a system to convert from. let e = if to_lonlat.is_some() { lonlat_extent } else { ds.extent() }; if e.beyond_lonlat() { - report.messages.push(if to_lonlat.is_some() { + report.messages.push(crate::loss::Note::loss(crate::loss::LossCode::AssumedCrs, if to_lonlat.is_some() { "coordinates are not longitude/latitude once converted from the .prj's coordinate system; the .prj may not match them, and they may draw out of place" } else { "coordinates are not longitude/latitude; RustGIS reads them as WGS 84 and they may draw out of place" - }); + })); } if report.skipped > 0 { report.messages.push(format!("{} shapes were unreadable or unsupported", report.skipped)); } if not_numbers > 0 { - report.messages.push(format!( + report.messages.push(crate::loss::Note::loss(crate::loss::LossCode::DroppedGeometry, format!( "{name}: {not_numbers} shape(s) have a coordinate that isn't a number (NaN or infinite): their features are kept without geometry" - )); + ))); } ds.crs_incomplete = unconverted > 0; if unconverted > 0 && converted == 0 { report.messages.push("no shape could be converted to longitude/latitude: the .prj doesn't seem to match the coordinates"); } else if unconverted > 0 { - report.messages.push(format!("{unconverted} shapes couldn't be converted to longitude/latitude and have no geometry")); + report.messages.push(crate::loss::Note::loss( + crate::loss::LossCode::DroppedGeometry, + format!("{unconverted} shapes couldn't be converted to longitude/latitude and have no geometry"), + )); } Ok((ds, report)) } @@ -4202,7 +4240,10 @@ fn shapefile_crs(prj: Option<&str>, report: &mut ReadReport) -> Result, report: &mut ReadReport) -> Result Ok(Some((crs, t))), Err(e) => { - report.messages.push(format!("the .prj file: {e}; coordinates are read as longitude/latitude")); + report.messages.push(crate::loss::Note::loss( + crate::loss::LossCode::AssumedCrs, + format!("the .prj file: {e}; coordinates are read as longitude/latitude"), + )); Ok(None) } } @@ -5780,7 +5824,8 @@ mod tests { assert_eq!(ds.features[0].attrs, [Value::Int(7), Value::Text("kept".into())]); assert_eq!(ds.features[1].attrs, [Value::Int(8), Value::Null]); assert_eq!(report.skipped, 0); - assert_eq!(report.messages, expected); + assert_eq!(report.messages.texts().collect::>(), expected); + assert!(report.messages.iter().all(|m| m.loss == Some(crate::loss::LossCode::DroppedExtraAttributes))); } } @@ -6517,7 +6562,8 @@ mod tests { let (ds, report) = read_geojson(&root.to_string(), "collection").unwrap(); assert!(ds.features.is_empty(), "must not retain a partial collection: {root}"); assert_eq!(report.skipped, 1); - assert_eq!(report.messages, ["1 features had unreadable geometry"]); + assert_eq!(report.messages.texts().collect::>(), ["1 features had unreadable geometry"]); + assert_eq!(report.messages[0].loss, Some(crate::loss::LossCode::DroppedFeature)); assert!(to_geojson(&ds)["features"].as_array().unwrap().is_empty()); } } @@ -6603,7 +6649,7 @@ mod tests { let ds = ds.in_lonlat().unwrap().into_owned(); let Some(Geometry::Point(c)) = &ds.features[0].geometry else { panic!() }; assert!((c.x + 73.96).abs() < 0.05 && (c.y - 40.78).abs() < 0.05, "{c:?}"); - assert_eq!(rep.messages, ["1 rows had no usable coordinates"]); + assert_eq!(rep.messages.texts().collect::>(), ["1 rows had no usable coordinates"]); // Without the coordinate system, the points are said to be out of place. let (_, rep) = read_csv_with(text, "t", &CsvOptions { crs: None, ..opts.clone() }).unwrap(); assert!(rep.messages.iter().any(|m| m.contains("\"crs\"")), "{:?}", rep.messages); @@ -6658,7 +6704,7 @@ mod tests { let (ds, report) = read_csv(&csv, "collections").unwrap(); assert_eq!(report.skipped, 0); assert_eq!( - report.messages, + report.messages.texts().collect::>(), ["2 WKT values in 'wkt' lost later non-empty geometry-collection members; only the first non-empty member is kept"] ); assert_eq!(ds.held_in, crate::raster::Crs::LonLat); @@ -6679,7 +6725,10 @@ mod tests { report.messages, [ crate::loss::Note::loss(crate::loss::LossCode::DroppedZm, crate::zm_note(Some(1))), - "1 WKT value in 'wkt' lost later non-empty geometry-collection members; only the first non-empty member is kept".into() + crate::loss::Note::loss( + crate::loss::LossCode::DroppedGeometry, + "1 WKT value in 'wkt' lost later non-empty geometry-collection members; only the first non-empty member is kept" + ) ] ); } @@ -6766,7 +6815,7 @@ mod tests { let (ds, rep) = read_geojson(mixed, "mixed").unwrap(); assert!(ds.features.is_empty() && !ds.zm_dropped && !said(&rep)); assert_eq!(rep.skipped, 1); - assert_eq!(rep.messages, ["1 features had unreadable geometry"]); + assert_eq!(rep.messages.texts().collect::>(), ["1 features had unreadable geometry"]); let curve = r#"{"type":"FeatureCollection","features":[{"type":"Feature","properties":{},"geometry":{"type":"Curve","coordinates":[[1,2,3]]}},{"type":"Feature","properties":{},"geometry":{"type":"Point","coordinates":[1,2]}}]}"#; let (ds, rep) = read_geojson(curve, "curve").unwrap(); assert!(!ds.zm_dropped && !said(&rep) && rep.skipped == 1, "{rep:?}"); @@ -9704,7 +9753,11 @@ mod tests { let path = three_named_points(dir.path()); let clean = std::fs::read(path.with_extension("dbf")).unwrap(); let notes = |r: &ReadReport| { - r.messages.iter().filter(|m| m.contains("marked deleted") || m.contains("unreadable")).cloned().collect::>() + r.messages + .iter() + .filter(|m| m.contains("marked deleted") || m.contains("unreadable")) + .map(|m| m.as_str().to_string()) + .collect::>() }; let (ds, report) = read_bytes("t.dbf", &clean).unwrap(); assert_eq!(ds.features.len(), 3); diff --git a/crates/data/src/kml.rs b/crates/data/src/kml.rs index 9f61383e0d..6ff3f9fcf5 100644 --- a/crates/data/src/kml.rs +++ b/crates/data/src/kml.rs @@ -727,7 +727,10 @@ impl Reader { self.geometry_losses.report(name, &mut report); report.skipped = self.skipped; if self.skipped > 0 { - report.messages.push(format!("{name}: {} placemarks without a geometry RustGIS draws were skipped", self.skipped)); + report.messages.push(crate::loss::Note::loss( + crate::loss::LossCode::DroppedFeature, + format!("{name}: {} placemarks without a geometry RustGIS draws were skipped", self.skipped), + )); } if self.duplicate_entries > 0 { report.messages.push(format!( @@ -736,7 +739,10 @@ impl Reader { )); } if self.dropped_keys > 0 { - report.messages.push(format!("{name}: extended data past {MAX_KEYS} distinct names was left out")); + report.messages.push(crate::loss::Note::loss( + crate::loss::LossCode::DroppedOverLimit, + format!("{name}: extended data past {MAX_KEYS} distinct names was left out"), + )); } if !renamed.is_empty() { let listed: Vec = renamed diff --git a/crates/data/src/landxml.rs b/crates/data/src/landxml.rs index aeba0300cf..2ebf3de6c9 100644 --- a/crates/data/src/landxml.rs +++ b/crates/data/src/landxml.rs @@ -71,9 +71,9 @@ pub fn read(file_name: &str, bytes: &[u8], crs: Option) -> Result {} - (None, Some(code)) => report.messages.push(format!( + (None, Some(code)) => report.messages.push(crate::loss::Note::loss(crate::loss::LossCode::AssumedCrs, format!( "the file's coordinate system, EPSG:{code}, isn't one RustGIS converts (give \"crs\" as a WKT or another code): coordinates are kept as they are" - )), + ))), (None, None) => report .messages .push("the file doesn't say its coordinate system (give \"crs\", such as EPSG:2263): coordinates are kept as they are"), @@ -193,7 +193,10 @@ pub fn read(file_name: &str, bytes: &[u8], crs: Option) -> Result= MAX_FACES { - report.messages.push(format!("surface '{sname}' has more than {MAX_FACES} faces: the rest are left out")); + report.messages.push(crate::loss::Note::loss( + crate::loss::LossCode::DroppedOverLimit, + format!("surface '{sname}' has more than {MAX_FACES} faces: the rest are left out"), + )); break; } // Invisible faces (i="1") are holes in the surface. @@ -217,11 +220,17 @@ pub fn read(file_name: &str, bytes: &[u8], crs: Option) -> Result 0 { let (parcels, verb) = if missing_parcels == 1 { ("parcel", "was") } else { ("parcels", "were") }; - report.messages.push(format!("{missing_parcels} LandXML {parcels} without CoordGeom {verb} left out")); + report.messages.push(crate::loss::Note::loss( + crate::loss::LossCode::DroppedFeature, + format!("{missing_parcels} LandXML {parcels} without CoordGeom {verb} left out"), + )); } report.skipped = skipped + missing_parcels; if skipped > 0 { - report.messages.push(format!("{skipped} points, faces or figures couldn't be read and were left out")); + report.messages.push(crate::loss::Note::loss( + crate::loss::LossCode::DroppedFeature, + format!("{skipped} points, faces or figures couldn't be read and were left out"), + )); } let mut out: Vec<(Dataset, ReadReport)> = Vec::new(); let transformer = match crs.filter(|c| *c != Crs::LonLat) { @@ -249,7 +258,10 @@ pub fn read(file_name: &str, bytes: &[u8], crs: Option) -> Result 0 { - rep.messages.push(format!("{lost} features couldn't be converted from {}", c.label())); + rep.messages.push(crate::loss::Note::loss( + crate::loss::LossCode::DroppedFeature, + format!("{lost} features couldn't be converted from {}", c.label()), + )); } } out.push((ds, rep)); @@ -271,7 +283,7 @@ mod tests { assert_eq!(layers.len(), 1); assert_eq!(layers[0].0.features[0].geometry, Some(Geometry::Point(Coord::new(2.0, 1.0)))); assert_eq!(layers[0].0.value(0, 0), &Value::Text("kept".into())); - assert_eq!(layers[0].1.messages, ["2 LandXML parcels without CoordGeom were left out"]); + assert_eq!(layers[0].1.messages.texts().collect::>(), ["2 LandXML parcels without CoordGeom were left out"]); let clean = br#"1 2"#; assert!(read("a.xml", clean, None).unwrap()[0].1.messages.is_empty()); } diff --git a/crates/data/src/lidar.rs b/crates/data/src/lidar.rs index 76532a5a5b..b63bdc97ba 100644 --- a/crates/data/src/lidar.rs +++ b/crates/data/src/lidar.rs @@ -283,7 +283,10 @@ fn read_points(mut r: R, name: &str, crs: Option { - report.messages.push(format!("{name}: {e}; coordinates are kept as they are")); + report.messages.push(crate::loss::Note::loss( + crate::loss::LossCode::AssumedCrs, + format!("{name}: {e}; coordinates are kept as they are"), + )); said = true; None } @@ -299,13 +302,19 @@ fn read_points(mut r: R, name: &str, crs: Option match c.transformer() { Ok(t) => Some(t), Err(e) => { - report.messages.push(format!("{name}: the coordinate system: {e}; coordinates are kept as they are")); + report.messages.push(crate::loss::Note::loss( + crate::loss::LossCode::AssumedCrs, + format!("{name}: the coordinate system: {e}; coordinates are kept as they are"), + )); None } }, }; if crs.is_none() && !lonlat_bounds && !said { - report.messages.push(format!("{name}: the file doesn't say its coordinate system; coordinates are kept as they are")); + report.messages.push(crate::loss::Note::loss( + crate::loss::LossCode::AssumedCrs, + format!("{name}: the file doesn't say its coordinate system; coordinates are kept as they are"), + )); } let has_rgb = matches!(h.format, 2 | 3 | 5 | 7 | 8 | 10); @@ -351,7 +360,10 @@ fn read_points(mut r: R, name: &str, crs: Option(mut r: R, name: &str, crs: Option(mut r: R, name: &str, crs: Option 1 { - report.messages.push(format!("{name}: {} of its {total} points are shown, evenly spread", points.len())); + report.messages.push(crate::loss::Note::loss( + crate::loss::LossCode::DroppedOverLimit, + format!("{name}: {} of its {total} points are shown, evenly spread", points.len()), + )); } // LAS colours are 16-bit by the standard, but some writers store 8-bit values: a file whose // colours never pass 255 (over every point read) is taken as 8-bit. A 16-bit file that dark @@ -413,7 +431,10 @@ fn read_points(mut r: R, name: &str, crs: Option 0 { report.skipped += lost; - report.messages.push(format!("{name}: {lost} points couldn't be converted to longitude/latitude")); + report.messages.push(crate::loss::Note::loss( + crate::loss::LossCode::DroppedFeature, + format!("{name}: {lost} points couldn't be converted to longitude/latitude"), + )); } Ok((ds, report, total)) } diff --git a/crates/data/src/loss.rs b/crates/data/src/loss.rs index 787c7d54cc..70c3528158 100644 --- a/crates/data/src/loss.rs +++ b/crates/data/src/loss.rs @@ -83,6 +83,21 @@ loss_codes! { Dropped, "Keep the source file's coordinate system definition with the export." ), + DroppedFeature => ( + "dropped.feature", + Dropped, + "Correct the features the notice names in the source, or read it another way the notice suggests." + ), + DroppedGeometry => ( + "dropped.geometry", + Dropped, + "Correct the geometry in the source, or give the coordinate system its coordinates are in." + ), + DroppedOverLimit => ( + "dropped.over-limit", + Dropped, + "Read less at once, such as by filtering or clipping the source first." + ), ChangedTruncated => ("changed.truncated", Changed, "Use a decimal field to keep the fractional part."), ChangedBody => ("changed.body", Changed, "Export in the layer's own coordinate system, which keeps its body."), ChangedEncoding => ( @@ -105,11 +120,21 @@ loss_codes! { Approximated, "Export in the layer's own coordinate system, or give that system with a known transformation to WGS 84." ), + ApproximatedCurve => ( + "approximated.curve", + Approximated, + "Keep the source file where exact curves matter: RustGIS draws curves as straight segments." + ), AssumedNullMarker => ( "assumed.null-marker", Assumed, "Write the value another way if the text Null is meant as text, not as an empty value." ), + AssumedCrs => ( + "assumed.crs", + Assumed, + "Give the coordinate system the coordinates are in (\"crs\" when adding the data, or Define Projection)." + ), } impl LossCode { diff --git a/crates/data/src/mapinfo.rs b/crates/data/src/mapinfo.rs index ae61655a6f..396da8703e 100644 --- a/crates/data/src/mapinfo.rs +++ b/crates/data/src/mapinfo.rs @@ -435,7 +435,10 @@ pub fn read(mif: &str, mid: Option<&str>, name: &str) -> Result<(Dataset, ReadRe Some(c) => match c.transformer() { Ok(t) => Some(t), Err(e) => { - report.messages.push(format!("the coordinate system: {e}; coordinates are kept as they are")); + report.messages.push(crate::loss::Note::loss( + crate::loss::LossCode::AssumedCrs, + format!("the coordinate system: {e}; coordinates are kept as they are"), + )); None } }, diff --git a/crates/data/src/ogc.rs b/crates/data/src/ogc.rs index 6aad11fe72..724e595ddf 100644 --- a/crates/data/src/ogc.rs +++ b/crates/data/src/ogc.rs @@ -6363,7 +6363,7 @@ mod tests { report .messages .iter() - .any(|m| m == "coordinate system 999999 can't be used; coordinates are read in EPSG:2056, the system asked for"), + .any(|m| m.as_str() == "coordinate system 999999 can't be used; coordinates are read in EPSG:2056, the system asked for"), "{:?}", report.messages ); diff --git a/crates/data/src/osm.rs b/crates/data/src/osm.rs index 9cc1b87854..f0c58d7fcb 100644 --- a/crates/data/src/osm.rs +++ b/crates/data/src/osm.rs @@ -768,15 +768,23 @@ pub fn read(file_name: &str, bytes: &[u8]) -> Result> let mut report = ReadReport { skipped: missing + short_ways + no_closed_outer, ..ReadReport::default() }; if osm.omitted_members > 0 { let members = if osm.omitted_members == 1 { "relation member" } else { "relation members" }; - report.messages.push(format!("{} {members} left out at the per-relation limit of {MAX_MEMBERS}", osm.omitted_members)); + report.messages.push(crate::loss::Note::loss( + crate::loss::LossCode::DroppedOverLimit, + format!("{} {members} left out at the per-relation limit of {MAX_MEMBERS}", osm.omitted_members), + )); } if short_ways > 0 { let subject = if short_ways == 1 { "tagged way left out because it has" } else { "tagged ways left out because they have" }; - report.messages.push(format!("{short_ways} {subject} fewer than two nodes")); + report + .messages + .push(crate::loss::Note::loss(crate::loss::LossCode::DroppedFeature, format!("{short_ways} {subject} fewer than two nodes"))); } if no_closed_outer > 0 { let subject = if no_closed_outer == 1 { "relation left out because it has" } else { "relations left out because they have" }; - report.messages.push(format!("{no_closed_outer} {subject} no usable closed outer ring")); + report.messages.push(crate::loss::Note::loss( + crate::loss::LossCode::DroppedFeature, + format!("{no_closed_outer} {subject} no usable closed outer ring"), + )); } if osm.capped { report @@ -820,7 +828,10 @@ pub fn read(file_name: &str, bytes: &[u8]) -> Result> } if containment_limited > 0 { let subject = if containment_limited == 1 { "inner ring was" } else { "inner rings were" }; - report.messages.push(format!("{containment_limited} OSM {subject} omitted after the containment-test limit of {MAX_MEMBERS}")); + report.messages.push(crate::loss::Note::loss( + crate::loss::LossCode::DroppedOverLimit, + format!("{containment_limited} OSM {subject} omitted after the containment-test limit of {MAX_MEMBERS}"), + )); } // The notices are the file's: said once, with the first layer. let mut out: Vec<(Dataset, ReadReport)> = @@ -1157,12 +1168,15 @@ pub(crate) mod tests { .unwrap(); assert_eq!(lossy[1].0.features.iter().collect::>(), clean[1].0.features.iter().collect::>()); assert_eq!(lossy[0].1.skipped, 0); - assert_eq!(lossy[0].1.messages, ["1 OSM sub-relation member was omitted because nested relations are not supported"]); + assert_eq!( + lossy[0].1.messages.texts().collect::>(), + ["1 OSM sub-relation member was omitted because nested relations are not supported"] + ); assert!(lossy[1].1.messages.is_empty()); let omitted = read("nested.pbf", &finite_member_arrays_file(ways, &[(200, &[8], &[201], &[2]), (201, &[7], &[101], &[1])])).unwrap(); assert_eq!(omitted[0].1.skipped, 1); - assert_eq!(omitted[0].1.messages, ["1 relation left out because it has no usable closed outer ring"]); + assert_eq!(omitted[0].1.messages.texts().collect::>(), ["1 relation left out because it has no usable closed outer ring"]); } /// Parallel member arrays must agree; valid geometry must not hide an unmatched tail. @@ -1210,7 +1224,10 @@ pub(crate) mod tests { let lossy = read("budget.pbf", &finite_omission_file(ways, Some(&members))).unwrap(); assert_eq!(lossy[1].0.features.iter().collect::>(), clean[1].0.features.iter().collect::>()); assert_eq!(lossy[0].1.skipped, 0); - assert_eq!(lossy[0].1.messages, ["1 OSM inner ring was omitted after the containment-test limit of 100000"]); + assert_eq!( + lossy[0].1.messages.texts().collect::>(), + ["1 OSM inner ring was omitted after the containment-test limit of 100000"] + ); assert!(lossy[1].1.messages.is_empty()); } @@ -1228,7 +1245,7 @@ pub(crate) mod tests { assert_eq!(layers.len(), 2); assert_eq!(layers[1].0.features.iter().collect::>(), clean[1].0.features.iter().collect::>()); assert_eq!(layers[0].1.skipped, 0, "a member is not a whole skipped feature"); - assert_eq!(layers[0].1.messages, ["1 relation member left out at the per-relation limit of 100000"]); + assert_eq!(layers[0].1.messages.texts().collect::>(), ["1 relation member left out at the per-relation limit of 100000"]); assert!(layers[1].1.messages.is_empty()); } @@ -1240,7 +1257,7 @@ pub(crate) mod tests { assert_eq!(layers[1].0.features.len(), 1); assert_eq!(layers[1].0.features[0].attrs[0], Value::Int(103)); assert_eq!(layers[0].1.skipped, 2); - assert_eq!(layers[0].1.messages, ["2 tagged ways left out because they have fewer than two nodes"]); + assert_eq!(layers[0].1.messages.texts().collect::>(), ["2 tagged ways left out because they have fewer than two nodes"]); } #[test] @@ -1257,7 +1274,7 @@ pub(crate) mod tests { assert_eq!(layers.len(), 1); assert_eq!(layers[0].0.features.len(), 1); assert_eq!(layers[0].1.skipped, 1); - assert_eq!(layers[0].1.messages, [reason], "refs={refs:?}, members={members:?}"); + assert_eq!(layers[0].1.messages.texts().collect::>(), [reason], "refs={refs:?}, members={members:?}"); } } @@ -1267,7 +1284,7 @@ pub(crate) mod tests { let layers = read("missing-outer.pbf", &sample_with_missing_outer(true)).unwrap(); assert_eq!(layers.iter().map(|(ds, _)| ds.features.len()).collect::>(), [1, 2, 2]); assert_eq!(layers[0].1.skipped, 1); - assert_eq!(layers[0].1.messages, ["1 ways or relations refer to nodes or ways the file doesn't hold"]); + assert_eq!(layers[0].1.messages.texts().collect::>(), ["1 ways or relations refer to nodes or ways the file doesn't hold"]); assert!(layers.iter().skip(1).all(|(_, report)| report.skipped == 0 && report.messages.is_empty())); } diff --git a/crates/data/src/photo.rs b/crates/data/src/photo.rs index 7a9e83fb75..45a8f7ba62 100644 --- a/crates/data/src/photo.rs +++ b/crates/data/src/photo.rs @@ -369,7 +369,10 @@ impl Reader { self.report.messages.push(format!("{what} left out: {}{more}", shown.join("; "))); } if self.over { - self.report.messages.push(format!("a photo layer holds up to {MAX_PHOTOS} photos; the rest were left out")); + self.report.messages.push(crate::loss::Note::loss( + crate::loss::LossCode::DroppedOverLimit, + format!("a photo layer holds up to {MAX_PHOTOS} photos; the rest were left out"), + )); } (self.ds, self.report) } diff --git a/crates/data/src/publish.rs b/crates/data/src/publish.rs index 285e3e6419..40f8f8e716 100644 --- a/crates/data/src/publish.rs +++ b/crates/data/src/publish.rs @@ -241,7 +241,7 @@ pub fn shapefile(ds: &Dataset, path: &Path, synced: &Synced) -> Result Result 0 { - notes.push(format!( + notes.push(crate::loss::Note::loss(crate::loss::LossCode::DroppedFeature, format!( "{unplaced} features have coordinates outside their coordinate system, so are left out of the view, counted in the pages read for it" - )); + ))); } notes } diff --git a/crates/data/src/source/fgb.rs b/crates/data/src/source/fgb.rs index 6ebb37d5f3..1e11f15ed9 100644 --- a/crates/data/src/source/fgb.rs +++ b/crates/data/src/source/fgb.rs @@ -30,7 +30,7 @@ pub(crate) fn header_feature_count(path: &Path) -> Result { } /// The system a FlatGeobuf header says, read as a GeoPackage row's is ([`super::declared_reproject`]). -fn header_reproject(header_crs: Option>, notes: &mut Vec) -> Result { +fn header_reproject(header_crs: Option>, notes: &mut crate::loss::Notes) -> Result { // The header's system is read as a GeoPackage row's is ([`super::declared_reproject`]): by // its EPSG code, or by its WKT when the WKT gives another shift to WGS 84 or there is no // EPSG code (#1855). The code is an EPSG one only when the organization is EPSG (or not @@ -52,9 +52,15 @@ fn header_reproject(header_crs: Option>, notes: &mut Vec { if !epsg_org && let Some(org) = organization { - notes.push(format!("its coordinate system is defined by {org}, not EPSG; read as longitude/latitude")); + notes.push(crate::loss::Note::loss( + crate::loss::LossCode::AssumedCrs, + format!("its coordinate system is defined by {org}, not EPSG; read as longitude/latitude"), + )); } else if let Some(code) = code { - notes.push(format!("its coordinate system's code {code} isn't an EPSG code; read as longitude/latitude")); + notes.push(crate::loss::Note::loss( + crate::loss::LossCode::AssumedCrs, + format!("its coordinate system's code {code} isn't an EPSG code; read as longitude/latitude"), + )); } Reproject::from_crs(Crs::LonLat, notes) } @@ -67,7 +73,7 @@ fn header_reproject(header_crs: Option>, notes: &mut Vec Result> { let reader = open_reader(BufReader::new(std::fs::File::open(path)?))?; - Ok(header_reproject(reader.header().crs(), &mut Vec::new()).map(|r| r.crs())) + Ok(header_reproject(reader.header().crs(), &mut crate::loss::Notes::new()).map(|r| r.crs())) } /// Whether a FlatGeobuf's header says WGS 84 longitude/latitude or no system: EPSG:4326 (or no @@ -227,7 +233,7 @@ impl FgbSource { fn prepare(r: R, input: Input, name: &str) -> Result { let reader = open_reader(r)?; let h = reader.header(); - let mut notes = Vec::new(); + let mut notes = crate::loss::Notes::new(); let reproject = header_reproject(h.crs(), &mut notes)?; let mut date_columns = Vec::new(); let mut fields = Vec::new(); @@ -277,7 +283,7 @@ impl FgbSource { crs: reproject.info_crs(), // The crate's index search assumes the default node size; other files are scanned. indexed: h.index_node_size() == flatgeobuf::packed_r_tree::PackedRTree::DEFAULT_NODE_SIZE && count > 0, - notes: notes.into(), + notes, zm_dropped: false, }; info.note_columns( diff --git a/crates/data/src/source/gdal.rs b/crates/data/src/source/gdal.rs index 333038c47e..58b612f652 100644 --- a/crates/data/src/source/gdal.rs +++ b/crates/data/src/source/gdal.rs @@ -437,7 +437,7 @@ struct Conversion { path: PathBuf, unprojected: bool, in_lonlat: bool, - notes: Vec, + notes: crate::loss::Notes, empty: bool, } @@ -473,7 +473,10 @@ fn convert_one_fresh_in(dir: &Path, src: &Path, layer: &str, family: Option 0) { touch(&out); touch(&keyfile); - return Ok(Some(Conversion { path: out, unprojected: was_unprojected, in_lonlat: was_in_lonlat, notes: Vec::new(), empty: false })); + return Ok(Some(Conversion { + path: out, + unprojected: was_unprojected, + in_lonlat: was_in_lonlat, + notes: crate::loss::Notes::new(), + empty: false, + })); } // A count of Z/M features kept for an earlier conversion with this tag isn't this one's. if !fresh { @@ -711,19 +720,23 @@ fn convert_one_in(dir: &Path, src: &Path, layer: &str, request: ConversionReques let count = counts.entry(line.to_string()).or_default(); *count = count.saturating_add(1); } - let mut notes: Vec = counts.into_iter().map(|(line, count)| format!("GDAL: {line} ({count} occurrence(s))")).collect(); + let mut notes: crate::loss::Notes = + counts.into_iter().map(|(line, count)| format!("GDAL: {line} ({count} occurrence(s))")).collect(); // A layer declaring one geometry type holds no other; only a mixed layer is counted. A // count that fails doesn't undo a good conversion: the possible loss is said instead. if let Some(family) = family.filter(|_| kind.is_none()) { match count_other_families(&full, layer, family) { Ok(0) => {} - Ok(other) => notes.push(format!("GDAL: {other} features of another geometry type were left out")), - Err(_) => notes.push("GDAL: an unknown number of features of another geometry type may have been left out".into()), + Ok(other) => notes.push(crate::loss::Note::loss( + crate::loss::LossCode::DroppedFeature, + format!("GDAL: {other} features of another geometry type were left out"), + )), + Err(_) => notes.push("GDAL: an unknown number of features of another geometry type may have been left out"), } } notes } else { - Vec::new() + crate::loss::Notes::new() }; Ok(Some(Conversion { path: out, unprojected, in_lonlat, notes, empty: !any })) } @@ -1442,7 +1455,10 @@ mod tests { let fresh = convert_one_fresh_in(&dir.path().join("cache"), &path, "survey", Some(Family::Points), None).unwrap(); let omitted = fresh.notes.iter().filter(|note| note.contains("another geometry type")).collect::>(); if mixed { - assert_eq!(omitted, vec!["GDAL: 2 features of another geometry type were left out"]); + assert_eq!( + omitted.iter().map(|n| n.as_str()).collect::>(), + vec!["GDAL: 2 features of another geometry type were left out"] + ); } else { assert!(omitted.is_empty(), "{:?}", fresh.notes); assert!(fresh.notes.is_empty(), "single-family input has no conversion losses: {:?}", fresh.notes); diff --git a/crates/data/src/source/geojson.rs b/crates/data/src/source/geojson.rs index ff48277804..d872fb8ddc 100644 --- a/crates/data/src/source/geojson.rs +++ b/crates/data/src/source/geojson.rs @@ -226,9 +226,12 @@ impl GeoJsonSource { if rest.get("type").and_then(Json::as_str) != Some("FeatureCollection") { return Err(DataError::Unsupported("only GeoJSON FeatureCollections are read in place".into())); } - let mut notes = Vec::new(); + let mut notes = crate::loss::Notes::new(); if scan.skipped > 0 { - notes.push(format!("{} features had unreadable geometry", scan.skipped)); + notes.push(crate::loss::Note::loss( + crate::loss::LossCode::DroppedFeature, + format!("{} features had unreadable geometry", scan.skipped), + )); } let reproject = Reproject::known(declared_crs(&rest, &mut notes)?); // The declaration may come after the features, so only now can each be tried: those the @@ -244,10 +247,13 @@ impl GeoJsonSource { *kept = kept.saturating_sub(lost); } if !pass.failed.is_empty() { - notes.push(format!( - "{} features couldn't be converted from {} to longitude/latitude and were skipped", - pass.failed.len(), - reproject.label() + notes.push(crate::loss::Note::loss( + crate::loss::LossCode::DroppedFeature, + format!( + "{} features couldn't be converted from {} to longitude/latitude and were skipped", + pass.failed.len(), + reproject.label() + ), )); } failed = pass.failed; @@ -272,7 +278,7 @@ impl GeoJsonSource { count: Some((scan.places.len() - failed.len()) as u64), crs: reproject.label(), indexed: false, - notes: notes.into(), + notes, zm_dropped: false, }; // Features the declared system can't convert are left out, and so are their heights. diff --git a/crates/data/src/source/gpkg.rs b/crates/data/src/source/gpkg.rs index a6f86f2dbc..b2e200a6d5 100644 --- a/crates/data/src/source/gpkg.rs +++ b/crates/data/src/source/gpkg.rs @@ -196,7 +196,7 @@ impl GpkgSource { .ok_or_else(|| DataError::Format(format!("no feature table '{l}' (tables: {})", tables.join(", "))))?, None => tables.first().cloned().ok_or_else(|| DataError::Format("the GeoPackage has no feature tables".into()))?, }; - let mut notes = Vec::new(); + let mut notes = crate::loss::Notes::new(); if layer.is_none() && tables.len() > 1 { notes.push(format!("the first of {} feature tables ({})", tables.len(), tables.join(", "))); } @@ -308,7 +308,7 @@ impl GpkgSource { // (`SourceInfo::coordinate_system`), as a Shapefile's .prj does (#1476). crs: reproject.info_crs(), indexed: rtree.is_some(), - notes: notes.into(), + notes, zm_dropped: false, }; let file = Some((path.to_path_buf(), id)); diff --git a/crates/data/src/source/gpkg_mem.rs b/crates/data/src/source/gpkg_mem.rs index 48a9ac6df0..bea415d8a0 100644 --- a/crates/data/src/source/gpkg_mem.rs +++ b/crates/data/src/source/gpkg_mem.rs @@ -158,7 +158,7 @@ impl GpkgMemSource { .ok_or_else(|| DataError::Format(format!("no feature table '{l}' (tables: {})", tables.join(", "))))?, None => tables.first().cloned().ok_or_else(|| DataError::Format("the GeoPackage has no feature tables".into()))?, }; - let mut notes = Vec::new(); + let mut notes = crate::loss::Notes::new(); if layer.is_none() && tables.len() > 1 { notes.push(format!("the first of {} feature tables ({})", tables.len(), tables.join(", "))); } @@ -222,7 +222,7 @@ impl GpkgMemSource { // (`SourceInfo::coordinate_system`), as a Shapefile's .prj does (#1476). crs: reproject.info_crs(), indexed: false, - notes: notes.into(), + notes, zm_dropped: false, }; let mut src = GpkgMemSource { info, db, table, geom_col, field_cols, reproject }; diff --git a/crates/data/src/source/mod.rs b/crates/data/src/source/mod.rs index 5515bf546e..0b92c8ff04 100644 --- a/crates/data/src/source/mod.rs +++ b/crates/data/src/source/mod.rs @@ -921,7 +921,7 @@ impl Reproject { authority: Option<&str>, code: Option, wkt: Option<&str>, - notes: &mut Vec, + notes: &mut crate::loss::Notes, ) -> Option> { use crate::raster::planetary::{Declared, declared}; Some(match declared(authority, code, wkt)? { @@ -934,7 +934,7 @@ impl Reproject { } /// From an EPSG code; an unknown or missing code is taken as longitude/latitude, with a note. - pub(crate) fn from_epsg(code: Option, notes: &mut Vec) -> Reproject { + pub(crate) fn from_epsg(code: Option, notes: &mut crate::loss::Notes) -> Reproject { let crs = match code { None | Some(0) => Crs::LonLat, Some(c) => match Crs::from_epsg(c) { @@ -942,7 +942,10 @@ impl Reproject { None => { // Unknown, or one only the desktop app can use (an azimuthal equidistant one in // the web app), which it says. - notes.push(format!("{}; read as longitude/latitude", crate::raster::crs::unusable_epsg(c))); + notes.push(crate::loss::Note::loss( + crate::loss::LossCode::AssumedCrs, + format!("{}; read as longitude/latitude", crate::raster::crs::unusable_epsg(c)), + )); Crs::LonLat } }, @@ -952,13 +955,13 @@ impl Reproject { /// From a coordinate system; one that can't be converted is taken as longitude/latitude, with /// a note. - pub(crate) fn from_crs(crs: Crs, notes: &mut Vec) -> Reproject { + pub(crate) fn from_crs(crs: Crs, notes: &mut crate::loss::Notes) -> Reproject { let t = match crs { Crs::LonLat => None, other => match other.transformer() { Ok(t) => Some(t), Err(e) => { - notes.push(format!("{e}; read as longitude/latitude")); + notes.push(crate::loss::Note::loss(crate::loss::LossCode::AssumedCrs, format!("{e}; read as longitude/latitude"))); None } }, @@ -1141,7 +1144,7 @@ pub(crate) struct GpkgSrs { /// extension) takes priority over its `definition`, as OGC 12-128r19 F.10 says. With no row for /// `srs_id`, it is taken as an EPSG code only for WGS 84 and Web Mercator, the ids writers commonly /// use without defining. -pub(crate) fn gpkg_reproject(srs_id: i64, row: Option, notes: &mut Vec) -> Result { +pub(crate) fn gpkg_reproject(srs_id: i64, row: Option, notes: &mut crate::loss::Notes) -> Result { let wkt2 = row.as_ref().and_then(|r| defined(r.definition_12_063.as_deref())); let wkt1 = row.as_ref().and_then(|r| defined(r.definition.as_deref())); // An EPSG code: the row's when its organization is EPSG (a table-local id such as 100001 @@ -1172,7 +1175,10 @@ pub(crate) fn gpkg_reproject(srs_id: i64, row: Option, notes: &mut Vec< // Longitude/latitude is what WGS 84 and the spec's "undefined geographic" id 0 mean; any other // id, the "undefined cartesian" -1 too, is assumed to be it. if srs_id != 0 && srs_id != 4326 { - notes.push(format!("{what} has no EPSG code; read as longitude/latitude")); + notes.push(crate::loss::Note::loss( + crate::loss::LossCode::AssumedCrs, + format!("{what} has no EPSG code; read as longitude/latitude"), + )); } Ok(Reproject::from_crs(Crs::LonLat, notes)) } @@ -1208,7 +1214,7 @@ pub(crate) struct DeclaredCrs<'a> { /// as longitude/latitude. An Earth definition beside another body's IAU code is read, and said. /// `None` when there is nothing to read it by: no EPSG code, no definition and no other body's /// code; the format then says what its coordinates are taken as. -pub(crate) fn declared_reproject(declared: DeclaredCrs, notes: &mut Vec) -> Option> { +pub(crate) fn declared_reproject(declared: DeclaredCrs, notes: &mut crate::loss::Notes) -> Option> { let DeclaredCrs { what, organization, code: declared_code, epsg, wkt1, wkt2 } = declared; let definition = wkt2.or(wkt1); if let Some(code) = epsg @@ -1257,8 +1263,9 @@ pub(crate) fn declared_reproject(declared: DeclaredCrs, notes: &mut Vec) // its organization and code (an IAU one). Its longitude/latitude are read with a notice. Other // coordinates are refused, because they would land in the wrong place. A planetary definition // that `read_wkt` reads is converted like any other, with its own notice. - let other_body = - |definition: Option<&str>, notes: &mut Vec| Reproject::planetary(what, organization, declared_code, definition, notes); + let other_body = |definition: Option<&str>, notes: &mut crate::loss::Notes| { + Reproject::planetary(what, organization, declared_code, definition, notes) + }; // Else the WKT it is defined with: a custom system, or a code this build doesn't know. if let Some(mut definition) = definition { // The definition read is the WKT2 whenever there is one. @@ -1273,7 +1280,7 @@ pub(crate) fn declared_reproject(declared: DeclaredCrs, notes: &mut Vec) // Unless the WKT2 is another body's system that is refused: it is the one that counts. // (One the WKT2 can't tell the coordinates of, as when it can't be parsed, gives way, // so the code isn't asked here: an IAU projected code would refuse a WKT1 that reads.) - if let Some(Err(refused)) = Reproject::planetary(what, None, None, Some(definition), &mut Vec::new()) { + if let Some(Err(refused)) = Reproject::planetary(what, None, None, Some(definition), &mut crate::loss::Notes::new()) { return Some(Err(refused)); } notes.push(format!("{what}: its WKT2 definition can't be read ({e}), so its WKT1 definition is used")); @@ -1300,7 +1307,10 @@ pub(crate) fn declared_reproject(declared: DeclaredCrs, notes: &mut Vec) if let Some(reproject) = wkt2.into_iter().chain([definition]).find_map(|d| other_body(Some(d), notes)) { return Some(reproject); } - notes.push(format!("{what} can't be read ({e}); read as longitude/latitude")); + notes.push(crate::loss::Note::loss( + crate::loss::LossCode::AssumedCrs, + format!("{what} can't be read ({e}); read as longitude/latitude"), + )); Crs::LonLat } }; diff --git a/crates/data/src/source/mysql.rs b/crates/data/src/source/mysql.rs index b769e95ca0..7a7fb36e81 100644 --- a/crates/data/src/source/mysql.rs +++ b/crates/data/src/source/mysql.rs @@ -712,7 +712,7 @@ impl MysqlSource { /// Opens a table's geometry column (`family`: the one family to read of a column of mixed /// types). `crs` (`EPSG:…`) is the coordinate system of a geometry whose SRID is 0. pub fn open(conn: Arc, table: Table, family: Option, crs: Option<&str>) -> Result { - let mut notes = Vec::new(); + let mut notes = crate::loss::Notes::new(); let g = ident(&table.column); let from = table.sql_from(); let server = conn.server; @@ -745,7 +745,10 @@ impl MysqlSource { }; let constrained = declared.is_some(); if !constrained && raw_srid != 0 { - notes.push(format!("the column doesn't fix a coordinate system: rows in one other than EPSG:{raw_srid} are left out")); + notes.push(crate::loss::Note::loss( + crate::loss::LossCode::DroppedFeature, + format!("the column doesn't fix a coordinate system: rows in one other than EPSG:{raw_srid} are left out"), + )); } let mut srid = raw_srid; if srid == 0 { @@ -755,13 +758,11 @@ impl MysqlSource { srid = u32::from(code); notes.extend(note); } - None => notes.push( - "the geometry doesn't say its coordinate system; read as longitude/latitude (add it again with \"crs\", such as EPSG:2263)".into(), - ), + None => notes.push(crate::loss::Note::loss(crate::loss::LossCode::AssumedCrs, "the geometry doesn't say its coordinate system; read as longitude/latitude (add it again with \"crs\", such as EPSG:2263)",)), } } if let Some(note) = tls_note(&conn.config.tls, conn.is_plain()) { - notes.push(note.into()); + notes.push(note); } let reproject = Reproject::from_epsg(Some(srid), &mut notes); let wkb = format!("ST_AsBinary({g}{})", server.axis_option()); @@ -804,9 +805,7 @@ impl MysqlSource { // Ids stable between reads: the key; without one, the rows are numbered as read. let numbered = pk.is_none(); if numbered { - notes.push( - "no single-column integer key: features are numbered as read, so their ids can change from one read to the next".into(), - ); + notes.push("no single-column integer key: features are numbered as read, so their ids can change from one read to the next"); } let order = pk.as_deref().map(|k| format!("ORDER BY t.{}", ident(k))).unwrap_or_default(); let id = pk.map(|k| ident(&k)).unwrap_or_else(|| "`rustgis rn`".into()); @@ -824,7 +823,7 @@ impl MysqlSource { count: None, crs: if srid == 0 { "EPSG:4326".into() } else { format!("EPSG:{srid}") }, indexed: false, - notes: notes.into(), + notes, zm_dropped: false, }, conn, @@ -1313,7 +1312,7 @@ mod tests { #[test] fn refused_database_view_is_not_a_whole_table_sample() { - let r = Reproject::from_crs(crate::raster::Crs::from_epsg(32617).unwrap(), &mut Vec::new()); + let r = Reproject::from_crs(crate::raster::Crs::from_epsg(32617).unwrap(), &mut crate::loss::Notes::new()); let req = Request { extent: Some(Extent::new(-120.0, -30.0, 10.0, 30.0)), limit: 10, own: None }; let all = Extent::new(-84.0, 0.0, -78.0, 25.0); assert!(native_window(&req, all, &r).unwrap_err().to_string().contains("can't be bounded")); diff --git a/crates/data/src/source/own_box_tests.rs b/crates/data/src/source/own_box_tests.rs index 960eb24918..feecd56ead 100644 --- a/crates/data/src/source/own_box_tests.rs +++ b/crates/data/src/source/own_box_tests.rs @@ -121,7 +121,7 @@ fn a_geojson_read_in_place_given_its_box_in_its_own_system_tests_features_there( #[test] fn a_box_in_its_own_system_is_tested_without_converting() { - let mut notes = Vec::new(); + let mut notes = crate::loss::Notes::new(); let r = Reproject::from_crs(utm31(), &mut notes); let (lonlat, utm) = around_paris(); let far = Geometry::Line(vec![vec![Coord::new(451_500.0, 5_411_500.0), Coord::new(1e9, 5_411_500.0)]]); @@ -141,7 +141,7 @@ fn a_box_in_its_own_system_is_tested_without_converting() { #[test] fn a_coordinate_that_isnt_a_number_is_left_out_in_its_own_system_too() { - let mut notes = Vec::new(); + let mut notes = crate::loss::Notes::new(); let r = Reproject::from_crs(utm31(), &mut notes); let (lonlat, utm) = around_paris(); let req = Request { extent: Some(lonlat), limit: 1, own: Some((utm31(), utm)) }; diff --git a/crates/data/src/source/parquet.rs b/crates/data/src/source/parquet.rs index 94fdb484e5..da9165cf6d 100644 --- a/crates/data/src/source/parquet.rs +++ b/crates/data/src/source/parquet.rs @@ -223,7 +223,7 @@ impl ParquetSource { if schema.column(geom_col).physical_type() != Physical::BYTE_ARRAY { return Err(DataError::Format(format!("geometry column '{primary}' is not binary"))); } - let mut notes = Vec::new(); + let mut notes = crate::loss::Notes::new(); let crs = col_meta.and_then(|c| c.get("crs")); let code = crs_code(crs); // Another body's system is said, or refused when its coordinates aren't longitude/latitude. @@ -235,7 +235,10 @@ impl ParquetSource { notes.push(format!("its coordinate system: {note}")); } else if code.is_none() && crs.is_some_and(|c| !c.is_null() && !is_crs84(c)) { // A coordinate system given without an EPSG code (and not OGC:CRS84) can't be converted. - notes.push("its coordinate system has no EPSG code; read as longitude/latitude".into()); + notes.push(crate::loss::Note::loss( + crate::loss::LossCode::AssumedCrs, + "its coordinate system has no EPSG code; read as longitude/latitude", + )); } let reproject = Reproject::from_epsg(code, &mut notes); let covering = find_covering(md, col_meta, &primary); @@ -315,7 +318,7 @@ impl ParquetSource { count, crs: reproject.label(), indexed: covering.is_some(), - notes: notes.into(), + notes, zm_dropped: false, }; info.note_columns( diff --git a/crates/data/src/source/postgis.rs b/crates/data/src/source/postgis.rs index ffe85406f1..1fa6a4ba45 100644 --- a/crates/data/src/source/postgis.rs +++ b/crates/data/src/source/postgis.rs @@ -882,7 +882,7 @@ impl PostgisSource { /// Opens a table's geometry column (`family`: the one family to read of a column of mixed /// types). `crs` (`EPSG:…`) is the coordinate system of a geometry that doesn't say its own. pub fn open(conn: Arc, table: Table, family: Option, crs: Option<&str>) -> Result { - let mut notes = Vec::new(); + let mut notes = crate::loss::Notes::new(); let g = table.geom(); // The SRID: the column's, else its rows', else the one given. let mut srid = if table.geography && table.srid == 0 { 4326 } else { table.srid }; @@ -892,7 +892,10 @@ impl PostgisSource { } let raw_srid = srid; if table.srid == 0 && !table.geography && raw_srid != 0 { - notes.push(format!("the column doesn't fix a coordinate system: rows in one other than EPSG:{raw_srid} are left out")); + notes.push(crate::loss::Note::loss( + crate::loss::LossCode::DroppedFeature, + format!("the column doesn't fix a coordinate system: rows in one other than EPSG:{raw_srid} are left out"), + )); } let given = crs.map(str::trim).filter(|c| !c.is_empty()); let mut native = g.clone(); @@ -904,18 +907,20 @@ impl PostgisSource { native = format!("ST_SetSRID({g}, {srid})"); notes.extend(note); } - None => notes.push( - "the geometry doesn't say its coordinate system; read as longitude/latitude (add it again with \"crs\", such as EPSG:2263)".into(), - ), + None => notes.push(crate::loss::Note::loss(crate::loss::LossCode::AssumedCrs, "the geometry doesn't say its coordinate system; read as longitude/latitude (add it again with \"crs\", such as EPSG:2263)",)), } } if let Some(note) = tls_note(&conn.tls, conn.is_plain()) { - notes.push(note.into()); + notes.push(note); } let reproject = match srid { - 0 | 4326 => Some(Reproject::from_crs(Crs::LonLat, &mut Vec::new())), + 0 | 4326 => Some(Reproject::from_crs(Crs::LonLat, &mut crate::loss::Notes::new())), // A coordinate system RustGIS can't convert itself is left to the server. - s => u32::try_from(s).ok().and_then(Crs::from_epsg).map(|c| Reproject::from_crs(c, &mut Vec::new())).filter(|r| !r.is_lonlat()), + s => u32::try_from(s) + .ok() + .and_then(Crs::from_epsg) + .map(|c| Reproject::from_crs(c, &mut crate::loss::Notes::new())) + .filter(|r| !r.is_lonlat()), }; // Read as the table holds it in a system RustGIS converts itself; otherwise the server // gives it in longitude/latitude. @@ -973,11 +978,10 @@ impl PostgisSource { _ => "(row_number() OVER ())::int8".to_string(), }; if pk.is_none() && !matches!(relkind.as_str(), "r" | "m") { - notes.push("a view or partitioned table without a single-column key: its features are numbered as read, so their ids can change from one read to the next".into()); + notes.push("a view or partitioned table without a single-column key: its features are numbered as read, so their ids can change from one read to the next"); } else if pk.is_none() { notes.push( - "no single-column integer key: features are numbered by their place in the table, which changes when rows are updated" - .into(), + "no single-column integer key: features are numbered by their place in the table, which changes when rows are updated", ); } let mut select = vec![id, wkb]; @@ -995,7 +999,7 @@ impl PostgisSource { count: None, crs: if srid == 0 { "EPSG:4326".into() } else { format!("EPSG:{srid}") }, indexed: false, - notes: notes.into(), + notes, zm_dropped: false, }, conn, @@ -1793,12 +1797,12 @@ mod tests { let utm = Crs::from_epsg(32631).unwrap(); let own = Extent::new(440_000.0, 5_400_000.0, 470_000.0, 5_420_000.0); let lonlat = Some(Extent::new(2.2, 48.75, 2.5, 48.95)); - let table = Reproject::from_crs(utm, &mut Vec::new()); + let table = Reproject::from_crs(utm, &mut crate::loss::Notes::new()); assert_eq!(own_query_box(Some(&table), &Request { extent: lonlat, limit: 10, own: Some((utm, own)) }), Some(own)); let swiss = Crs::from_epsg(2056).unwrap(); assert_eq!(own_query_box(Some(&table), &Request { extent: lonlat, limit: 10, own: Some((swiss, own)) }), None); assert_eq!(own_query_box(Some(&table), &Request { extent: lonlat, limit: 10, own: None }), None); - let geographic = Reproject::from_crs(Crs::LonLat, &mut Vec::new()); + let geographic = Reproject::from_crs(Crs::LonLat, &mut crate::loss::Notes::new()); assert_eq!(own_query_box(Some(&geographic), &Request { extent: lonlat, limit: 10, own: Some((Crs::LonLat, own)) }), None); assert_eq!(own_query_box(None, &Request { extent: lonlat, limit: 10, own: Some((utm, own)) }), None); } @@ -1860,7 +1864,7 @@ mod tests { #[test] fn refused_database_view_does_not_reach_the_connection() { let mut source = source("POINT"); - source.reproject = Some(Reproject::from_crs(Crs::from_epsg(32617).unwrap(), &mut Vec::new())); + source.reproject = Some(Reproject::from_crs(Crs::from_epsg(32617).unwrap(), &mut crate::loss::Notes::new())); for limit in [0, 10] { let req = Request { extent: Some(Extent::new(-120.0, -30.0, 10.0, 30.0)), limit, own: None }; let error = source.read(&req).unwrap_err().to_string(); diff --git a/crates/data/src/source/shp.rs b/crates/data/src/source/shp.rs index e9012a6942..085dcb682d 100644 --- a/crates/data/src/source/shp.rs +++ b/crates/data/src/source/shp.rs @@ -144,7 +144,7 @@ impl ShpSource { } // Taken before anything is read, so a file written while it opens is seen as changed. let stamps = [Stamp::of(path), Stamp::of(&dbf)]; - let mut notes = Vec::new(); + let mut notes = crate::loss::Notes::new(); let table = read_table(&dbf)?; let cpg = crate::dbf::read_cpg(path, &mut notes); let encoding = crate::dbf::encoding(cpg.as_deref(), table.ldid, &mut notes); @@ -206,8 +206,7 @@ impl ShpSource { // is said. if !zero && !(a_box && h0 <= x0 && h1 <= y0 && h2 >= x1 && h3 >= y1) { notes.push( - "the .shp header's bounding box doesn't hold its shapes, or isn't a box: the layer's extent is taken from the shapes" - .into(), + "the .shp header's bounding box doesn't hold its shapes, or isn't a box: the layer's extent is taken from the shapes", ); } Extent::new(f64::from(x0), f64::from(y0), f64::from(x1), f64::from(y1)) @@ -217,7 +216,7 @@ impl ShpSource { // holds): said, as the layer has no extent. A file of no records loses nothing by it; // shapes there but without a usable box are said below instead. if native.is_none() && index.count > 0 && index.unboxed == 0 && !zero { - notes.push("the .shp has no shapes to frame: its header's box isn't used, and the layer has no extent".into()); + notes.push("the .shp has no shapes to frame: its header's box isn't used, and the layer has no extent"); } // Records with no usable box, neither stored nor from their own points (a coordinate that // isn't a number or past f32's range, or a record that can't be read; a backwards stored @@ -233,10 +232,12 @@ impl ShpSource { } let extent = native.map_or(Extent::EMPTY, |n| reproject.extent_to_lonlat(&n)); if reproject.is_lonlat() && extent.beyond_lonlat() { - notes.push("coordinates are not longitude/latitude; RustGIS reads them as WGS 84 and they may draw out of place".into()); + notes.push(crate::loss::Note::loss( + crate::loss::LossCode::AssumedCrs, + "coordinates are not longitude/latitude; RustGIS reads them as WGS 84 and they may draw out of place", + )); } let (names, not_utf8) = read_names(&dbf, table.columns.len(), &encoding)?; - let mut notes = crate::loss::Notes::from(notes); notes.extend(crate::dbf::not_utf8_names_note(¬_utf8, encoding.name())); let fields = table.columns.iter().zip(names).map(|(c, n)| Field::new(n, c.out)).collect(); let mut info = SourceInfo { @@ -303,6 +304,7 @@ impl ShpSource { let mut buf = Vec::new(); let mut row = vec![0u8; self.table.row_len]; let (mut skipped, mut unread_dates, mut null_text, mut boxed_off, mut not_utf8) = (0, Vec::new(), Vec::new(), 0u64, Vec::new()); + let mut nonfinite = Vec::new(); let mut deleted = 0usize; // The same directory, ordering, extent rules and read-only scan fallback as sampled // reads, with no interaction row cap. The index visits records without materializing @@ -370,7 +372,7 @@ impl ShpSource { deleted += 1; return Ok(()); } - self.table.values(&row, &encoding, &self.encoding, &mut unread_dates, &mut null_text, &mut not_utf8) + self.table.values(&row, &encoding, &self.encoding, &mut unread_dates, &mut null_text, &mut not_utf8, &mut nonfinite) } else { vec![Value::Null; self.table.columns.len()] }; @@ -392,7 +394,12 @@ impl ShpSource { unread_dates, rounded_dates: Vec::new(), null_text, - notes: boxed_off_note(boxed_off, false, late).into_iter().chain(deleted_note(deleted, false)).collect(), + notes: boxed_off_note(boxed_off, false, late) + .into_iter() + .chain(deleted_note(deleted, false)) + .map(crate::loss::Note::from) + .chain(crate::io::nonfinite_note(&self.info.fields, &nonfinite)) + .collect(), not_utf8, }) } @@ -437,6 +444,7 @@ impl FeatureSource for ShpSource { let mut row = vec![0u8; self.table.row_len]; let mut features = Vec::new(); let (mut skipped, mut unread_dates, mut null_text, mut boxed_off, mut not_utf8) = (0, Vec::new(), Vec::new(), 0u64, Vec::new()); + let mut nonfinite = Vec::new(); let mut deleted = 0usize; // An extent the file's system couldn't bound (#1925) has no boxes for the index to sample // by: every record is visited, tested, and the matches sampled as they come. @@ -501,7 +509,7 @@ impl FeatureSource for ShpSource { if late && !sample.wants() { return Ok(()); } - self.table.values(&row, &encoding, &self.encoding, &mut unread_dates, &mut null_text, &mut not_utf8) + self.table.values(&row, &encoding, &self.encoding, &mut unread_dates, &mut null_text, &mut not_utf8, &mut nonfinite) } else { if late && !sample.wants() { return Ok(()); @@ -536,6 +544,8 @@ impl FeatureSource for ShpSource { notes: boxed_off_note(boxed_off, !late && !complete, late) .into_iter() .chain(deleted_note(deleted, !late && !complete)) + .map(crate::loss::Note::from) + .chain(crate::io::nonfinite_note(&self.info.fields, &nonfinite)) .collect(), not_utf8, }) @@ -852,6 +862,7 @@ impl Table { unread_dates: &mut Vec, null_text: &mut Vec, not_utf8: &mut Vec, + nonfinite: &mut Vec, ) -> Vec { let mut out = Vec::with_capacity(self.columns.len()); for (k, c) in self.columns.iter().enumerate() { @@ -877,6 +888,9 @@ impl Table { if matches!(v, Value::Text(_)) && declared.malformed(padded(b)) { super::not_utf8_at(not_utf8, k); } + if matches!(v, Value::Null) && not_finite(c, b) { + super::unread_dates_by(nonfinite, k, 1); + } v } }); @@ -922,6 +936,16 @@ fn trimmed(b: &[u8]) -> &[u8] { b.get(start..end).unwrap_or(&[]) } +/// Whether a numeric `.dbf` value holds a number that isn't finite (nan or inf), which [`value`] +/// reads as empty; a blank one doesn't. +fn not_finite(c: &Column, b: &[u8]) -> bool { + match c.ty { + b'N' | b'F' => std::str::from_utf8(trimmed(b)).ok().and_then(|t| t.parse::().ok()).is_some_and(|v| !v.is_finite()), + b'O' | b'Y' => b.get(..8).and_then(|v| v.try_into().ok()).map(f64::from_le_bytes).is_some_and(|v| !v.is_finite()), + _ => false, + } +} + /// One `.dbf` value, as a Shapefile read whole gives it (blank and unreadable values are null; /// [`Table::values`] counts the dates). fn value(c: &Column, b: &[u8], encoding: &dyn shapefile::dbase::Encoding) -> Value { @@ -976,7 +1000,7 @@ fn value(c: &Column, b: &[u8], encoding: &dyn shapefile::dbase::Encoding) -> Val /// The coordinate system in a `.prj`, with what couldn't be understood said in the notes. Another /// body's system that can't be read is an error, as when the file is read whole. -fn shp_reproject(prj: Option<&str>, notes: &mut Vec) -> Result { +fn shp_reproject(prj: Option<&str>, notes: &mut crate::loss::Notes) -> Result { use crate::raster::planetary; let crs = match prj.map(|p| (p, crate::raster::wkt::read_wkt(p))) { None => crate::raster::Crs::LonLat, @@ -990,7 +1014,10 @@ fn shp_reproject(prj: Option<&str>, notes: &mut Vec) -> Result) -> Result { + pub fn open(path: &Path, len: u64, notes: &mut crate::loss::Notes) -> Result { use super::cache; use crate::source::external::{fnv1a, stamp}; // Cancel is looked at once even when the index is reused, so an opening can always be @@ -402,7 +402,7 @@ enum Storage { Scan { path: std::path::PathBuf, len: u64 }, } impl Index { - pub fn open(path: &Path, len: u64, notes: &mut Vec) -> Result { + pub fn open(path: &Path, len: u64, notes: &mut crate::loss::Notes) -> Result { match DiskIndex::open(path, len, notes) { Ok(disk) => Ok(Self { count: disk.count, bounds: disk.bounds, unboxed: disk.unboxed, storage: Storage::Disk(disk) }), // Canceled while it was built: the run stops, not a scan in its place. @@ -414,7 +414,7 @@ impl Index { } } /// The index without a cache: the records' headers scanned now, and again for each read. - fn scanning(path: &Path, len: u64, notes: &mut Vec) -> Result { + fn scanning(path: &Path, len: u64, notes: &mut crate::loss::Notes) -> Result { let Scanned { count, note, bounds, unboxed } = scanned(path, len)?; if !note.is_empty() { notes.push(note); @@ -682,7 +682,7 @@ mod tests { crate::io::write_path(&ds, &path).unwrap(); let len = std::fs::metadata(&path).unwrap().len(); super::super::cache::with_index_dir(tmp.path().join("cache"), || { - let index = Index::open(&path, len, &mut Vec::new()).unwrap(); + let index = Index::open(&path, len, &mut crate::loss::Notes::new()).unwrap(); assert!(index.indexed()); for (area, many) in [([2.5f32, 2.5, 4.5, 5.5], false), ([0.0, 0.0, 12.0, 15.0], true), ([50.0, 50.0, 60.0, 60.0], false)] { let mut expected = Vec::new(); @@ -779,7 +779,7 @@ mod tests { .unwrap(); ids }; - let mut notes = Vec::new(); + let mut notes = crate::loss::Notes::new(); let scan = Index::scanning(&path, len, &mut notes).unwrap(); assert!(!scan.indexed()); assert_eq!((scan.bounds, scan.unboxed), (whole, 0)); @@ -834,7 +834,7 @@ mod tests { std::fs::write(&path, &b).unwrap(); let len = b.len() as u64; let second = Some([12.0, 22.0, 12.5, 22.5]); - let mut notes = Vec::new(); + let mut notes = crate::loss::Notes::new(); let scan = Index::scanning(&path, len, &mut notes).unwrap(); assert_eq!((scan.bounds, scan.unboxed), (second, 0)); super::super::cache::with_index_dir(tmp.path().join("cache"), || { @@ -857,8 +857,8 @@ mod tests { crate::io::write_path(&ds, &path).unwrap(); let mut b = std::fs::read(&path).unwrap(); let len = b.len() as u64; - let mut notes = Vec::new(); - let both = |p: &Path, notes: &mut Vec, cache: &str| { + let mut notes = crate::loss::Notes::new(); + let both = |p: &Path, notes: &mut crate::loss::Notes, cache: &str| { let scan = Index::scanning(p, len, notes).unwrap(); let disk = super::super::cache::with_index_dir(tmp.path().join(cache), || Index::open(p, len, notes).unwrap()); assert!(disk.indexed()); @@ -895,7 +895,7 @@ mod tests { // Records of 28 bytes from 100 to 240, each read 60 bytes ahead: past the real end (taken as // 100 bytes further) from the fourth. let len = std::fs::metadata(&path).unwrap().len() + 100; - let mut notes = Vec::new(); + let mut notes = crate::loss::Notes::new(); let scan = Index::scanning(&path, len, &mut notes).unwrap(); assert_eq!(scan.count, 3); assert!(notes.iter().any(|n| n.contains("couldn't be read from record 4; the rest are left out")), "{notes:?}"); @@ -952,7 +952,7 @@ mod tests { let probe = std::sync::Arc::new(crate::progress::tests::Counted::default()); probe.cancel.store(true, std::sync::atomic::Ordering::Relaxed); let _installed = crate::progress::install(Some(probe)); - let mut notes = Vec::new(); + let mut notes = crate::loss::Notes::new(); super::super::cache::with_index_dir(tmp.path().join("cache"), || { assert!(matches!(Index::open(&path, len, &mut notes), Err(crate::DataError::Cancelled))); }); diff --git a/crates/data/src/source/shp/tests.rs b/crates/data/src/source/shp/tests.rs index 4ba32c65f7..59017d8897 100644 --- a/crates/data/src/source/shp/tests.rs +++ b/crates/data/src/source/shp/tests.rs @@ -665,7 +665,7 @@ fn a_nan_shape_outside_an_area_its_system_cant_bound_is_counted_as_of_the_layer( p }; let view = Extent::new(-120.0, -30.0, 10.0, 30.0); - let r = Reproject::from_crs(crs, &mut Vec::new()); + let r = Reproject::from_crs(crs, &mut crate::loss::Notes::new()); assert!(r.extent_from_lonlat(&view).is_none(), "the view's edge is refused"); const SAID: &str = "have a coordinate that isn't a number under a bounding box that is one"; let said = |notes: &[crate::loss::Note]| notes.iter().filter(|n| n.contains(SAID)).map(|n| n.text.clone()).collect::>(); diff --git a/crates/data/src/source/sqlserver.rs b/crates/data/src/source/sqlserver.rs index 63c307194e..1981e6edf6 100644 --- a/crates/data/src/source/sqlserver.rs +++ b/crates/data/src/source/sqlserver.rs @@ -743,9 +743,9 @@ const FINE_TIMES_SAMPLE: u64 = 100_000; /// (`fine`), which are read to the microsecond: the columns where a row looked at (up to 100,000, /// whichever the server returns) has one, and those that may when the rows looked at have none but /// weren't all of them (or the look failed). -fn fine_times_note(conn: &Conn, from: &str, fine: &[String]) -> Vec { +fn fine_times_note(conn: &Conn, from: &str, fine: &[String]) -> crate::loss::Notes { if fine.is_empty() { - return Vec::new(); + return crate::loss::Notes::new(); } let checks: Vec = fine.iter().map(|c| format!("MAX(CASE WHEN DATEPART(NANOSECOND, {}) % 1000 <> 0 THEN 1 ELSE 0 END)", ident(c))).collect(); @@ -765,23 +765,26 @@ fn fine_times_note(conn: &Conn, from: &str, fine: &[String]) -> Vec { /// [`fine_times_note`]'s text: `found` counts, for each column of `fine`, whether a row looked at /// has a 100-nanosecond digit (`None` when the look failed); `complete` is whether the rows looked /// at were all of them. -fn fine_times_said(fine: &[String], found: Option<&[usize]>, complete: bool) -> Vec { +fn fine_times_said(fine: &[String], found: Option<&[usize]>, complete: bool) -> crate::loss::Notes { if fine.is_empty() { - return Vec::new(); + return crate::loss::Notes::new(); } let fields: Vec = fine.iter().map(|c| Field::new(c.clone(), FieldType::DateTime)).collect(); let Some(found) = found else { - return vec![format!( + return crate::loss::Notes::from(vec![format!( "date-times in {} may hold 100-nanosecond digits (they couldn't be checked): any are read to the microsecond, the last digit left out", crate::io::named_fields(&fields, &vec![1; fine.len()]) - )]; + )]); }; let has = |i: usize| found.get(i).is_some_and(|&n| n > 0); - let mut notes = Vec::new(); + let mut notes = crate::loss::Notes::new(); if (0..fine.len()).any(has) { - notes.push(format!( - "date-times in {} hold 100-nanosecond digits: they're read to the microsecond, the last digit left out", - crate::io::named_fields(&fields, found) + notes.push(crate::loss::Note::loss( + crate::loss::LossCode::ChangedRounded, + format!( + "date-times in {} hold 100-nanosecond digits: they're read to the microsecond, the last digit left out", + crate::io::named_fields(&fields, found) + ), )); } let rest: Vec = (0..fine.len()).map(|i| usize::from(!has(i))).collect(); @@ -800,7 +803,7 @@ impl SqlServerSource { if conn.major < 11 { return Err(DataError::Unsupported("SQL Server tables are read from SQL Server 2012 and later".into())); } - let mut notes = Vec::new(); + let mut notes = crate::loss::Notes::new(); let g = ident(&table.column); let geography = table.geography(); let columns = gdb::columns_of(&conn, &table.schema, &table.name)?; @@ -819,7 +822,10 @@ impl SqlServerSource { let raw_srid = rows.first().and_then(|r| int_of(at(r, 0))).and_then(|n| u32::try_from(n).ok()).unwrap_or(if geography { 4326 } else { 0 }); if raw_srid != 0 { - notes.push(format!("the column doesn't fix a coordinate system: rows in one other than EPSG:{raw_srid} are left out")); + notes.push(crate::loss::Note::loss( + crate::loss::LossCode::DroppedFeature, + format!("the column doesn't fix a coordinate system: rows in one other than EPSG:{raw_srid} are left out"), + )); } let mut srid = raw_srid; if srid == 0 @@ -835,14 +841,14 @@ impl SqlServerSource { srid = u32::from(code); notes.extend(note); } - None => notes.push("the geometry doesn't say its coordinate system; read as longitude/latitude (add it again with \"crs\", such as EPSG:2263)".into()), + None => notes.push(crate::loss::Note::loss(crate::loss::LossCode::AssumedCrs, "the geometry doesn't say its coordinate system; read as longitude/latitude (add it again with \"crs\", such as EPSG:2263)")), } } if conn.config.encrypt == Encrypt::Off { - notes.push("the connection isn't encrypted after login (encrypt=false)".into()); + notes.push("the connection isn't encrypted after login (encrypt=false)"); } if conn.config.trust_cert { - notes.push("the server's certificate isn't checked (trust-server-certificate=true)".into()); + notes.push("the server's certificate isn't checked (trust-server-certificate=true)"); } let reproject = Reproject::from_epsg(Some(srid), &mut notes); let cols = conn.query("SELECT COLUMN_NAME, LOWER(DATA_TYPE), DATETIME_PRECISION FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = @P1 AND TABLE_NAME = @P2 ORDER BY ORDINAL_POSITION", &[&table.schema, &table.name])?; @@ -878,9 +884,7 @@ impl SqlServerSource { notes.extend(r.notes); } if projection.numbered { - notes.push( - "no single-column integer key: features are numbered as read, so their ids can change from one read to the next".into(), - ); + notes.push("no single-column integer key: features are numbered as read, so their ids can change from one read to the next"); } let mut src = SqlServerSource { info: SourceInfo { @@ -892,7 +896,7 @@ impl SqlServerSource { count: None, crs: if srid == 0 { "EPSG:4326".into() } else { format!("EPSG:{srid}") }, indexed: false, - notes: notes.into(), + notes, zm_dropped: false, }, conn, @@ -1271,7 +1275,7 @@ mod tests { // whole without any, say nothing; a larger table without any in the rows looked at may. let fine = ["seen".to_string(), "logged".to_string()]; assert_eq!( - fine_times_said(&fine, Some(&[0, 1]), true), + fine_times_said(&fine, Some(&[0, 1]), true).texts().collect::>(), ["date-times in 'logged' hold 100-nanosecond digits: they're read to the microsecond, the last digit left out"] ); assert!(fine_times_said(&fine, Some(&[0, 0]), true).is_empty()); @@ -1327,7 +1331,7 @@ mod tests { #[test] fn refused_database_view_is_not_a_whole_table_sample() { - let r = Reproject::from_crs(Crs::from_epsg(32617).unwrap(), &mut Vec::new()); + let r = Reproject::from_crs(Crs::from_epsg(32617).unwrap(), &mut crate::loss::Notes::new()); let req = Request { extent: Some(Extent::new(-120.0, -30.0, 10.0, 30.0)), limit: 10, own: None }; let all = Extent::new(-84.0, 0.0, -78.0, 25.0); assert!(native_window(&req, all, &r, false, 160).unwrap_err().to_string().contains("can't be bounded")); @@ -1337,7 +1341,7 @@ mod tests { #[test] fn native_windows_respect_database_compatibility() { - let reproject = Reproject::from_crs(Crs::LonLat, &mut Vec::new()); + let reproject = Reproject::from_crs(Crs::LonLat, &mut crate::loss::Notes::new()); let req = Request { extent: Some(Extent::new(-180.0, -90.0, 180.0, 90.0)), limit: 100, own: None }; for compatibility in [0, 80, 90, 100] { assert_eq!(native_window(&req, Extent::EMPTY, &reproject, true, compatibility).unwrap(), None); diff --git a/crates/data/src/source/tests.rs b/crates/data/src/source/tests.rs index 665e7d1807..2a0ffb9317 100644 --- a/crates/data/src/source/tests.rs +++ b/crates/data/src/source/tests.rs @@ -63,7 +63,7 @@ fn explicit_method_1028_warns_for_known_geopackage_authorities() { let sphere = wkt.replace("298.257223563", "0"); let wkt1 = crate::raster::wkt::to_wkt(Crs::from_epsg(4087).unwrap()).unwrap(); for (definition, code, warned) in [(wkt, 4087, true), (&sphere, 4087, false), (&wkt1, 4087, false), (wkt, 3857, false)] { - let mut notes = Vec::new(); + let mut notes = crate::loss::Notes::new(); let row = GpkgSrs { organization: Some("EPSG".into()), code: Some(code), definition: Some(definition.into()), definition_12_063: None }; let read = gpkg_reproject(100001, Some(row), &mut notes).unwrap(); @@ -86,7 +86,7 @@ fn explicit_method_1028_warns_for_known_geopackage_authorities() { [("GEOGCRS[", true), (r#"ENGCRS["site",EDATUM["site"]]"#, true), (&wkt.replace(r#",ID["EPSG",1028]"#, ""), true), (&sphere, false)] { assert_ne!(wkt2, wkt); - let mut notes = Vec::new(); + let mut notes = crate::loss::Notes::new(); let row = GpkgSrs { organization: Some("EPSG".into()), code: Some(4087), @@ -124,7 +124,7 @@ fn a_geopackage_row_read_by_its_code_says_its_definitions_grid() { let xy = Coord::new(430_000.0, 4_580_000.0); let by_code = Crs::from_epsg(23031).unwrap().transformer().unwrap().to_lonlat(xy).unwrap(); for (definition, wkt2, notice) in [(bound.as_str(), false, true), (bound.as_str(), true, true), (ED50_UTM31, false, false)] { - let mut notes = Vec::new(); + let mut notes = crate::loss::Notes::new(); let row = GpkgSrs { organization: Some("EPSG".into()), code: Some(23031), @@ -158,7 +158,7 @@ fn a_geopackage_rows_code_gives_way_to_its_definitions_shift() { definition_12_063: wkt2.map(Into::into), }; let read = |row: GpkgSrs| { - let mut notes = Vec::new(); + let mut notes = crate::loss::Notes::new(); let read = gpkg_reproject(100001, Some(row), &mut notes).unwrap(); (read, notes) }; @@ -243,7 +243,7 @@ fn a_geopackage_rows_unread_wkt2_is_said_beside_its_code() { definition_12_063: Some(wkt2.into()), }; let read = |row: GpkgSrs| { - let mut notes = Vec::new(); + let mut notes = crate::loss::Notes::new(); let read = gpkg_reproject(100001, Some(row), &mut notes).unwrap(); (read, notes) }; @@ -261,7 +261,7 @@ fn a_geopackage_rows_unread_wkt2_is_said_beside_its_code() { // The same notice as without a code. assert_eq!(read(row(None, &other, "PROJCRS[")).1, notes); // And when the code is used: the WKT1 gives the code's own shift, or none, or there is none. - let by_code = notes[0].replace("so its WKT1 definition is used", "so EPSG:27700 is used"); + let by_code = notes[0].as_str().replace("so its WKT1 definition is used", "so EPSG:27700 is used"); let bng = crate::raster::wkt::tests::bng_wkt1(); for wkt1 in [Some(bng.clone()), Some(bng.replace(&format!(",{BNG_SHIFT}"), "")), None] { let (r, used) = read(GpkgSrs { definition: wkt1, ..row(Some(27700), "", "PROJCRS[") }); @@ -307,7 +307,7 @@ fn a_geopackage_rows_unread_bound_definition_is_said_beside_its_code() { definition_12_063: wkt2.map(Into::into), }; let read = |row: GpkgSrs| { - let mut notes = Vec::new(); + let mut notes = crate::loss::Notes::new(); let read = gpkg_reproject(100001, Some(row), &mut notes).unwrap(); (read, notes) }; @@ -321,7 +321,7 @@ fn a_geopackage_rows_unread_bound_definition_is_said_beside_its_code() { let (r, notes) = read(row(None, definition, wkt2)); assert_eq!(r.crs, Crs::LonLat); assert_eq!( - notes, + notes.texts().collect::>(), [ "its coordinate system (srs_id 100001) can't be read (the shift from NAD27 to WGS 84 isn't known); read as longitude/latitude" ] @@ -2501,6 +2501,41 @@ fn shapefile_text_keeps_its_leading_spaces_and_counts_null_markers() { assert!(whole_report.messages.iter().chain(&report.messages).all(|m| !m.contains("written as Null")), "{:?}", report.messages); } +/// A `.dbf` number that isn't finite (nan or inf) is read as empty in place as it is whole, and +/// said as `dropped.value` both ways; a blank one isn't counted. +#[test] +fn shapefile_in_place_says_numbers_that_arent_finite() { + let d = dir().join("shp-nonfinite"); + std::fs::create_dir_all(&d).unwrap(); + let mut ds = Dataset::new("depths", GeometryType::Point, vec![Field::new("depth", FieldType::Double)]); + for (i, v) in [Value::Float(1_234_567.0), Value::Float(2.5), Value::Null].into_iter().enumerate() { + ds.push(Some(Geometry::Point(Coord::new(i as f64, 0.0))), vec![v]); + } + let p = d.join("depths.shp"); + write_shapefile(&ds, &p); + let dbf = p.with_extension("dbf"); + let mut bytes = std::fs::read(&dbf).unwrap(); + // The whole number as written (`1234567.000…`), replaced by `nan` in the same width. + let at = bytes.windows(7).position(|w| w == b"1234567").unwrap(); + let end = at + bytes[at..].iter().position(|c| *c == b' ' || *c == 0x1A).unwrap_or(bytes.len() - at); + bytes[at..end].fill(b' '); + bytes[end - 3..end].copy_from_slice(b"nan"); + std::fs::write(&dbf, bytes).unwrap(); + let (whole, whole_report) = crate::io::read_path(&p).unwrap(); + let (inplace, report) = materialize(open_path(&p, None).unwrap().as_ref()).unwrap(); + let values: Vec<&Value> = whole.features.iter().map(|f| &f.attrs[0]).collect(); + assert_eq!(values.iter().filter(|v| ***v == Value::Null).count(), 2, "{values:?}"); + assert!(values.contains(&&Value::Float(2.5)), "{values:?}"); + assert_eq!(inplace.features, whole.features); + let said = "1 number isn't finite (nan or inf) and was read as empty, in 'depth'"; + for messages in [&whole_report.messages, &report.messages] { + let notes: Vec<_> = messages.iter().filter(|m| m.contains("finite")).collect(); + assert_eq!(notes.len(), 1, "{messages:?}"); + assert!(notes[0].as_str().ends_with(said), "{messages:?}"); + assert_eq!(notes[0].loss, Some(crate::loss::LossCode::DroppedValue)); + } +} + #[test] fn shapefile_in_place_reprojects_from_its_prj() { let d = dir().join("shp-utm"); @@ -2683,7 +2718,7 @@ fn geojson_in_place_rejects_partial_collections_with_a_notice() { let src = geojson::GeoJsonSource::open_with(&p, "x", in_memory).unwrap(); assert_eq!(src.info().count, Some(1)); assert_eq!(src.skipped_at_open(), 1); - assert_eq!(src.info().notes, ["1 features had unreadable geometry"]); + assert_eq!(src.info().notes.texts().collect::>(), ["1 features had unreadable geometry"]); let (ds, streamed_report) = materialize(&src).unwrap(); assert_eq!(ds.features, whole.features); assert_eq!(streamed_report.skipped, report.skipped); @@ -3718,12 +3753,12 @@ fn geoparquet_columns_not_kept_or_read_as_numbers_are_said() { // Read in place: the source's notes, which adding the layer gives as notices. let src = open_path(&path, None).unwrap(); let info = src.info(); - assert_eq!(info.notes, vec![left_out.to_string()]); + assert_eq!(info.notes.texts().collect::>(), vec![left_out.to_string()]); let names: Vec<&str> = info.fields.iter().map(|f| f.name.as_str()).collect(); assert_eq!(names, ["name", "seen", "logged", "day"]); // Read whole: the same, in the read's report, and the values as said. let (ds, report) = materialize(src.as_ref()).unwrap(); - assert_eq!(report.messages, vec![format!("columns: {left_out}")]); + assert_eq!(report.messages.texts().collect::>(), vec![format!("columns: {left_out}")]); assert_eq!( ds.features[0].attrs, vec![ @@ -3765,11 +3800,11 @@ fn flatgeobuf_binary_columns_are_said_and_left_out() { let note = "1 column of a type RustGIS has no field for was left out: blob (binary)"; let src = open_path(&path, None).unwrap(); - assert_eq!(src.info().notes, vec![note.to_string()]); + assert_eq!(src.info().notes.texts().collect::>(), vec![note.to_string()]); let names: Vec<&str> = src.info().fields.iter().map(|f| f.name.as_str()).collect(); assert_eq!(names, ["name", "value"]); let (ds, report) = materialize(src.as_ref()).unwrap(); - assert_eq!(report.messages, vec![format!("blobs: {note}")]); + assert_eq!(report.messages.texts().collect::>(), vec![format!("blobs: {note}")]); assert_eq!(ds.features[0].attrs, vec![Value::Text("a".into()), Value::Int(42)]); let clean = d.path().join("clean.fgb"); @@ -4601,7 +4636,7 @@ fn a_feature_just_outside_an_extent_is_left_out_of_its_read() { /// from its meridian, where transverse Mercator refuses places: such a view isn't bounded. #[test] fn a_query_box_leaves_out_nothing_in_view_when_its_edge_is_refused() { - let r = Reproject::from_crs(Crs::from_epsg(32617).unwrap(), &mut Vec::new()); + let r = Reproject::from_crs(Crs::from_epsg(32617).unwrap(), &mut crate::loss::Notes::new()); let t = r.transformer().unwrap(); for view in [ Extent::new(-120.0, -30.0, 10.0, 30.0), @@ -4669,7 +4704,7 @@ fn a_view_its_system_cant_bound_reads_what_is_in_view() { } ds.push(None, vec![Value::Int(-1)]); let view = Extent::new(-120.0, -30.0, 10.0, 30.0); - let r = Reproject::from_crs(Crs::from_epsg(32617).unwrap(), &mut Vec::new()); + let r = Reproject::from_crs(Crs::from_epsg(32617).unwrap(), &mut crate::loss::Notes::new()); assert!(r.extent_from_lonlat(&view).is_none(), "the view's edge is refused"); for ext in ["shp", "fgb", "gpkg", "parquet", "geojson"] { let p = d.join(format!("pts.{ext}")); diff --git a/crates/data/src/topojson.rs b/crates/data/src/topojson.rs index b5c42be68a..8e4a565b07 100644 --- a/crates/data/src/topojson.rs +++ b/crates/data/src/topojson.rs @@ -475,15 +475,18 @@ fn read_with(file_name: &str, text: &str, budget: usize) -> Result 0 { - rep.messages.push(format!( + rep.messages.push(crate::loss::Note::loss(crate::loss::LossCode::DroppedGeometry, format!( "{} couldn't be read (unreadable coordinates or arcs, a member of a collection that can't be read, or a kind of geometry not read): kept as features without geometry", counted(bad, "geometry", "geometries") - )); + ))); } if cut > 0 { - rep.messages.push(format!( - "{} left out at the limit of {budget} coordinates rebuilt from the file's arcs: kept as features without geometry", - counted(cut, "geometry", "geometries") + rep.messages.push(crate::loss::Note::loss( + crate::loss::LossCode::DroppedGeometry, + format!( + "{} left out at the limit of {budget} coordinates rebuilt from the file's arcs: kept as features without geometry", + counted(cut, "geometry", "geometries") + ), )); } let lost: usize = used.iter().filter_map(|i| topo.arcs_lost.get(*i)).sum(); @@ -501,16 +504,22 @@ fn read_with(file_name: &str, text: &str, budget: usize) -> Result MAX_OBJECTS && let Some((_, rep)) = out.first_mut() { - rep.messages.push(format!( - "{} left out past the limit of {MAX_OBJECTS} objects: only the first {MAX_OBJECTS} are read", - counted(objects.len() - MAX_OBJECTS, "object", "objects") + rep.messages.push(crate::loss::Note::loss( + crate::loss::LossCode::DroppedOverLimit, + format!( + "{} left out past the limit of {MAX_OBJECTS} objects: only the first {MAX_OBJECTS} are read", + counted(objects.len() - MAX_OBJECTS, "object", "objects") + ), )); } if out.is_empty() { diff --git a/crates/engine/tests/integration/never_silent_reading.rs b/crates/engine/tests/integration/never_silent_reading.rs index 45ffd222da..9718ecd9f8 100644 --- a/crates/engine/tests/integration/never_silent_reading.rs +++ b/crates/engine/tests/integration/never_silent_reading.rs @@ -947,7 +947,8 @@ fn read(dir: &std::path::Path, file: &str, content: &[u8], beside: &[(&str, Vec< || native.features[0].geometry != Some(rustgis_engine::data::Geometry::Point(rustgis_engine::geom::Coord::new(1.0, 2.0))) || native.features[0].attrs != [rustgis_engine::data::Value::Int(1)] || report.skipped != 0 - || report.messages != if collection { vec![collection_note] } else { vec![] } + || report.messages.texts().collect::>() != if collection { vec![collection_note] } else { vec![] } + || report.messages.iter().any(|m| m.loss != Some(LossCode::DroppedGeometry)) { return Err(std::io::Error::other(format!("CSV collection retained data or notice differs: {native:?}, {report:?}"))); } @@ -966,8 +967,8 @@ fn read(dir: &std::path::Path, file: &str, content: &[u8], beside: &[(&str, Vec< check_dbf_date(&native, dbf_invalid)?; } let expected = if csv_extra { &extra_messages } else { &dbf_messages }; - // The invalid date is said as `dropped.value`; the extra cell isn't coded yet. - let coded = report.messages.iter().all(|m| (m.loss == Some(LossCode::DroppedValue)) == dbf_invalid); + let code = if csv_extra { LossCode::DroppedExtraAttributes } else { LossCode::DroppedValue }; + let coded = report.messages.iter().all(|m| m.loss == Some(code)); if report.skipped != 0 || report.messages.texts().collect::>() != *expected || !coded { return Err(std::io::Error::other(format!("tabular native report: {report:?}"))); } @@ -993,7 +994,10 @@ fn read(dir: &std::path::Path, file: &str, content: &[u8], beside: &[(&str, Vec< || content == include_bytes!("../../testdata/reading-losses/book-z.xls") || content == include_bytes!("../../testdata/reading-losses/book-z.xlsb"); let errors = content == include_bytes!("../../testdata/reading-losses/book-error.xlsx"); - if collection && report.messages != [collection_note] { + if collection + && (report.messages.texts().collect::>() != [collection_note] + || report.messages[0].loss != Some(LossCode::DroppedGeometry)) + { return Err(std::io::Error::other(format!("native spreadsheet collection notice: {report:?}"))); } if errors && report.messages != ["1 spreadsheet error cell was read as empty, in 'note'"] { diff --git a/docs/cli.md b/docs/cli.md index b5ba259f40..41b1369172 100644 --- a/docs/cli.md +++ b/docs/cli.md @@ -164,13 +164,18 @@ An `--allow` that names no kind or code is refused with status 2, as is `--allow | `dropped.calculation-result` | Correct the expression or check the input rows named in the notice. | | `dropped.zm` | Keep the source file where heights or measures matter: RustGIS keeps x and y only. | | `dropped.crs-name` | Keep the source file's coordinate system definition with the export. | +| `dropped.feature` | Correct the features the notice names in the source, or read it another way the notice suggests. | +| `dropped.geometry` | Correct the geometry in the source, or give the coordinate system its coordinates are in. | +| `dropped.over-limit` | Read less at once, such as by filtering or clipping the source first. | | `changed.truncated` | Use a decimal field to keep the fractional part. | | `changed.body` | Export in the layer's own coordinate system, which keeps its body. | | `changed.encoding` | Put a .cpg file naming the file's own encoding beside it. | | `changed.rounded` | Keep the source file where times finer than a microsecond matter. | | `changed.position` | Export in a coordinate system that holds the positions, such as WGS 84. | | `approximated.datum` | Export in the layer's own coordinate system, or give that system with a known transformation to WGS 84. | +| `approximated.curve` | Keep the source file where exact curves matter: RustGIS draws curves as straight segments. | | `assumed.null-marker` | Write the value another way if the text Null is meant as text, not as an empty value. | +| `assumed.crs` | Give the coordinate system the coordinates are in ("crs" when adding the data, or Define Projection). | Not every loss has a code yet: losses still reported without one don't stop a strict run. From 252438600a0021773632a6d678abe42891760725 Mon Sep 17 00:00:00 2001 From: mavrick Date: Tue, 24 Nov 2026 07:16:55 -0600 Subject: [PATCH 2/7] fix(data): code the loss notices review found, and keep possible losses plain (#2371) Code the remaining unknown-system notes (LandXML, GML, DXF, feature service pages), every shape left without geometry, and OSM's extract limit. Rows kept without their geometry say dropped.geometry, not dropped.feature. The SRID policy notes, a collection without a list and a range warning for a given system stay plain, as they don't say a loss happened. SQL Server's time probe looks only at the rows the layer reads. --- crates/data/src/citymodel.rs | 5 +---- crates/data/src/dxf.rs | 9 +++++---- crates/data/src/esripbf.rs | 5 ++++- crates/data/src/esripbf/tests.rs | 5 ++++- crates/data/src/gml.rs | 5 ++++- crates/data/src/io.rs | 16 +++++++++++----- crates/data/src/landxml.rs | 9 +++------ crates/data/src/loss.rs | 2 +- crates/data/src/osm.rs | 2 +- crates/data/src/source/mysql.rs | 10 +++++----- crates/data/src/source/postgis.rs | 10 +++++----- crates/data/src/source/sqlserver.rs | 18 +++++++++--------- crates/data/src/source/tests.rs | 6 ++++++ crates/data/src/topojson.rs | 5 +---- .../tests/integration/never_silent_reading.rs | 19 +++++++++++++++---- docs/cli.md | 2 +- 16 files changed, 76 insertions(+), 52 deletions(-) diff --git a/crates/data/src/citymodel.rs b/crates/data/src/citymodel.rs index d2e5985fef..a4b6de767d 100644 --- a/crates/data/src/citymodel.rs +++ b/crates/data/src/citymodel.rs @@ -497,10 +497,7 @@ pub(crate) fn coordinate_system( return Err(DataError::Format(format!("{file_name}: {} is a geocentric coordinate system, which isn't a map's", crs.label()))); } if crs == Crs::LonLat && !reach.within(180.5, 90.5) { - notes.push(crate::loss::Note::loss( - crate::loss::LossCode::AssumedCrs, - "coordinates are not longitude/latitude; RustGIS reads them as WGS 84 and they may draw out of place", - )); + notes.push("coordinates are not longitude/latitude; RustGIS reads them as WGS 84 and they may draw out of place"); } if let Some(unit) = crs.height_unit_not_metre().filter(|_| !vertical_named) { notes.push(format!( diff --git a/crates/data/src/dxf.rs b/crates/data/src/dxf.rs index 3b4512601c..e6f74e6f5b 100644 --- a/crates/data/src/dxf.rs +++ b/crates/data/src/dxf.rs @@ -1636,9 +1636,10 @@ pub fn read(file_name: &str, bytes: &[u8], opts: &Options) -> Result crate::loss::Notes { let mut out = crate::loss::Notes::new(); if self.no_crs { - out.push("the answer names no coordinate system; coordinates are read as longitude/latitude"); + out.push(crate::loss::Note::loss( + crate::loss::LossCode::AssumedCrs, + "the answer names no coordinate system; coordinates are read as longitude/latitude", + )); } if self.unreadable > 0 { out.push(format!("{} values don't fit their field's type and are left empty", self.unreadable)); diff --git a/crates/data/src/esripbf/tests.rs b/crates/data/src/esripbf/tests.rs index b246efe940..9d39a3a61d 100644 --- a/crates/data/src/esripbf/tests.rs +++ b/crates/data/src/esripbf/tests.rs @@ -244,7 +244,10 @@ fn an_answer_without_a_coordinate_system_is_said_to_be_read_as_longitude_latitud let bytes = answer(&[transform(false, 1.0, 0.0, 0.0), feature(&[geometry(&[], &[1, 2])])]); let (ds, report) = read(&bytes, "t").unwrap(); assert_eq!(ds.features[0].geometry, Some(Geometry::Point(c(1.0, 2.0)))); - assert_eq!(report.messages, ["the answer names no coordinate system; coordinates are read as longitude/latitude"]); + assert_eq!( + report.messages.texts().collect::>(), + ["the answer names no coordinate system; coordinates are read as longitude/latitude"] + ); } #[test] diff --git a/crates/data/src/gml.rs b/crates/data/src/gml.rs index 7110de14ad..0662e4382d 100644 --- a/crates/data/src/gml.rs +++ b/crates/data/src/gml.rs @@ -738,7 +738,10 @@ pub fn read(file_name: &str, bytes: &[u8]) -> Result> ))); } if file_srs.is_none() && outside { - rep.messages.push("the GML doesn't say its coordinate system (srsName) and its coordinates aren't longitude/latitude"); + rep.messages.push(crate::loss::Note::loss( + crate::loss::LossCode::AssumedCrs, + "the GML doesn't say its coordinate system (srsName) and its coordinates aren't longitude/latitude", + )); } // Said with the layer it happened in, which may be the only one added. if kind.lost > 0 { diff --git a/crates/data/src/io.rs b/crates/data/src/io.rs index 2686c5d0c3..aab351c027 100644 --- a/crates/data/src/io.rs +++ b/crates/data/src/io.rs @@ -2960,12 +2960,15 @@ pub(crate) fn read_rows( } if report.skipped > malformed { report.messages.push(crate::loss::Note::loss( - crate::loss::LossCode::DroppedFeature, + crate::loss::LossCode::DroppedGeometry, format!("{} rows had no usable coordinates", report.skipped - malformed), )); } if bad_wkt > 0 { - report.messages.push(format!("{bad_wkt} rows had geometry that isn't readable WKT")); + report.messages.push(crate::loss::Note::loss( + crate::loss::LossCode::DroppedGeometry, + format!("{bad_wkt} rows had geometry that isn't readable WKT"), + )); } if wkt.is_some() { // The most common kind, as GeoJSON's reader takes it; rows of other kinds are kept (they @@ -3011,7 +3014,7 @@ pub(crate) fn read_rows( if lost > 0 { report.skipped += lost; report.messages.push(crate::loss::Note::loss( - crate::loss::LossCode::DroppedFeature, + crate::loss::LossCode::DroppedGeometry, format!("{lost} rows couldn't be converted from {} to longitude/latitude", c.label()), )); } @@ -4213,7 +4216,10 @@ pub(crate) fn read_shapefile_parts(parts: ShapefileParts, name: &str, crs: Optio } ds.crs_incomplete = unconverted > 0; if unconverted > 0 && converted == 0 { - report.messages.push("no shape could be converted to longitude/latitude: the .prj doesn't seem to match the coordinates"); + report.messages.push(crate::loss::Note::loss( + crate::loss::LossCode::DroppedGeometry, + "no shape could be converted to longitude/latitude: the .prj doesn't seem to match the coordinates", + )); } else if unconverted > 0 { report.messages.push(crate::loss::Note::loss( crate::loss::LossCode::DroppedGeometry, @@ -6674,7 +6680,7 @@ mod tests { rep.messages, [ crate::loss::Note::loss(crate::loss::LossCode::DroppedZm, crate::zm_note(Some(1))), - "1 rows had geometry that isn't readable WKT".into(), + crate::loss::Note::loss(crate::loss::LossCode::DroppedGeometry, "1 rows had geometry that isn't readable WKT"), "1 rows have another kind of geometry than the layer's polyline".into() ] ); diff --git a/crates/data/src/landxml.rs b/crates/data/src/landxml.rs index 2ebf3de6c9..cc741ea74d 100644 --- a/crates/data/src/landxml.rs +++ b/crates/data/src/landxml.rs @@ -76,7 +76,7 @@ pub fn read(file_name: &str, bytes: &[u8], crs: Option) -> Result report .messages - .push("the file doesn't say its coordinate system (give \"crs\", such as EPSG:2263): coordinates are kept as they are"), + .push(crate::loss::Note::loss(crate::loss::LossCode::AssumedCrs, "the file doesn't say its coordinate system (give \"crs\", such as EPSG:2263): coordinates are kept as they are")), } let mut skipped = 0usize; let mut missing_parcels = 0usize; @@ -227,10 +227,7 @@ pub fn read(file_name: &str, bytes: &[u8], crs: Option) -> Result 0 { - report.messages.push(crate::loss::Note::loss( - crate::loss::LossCode::DroppedFeature, - format!("{skipped} points, faces or figures couldn't be read and were left out"), - )); + report.messages.push(format!("{skipped} points, faces or figures couldn't be read and were left out")); } let mut out: Vec<(Dataset, ReadReport)> = Vec::new(); let transformer = match crs.filter(|c| *c != Crs::LonLat) { @@ -259,7 +256,7 @@ pub fn read(file_name: &str, bytes: &[u8], crs: Option) -> Result 0 { rep.messages.push(crate::loss::Note::loss( - crate::loss::LossCode::DroppedFeature, + crate::loss::LossCode::DroppedGeometry, format!("{lost} features couldn't be converted from {}", c.label()), )); } diff --git a/crates/data/src/loss.rs b/crates/data/src/loss.rs index 70c3528158..77d99f7e44 100644 --- a/crates/data/src/loss.rs +++ b/crates/data/src/loss.rs @@ -86,7 +86,7 @@ loss_codes! { DroppedFeature => ( "dropped.feature", Dropped, - "Correct the features the notice names in the source, or read it another way the notice suggests." + "Correct those features in the source, or read the source in the way the notice suggests." ), DroppedGeometry => ( "dropped.geometry", diff --git a/crates/data/src/osm.rs b/crates/data/src/osm.rs index f0c58d7fcb..90fd9d362e 100644 --- a/crates/data/src/osm.rs +++ b/crates/data/src/osm.rs @@ -789,7 +789,7 @@ pub fn read(file_name: &str, bytes: &[u8]) -> Result> if osm.capped { report .messages - .push("the extract is larger than RustGIS reads at once: the rest is left out (use a smaller extract; on the desktop, files over 256 MB open through GDAL when it is installed)"); + .push(crate::loss::Note::loss(crate::loss::LossCode::DroppedOverLimit, "the extract is larger than RustGIS reads at once: the rest is left out (use a smaller extract; on the desktop, files over 256 MB open through GDAL when it is installed)")); } if missing > 0 { report.messages.push(format!("{missing} ways or relations refer to nodes or ways the file doesn't hold")); diff --git a/crates/data/src/source/mysql.rs b/crates/data/src/source/mysql.rs index 7a7fb36e81..7788d5f4d9 100644 --- a/crates/data/src/source/mysql.rs +++ b/crates/data/src/source/mysql.rs @@ -745,10 +745,7 @@ impl MysqlSource { }; let constrained = declared.is_some(); if !constrained && raw_srid != 0 { - notes.push(crate::loss::Note::loss( - crate::loss::LossCode::DroppedFeature, - format!("the column doesn't fix a coordinate system: rows in one other than EPSG:{raw_srid} are left out"), - )); + notes.push(format!("the column doesn't fix a coordinate system: rows in one other than EPSG:{raw_srid} are left out")); } let mut srid = raw_srid; if srid == 0 { @@ -758,7 +755,10 @@ impl MysqlSource { srid = u32::from(code); notes.extend(note); } - None => notes.push(crate::loss::Note::loss(crate::loss::LossCode::AssumedCrs, "the geometry doesn't say its coordinate system; read as longitude/latitude (add it again with \"crs\", such as EPSG:2263)",)), + None => notes.push(crate::loss::Note::loss( + crate::loss::LossCode::AssumedCrs, + "the geometry doesn't say its coordinate system; read as longitude/latitude (add it again with \"crs\", such as EPSG:2263)", + )), } } if let Some(note) = tls_note(&conn.config.tls, conn.is_plain()) { diff --git a/crates/data/src/source/postgis.rs b/crates/data/src/source/postgis.rs index 1fa6a4ba45..790413c391 100644 --- a/crates/data/src/source/postgis.rs +++ b/crates/data/src/source/postgis.rs @@ -892,10 +892,7 @@ impl PostgisSource { } let raw_srid = srid; if table.srid == 0 && !table.geography && raw_srid != 0 { - notes.push(crate::loss::Note::loss( - crate::loss::LossCode::DroppedFeature, - format!("the column doesn't fix a coordinate system: rows in one other than EPSG:{raw_srid} are left out"), - )); + notes.push(format!("the column doesn't fix a coordinate system: rows in one other than EPSG:{raw_srid} are left out")); } let given = crs.map(str::trim).filter(|c| !c.is_empty()); let mut native = g.clone(); @@ -907,7 +904,10 @@ impl PostgisSource { native = format!("ST_SetSRID({g}, {srid})"); notes.extend(note); } - None => notes.push(crate::loss::Note::loss(crate::loss::LossCode::AssumedCrs, "the geometry doesn't say its coordinate system; read as longitude/latitude (add it again with \"crs\", such as EPSG:2263)",)), + None => notes.push(crate::loss::Note::loss( + crate::loss::LossCode::AssumedCrs, + "the geometry doesn't say its coordinate system; read as longitude/latitude (add it again with \"crs\", such as EPSG:2263)", + )), } } if let Some(note) = tls_note(&conn.tls, conn.is_plain()) { diff --git a/crates/data/src/source/sqlserver.rs b/crates/data/src/source/sqlserver.rs index 1981e6edf6..ae43cc4f0a 100644 --- a/crates/data/src/source/sqlserver.rs +++ b/crates/data/src/source/sqlserver.rs @@ -740,10 +740,10 @@ fn projection(geometry: &str, columns: impl IntoIterator crate::loss::Notes { +fn fine_times_note(conn: &Conn, from: &str, rows: &str, fine: &[String]) -> crate::loss::Notes { if fine.is_empty() { return crate::loss::Notes::new(); } @@ -751,7 +751,7 @@ fn fine_times_note(conn: &Conn, from: &str, fine: &[String]) -> crate::loss::Not fine.iter().map(|c| format!("MAX(CASE WHEN DATEPART(NANOSECOND, {}) % 1000 <> 0 THEN 1 ELSE 0 END)", ident(c))).collect(); let cols: Vec = fine.iter().map(|c| ident(c)).collect(); let sql = format!( - "SELECT COUNT_BIG(*), {} FROM (SELECT TOP ({}) {} FROM {from}) s", + "SELECT COUNT_BIG(*), {} FROM (SELECT TOP ({}) {} FROM {from} t WHERE {rows}) s", checks.join(", "), FINE_TIMES_SAMPLE + 1, cols.join(", ") @@ -822,10 +822,7 @@ impl SqlServerSource { let raw_srid = rows.first().and_then(|r| int_of(at(r, 0))).and_then(|n| u32::try_from(n).ok()).unwrap_or(if geography { 4326 } else { 0 }); if raw_srid != 0 { - notes.push(crate::loss::Note::loss( - crate::loss::LossCode::DroppedFeature, - format!("the column doesn't fix a coordinate system: rows in one other than EPSG:{raw_srid} are left out"), - )); + notes.push(format!("the column doesn't fix a coordinate system: rows in one other than EPSG:{raw_srid} are left out")); } let mut srid = raw_srid; if srid == 0 @@ -841,7 +838,10 @@ impl SqlServerSource { srid = u32::from(code); notes.extend(note); } - None => notes.push(crate::loss::Note::loss(crate::loss::LossCode::AssumedCrs, "the geometry doesn't say its coordinate system; read as longitude/latitude (add it again with \"crs\", such as EPSG:2263)")), + None => notes.push(crate::loss::Note::loss( + crate::loss::LossCode::AssumedCrs, + "the geometry doesn't say its coordinate system; read as longitude/latitude (add it again with \"crs\", such as EPSG:2263)", + )), } } if conn.config.encrypt == Encrypt::Off { @@ -860,7 +860,7 @@ impl SqlServerSource { }) .filter_map(|r| text_of(at(r, 0))) .collect(); - notes.extend(fine_times_note(&conn, &from, &fine)); + notes.extend(fine_times_note(&conn, &from, &format!("{g} IS NOT NULL AND {g}.STSrid = {raw_srid}"), &fine)); let keys = conn.query("SELECT k.COLUMN_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS c JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE k ON k.CONSTRAINT_SCHEMA = c.CONSTRAINT_SCHEMA AND k.CONSTRAINT_NAME = c.CONSTRAINT_NAME WHERE c.CONSTRAINT_TYPE = 'PRIMARY KEY' AND c.TABLE_SCHEMA = @P1 AND c.TABLE_NAME = @P2", &[&table.schema, &table.name])?; let mut key = if keys.len() == 1 { keys.first().and_then(|r| text_of(at(r, 0))) } else { None }; // The registered ObjectID column is the feature id when the table has it. diff --git a/crates/data/src/source/tests.rs b/crates/data/src/source/tests.rs index 2a0ffb9317..f349448415 100644 --- a/crates/data/src/source/tests.rs +++ b/crates/data/src/source/tests.rs @@ -2534,6 +2534,12 @@ fn shapefile_in_place_says_numbers_that_arent_finite() { assert!(notes[0].as_str().ends_with(said), "{messages:?}"); assert_eq!(notes[0].loss, Some(crate::loss::LossCode::DroppedValue)); } + // Finite numbers and a blank one say nothing, in place or whole. + let p = d.join("clean.shp"); + write_shapefile(&ds, &p); + let (_, whole_report) = crate::io::read_path(&p).unwrap(); + let (_, report) = materialize(open_path(&p, None).unwrap().as_ref()).unwrap(); + assert!(whole_report.messages.iter().chain(&report.messages).all(|m| !m.contains("finite")), "{:?}", report.messages); } #[test] diff --git a/crates/data/src/topojson.rs b/crates/data/src/topojson.rs index 8e4a565b07..f328564b52 100644 --- a/crates/data/src/topojson.rs +++ b/crates/data/src/topojson.rs @@ -504,10 +504,7 @@ fn read_with(file_name: &str, text: &str, budget: usize) -> Result>() != dxf_messages { return Err(std::io::Error::other(format!("DXF vertex native report: {native:?}"))); } check_dxf_vertex(&native[0].0, dxf_vertex_lossy)?; @@ -1049,8 +1049,7 @@ fn read(dir: &std::path::Path, file: &str, content: &[u8], beside: &[(&str, Vec< } if dxf_height { let native = rustgis_engine::data::dxf::read(file, content, &Default::default()).map_err(std::io::Error::other)?; - // The varying heights lost are coded `dropped.zm`; nothing else is. - let expected: Vec> = dxf_messages.iter().map(|m| m.contains("varying Z").then_some(LossCode::DroppedZm)).collect(); + let expected: Vec> = dxf_messages.iter().map(|m| dxf_code(m)).collect(); if native.len() != 1 || native[0].1.skipped != 0 || native[0].1.messages.texts().collect::>() != dxf_messages @@ -1155,7 +1154,7 @@ fn read(dir: &std::path::Path, file: &str, content: &[u8], beside: &[(&str, Vec< check_dxf_height(&s.map().layers[0].dataset)?; let said: Vec = s.notices_since(mark).iter().map(|n| n.text.clone()).collect(); let codes: Vec> = s.notices_since(mark).iter().map(|n| n.loss()).collect(); - let expected: Vec> = dxf_messages.iter().map(|m| m.contains("varying Z").then_some(LossCode::DroppedZm)).collect(); + let expected: Vec> = dxf_messages.iter().map(|m| dxf_code(m)).collect(); if said != dxf_messages || codes != expected { return Err(std::io::Error::other(format!("DXF height command notices: {said:?}"))); } @@ -1294,3 +1293,15 @@ fn xml_losses_keep_data_and_reach_command() { assert_eq!(checked, 17, "ten logical cases, seventeen rows with the KMZ twins"); let _ = std::fs::remove_dir_all(root); } + +/// The code a DXF fixture's notice carries: `dropped.zm` for the varying heights lost and +/// `assumed.crs` for the system the drawing doesn't say; nothing else is coded. +fn dxf_code(message: &str) -> Option { + if message.contains("varying Z") { + Some(LossCode::DroppedZm) + } else if message.contains("doesn't say its coordinate system") { + Some(LossCode::AssumedCrs) + } else { + None + } +} diff --git a/docs/cli.md b/docs/cli.md index 41b1369172..1f01b59b65 100644 --- a/docs/cli.md +++ b/docs/cli.md @@ -164,7 +164,7 @@ An `--allow` that names no kind or code is refused with status 2, as is `--allow | `dropped.calculation-result` | Correct the expression or check the input rows named in the notice. | | `dropped.zm` | Keep the source file where heights or measures matter: RustGIS keeps x and y only. | | `dropped.crs-name` | Keep the source file's coordinate system definition with the export. | -| `dropped.feature` | Correct the features the notice names in the source, or read it another way the notice suggests. | +| `dropped.feature` | Correct those features in the source, or read the source in the way the notice suggests. | | `dropped.geometry` | Correct the geometry in the source, or give the coordinate system its coordinates are in. | | `dropped.over-limit` | Read less at once, such as by filtering or clipping the source first. | | `changed.truncated` | Use a decimal field to keep the fractional part. | From 2d283bfbb7edf626d2bb15b09127729f9ddc62dd Mon Sep 17 00:00:00 2001 From: mavrick Date: Tue, 24 Nov 2026 10:24:09 -0600 Subject: [PATCH 3/7] fix(data): a declared .prj isn't an assumed system, a sample's count says so, and OSM parts left out are geometry (#2371) A Shapefile's out-of-range note says assumed.crs only when no system was given or declared in a .prj, read whole or in place. A sampled in-place read's count of numbers that aren't finite says it is of the records read. OSM relation parts left out of a kept polygon say dropped.geometry. Tests check the codes of SQL Server's time notes. --- crates/data/src/io.rs | 15 +++++++++++---- crates/data/src/osm.rs | 6 ++++-- crates/data/src/source/shp.rs | 27 ++++++++++++++++++++------- crates/data/src/source/sqlserver.rs | 5 +++++ crates/data/src/source/tests.rs | 22 +++++++++++++++++++++- 5 files changed, 61 insertions(+), 14 deletions(-) diff --git a/crates/data/src/io.rs b/crates/data/src/io.rs index d5e491eb7f..40dee76e70 100644 --- a/crates/data/src/io.rs +++ b/crates/data/src/io.rs @@ -4030,6 +4030,9 @@ pub(crate) fn read_shapefile_parts(parts: ShapefileParts, name: &str, crs: Optio } .map_err(fmt)?; let mut ds = Dataset::new(name, GeometryType::None, fields); + // A system given or in a `.prj` (even one that can't be used, said on its own) isn't one + // RustGIS assumed. + let declared = crs.is_some() || parts.prj.is_some(); let to_lonlat = match crs { Some(c) => { ds.crs = Some(c); @@ -4196,10 +4199,14 @@ pub(crate) fn read_shapefile_parts(parts: ShapefileParts, name: &str, crs: Optio // (one that doesn't match them), counted; or as they are without a system to convert from. match ds.crs.filter(|_| to_lonlat.is_some()) { Some(c) => report.messages.extend(beyond_lonlat_note("shapes", beyond, c)), - None if ds.extent().beyond_lonlat() => report.messages.push(crate::loss::Note::loss( - crate::loss::LossCode::AssumedCrs, - "coordinates are not longitude/latitude; RustGIS reads them as WGS 84 and they may draw out of place", - )), + None if ds.extent().beyond_lonlat() => { + let text = "coordinates are not longitude/latitude; RustGIS reads them as WGS 84 and they may draw out of place"; + report.messages.push(if declared { + crate::loss::Note::plain(text) + } else { + crate::loss::Note::loss(crate::loss::LossCode::AssumedCrs, text) + }); + } None => {} } if report.skipped > 0 { diff --git a/crates/data/src/osm.rs b/crates/data/src/osm.rs index 11228ef0e3..0a1f0cc219 100644 --- a/crates/data/src/osm.rs +++ b/crates/data/src/osm.rs @@ -826,7 +826,7 @@ pub fn read(file_name: &str, bytes: &[u8]) -> Result> ] { if count > 0 { let subject = if count == 1 { one } else { many }; - report.messages.push(format!("{count} {subject}")); + report.messages.push(crate::loss::Note::loss(crate::loss::LossCode::DroppedGeometry, format!("{count} {subject}"))); } } if containment_limited > 0 { @@ -1325,7 +1325,9 @@ pub(crate) mod tests { assert_eq!(parts[0].len(), rings); assert_eq!(parts[0][0], vec![Coord::new(0.0, 0.0), Coord::new(10.0, 0.0), Coord::new(0.0, 10.0), Coord::new(0.0, 0.0)]); assert_eq!(report.skipped, 0, "no feature was skipped"); - report.messages.clone() + // Parts of a polygon that is kept are its geometry's loss, not a feature's. + assert!(report.messages.iter().all(|m| m.loss == Some(crate::loss::LossCode::DroppedGeometry)), "{report:?}"); + report.messages.texts().map(str::to_string).collect::>() }; assert!(kept(clean, 2).is_empty()); for (bytes, message) in cases { diff --git a/crates/data/src/source/shp.rs b/crates/data/src/source/shp.rs index 085dcb682d..a825a9a991 100644 --- a/crates/data/src/source/shp.rs +++ b/crates/data/src/source/shp.rs @@ -176,9 +176,13 @@ impl ShpSource { if table.rows != index.count { notes.push(format!("the .shp holds {} shapes and the .dbf {} rows; rows are matched by position", index.count, table.rows)); } + let prj = if crs.is_none() { crate::raster::read_prj(path) } else { None }; + // A system given or in a `.prj` (even one that can't be used, said on its own) isn't one + // RustGIS assumed, as for a Shapefile read whole. + let declared = crs.is_some() || prj.is_some(); let reproject = match crs { Some(c) => Reproject::from_crs(c, &mut notes), - None => shp_reproject(crate::raster::read_prj(path).as_deref(), &mut notes)?, + None => shp_reproject(prj.as_deref(), &mut notes)?, }; // The records' own boxes frame the layer, as the index holds them (rounded outward to f32); // with none (no records, or every shape null, empty or not a number) it has no extent, @@ -232,10 +236,12 @@ impl ShpSource { } let extent = native.map_or(Extent::EMPTY, |n| reproject.extent_to_lonlat(&n)); if reproject.is_lonlat() && extent.beyond_lonlat() { - notes.push(crate::loss::Note::loss( - crate::loss::LossCode::AssumedCrs, - "coordinates are not longitude/latitude; RustGIS reads them as WGS 84 and they may draw out of place", - )); + let text = "coordinates are not longitude/latitude; RustGIS reads them as WGS 84 and they may draw out of place"; + notes.push(if declared { + crate::loss::Note::plain(text) + } else { + crate::loss::Note::loss(crate::loss::LossCode::AssumedCrs, text) + }); } let (names, not_utf8) = read_names(&dbf, table.columns.len(), &encoding)?; notes.extend(crate::dbf::not_utf8_names_note(¬_utf8, encoding.name())); @@ -398,7 +404,7 @@ impl ShpSource { .into_iter() .chain(deleted_note(deleted, false)) .map(crate::loss::Note::from) - .chain(crate::io::nonfinite_note(&self.info.fields, &nonfinite)) + .chain(nonfinite_note(&self.info.fields, &nonfinite, false)) .collect(), not_utf8, }) @@ -545,7 +551,7 @@ impl FeatureSource for ShpSource { .into_iter() .chain(deleted_note(deleted, !late && !complete)) .map(crate::loss::Note::from) - .chain(crate::io::nonfinite_note(&self.info.fields, &nonfinite)) + .chain(nonfinite_note(&self.info.fields, &nonfinite, !late && !complete)) .collect(), not_utf8, }) @@ -614,6 +620,13 @@ fn boxed_off_note(n: u64, sampled: bool, late: bool) -> Vec { /// The note for `n` records marked deleted in the `.dbf`, left out with their shapes; of those /// read when the read is `sampled`. +/// The numbers in the `.dbf` that aren't finite, read as empty ([`crate::io::nonfinite_note`]); a +/// `sampled` read counts only the records it read, and says so, as [`deleted_note`] does. +fn nonfinite_note(fields: &[crate::Field], counts: &[usize], sampled: bool) -> Option { + let note = crate::io::nonfinite_note(fields, counts)?; + Some(if sampled { note.map_text(|t| format!("in the records read (a sample of the layer, which may hold more), {t}")) } else { note }) +} + fn deleted_note(n: usize, sampled: bool) -> Option { if sampled && n > 0 { return Some(format!( diff --git a/crates/data/src/source/sqlserver.rs b/crates/data/src/source/sqlserver.rs index 3d9b7cb3b8..227a6d15eb 100644 --- a/crates/data/src/source/sqlserver.rs +++ b/crates/data/src/source/sqlserver.rs @@ -1289,9 +1289,12 @@ mod tests { fine_times_said(&fine, Some(&[0, 1]), true).texts().collect::>(), ["date-times in 'logged' hold 100-nanosecond digits: they're read to the microsecond, the last digit left out"] ); + assert_eq!(fine_times_said(&fine, Some(&[0, 1]), true)[0].loss, Some(crate::loss::LossCode::ChangedRounded)); assert!(fine_times_said(&fine, Some(&[0, 0]), true).is_empty()); + // What only may have been rounded is said without a code. let notes = fine_times_said(&fine, Some(&[0, 0]), false); assert!(notes.len() == 1 && notes[0].starts_with("date-times in 'seen', 'logged' may hold"), "{notes:?}"); + assert_eq!(notes[0].loss, None); // Columns that have them are named apart from those that may. let notes = fine_times_said(&fine, Some(&[1, 0]), false); assert!( @@ -1300,6 +1303,7 @@ mod tests { && notes[1].starts_with("date-times in 'logged' may hold"), "{notes:?}" ); + assert_eq!((notes[0].loss, notes[1].loss), (Some(crate::loss::LossCode::ChangedRounded), None)); assert!(fine_times_said(&fine, Some(&[1, 1]), false).len() == 1); // A look that failed says so, naming every column. let notes = fine_times_said(&fine, None, true); @@ -1307,6 +1311,7 @@ mod tests { notes.len() == 1 && notes[0].starts_with("date-times in 'seen', 'logged' may hold") && notes[0].contains("couldn't be checked"), "{notes:?}" ); + assert_eq!(notes[0].loss, None); assert!(fine_times_said(&[], Some(&[]), false).is_empty() && fine_times_said(&[], None, false).is_empty()); // A seventh digit of a second is cut; the offset after it stays. assert_eq!(to_micros("2026-03-05T14:30:00.1234567+02:00"), "2026-03-05T14:30:00.123456+02:00"); diff --git a/crates/data/src/source/tests.rs b/crates/data/src/source/tests.rs index 59c0e38a52..a6ce638923 100644 --- a/crates/data/src/source/tests.rs +++ b/crates/data/src/source/tests.rs @@ -2534,6 +2534,13 @@ fn shapefile_in_place_says_numbers_that_arent_finite() { assert!(notes[0].as_str().ends_with(said), "{messages:?}"); assert_eq!(notes[0].loss, Some(crate::loss::LossCode::DroppedValue)); } + // A read of a sample (here the first and third records) counts only what it read, and says so. + let some = open_path(&p, None).unwrap().read(&Request { limit: 2, ..Request::all() }).unwrap(); + assert!(!some.complete); + let sampled: Vec<_> = some.notes.iter().filter(|m| m.contains("finite")).collect(); + assert_eq!(sampled.len(), 1, "{:?}", some.notes); + assert_eq!(sampled[0].as_str(), format!("in the records read (a sample of the layer, which may hold more), {said}")); + assert_eq!(sampled[0].loss, Some(crate::loss::LossCode::DroppedValue)); // Finite numbers and a blank one say nothing, in place or whole. let p = d.join("clean.shp"); write_shapefile(&ds, &p); @@ -2566,7 +2573,20 @@ fn shapefile_in_place_reprojects_from_its_prj() { // Without the .prj the coordinates are taken as they are, and that's said. std::fs::remove_file(p.with_extension("prj")).unwrap(); let src = open_path(&p, None).unwrap(); - assert!(src.info().notes.iter().any(|n| n.contains("not longitude/latitude")), "{:?}", src.info().notes); + let said: Vec<_> = src.info().notes.iter().filter(|n| n.contains("not longitude/latitude")).collect(); + assert_eq!(said.len(), 1, "{:?}", src.info().notes); + assert_eq!(said[0].loss, Some(crate::loss::LossCode::AssumedCrs), "assumed without a .prj"); + // A .prj that says WGS 84 gives the system, so nothing is assumed: the same note, uncoded, + // as a whole read says it. + let wgs84 = r#"GEOGCS["GCS_WGS_1984",DATUM["D_WGS_1984",SPHEROID["WGS_1984",6378137.0,298.257223563]],PRIMEM["Greenwich",0.0],UNIT["Degree",0.0174532925199433]]"#; + std::fs::write(p.with_extension("prj"), wgs84).unwrap(); + let src = open_path(&p, None).unwrap(); + let said: Vec<_> = src.info().notes.iter().filter(|n| n.contains("not longitude/latitude")).collect(); + assert_eq!(said.len(), 1, "{:?}", src.info().notes); + assert_eq!(said[0].loss, None, "declared in the .prj"); + let (_, whole) = crate::io::read_path(&p).unwrap(); + let said: Vec<_> = whole.messages.iter().filter(|n| n.contains("not longitude/latitude")).collect(); + assert_eq!((said.len(), said.first().and_then(|n| n.loss)), (1, None), "{:?}", whole.messages); } #[test] From f725247c808b4ce07d3a5f9402eea1cb1d7edfd8 Mon Sep 17 00:00:00 2001 From: mavrick Date: Tue, 24 Nov 2026 12:27:17 -0600 Subject: [PATCH 4/7] fix(data): shapes a streamed Shapefile leaves out say dropped.feature, and a late read's count says it is of a sample (#2371) The note for shapes with a coordinate that isn't a number under a box that is one, left out of an in-place read, says dropped.feature. A late read decodes only the records its sample keeps, so its count of numbers that aren't finite says so whenever the sample isn't the whole layer. --- crates/data/src/source/shp.rs | 23 +++++++++++++---------- crates/data/src/source/shp/tests.rs | 10 +++++++++- crates/data/src/source/tests.rs | 3 +++ 3 files changed, 25 insertions(+), 11 deletions(-) diff --git a/crates/data/src/source/shp.rs b/crates/data/src/source/shp.rs index a825a9a991..913efb1eb1 100644 --- a/crates/data/src/source/shp.rs +++ b/crates/data/src/source/shp.rs @@ -402,8 +402,7 @@ impl ShpSource { null_text, notes: boxed_off_note(boxed_off, false, late) .into_iter() - .chain(deleted_note(deleted, false)) - .map(crate::loss::Note::from) + .chain(deleted_note(deleted, false).map(crate::loss::Note::from)) .chain(nonfinite_note(&self.info.fields, &nonfinite, false)) .collect(), not_utf8, @@ -549,9 +548,10 @@ impl FeatureSource for ShpSource { // visits the whole layer, so its count is of the layer. notes: boxed_off_note(boxed_off, !late && !complete, late) .into_iter() - .chain(deleted_note(deleted, !late && !complete)) - .map(crate::loss::Note::from) - .chain(nonfinite_note(&self.info.fields, &nonfinite, !late && !complete)) + .chain(deleted_note(deleted, !late && !complete).map(crate::loss::Note::from)) + // The values a late read decodes are of the records its sample keeps (geometry checks + // aside), so its count is of a sample whenever the sample isn't the whole layer. + .chain(nonfinite_note(&self.info.fields, &nonfinite, !complete)) .collect(), not_utf8, }) @@ -602,7 +602,7 @@ impl FeatureSource for ShpSource { /// the shapes it read, not of the layer. A `late` read (an area the layer's system couldn't bound, /// #1925) visited every record and can't place a NaN shape's stored box in the area, so its count /// is of the whole layer, and says so. -fn boxed_off_note(n: u64, sampled: bool, late: bool) -> Vec { +fn boxed_off_note(n: u64, sampled: bool, late: bool) -> Vec { if n == 0 { return Vec::new(); } @@ -613,13 +613,14 @@ fn boxed_off_note(n: u64, sampled: bool, late: bool) -> Vec { } else { format!("{n} shape(s)") }; - vec![format!( - "{what} have a coordinate that isn't a number under a bounding box that is one: they're left out of the read, but the layer's extent and its index still take in their stored boxes" + vec![crate::loss::Note::loss( + crate::loss::LossCode::DroppedFeature, + format!( + "{what} have a coordinate that isn't a number under a bounding box that is one: they're left out of the read, but the layer's extent and its index still take in their stored boxes" + ), )] } -/// The note for `n` records marked deleted in the `.dbf`, left out with their shapes; of those -/// read when the read is `sampled`. /// The numbers in the `.dbf` that aren't finite, read as empty ([`crate::io::nonfinite_note`]); a /// `sampled` read counts only the records it read, and says so, as [`deleted_note`] does. fn nonfinite_note(fields: &[crate::Field], counts: &[usize], sampled: bool) -> Option { @@ -627,6 +628,8 @@ fn nonfinite_note(fields: &[crate::Field], counts: &[usize], sampled: bool) -> O Some(if sampled { note.map_text(|t| format!("in the records read (a sample of the layer, which may hold more), {t}")) } else { note }) } +/// The note for `n` records marked deleted in the `.dbf`, left out with their shapes; of those +/// read when the read is `sampled`. fn deleted_note(n: usize, sampled: bool) -> Option { if sampled && n > 0 { return Some(format!( diff --git a/crates/data/src/source/shp/tests.rs b/crates/data/src/source/shp/tests.rs index 59017d8897..54eb599e5d 100644 --- a/crates/data/src/source/shp/tests.rs +++ b/crates/data/src/source/shp/tests.rs @@ -722,7 +722,15 @@ fn a_nan_shape_under_a_finite_box_is_said_when_left_out() { p }; const SAID: &str = "have a coordinate that isn't a number under a bounding box that is one"; - let said = |notes: &[crate::loss::Note]| notes.iter().filter(|n| n.contains(SAID)).map(|n| n.text.clone()).collect::>(); + // Each read says the shapes it left out as dropped features, which the checks below see. + let said = |notes: &[crate::loss::Note]| { + notes + .iter() + .filter(|n| n.contains(SAID)) + .inspect(|n| assert_eq!(n.loss, Some(crate::loss::LossCode::DroppedFeature), "{n:?}")) + .map(|n| n.text.clone()) + .collect::>() + }; let chunk_notes = |src: &dyn FeatureSource, extent| { let batch = src.visit_chunks(extent, 1 << 20, &mut |_| Ok(())).unwrap(); (batch.skipped, said(&batch.notes)) diff --git a/crates/data/src/source/tests.rs b/crates/data/src/source/tests.rs index a6ce638923..099d3b1794 100644 --- a/crates/data/src/source/tests.rs +++ b/crates/data/src/source/tests.rs @@ -2576,6 +2576,9 @@ fn shapefile_in_place_reprojects_from_its_prj() { let said: Vec<_> = src.info().notes.iter().filter(|n| n.contains("not longitude/latitude")).collect(); assert_eq!(said.len(), 1, "{:?}", src.info().notes); assert_eq!(said[0].loss, Some(crate::loss::LossCode::AssumedCrs), "assumed without a .prj"); + let (_, whole) = crate::io::read_path(&p).unwrap(); + let said: Vec<_> = whole.messages.iter().filter(|n| n.contains("not longitude/latitude")).collect(); + assert_eq!((said.len(), said.first().and_then(|n| n.loss)), (1, Some(crate::loss::LossCode::AssumedCrs)), "{:?}", whole.messages); // A .prj that says WGS 84 gives the system, so nothing is assumed: the same note, uncoded, // as a whole read says it. let wgs84 = r#"GEOGCS["GCS_WGS_1984",DATUM["D_WGS_1984",SPHEROID["WGS_1984",6378137.0,298.257223563]],PRIMEM["Greenwich",0.0],UNIT["Degree",0.0174532925199433]]"#; From 62ad4533f048e01ef9a506ef65c2f9e2e5ec0c2f Mon Sep 17 00:00:00 2001 From: mavrick Date: Tue, 24 Nov 2026 13:34:42 -0600 Subject: [PATCH 5/7] fix(data): keep notices plain where their count can hold what wasn't lost, and code GDAL's known shortfall (#2371) DXF's unread and unplaced entities (which count unused blocks), GPX's skipped items (which count route points of kept routes), LandXML's face cap (which counts invisible faces), OSM's member limit (which counts node members it ignores) and a feature service page's unusable system (said before it is known whether any geometry used it) stay plain until their counts are exact. GDAL's conversion that keeps fewer features than a known count says dropped.feature. --- crates/data/src/dxf.rs | 12 +++--------- crates/data/src/esripbf.rs | 5 +---- crates/data/src/gpx.rs | 5 +---- crates/data/src/landxml.rs | 5 +---- crates/data/src/osm.rs | 5 +---- crates/data/src/source/gdal.rs | 22 ++++++++++++---------- 6 files changed, 19 insertions(+), 35 deletions(-) diff --git a/crates/data/src/dxf.rs b/crates/data/src/dxf.rs index 6784c5f9c4..eba292ec31 100644 --- a/crates/data/src/dxf.rs +++ b/crates/data/src/dxf.rs @@ -1680,19 +1680,13 @@ pub fn read(file_name: &str, bytes: &[u8], opts: &Options) -> Result = d.unread.iter().map(|(k, n)| format!("{n} {k}")).collect(); - report.messages.push(crate::loss::Note::loss( - crate::loss::LossCode::DroppedFeature, - format!("entities RustGIS doesn't draw were left out: {}", kinds.join(", ")), - )); + report.messages.push(format!("entities RustGIS doesn't draw were left out: {}", kinds.join(", "))); } let skipped = d.bad + out.cut; report.skipped = skipped; if skipped > 0 { - report.messages.push(crate::loss::Note::loss( - crate::loss::LossCode::DroppedFeature, - format!( - "{skipped} entities couldn't be read or placed (missing blocks, blocks nested too deep or in a cycle) and were left out" - ), + report.messages.push(format!( + "{skipped} entities couldn't be read or placed (missing blocks, blocks nested too deep or in a cycle) and were left out" )); } let transformer = match opts.crs.filter(|c| *c != Crs::LonLat) { diff --git a/crates/data/src/esripbf.rs b/crates/data/src/esripbf.rs index 6a13bc9c69..1287b0cd58 100644 --- a/crates/data/src/esripbf.rs +++ b/crates/data/src/esripbf.rs @@ -360,10 +360,7 @@ pub fn read_page_within(bytes: &[u8], name: &str, limit: usize) -> Result && crate::filegdb::crs_of_code(code) != Some(crate::raster::Crs::LonLat) { unread_code = true; - report.messages.push(crate::loss::Note::loss( - crate::loss::LossCode::AssumedCrs, - format!("coordinate system {code} can't be used; coordinates are read as longitude/latitude"), - )); + report.messages.push(format!("coordinate system {code} can't be used; coordinates are read as longitude/latitude")); } let layer_type = match shape_kind { diff --git a/crates/data/src/gpx.rs b/crates/data/src/gpx.rs index 1b71b3b18a..074285c670 100644 --- a/crates/data/src/gpx.rs +++ b/crates/data/src/gpx.rs @@ -200,10 +200,7 @@ pub fn read(file_name: &str, bytes: &[u8]) -> Result> } report.skipped = skipped; if skipped > 0 { - report.messages.push(crate::loss::Note::loss( - crate::loss::LossCode::DroppedFeature, - format!("{name}: {skipped} points, routes or tracks without usable geometry were skipped"), - )); + report.messages.push(format!("{name}: {skipped} points, routes or tracks without usable geometry were skipped")); } } if out.is_empty() { diff --git a/crates/data/src/landxml.rs b/crates/data/src/landxml.rs index b692da4a4a..d1f0c8331d 100644 --- a/crates/data/src/landxml.rs +++ b/crates/data/src/landxml.rs @@ -193,10 +193,7 @@ pub fn read(file_name: &str, bytes: &[u8], crs: Option) -> Result= MAX_FACES { - report.messages.push(crate::loss::Note::loss( - crate::loss::LossCode::DroppedOverLimit, - format!("surface '{sname}' has more than {MAX_FACES} faces: the rest are left out"), - )); + report.messages.push(format!("surface '{sname}' has more than {MAX_FACES} faces: the rest are left out")); break; } // Invisible faces (i="1") are holes in the surface. diff --git a/crates/data/src/osm.rs b/crates/data/src/osm.rs index 0a1f0cc219..f0f3a94bec 100644 --- a/crates/data/src/osm.rs +++ b/crates/data/src/osm.rs @@ -768,10 +768,7 @@ pub fn read(file_name: &str, bytes: &[u8]) -> Result> let mut report = ReadReport { skipped: missing + short_ways + no_closed_outer, ..ReadReport::default() }; if osm.omitted_members > 0 { let members = if osm.omitted_members == 1 { "relation member" } else { "relation members" }; - report.messages.push(crate::loss::Note::loss( - crate::loss::LossCode::DroppedOverLimit, - format!("{} {members} left out at the per-relation limit of {MAX_MEMBERS}", osm.omitted_members), - )); + report.messages.push(format!("{} {members} left out at the per-relation limit of {MAX_MEMBERS}", osm.omitted_members)); } if short_ways > 0 { let subject = if short_ways == 1 { "tagged way left out because it has" } else { "tagged ways left out because they have" }; diff --git a/crates/data/src/source/gdal.rs b/crates/data/src/source/gdal.rs index 58b612f652..95547a6c15 100644 --- a/crates/data/src/source/gdal.rs +++ b/crates/data/src/source/gdal.rs @@ -528,14 +528,16 @@ fn convert_one_fresh_in(dir: &Path, src: &Path, layer: &str, family: Option, actual: u64, nonempty: bool) -> Option { +fn conversion_count_note(layer: &str, expected: Option, actual: u64, nonempty: bool) -> Option { match expected { - Some(expected) if actual < expected => { - Some(format!("{layer}: GDAL conversion left out {} of {expected} source features", expected - actual)) - } - None if nonempty => Some(format!( - "{layer}: couldn't check how many source features GDAL's conversion kept because the source count is unknown; features may have been left out" + Some(expected) if actual < expected => Some(crate::loss::Note::loss( + crate::loss::LossCode::DroppedFeature, + format!("{layer}: GDAL conversion left out {} of {expected} source features", expected - actual), )), + // Only a possible loss: said without a code. + None if nonempty => Some(crate::loss::Note::plain(format!( + "{layer}: couldn't check how many source features GDAL's conversion kept because the source count is unknown; features may have been left out" + ))), _ => None, } } @@ -1231,13 +1233,13 @@ mod tests { fn unknown_nonempty_conversion_counts_are_reported_and_known_clean_counts_are_silent() { let note = conversion_count_note("source", None, 1, true).unwrap(); assert!(note.contains("source count is unknown") && note.contains("features may have been left out")); + assert_eq!(note.loss, None, "only a possible loss"); assert!(conversion_count_note("source", Some(1), 1, true).is_none()); assert!(conversion_count_note("source", Some(0), 0, false).is_none()); assert!(conversion_count_note("source", None, 0, false).is_none()); - assert_eq!( - conversion_count_note("source", Some(3), 1, true).as_deref(), - Some("source: GDAL conversion left out 2 of 3 source features") - ); + let short = conversion_count_note("source", Some(3), 1, true).unwrap(); + assert_eq!(short.as_str(), "source: GDAL conversion left out 2 of 3 source features"); + assert_eq!(short.loss, Some(crate::loss::LossCode::DroppedFeature)); } /// Indexed FlatGeobuf conversion drops empty polygons in GDAL, before RustGIS reads it. From 884c56c30fc708738c652e0118740f51767a9b37 Mon Sep 17 00:00:00 2001 From: mavrick Date: Tue, 24 Nov 2026 14:10:20 -0600 Subject: [PATCH 6/7] fix(data): a workbook date that empties a WKT cell says dropped.geometry (#2371) The row is kept without its geometry, which is what was lost. --- crates/data/src/io.rs | 4 ++-- crates/data/src/sheets.rs | 3 +++ 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/crates/data/src/io.rs b/crates/data/src/io.rs index 40dee76e70..4f97bfb2c1 100644 --- a/crates/data/src/io.rs +++ b/crates/data/src/io.rs @@ -2876,11 +2876,11 @@ pub(crate) fn read_rows( match workbook.and_then(|(_, empty)| empty.get(w)).copied().unwrap_or(0) { 0 => {} 1 => report.messages.push(crate::loss::Note::loss( - crate::loss::LossCode::DroppedValue, + crate::loss::LossCode::DroppedGeometry, format!("1 value in '{column}' isn't a date and was read as empty, so its row has no geometry"), )), n => report.messages.push(crate::loss::Note::loss( - crate::loss::LossCode::DroppedValue, + crate::loss::LossCode::DroppedGeometry, format!("{n} values in '{column}' aren't dates and were read as empty, so their rows have no geometry"), )), } diff --git a/crates/data/src/sheets.rs b/crates/data/src/sheets.rs index 495010e739..b6a2912c01 100644 --- a/crates/data/src/sheets.rs +++ b/crates/data/src/sheets.rs @@ -805,6 +805,9 @@ mod tests { "{:?}", report.messages ); + // The row is kept without its geometry, which is what was lost. + let said = report.messages.iter().find(|m| m.contains("isn't a date")).unwrap(); + assert_eq!(said.loss, Some(crate::loss::LossCode::DroppedGeometry)); let (_, report) = book("POINT (3 4)"); assert!(!report.messages.iter().any(|m| m.contains("isn't a date")), "{:?}", report.messages); } From e08805345f35fbebbd32c5b84047f948ccecad42 Mon Sep 17 00:00:00 2001 From: mavrick Date: Tue, 24 Nov 2026 14:41:09 -0600 Subject: [PATCH 7/7] fix(data): keep the workbook date note plain until its count is of the rows kept (#2371) Its count also takes in a heading cell and rows left out whole, so it can't yet say dropped.geometry without counting what wasn't lost. --- crates/data/src/io.rs | 12 ++++-------- crates/data/src/sheets.rs | 3 --- 2 files changed, 4 insertions(+), 11 deletions(-) diff --git a/crates/data/src/io.rs b/crates/data/src/io.rs index 4f97bfb2c1..ae8cf8695d 100644 --- a/crates/data/src/io.rs +++ b/crates/data/src/io.rs @@ -2875,14 +2875,10 @@ pub(crate) fn read_rows( let column = headers.get(w).map_or("", |h| h.trim()); match workbook.and_then(|(_, empty)| empty.get(w)).copied().unwrap_or(0) { 0 => {} - 1 => report.messages.push(crate::loss::Note::loss( - crate::loss::LossCode::DroppedGeometry, - format!("1 value in '{column}' isn't a date and was read as empty, so its row has no geometry"), - )), - n => report.messages.push(crate::loss::Note::loss( - crate::loss::LossCode::DroppedGeometry, - format!("{n} values in '{column}' aren't dates and were read as empty, so their rows have no geometry"), - )), + 1 => report.messages.push(format!("1 value in '{column}' isn't a date and was read as empty, so its row has no geometry")), + n => report + .messages + .push(format!("{n} values in '{column}' aren't dates and were read as empty, so their rows have no geometry")), } } let (mut bad_wkt, mut zm_rows, mut collection_rows) = (0usize, 0usize, 0usize); diff --git a/crates/data/src/sheets.rs b/crates/data/src/sheets.rs index b6a2912c01..495010e739 100644 --- a/crates/data/src/sheets.rs +++ b/crates/data/src/sheets.rs @@ -805,9 +805,6 @@ mod tests { "{:?}", report.messages ); - // The row is kept without its geometry, which is what was lost. - let said = report.messages.iter().find(|m| m.contains("isn't a date")).unwrap(); - assert_eq!(said.loss, Some(crate::loss::LossCode::DroppedGeometry)); let (_, report) = book("POINT (3 4)"); assert!(!report.messages.iter().any(|m| m.contains("isn't a date")), "{:?}", report.messages); }