From aff01845605fe6ddbdd489243891378a24f0b874 Mon Sep 17 00:00:00 2001 From: mavrick Date: Tue, 17 Nov 2026 19:22:26 -0600 Subject: [PATCH 1/3] fix(data): preserve padded CSV decimals and report export losses (#1998) --- crates/data/src/export.rs | 4 +- crates/data/src/export/tests.rs | 20 ++- crates/data/src/io.rs | 170 ++++++++++++++---- crates/engine/src/cmd/share.rs | 20 +-- crates/engine/src/cmd/share/table.rs | 2 +- crates/engine/src/cmd/workflows.rs | 5 +- crates/engine/src/tests.rs | 10 +- crates/engine/tests/never_silent_roundtrip.rs | 5 +- crates/ui-egui/src/lib.rs | 3 +- docs/user-guide/data-formats.md | 8 +- 10 files changed, 185 insertions(+), 62 deletions(-) diff --git a/crates/data/src/export.rs b/crates/data/src/export.rs index 91ab2a446b..5aaf7eacf8 100644 --- a/crates/data/src/export.rs +++ b/crates/data/src/export.rs @@ -41,7 +41,7 @@ pub struct Exported { /// Vertices beyond 85.05° north or south, written at 85.05° by an export in Web Mercator, /// where it ends (0 in another system). See [`crate::web_mercator_moved_note`]. pub beyond_web_mercator: usize, - /// Geometry a CSV can't hold, counted over all chunks (none for the other formats). + /// Geometry and text changed by CSV export, counted over all chunks. pub csv: crate::io::CsvLosses, /// Per field of the layer, values of the source's date fields that weren't dates, so are /// written as null ([`crate::source::Batch::unread_dates`], said by @@ -183,7 +183,7 @@ fn write_chunks_as( total = total.saturating_add(chunk.len()); null_numbers = null_numbers.saturating_add(numbers_written_as_null(&chunk, &layer.fields, ext)); if ext == "csv" { - csv += crate::io::CsvLosses::of(&chunk, geometry_type); + csv += crate::io::CsvLosses::of(&chunk, geometry_type, &layer.fields)?; } if ext == "gpkg" { crate::source::add_unread_dates(&mut utc_dates, &crate::io::offset_dates(chunk.iter(), &layer.fields)); diff --git a/crates/data/src/export/tests.rs b/crates/data/src/export/tests.rs index 293eee1861..51f65ea745 100644 --- a/crates/data/src/export/tests.rs +++ b/crates/data/src/export/tests.rs @@ -133,6 +133,20 @@ fn an_explicit_export_format_ignores_case_and_the_filename() { std::fs::remove_dir_all(d).unwrap(); } +#[test] +fn a_streamed_csv_counts_guarded_values_across_chunks() { + let d = folder("csv-guarded"); + let mut ds = Dataset::new("places", GeometryType::None, vec![Field::new("value", FieldType::Text)]); + for value in ["-007", "-093.1445780", "=SUM(A1)"] { + ds.push_next(None, vec![Value::Text(value.into())]); + } + let path = d.join("places.csv"); + let exported = write_chunks_in(&Runs::new(&ds, 1), &ds, &path, Crs::LonLat, 1).unwrap(); + assert_eq!(exported.csv.guarded, [2]); + assert_eq!(std::fs::read_to_string(path).unwrap(), "value\n'-007\n-093.1445780\n'=SUM(A1)\n"); + std::fs::remove_dir_all(d).unwrap(); +} + /// An export in Web Mercator written a chunk at a time counts the vertices beyond 85.05° it /// writes at 85.05°, as it writes them: from a source that declares no extent, whose features /// beyond aren't in its first chunk. In longitude/latitude, or within 85.05°, it counts none. @@ -204,7 +218,11 @@ fn a_streamed_export_writes_what_a_whole_export_writes() { unfit, beyond_web_mercator: 0, // Counted over the chunks as the whole layer counts it. - csv: if ext == "csv" { crate::io::CsvLosses::of(&whole.features, whole.geometry_type) } else { Default::default() }, + csv: if ext == "csv" { + crate::io::CsvLosses::of(&whole.features, whole.geometry_type, &whole.fields).unwrap() + } else { + Default::default() + }, unread_dates: Vec::new(), rounded_dates: Vec::new(), null_text: Vec::new(), diff --git a/crates/data/src/io.rs b/crates/data/src/io.rs index 85779fb61d..120bdd7a8f 100644 --- a/crates/data/src/io.rs +++ b/crates/data/src/io.rs @@ -2351,17 +2351,25 @@ fn unguard(cell: &str) -> std::borrow::Cow<'_, str> { const FORMULA_START: [char; 6] = ['=', '+', '-', '@', '\t', '\r']; -/// A cell's text; text that a spreadsheet would run as a formula is prefixed with `'`. -/// Valid numbers whose digits fit in Double precision without loss, without leading zeros, -/// and with at most 15 significant digits (to avoid truncation in spreadsheets) are exported bare. +/// Text needs an apostrophe if it starts like a spreadsheet formula. The numeric exception +/// keeps finite numbers that fit Double precision and have at most 15 significant digits. +/// A leading-zero code stays guarded unless its mantissa has digits after a decimal point. +fn csv_needs_guard(text: &str) -> bool { + if !text.starts_with(FORMULA_START) { + return false; + } + let mantissa = text.split(['e', 'E']).next().unwrap_or_default(); + let fraction = mantissa.split_once('.').is_some_and(|(_, frac)| !frac.is_empty()); + !((!has_leading_zero(text) || fraction) + && text.parse::().is_ok_and(|f| f.is_finite()) + && !is_long_number(text) + && double_holds(text)) +} + +/// A cell's file text, with an apostrophe when the spreadsheet guard applies. fn csv_cell(v: &Value) -> String { match v { - Value::Text(t) - if t.starts_with(FORMULA_START) - && !(t.parse::().is_ok_and(|f| f.is_finite()) && double_holds(t) && !has_leading_zero(t) && !is_long_number(t)) => - { - format!("'{t}") - } + Value::Text(t) if csv_needs_guard(t) => format!("'{t}"), other => other.to_file_text(), } } @@ -3718,9 +3726,8 @@ pub fn left_out_note(name: &str, ext: &str, left_out: usize) -> Option { }) } -/// What CSV can't hold of a layer's geometry: it has a point a row (a point layer's longitude -/// and latitude, see [`CsvWriter`]), and no geometry for a line or polygon layer. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +/// Changes made by a CSV export to geometry and to text guarded for spreadsheets. +#[derive(Clone, Debug, Default, PartialEq, Eq)] pub struct CsvLosses { /// Features of a point layer with more than one point (a multipoint), or another shape, /// written as one point. @@ -3731,13 +3738,20 @@ pub struct CsvLosses { /// Written with coordinate columns, as a point layer: a streamed export knows this from its /// chunks when the layer declares no type ([`CsvLosses::coordinates_note`]). pub points: bool, + /// Values prefixed with an apostrophe, counted by field. + pub guarded: Vec, } impl CsvLosses { /// The losses of `features` in a layer of type `gt`; a streamed export adds up its chunks'. - pub fn of(features: &[crate::Feature], gt: GeometryType) -> Self { - let mut out = Self { points: gt == GeometryType::Point, ..Self::default() }; - for g in features.iter().filter_map(|f| f.geometry.as_ref()) { + pub fn of(features: &[crate::Feature], gt: GeometryType, fields: &[Field]) -> Result { + let mut out = Self { points: gt == GeometryType::Point, guarded: vec![0; fields.len()], ..Self::default() }; + for f in features { + crate::progress::check()?; + for (count, value) in out.guarded.iter_mut().zip(&f.attrs) { + *count += usize::from(matches!(value, Value::Text(text) if csv_needs_guard(text))); + } + let Some(g) = &f.geometry else { continue }; match (gt, g) { (GeometryType::Point, Geometry::Point(_)) => {} // No point to write: its coordinate cells are left empty. @@ -3748,12 +3762,12 @@ impl CsvLosses { _ => out.unwritten += 1, } } - out + Ok(out) } /// One notice for each loss of a layer written to `target`; none without loss. Geometry /// not written is counted by feature, whatever its kind: a layer of one type can hold others. - pub fn notes(self, target: &str) -> Vec { + pub fn notes(&self, fields: &[Field], target: &str) -> Vec { let mut notes = Vec::new(); if self.as_one_point > 0 { let what = if self.as_one_point == 1 { "1 feature has".to_string() } else { format!("{} features have", self.as_one_point) }; @@ -3765,13 +3779,26 @@ impl CsvLosses { let what = if self.unwritten == 1 { "1 feature".to_string() } else { format!("{} features", self.unwritten) }; notes.push(format!("{target}: CSV holds a point a row, so the geometry of {what} wasn't written, only the attributes")); } + let total: usize = self.guarded.iter().sum(); + if total > 0 { + let target: String = target.chars().map(dbf_notice_char).collect(); + let values = if total == 1 { "value" } else { "values" }; + let affected = fields + .iter() + .zip(&self.guarded) + .filter(|(_, n)| **n > 0) + .map(|(f, n)| format!("'{}' ({n})", dbf_notice_name(&f.name))) + .collect::>() + .join(", "); + notes.push(format!("{target}: CSV prefixed {total} text {values} with an apostrophe for spreadsheet protection in {affected}")); + } notes } /// What a CSV export with these losses says when reading the file back wouldn't take its /// coordinate columns: its `fields` have every name reading takes for a longitude or a /// latitude, and reading takes those fields instead. `None` otherwise. - pub fn coordinates_note(self, fields: &[Field], target: &str) -> Option { + pub fn coordinates_note(&self, fields: &[Field], target: &str) -> Option { if !self.points { return None; } @@ -3795,28 +3822,62 @@ impl CsvLosses { } impl std::ops::AddAssign for CsvLosses { - /// Adds a chunk's losses. + /// Adds a chunk's losses for the same layer and fields. fn add_assign(&mut self, other: Self) { self.as_one_point += other.as_one_point; self.unwritten += other.unwritten; self.points |= other.points; + if self.guarded.is_empty() { + self.guarded = other.guarded; + } else { + for (total, count) in self.guarded.iter_mut().zip(other.guarded) { + *total += count; + } + } } } -/// What a CSV or GPX file (extension `ext`) of the whole dataset `ds` can't hold, written to -/// `target`: [`CsvLosses`]' notices, or [`gpx_notes`] with each feature named from `name_field`; -/// none for another format. A streamed export counts CSV's a chunk at a time instead. -pub fn export_losses_notes(ds: &Dataset, ext: &str, name_field: Option, target: &str) -> Vec { - match ext { +/// What a CSV, KML, KMZ or GPX file of the whole dataset changes when written to `target`. +/// A streamed export counts CSV's changes a chunk at a time instead. +pub fn export_losses_notes(ds: &Dataset, ext: &str, name_field: Option, target: &str) -> Result> { + Ok(match ext { "csv" => { - let losses = CsvLosses::of(&ds.features, ds.geometry_type); - let mut notes = losses.notes(target); + let losses = CsvLosses::of(&ds.features, ds.geometry_type, &ds.fields)?; + let mut notes = losses.notes(&ds.fields, target); notes.extend(losses.coordinates_note(&ds.fields, target)); notes } + "kml" | "kmz" => kml_empty_fields_note(ds, target)?.into_iter().collect(), "gpx" => gpx_notes(ds, name_field, target), _ => Vec::new(), + }) +} + +/// KML writes ExtendedData only for non-null values of placemarks it writes. Report every +/// field absent from that output, even when an unwritten feature has a value for it. +fn kml_empty_fields_note(ds: &Dataset, target: &str) -> Result> { + let mut written = vec![false; ds.fields.len()]; + for f in &ds.features { + crate::progress::check()?; + if f.geometry.is_some() { + for (written, value) in written.iter_mut().zip(&f.attrs) { + *written |= !value.is_null(); + } + } } + let empty: Vec<_> = ds + .fields + .iter() + .zip(written) + .filter(|(_, written)| !written) + .map(|(field, _)| format!("'{}'", dbf_notice_name(&field.name))) + .collect(); + let target: String = target.chars().map(dbf_notice_char).collect(); + Ok((!empty.is_empty()).then(|| { + let count = empty.len(); + let fields = if count == 1 { "field" } else { "fields" }; + format!("{target}: KML omitted {count} {fields} with no values from ExtendedData ({})", empty.join(", ")) + })) } /// Features a GPX file of `ds` leaves out: those without geometry, and multipoints without a @@ -5525,15 +5586,18 @@ mod tests { let mut ds = Dataset::new("t", GeometryType::None, vec![]); ds.push(Some(square), vec![]); ds.push(None, vec![]); - let losses = CsvLosses::of(&ds.features, ds.geometry_type); - assert_eq!(losses, CsvLosses { as_one_point: 0, unwritten: 1, points: false }); - assert!(losses.notes("t.csv")[0].contains("the geometry of 1 feature wasn't written")); + let losses = CsvLosses::of(&ds.features, ds.geometry_type, &ds.fields).unwrap(); + assert_eq!(losses, CsvLosses { unwritten: 1, ..CsvLosses::default() }); + assert!(losses.notes(&ds.fields, "t.csv")[0].contains("the geometry of 1 feature wasn't written")); assert!(!to_csv(&ds).unwrap().contains("longitude")); let points = [crate::Feature { id: 0, geometry: Some(Geometry::Point(Coord::new(1.0, 2.0))), attrs: vec![] }]; - assert_eq!(CsvLosses::of(&points, GeometryType::Point), CsvLosses { points: true, ..CsvLosses::default() }); + assert_eq!(CsvLosses::of(&points, GeometryType::Point, &[]).unwrap(), CsvLosses { points: true, ..CsvLosses::default() }); // A multipoint without a point in a point layer gets empty coordinate cells. let empty = [crate::Feature { id: 1, geometry: Some(Geometry::MultiPoint(vec![])), attrs: vec![] }]; - assert_eq!(CsvLosses::of(&empty, GeometryType::Point), CsvLosses { as_one_point: 0, unwritten: 1, points: true }); + assert_eq!( + CsvLosses::of(&empty, GeometryType::Point, &[]).unwrap(), + CsvLosses { unwritten: 1, points: true, ..CsvLosses::default() } + ); } /// GPX leaves out a feature without geometry and a multipoint without a point (no waypoint @@ -5548,6 +5612,27 @@ mod tests { assert_eq!(write_bytes(&ds, "gpx").unwrap().1, 2); } + #[test] + fn kml_and_kmz_name_fields_missing_from_exported_placemarks() { + let mut ds = + Dataset::new("parcels", GeometryType::Point, vec![Field::new("a", FieldType::Integer), Field::new("empty", FieldType::Text)]); + ds.push(Some(Geometry::Point(Coord::new(1.0, 2.0))), vec![Value::Int(1), Value::Null]); + ds.push(None, vec![Value::Int(2), Value::Text("no placemark".into())]); + for ext in ["kml", "kmz"] { + let target = format!("parcels.{ext}"); + let (bytes, _) = write_bytes(&ds, ext).unwrap(); + let back = &crate::kml::read(&target, &bytes).unwrap()[0].dataset; + assert!(back.field_index("a").is_some()); + assert!(back.field_index("empty").is_none()); + assert_eq!( + export_losses_notes(&ds, ext, None, &target).unwrap(), + [format!("{target}: KML omitted 1 field with no values from ExtendedData ('empty')")] + ); + } + ds.push(Some(Geometry::Point(Coord::new(3.0, 4.0))), vec![Value::Int(3), Value::Text("present".into())]); + assert!(export_losses_notes(&ds, "kml", None, "parcels.kml").unwrap().is_empty()); + } + /// A point layer's fields named like coordinates keep their values when its CSV is read back: /// the coordinate columns come first, so reading takes them, not the fields. (Reading keeps the /// coordinate columns as fields too.) @@ -5587,7 +5672,7 @@ mod tests { assert!(text.starts_with("lon_dd,lat_dd,"), "{text}"); let (back, _) = read_csv(&text, "back").unwrap(); assert_eq!(back.features[0].geometry, ds.features[0].geometry); - assert!(export_losses_notes(&ds, "csv", None, "t.csv").is_empty()); + assert!(export_losses_notes(&ds, "csv", None, "t.csv").unwrap().is_empty()); } /// A point layer with a field of every longitude name has its longitudes in a column reading @@ -5603,7 +5688,7 @@ mod tests { let every = layer(LON_NAMES); let out = to_csv(&every).unwrap(); assert!(out.starts_with("longitude_1,latitude,"), "{out}"); - let notes = export_losses_notes(&every, "csv", None, "t.csv"); + let notes = export_losses_notes(&every, "csv", None, "t.csv").unwrap(); assert_eq!(notes.len(), 1, "{notes:?}"); assert_eq!( notes[0], @@ -5613,8 +5698,8 @@ mod tests { let (back, _) = read_csv(&out, "t").unwrap(); assert_eq!(back.features[0].geometry, Some(Geometry::Point(Coord::new(1.0, 10.0)))); // A name left, or a layer that isn't of points: nothing to say. - assert!(export_losses_notes(&layer(&LON_NAMES[1..]), "csv", None, "t.csv").is_empty()); - assert_eq!(CsvLosses::of(&[], GeometryType::Polyline).coordinates_note(&every.fields, "t.csv"), None); + assert!(export_losses_notes(&layer(&LON_NAMES[1..]), "csv", None, "t.csv").unwrap().is_empty()); + assert_eq!(CsvLosses::of(&[], GeometryType::Polyline, &[]).unwrap().coordinates_note(&every.fields, "t.csv"), None); } #[test] @@ -5778,6 +5863,21 @@ mod tests { assert!(out.contains("'+cmd"), "{out}"); } + #[test] + fn csv_keeps_padded_decimals_and_reports_only_guarded_values() { + let mut ds = + Dataset::new("tiger", GeometryType::None, ["INTPTLAT", "INTPTLON"].map(|name| Field::new(name, FieldType::Text)).to_vec()); + ds.push(None, vec![Value::Text("+44.9500000".into()), Value::Text("-093.1445780".into())]); + assert_eq!(to_csv(&ds).unwrap(), "INTPTLAT,INTPTLON\n+44.9500000,-093.1445780\n"); + assert!(export_losses_notes(&ds, "csv", None, "tiger.csv").unwrap().is_empty()); + ds.push(None, vec![Value::Text("-007".into()), Value::Text("=SUM(A1)".into())]); + assert!(to_csv(&ds).unwrap().ends_with("'-007,'=SUM(A1)\n")); + assert_eq!( + export_losses_notes(&ds, "csv", None, "tiger.csv").unwrap(), + ["tiger.csv: CSV prefixed 2 text values with an apostrophe for spreadsheet protection in 'INTPTLAT' (1), 'INTPTLON' (1)"] + ); + } + #[test] fn csv_signed_numbers_and_text_round_trip() { let mut ds = Dataset::new( diff --git a/crates/engine/src/cmd/share.rs b/crates/engine/src/cmd/share.rs index 5746c6d732..7dcfc9563a 100644 --- a/crates/engine/src/cmd/share.rs +++ b/crates/engine/src/cmd/share.rs @@ -705,7 +705,7 @@ fn write_layer(l: &rustgis_map::Layer, path: &str, asked: Option, gpkg: Gpk return Err(format!("{path}: {e}")); } let parquet = matches!(ext.as_str(), "parquet" | "geoparquet"); - let (written, left_out, skipped, table, unfit, null_numbers, moved, csv, dates) = match &chunks { + let (written, left_out, skipped, table, unfit, null_numbers, moved, format_notes, dates) = match &chunks { Some((src, layer)) => { let (e, table) = rustgis_data::export::write_source_to(src.as_ref(), layer, Path::new(&path), crs, &gpkg).map_err(|e| e.to_string())?; @@ -731,16 +731,19 @@ fn write_layer(l: &rustgis_map::Layer, path: &str, asked: Option, gpkg: Gpk } dates.extend(e.date_messages.iter().map(|n| format!("{path}: {n}"))); dates.extend(e.read_notes.iter().map(|n| format!("{path}: {}: {n} when read for the export", layer.name))); - (e.written, e.left_out, e.skipped, table, unfit, e.null_numbers, moved, e.csv, dates) + let mut format_notes = e.csv.notes(&ds.fields, path); + format_notes.extend(e.csv.coordinates_note(&ds.fields, path)); + (e.written, e.left_out, e.skipped, table, unfit, e.null_numbers, moved, format_notes, dates) } None => { + let format_notes = + rustgis_data::io::export_losses_notes(ds, &ext, rustgis_data::io::name_field(ds), path).map_err(|e| e.to_string())?; let (left_out, table) = rustgis_data::io::write_path_to(ds, Path::new(&path), crs, &gpkg).map_err(|e| e.to_string())?; let unfit = if parquet { rustgis_data::source::parquet::values_note(ds, path) } else { None }; let null_numbers = rustgis_data::export::numbers_written_as_null(&ds.features, &ds.fields, &ext); - let csv = if ext == "csv" { rustgis_data::io::CsvLosses::of(&ds.features, ds.geometry_type) } else { Default::default() }; let mut dates = read_notes(path, &ds.name, &unreadable); dates.extend(gpkg_dates_note(ds, &ext, path)); - (ds.features.len().saturating_sub(left_out), left_out, unread, table, unfit, null_numbers, None, csv, dates) + (ds.features.len().saturating_sub(left_out), left_out, unread, table, unfit, null_numbers, None, format_notes, dates) } }; // The features written give their own extent. A streamed layer written a chunk at a time has @@ -770,14 +773,7 @@ fn write_layer(l: &rustgis_map::Layer, path: &str, asked: Option, gpkg: Gpk // geometry it can draw, of the layer's kind). let mut said = Vec::new(); said.extend(rustgis_data::io::left_out_note(path, &ext, left_out)); - // CSV holds a point a row, GPX a name for each feature and no areas. - if ext == "csv" { - said.extend(csv.notes(path)); - said.extend(csv.coordinates_note(&ds.fields, path)); - } - if ext == "gpx" { - said.extend(rustgis_data::io::gpx_notes(ds, rustgis_data::io::name_field(ds), path)); - } + said.extend(format_notes); if skipped > 0 { said.push(format!("{path}: {skipped} rows couldn't be read and were left out")); } diff --git a/crates/engine/src/cmd/share/table.rs b/crates/engine/src/cmd/share/table.rs index fc162f277d..4e1578709f 100644 --- a/crates/engine/src/cmd/share/table.rs +++ b/crates/engine/src/cmd/share/table.rs @@ -172,7 +172,7 @@ pub(in crate::cmd) fn table_work(s: &Session, p: &Value) -> Result notes.extend(rustgis_data::io::dates_as_text_note(&ds.fields, &path)); notes.extend(super::gpkg_dates_note(&ds, &ext, &path)); let name_field = rustgis_data::io::name_field(&ds); - notes.extend(rustgis_data::io::export_losses_notes(&ds, &ext, name_field, &path)); + notes.extend(rustgis_data::io::export_losses_notes(&ds, &ext, name_field, &path).map_err(|e| e.to_string())?); let (left_out, table) = rustgis_data::io::write_path_to(&ds, Path::new(&path), rustgis_data::raster::Crs::LonLat, &gpkg).map_err(|e| e.to_string())?; if let Some(note) = rustgis_data::io::left_out_note(&path, &ext, left_out) { diff --git a/crates/engine/src/cmd/workflows.rs b/crates/engine/src/cmd/workflows.rs index 073f05df51..9ab7e4db64 100644 --- a/crates/engine/src/cmd/workflows.rs +++ b/crates/engine/src/cmd/workflows.rs @@ -1929,7 +1929,7 @@ pub(crate) fn convert_work(s: &Session, p: &Value) -> Result 0 { notes.push(format!("{path}: {} rows couldn't be read and were left out", result.skipped)); @@ -2014,8 +2014,7 @@ fn converted(ds: &Dataset, p: &Value) -> Result<(String, Vec), String> { // Every format here is longitude/latitude. let target = ps(p, "path").unwrap_or(&ds.name); let mut notes = rustgis_data::export_notes([(ds, ds.extent())], target, rustgis_data::raster::Crs::LonLat); - // CSV holds a point a row, GPX a name for each feature and no areas. - notes.extend(rustgis_data::io::export_losses_notes(ds, format, name_field, target)); + notes.extend(rustgis_data::io::export_losses_notes(ds, format, name_field, target).map_err(|e| e.to_string())?); // KML and GPX hold features with geometry only. if let ext @ ("kml" | "gpx") = format { let without = diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index a4484153b2..df0d1903a8 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -24139,13 +24139,19 @@ fn csv_and_gpx_exports_say_what_they_leave_out() { assert!(n.iter().any(|t| t.contains("'height'")) && n.iter().any(|t| t.contains("tracks")), "{n:?}"); let n = said(&mut s, "data.convert", json!({"layer": "Areas", "format": "csv"})); assert!(n.iter().any(|t| t.contains("wasn't written, only the attributes")), "{n:?}"); - // A row without geometry, which KML and GPX can't hold, is counted. + // Both formats count the row without geometry. KML also names the omitted null field. let mut rows = layer("Rows", GeometryType::Point, vec![(Geometry::Point(Coord::new(1.0, 2.0)), vec![V::Text("P".into()), V::Null])]); rows.push(None, vec![V::Text("no place".into()), V::Null]); s.map_mut().add_dataset(rows); for format in ["kml", "gpx"] { let n = said(&mut s, "data.convert", json!({"layer": "Rows", "format": format})); - assert!(n.len() == 1 && n[0].contains("1 features without drawable geometry were left out"), "{format}: {n:?}"); + assert!(n.iter().any(|t| t.contains("1 features without drawable geometry were left out")), "{format}: {n:?}"); + if format == "kml" { + assert_eq!(n.len(), 2, "{n:?}"); + assert!(n.iter().any(|t| t.contains("KML omitted 1 field with no values from ExtendedData ('height')")), "{n:?}"); + } else { + assert_eq!(n.len(), 1, "{n:?}"); + } } // A standalone table keeps geometry too: Export Table says the same, and nothing for a clean one. let areas = layer("Area table", GeometryType::Polygon, vec![(square(0.0, true), vec![V::Text("A".into()), V::Float(2.5)])]); diff --git a/crates/engine/tests/never_silent_roundtrip.rs b/crates/engine/tests/never_silent_roundtrip.rs index b2658218e4..a79142bcbb 100644 --- a/crates/engine/tests/never_silent_roundtrip.rs +++ b/crates/engine/tests/never_silent_roundtrip.rs @@ -39,6 +39,7 @@ const LIMITS: &[(&str, &str, &str)] = &[ ("csv", "text became a number", "a column of numbers is a number column"), ("csv", "infinity or NaN became text", "inf and NaN aren't read as numbers"), ("csv", "not read back: nothing", "a layer without geometry or values is an empty file"), + ("gpx", "field of nulls missing", "GPX writes no attribute schema"), // GeoJSON types a property from its values. ("geojson", "field of nulls type changed", "a property that is null everywhere has no type"), ("geojson", "field type changed Date → Text", "a date is written as ISO 8601 text and stays text on read (#853)"), @@ -55,14 +56,12 @@ const LIMITS: &[(&str, &str, &str)] = &[ ]; /// KML and GPX hold text, read with types from the values as for CSV (`type_text_columns`); the -/// name field is written as the feature's name and read back as `name`, and a field that is -/// null everywhere isn't in the file. +/// name field is written as the feature's name and read back as `name`. const TEXT_FORMAT_LIMITS: &[&str] = &[ "text trimmed", "blank text became null", "field type changed", "field of nulls type changed", - "field of nulls missing", "field renamed", "boolean became text", "date became text", diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index da7eafeca3..32300e2321 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -4883,8 +4883,7 @@ impl RustGisApp { dbf_notes.push(format!("{name}: {} rows couldn't be read and were left out", lost.rows)); } dbf_notes.extend(rustgis_engine::cmd::share::read_notes(&name, &l.name, &lost)); - // CSV holds a point a row, GPX a name for each feature and no areas. - dbf_notes.extend(io::export_losses_notes(ds, &ext, io::name_field(ds), &name)); + dbf_notes.extend(io::export_losses_notes(ds, &ext, io::name_field(ds), &name).map_err(|e| e.to_string())?); if let Some(note) = io::left_out_note(&name, &ext, left_out) { self.session.notify(note, false); } diff --git a/docs/user-guide/data-formats.md b/docs/user-guide/data-formats.md index e2209c926b..74feab7223 100644 --- a/docs/user-guide/data-formats.md +++ b/docs/user-guide/data-formats.md @@ -637,7 +637,7 @@ were rounded, and Export Raster, which writes the rounded values, says so again. | GeoParquet (`.parquet`, `.geoparquet`) | Data › Export | GeoParquet 1.1: WKB geometry in WGS 84, Zstd level 9 compression, row groups of up to 65,536 features and a `bbox` covering column with byte-stream-split encoding. The covering keeps spatial range reads available; compression favours smaller files over export speed. Reading the file needs Zstd support, and reading its `bbox` column needs byte-stream-split support, which current GDAL, PyArrow and DuckDB have and some older readers lack (some of those refuse the file). A standalone table without geometry writes plain Parquet. | | Shapefile | Data › Export to `.shp` (or `.zip` for the files zipped) | Writes `.shp`, `.shx`, `.dbf`, `.prj` (the coordinate system, see below) and `.cpg` (UTF-8). Field names are cut to 10 bytes (made unique ignoring case, and reported), text to at most 254 bytes, and numbers that do not fit their dBase field are left empty. Date fields are written as dBase dates; date-time fields as ISO 8601 text, since dBase has no date-time field other programs read (said in a notice). Export notices count shortened text, non-null values left empty (including incompatible types), and numbers rounded to the field's precision, and name the affected source fields; features without geometry, and lines of a single point, are left out (and reported). An export in longitude/latitude leaves out vertices with a missing (NaN) or infinite coordinate; an export in a projected system refuses any coordinate that doesn't project to a finite one, naming its feature. In either, line parts and polygon rings too short to draw (fewer than 2 or 3 drawable vertices, whether written so or left so) and the holes of a polygon whose outer ring goes are left out. The export counts the vertices, and the parts or rings, in the features it writes; a feature with nothing drawable left is counted with the features left out. | | FlatGeobuf | Data › Export to `.fgb` | In the layer's coordinate system (see below), with a spatial index. Features are written in spatial-index order, so record order can change; keep an attribute key to match records after export. Features without geometry are left out (and reported). Desktop only: the writer needs a temporary file, which the browser doesn't have. | -| KML, KMZ, GPX | Data › Export to `.kml`, `.kmz` or `.gpx` | Placemarks named by a `name` field, if there is one; KML/KMZ writes a text field named exactly `description` as the placemark description, keeping its text and column name on re-import. A description containing characters XML 1.0 cannot represent is refused with a count and feature location. KML/KMZ also write all attributes to extended data (a null value is not written, so a field that is null for every feature is not recreated on re-import), and reserved-name collisions are reported when read. GPX writes only the name and geometry, so other attributes are not kept. Features without geometry are left out. | +| KML, KMZ, GPX | Data › Export to `.kml`, `.kmz` or `.gpx` | Placemarks named by a `name` field, if there is one; KML/KMZ writes a text field named exactly `description` as the placemark description, keeping its text and column name on re-import. A description containing characters XML 1.0 cannot represent is refused with a count and feature location. KML/KMZ write non-null attributes to extended data. The export reports fields omitted because they have no non-null values in the placemarks written. Reserved-name collisions are reported when read. GPX writes only the name and geometry, so other attributes are not kept. Features without geometry are left out. | | GeoJSON, KML, GPX, CSV, CSV with WKT | Analyze › Workflows › Data Interop (`data.convert`; `"format": "geojson"`, `"kml"`, `"gpx"`, `"csv"` or `"wkt"`) | Returns text when `"path"` is omitted; a streamed layer requires a path to avoid returning only its loaded view. Desktop conversion asks for a file first, then reads the whole source in the background with progress and Cancel. GeoJSON and CSV read a chunk at a time where supported; KML, GPX and WKT need the whole layer within the memory limit. | | GeoTIFF / Cloud-optimised GeoTIFF | Data › Export Raster (`share.exportRaster`) | Untiled GeoTIFF by default; `"cog": true` writes 512-pixel tiles, Deflate compression and overviews. Writes the loaded raster's resolution (an overview when that is what was opened), the selected band or its colour bands. A WMS, WMTS or XYZ tile layer (`"tiles"`) is written as its tiles at one zoom, RGBA in Web Mercator (see [Sharing](sharing.md#exporting)). The web app's Export Raster downloads an ordinary GeoTIFF. | | PNG | Publish › Export Map (`share.exportMap`) | Configurable DPI, with labels, scale bar and tile credits. | @@ -647,6 +647,12 @@ were rounded, and Export Raster, which writes the rounded values, says so again. | Web map, OGC API Features, MapLibre style | Publish › Share As | Open-format files that need no server: see [Sharing](sharing.md). | | Raster tiles | `imagery.hostedImagery` | A zip of `tiles/z/x/y.png` tiles, `tiles.json` and a viewer page; at most 5,000 tiles and 256 MiB of tile data. | +CSV writes signed decimals such as `-093.1445780` as stored, including leading zeros, when +they fit double precision and have at most 15 significant digits. Text that starts like +a spreadsheet formula is prefixed with an apostrophe, including signed zero-padded +integer codes such as `-007` and signed numbers that exceed those precision limits. +The export reports the number of prefixed values and the affected fields. + GeoPackage, Shapefile and FlatGeobuf exports default to the layer's original coordinate system. A system with an EPSG code is written by its code; one without (a Shapefile whose `.prj` names State Plane by its parameters, say) is written by its WKT definition, which a GeoPackage and a From 4ec3643045e426508df47c6d677afe4329274b9c Mon Sep 17 00:00:00 2001 From: mavrick Date: Wed, 18 Nov 2026 11:16:46 -0600 Subject: [PATCH 2/3] docs(data): say spreadsheets show padded CSV decimals as numbers (#1998) Co-Authored-By: Claude Opus 5.5 --- docs/user-guide/data-formats.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/docs/user-guide/data-formats.md b/docs/user-guide/data-formats.md index 74feab7223..19641df40c 100644 --- a/docs/user-guide/data-formats.md +++ b/docs/user-guide/data-formats.md @@ -648,7 +648,9 @@ were rounded, and Export Raster, which writes the rounded values, says so again. | Raster tiles | `imagery.hostedImagery` | A zip of `tiles/z/x/y.png` tiles, `tiles.json` and a viewer page; at most 5,000 tiles and 256 MiB of tile data. | CSV writes signed decimals such as `-093.1445780` as stored, including leading zeros, when -they fit double precision and have at most 15 significant digits. Text that starts like +they fit double precision and have at most 15 significant digits. The file keeps the +padding, but a spreadsheet opens these as numbers and shows them without it (`-93.144578`). +Text that starts like a spreadsheet formula is prefixed with an apostrophe, including signed zero-padded integer codes such as `-007` and signed numbers that exceed those precision limits. The export reports the number of prefixed values and the affected fields. From f6a54f02720b9b0b8c1072ef2a1d1604c190d3eb Mon Sep 17 00:00:00 2001 From: mavrick Date: Wed, 18 Nov 2026 12:30:29 -0600 Subject: [PATCH 3/3] fix(data): GPX export names every field it leaves out (#1998) A field null in every feature was dropped without a notice, so the round-trip test exempted it. GPX keeps no attributes, so the notice now names all of them, as the KML export names its omitted null fields. Co-Authored-By: Claude Opus 5.5 --- crates/data/src/io.rs | 7 ++--- crates/engine/src/tests.rs | 30 +++++++++---------- crates/engine/tests/never_silent_roundtrip.rs | 5 ++-- docs/user-guide/data-formats.md | 2 +- 4 files changed, 20 insertions(+), 24 deletions(-) diff --git a/crates/data/src/io.rs b/crates/data/src/io.rs index 120bdd7a8f..066dced4f8 100644 --- a/crates/data/src/io.rs +++ b/crates/data/src/io.rs @@ -3896,11 +3896,8 @@ pub fn gpx_left_out(ds: &Dataset) -> usize { /// multipoints (a waypoint per point). One notice per kind; none for a layer GPX holds whole. pub fn gpx_notes(ds: &Dataset, name_field: Option, target: &str) -> Vec { let drawn = || ds.features.iter().filter(|f| f.geometry.is_some()); - let fields: Vec<&str> = (ds.fields.iter().enumerate()) - .filter(|(k, _)| Some(*k) != name_field) - .filter(|(k, _)| drawn().any(|f| f.attrs.get(*k).is_some_and(|v| !v.is_null()))) - .map(|(_, f)| f.name.as_str()) - .collect(); + // Every other field, null everywhere or not: it isn't in the file, so it doesn't come back. + let fields: Vec<&str> = (ds.fields.iter().enumerate()).filter(|(k, _)| Some(*k) != name_field).map(|(_, f)| f.name.as_str()).collect(); let (mut polygons, mut holes, mut multipoints) = (0, 0, 0); for g in drawn().filter_map(|f| f.geometry.as_ref()) { match g { diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index df0d1903a8..b06d66ffed 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -24134,23 +24134,23 @@ fn csv_and_gpx_exports_say_what_they_leave_out() { "{n:?}" ); let n = said(&mut s, "share.exportLayer", json!({"layer": "Sites", "path": out("sites.gpx")})); - assert!(n.len() == 1 && n[0].contains("1 multipoint was written as a waypoint for each"), "{n:?}"); + assert!(n.len() == 2 && n[0].contains("'height'") && n[1].contains("1 multipoint was written as a waypoint for each"), "{n:?}"); let n = said(&mut s, "data.convert", json!({"layer": "Areas", "format": "gpx"})); assert!(n.iter().any(|t| t.contains("'height'")) && n.iter().any(|t| t.contains("tracks")), "{n:?}"); let n = said(&mut s, "data.convert", json!({"layer": "Areas", "format": "csv"})); assert!(n.iter().any(|t| t.contains("wasn't written, only the attributes")), "{n:?}"); - // Both formats count the row without geometry. KML also names the omitted null field. + // Both formats count the row without geometry and name the omitted null field. let mut rows = layer("Rows", GeometryType::Point, vec![(Geometry::Point(Coord::new(1.0, 2.0)), vec![V::Text("P".into()), V::Null])]); rows.push(None, vec![V::Text("no place".into()), V::Null]); s.map_mut().add_dataset(rows); for format in ["kml", "gpx"] { let n = said(&mut s, "data.convert", json!({"layer": "Rows", "format": format})); assert!(n.iter().any(|t| t.contains("1 features without drawable geometry were left out")), "{format}: {n:?}"); + assert_eq!(n.len(), 2, "{format}: {n:?}"); if format == "kml" { - assert_eq!(n.len(), 2, "{n:?}"); assert!(n.iter().any(|t| t.contains("KML omitted 1 field with no values from ExtendedData ('height')")), "{n:?}"); } else { - assert_eq!(n.len(), 1, "{n:?}"); + assert!(n.iter().any(|t| t.contains("1 field wasn't written: 'height'")), "{n:?}"); } } // A standalone table keeps geometry too: Export Table says the same, and nothing for a clean one. @@ -24163,17 +24163,17 @@ fn csv_and_gpx_exports_say_what_they_leave_out() { assert!(n.len() == 1 && n[0].contains("the geometry of 1 feature wasn't written"), "{n:?}"); let n = said(&mut s, "share.exportTable", json!({"table": 9001, "path": out("table.gpx")})); assert!(n.iter().any(|t| t.contains("'height'")) && n.iter().any(|t| t.contains("1 hole left out")), "{n:?}"); - for ext in ["csv", "gpx"] { - let n = said(&mut s, "share.exportTable", json!({"table": 9002, "path": out(&format!("clean-table.{ext}"))})); - assert_eq!(n, Vec::::new(), "{ext}"); - } - // Points alone, their other field empty: CSV and GPX hold them whole. - for ext in ["csv", "gpx"] { - assert_eq!( - said(&mut s, "share.exportLayer", json!({"layer": "Clean", "path": out(&format!("clean.{ext}"))})), - Vec::::new() - ); - assert_eq!(said(&mut s, "data.convert", json!({"layer": "Clean", "format": ext})), Vec::::new()); + let n = said(&mut s, "share.exportTable", json!({"table": 9002, "path": out("clean-table.csv")})); + assert_eq!(n, Vec::::new()); + // Points alone, their other field empty: CSV holds them whole; GPX names the field it leaves out. + assert_eq!(said(&mut s, "share.exportLayer", json!({"layer": "Clean", "path": out("clean.csv")})), Vec::::new()); + assert_eq!(said(&mut s, "data.convert", json!({"layer": "Clean", "format": "csv"})), Vec::::new()); + for n in [ + said(&mut s, "share.exportTable", json!({"table": 9002, "path": out("clean-table.gpx")})), + said(&mut s, "share.exportLayer", json!({"layer": "Clean", "path": out("clean.gpx")})), + said(&mut s, "data.convert", json!({"layer": "Clean", "format": "gpx"})), + ] { + assert!(n.len() == 1 && n[0].contains("1 field wasn't written: 'height'"), "{n:?}"); } std::fs::remove_dir_all(dir).unwrap(); } diff --git a/crates/engine/tests/never_silent_roundtrip.rs b/crates/engine/tests/never_silent_roundtrip.rs index a79142bcbb..c5bb5d83ca 100644 --- a/crates/engine/tests/never_silent_roundtrip.rs +++ b/crates/engine/tests/never_silent_roundtrip.rs @@ -23,8 +23,8 @@ const GEOMETRY_ONLY: [&str; 4] = ["fgb", "shp", "kml", "gpx"]; /// Changes a format makes without a notice, as (format, the start of a change from [`changes`], /// why). Each is what the format can hold or how its reader works, not a loss of a value's -/// number or text, except trimming (Shapefile, KML, GPX), blanks read as null and (KML, GPX) a -/// field of nulls left out, which are kept here until they are said (#1907). CSV keeps the spaces +/// number or text, except trimming (Shapefile, KML, GPX) and blanks read as null, which are kept +/// here until they are said (#1907). CSV keeps the spaces /// around a value (#2059). const LIMITS: &[(&str, &str, &str)] = &[ // CSV holds text: reading types each column from its values (`text_type`) and reads an empty @@ -39,7 +39,6 @@ const LIMITS: &[(&str, &str, &str)] = &[ ("csv", "text became a number", "a column of numbers is a number column"), ("csv", "infinity or NaN became text", "inf and NaN aren't read as numbers"), ("csv", "not read back: nothing", "a layer without geometry or values is an empty file"), - ("gpx", "field of nulls missing", "GPX writes no attribute schema"), // GeoJSON types a property from its values. ("geojson", "field of nulls type changed", "a property that is null everywhere has no type"), ("geojson", "field type changed Date → Text", "a date is written as ISO 8601 text and stays text on read (#853)"), diff --git a/docs/user-guide/data-formats.md b/docs/user-guide/data-formats.md index 19641df40c..c23dd8933b 100644 --- a/docs/user-guide/data-formats.md +++ b/docs/user-guide/data-formats.md @@ -637,7 +637,7 @@ were rounded, and Export Raster, which writes the rounded values, says so again. | GeoParquet (`.parquet`, `.geoparquet`) | Data › Export | GeoParquet 1.1: WKB geometry in WGS 84, Zstd level 9 compression, row groups of up to 65,536 features and a `bbox` covering column with byte-stream-split encoding. The covering keeps spatial range reads available; compression favours smaller files over export speed. Reading the file needs Zstd support, and reading its `bbox` column needs byte-stream-split support, which current GDAL, PyArrow and DuckDB have and some older readers lack (some of those refuse the file). A standalone table without geometry writes plain Parquet. | | Shapefile | Data › Export to `.shp` (or `.zip` for the files zipped) | Writes `.shp`, `.shx`, `.dbf`, `.prj` (the coordinate system, see below) and `.cpg` (UTF-8). Field names are cut to 10 bytes (made unique ignoring case, and reported), text to at most 254 bytes, and numbers that do not fit their dBase field are left empty. Date fields are written as dBase dates; date-time fields as ISO 8601 text, since dBase has no date-time field other programs read (said in a notice). Export notices count shortened text, non-null values left empty (including incompatible types), and numbers rounded to the field's precision, and name the affected source fields; features without geometry, and lines of a single point, are left out (and reported). An export in longitude/latitude leaves out vertices with a missing (NaN) or infinite coordinate; an export in a projected system refuses any coordinate that doesn't project to a finite one, naming its feature. In either, line parts and polygon rings too short to draw (fewer than 2 or 3 drawable vertices, whether written so or left so) and the holes of a polygon whose outer ring goes are left out. The export counts the vertices, and the parts or rings, in the features it writes; a feature with nothing drawable left is counted with the features left out. | | FlatGeobuf | Data › Export to `.fgb` | In the layer's coordinate system (see below), with a spatial index. Features are written in spatial-index order, so record order can change; keep an attribute key to match records after export. Features without geometry are left out (and reported). Desktop only: the writer needs a temporary file, which the browser doesn't have. | -| KML, KMZ, GPX | Data › Export to `.kml`, `.kmz` or `.gpx` | Placemarks named by a `name` field, if there is one; KML/KMZ writes a text field named exactly `description` as the placemark description, keeping its text and column name on re-import. A description containing characters XML 1.0 cannot represent is refused with a count and feature location. KML/KMZ write non-null attributes to extended data. The export reports fields omitted because they have no non-null values in the placemarks written. Reserved-name collisions are reported when read. GPX writes only the name and geometry, so other attributes are not kept. Features without geometry are left out. | +| KML, KMZ, GPX | Data › Export to `.kml`, `.kmz` or `.gpx` | Placemarks named by a `name` field, if there is one; KML/KMZ writes a text field named exactly `description` as the placemark description, keeping its text and column name on re-import. A description containing characters XML 1.0 cannot represent is refused with a count and feature location. KML/KMZ write non-null attributes to extended data. The export reports fields omitted because they have no non-null values in the placemarks written. Reserved-name collisions are reported when read. GPX writes only the name and geometry, so other attributes are not kept, and the export names them. Features without geometry are left out. | | GeoJSON, KML, GPX, CSV, CSV with WKT | Analyze › Workflows › Data Interop (`data.convert`; `"format": "geojson"`, `"kml"`, `"gpx"`, `"csv"` or `"wkt"`) | Returns text when `"path"` is omitted; a streamed layer requires a path to avoid returning only its loaded view. Desktop conversion asks for a file first, then reads the whole source in the background with progress and Cancel. GeoJSON and CSV read a chunk at a time where supported; KML, GPX and WKT need the whole layer within the memory limit. | | GeoTIFF / Cloud-optimised GeoTIFF | Data › Export Raster (`share.exportRaster`) | Untiled GeoTIFF by default; `"cog": true` writes 512-pixel tiles, Deflate compression and overviews. Writes the loaded raster's resolution (an overview when that is what was opened), the selected band or its colour bands. A WMS, WMTS or XYZ tile layer (`"tiles"`) is written as its tiles at one zoom, RGBA in Web Mercator (see [Sharing](sharing.md#exporting)). The web app's Export Raster downloads an ordinary GeoTIFF. | | PNG | Publish › Export Map (`share.exportMap`) | Configurable DPI, with labels, scale bar and tile credits. |