Repository navigation
fix(data): resolve nightly Shapefile and date regressions #3502
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from all commits
8c71dda
04ffc0e
23f9381
4df2897
0b95c75
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -1056,7 +1056,8 @@ pub fn write_bytes_in(ds: &Dataset, ext: &str, crs: Crs) -> Result<(Vec<u8>, usi | |
|
|
||
| /// [`write_bytes_in`] for an export (named `name` in its notes): a feature with a place `crs` | ||
| /// can't hold is written without its geometry ([`project_leaving_out`]), and the notes say how | ||
| /// many ([`unplaced_export_note`]). Also gives the dataset's [`Dataset::lonlat_extent`], as | ||
| /// many ([`unplaced_export_note`]). For Shapefiles, the notes also count value losses in the | ||
| /// rows written. Gives the dataset's [`Dataset::lonlat_extent`], as | ||
| /// [`write_path_placed`] does, so a download converts each place once too. | ||
| pub fn write_bytes_noted( | ||
| ds: &Dataset, | ||
|
|
@@ -1088,7 +1089,8 @@ pub fn write_bytes_noted_within( | |
| } | ||
| if crs == ds.coord_crs() { | ||
| let (bytes, left_out) = projected_bytes_within(ds, &ext, crs, limit)?; | ||
| return Ok((bytes, left_out, Vec::new(), ds.lonlat_extent())); | ||
| let notes = shapefile_export_values_notes(ds, &ext, name, crate::progress::check)?; | ||
| return Ok((bytes, left_out, notes, ds.lonlat_extent())); | ||
| } | ||
| if limit.bounded() { | ||
| if goes_a_feature_at_a_time(&ext) { | ||
|
|
@@ -1105,7 +1107,10 @@ pub fn write_bytes_noted_within( | |
| } | ||
| let (projected, unplaced, placed) = project_leaving_out_placed(ds, crs)?; | ||
| let (bytes, left_out) = projected_bytes_within(&projected, &ext, crs, limit)?; | ||
| let notes = unplaced_export_note(name, &ds.name, unplaced, crs).into_iter().collect(); | ||
| let notes = unplaced_export_note(name, &ds.name, unplaced, crs) | ||
| .into_iter() | ||
| .chain(shapefile_export_values_notes(&projected, &ext, name, crate::progress::check)?) | ||
| .collect(); | ||
| Ok((bytes, left_out, notes, lonlat_extent_placed(ds, crs, placed))) | ||
| } | ||
|
|
||
|
|
@@ -1444,8 +1449,8 @@ pub fn write_path_in(ds: &Dataset, path: &Path, crs: Crs) -> Result<usize> { | |
| } | ||
|
|
||
| /// As [`write_path_in`], a GeoPackage's table placed as `gpkg` says (other formats ignore it): | ||
| /// also returns the table written, and notes to give with the export (a Shapefile's old parts it | ||
| /// couldn't remove once the new ones landed, [`kept_backups_note`]). A feature with a place `crs` | ||
| /// also returns the table written and export notes. For a Shapefile, these include value losses | ||
| /// and old parts left behind after replacement ([`kept_backups_note`]). A feature with a place `crs` | ||
| /// can't hold is written without its geometry, and the notes say how many | ||
| /// ([`unplaced_export_note`]). | ||
| pub fn write_path_to( | ||
|
|
@@ -1497,7 +1502,15 @@ fn write_path_as( | |
| (projected, unplaced, placed) = if leaving_out { project_leaving_out_placed(ds, crs)? } else { (project(ds, crs)?, 0, None) }; | ||
| &projected | ||
| }; | ||
| let unplaced = unplaced_export_note(&path.display().to_string(), &ds.name, unplaced, crs); | ||
| let target = path.to_string_lossy(); | ||
| let notes = || { | ||
| let mut notes: Vec<_> = unplaced_export_note(&target, &ds.name, unplaced, crs).into_iter().collect(); | ||
| if leaving_out { | ||
| // The file is in place: Cancel can't take it back, nor its notices. | ||
| notes.extend(shapefile_export_values_notes(ds, &ext, &target, || Ok(())).unwrap_or_default()); | ||
| } | ||
| notes | ||
| }; | ||
| match ext.as_str() { | ||
| "gpkg" => { | ||
| #[cfg(not(target_arch = "wasm32"))] | ||
|
|
@@ -1507,12 +1520,7 @@ fn write_path_as( | |
| // column, and one that declares no type takes its geometry's. | ||
| let table = crate::source::gpkg::write_table_in(ds, path, crs, gpkg)?; | ||
| Ok(( | ||
| PathWritten { | ||
| left_out: 0, | ||
| table: Some(table), | ||
| notes: unplaced.into_iter().collect(), | ||
| declaration_changes: DeclarationChanges::Unchanged, | ||
| }, | ||
| PathWritten { left_out: 0, table: Some(table), notes: notes(), declaration_changes: DeclarationChanges::Unchanged }, | ||
| placed, | ||
| )) | ||
| } | ||
|
|
@@ -1530,7 +1538,8 @@ fn write_path_as( | |
| let declaration_changes = | ||
| if compare { shapefile_declaration_changes(path, &parts, &ds.fields) } else { DeclarationChanges::Unchanged }; | ||
| let kept = place_shapefile(path, &staged)?; | ||
| let notes = unplaced.into_iter().chain(kept_backups_note(path, &kept).map(crate::loss::Note::plain)).collect(); | ||
| let mut notes = notes(); | ||
| notes.extend(kept_backups_note(path, &kept).map(crate::loss::Note::plain)); | ||
| Ok((PathWritten { left_out, table: None, notes, declaration_changes }, placed)) | ||
| } | ||
| _ if crs != Crs::LonLat && !holds_a_system(&ext) => { | ||
|
|
@@ -1544,7 +1553,7 @@ fn write_path_as( | |
| DeclarationChanges::Unchanged | ||
| }; | ||
| write_atomic(path, &bytes)?; | ||
| Ok((PathWritten { left_out, table: None, notes: unplaced.into_iter().collect(), declaration_changes }, placed)) | ||
| Ok((PathWritten { left_out, table: None, notes: notes(), declaration_changes }, placed)) | ||
| } | ||
| } | ||
| } | ||
|
|
@@ -5811,15 +5820,28 @@ struct DbfLosses { | |
| rounded: usize, | ||
| } | ||
|
|
||
| /// Shapefile value losses are counted on the dataset the writer sees after any reprojection. | ||
| fn shapefile_export_values_notes(ds: &Dataset, ext: &str, target: &str, check: fn() -> Result<()>) -> Result<Vec<crate::loss::Note>> { | ||
| if matches!(ext, "shp" | "zip") { shapefile_values_notes_checked(ds, target, check) } else { Ok(Vec::new()) } | ||
| } | ||
|
|
||
| /// Counts text cut to 254 bytes, non-null values left empty, and numbers rounded to the field's | ||
| /// precision, in rows whose geometry is written. Each kind has one notice naming the affected | ||
| /// source fields (first five, bounded and flattened); a clean dataset gives none. | ||
| pub fn shapefile_values_notes(ds: &Dataset, target: &str) -> Vec<crate::loss::Note> { | ||
| let decimals: Vec<_> = | ||
| ds.fields.iter().enumerate().map(|(k, f)| if f.ty == FieldType::Double { dbf_decimals(ds, k) } else { 0 }).collect(); | ||
| // A check that never stops can't fail. | ||
| shapefile_values_notes_checked(ds, target, || Ok(())).unwrap_or_default() | ||
| } | ||
|
|
||
| /// [`shapefile_values_notes`], asking `check` before each row. | ||
| fn shapefile_values_notes_checked(ds: &Dataset, target: &str, check: fn() -> Result<()>) -> Result<Vec<crate::loss::Note>> { | ||
| let decimals = shapefile_decimals(ds, check)?; | ||
| let mut counts = vec![DbfLosses::default(); ds.fields.len()]; | ||
| // Geometry is examined once per row, regardless of how many attribute fields it has. | ||
| for row in ds.features.iter().filter(|f| shapefile_keeps(f.geometry.as_ref(), ds.geometry_type)) { | ||
| for row in &ds.features { | ||
| check()?; | ||
| if !shapefile_keeps(row.geometry.as_ref(), ds.geometry_type) { | ||
| continue; | ||
| } | ||
| for (k, (field, value)) in ds.fields.iter().zip(&row.attrs).enumerate() { | ||
| if value.is_null() { | ||
| continue; | ||
|
|
@@ -5881,7 +5903,7 @@ pub fn shapefile_values_notes(ds: &Dataset, target: &str) -> Vec<crate::loss::No | |
| format!("{target}: {what} rounded to fit dBase field precision, in {fields}"), | ||
| )); | ||
| } | ||
| notes | ||
| Ok(notes) | ||
| } | ||
|
|
||
| /// The names of the `.dbf` columns a Shapefile written from `fields` has, in order | ||
|
|
@@ -5930,18 +5952,36 @@ fn dbf_names(fields: &[Field]) -> Vec<String> { | |
| fields.iter().map(|field| names.assign(&field.name)).collect() | ||
| } | ||
|
|
||
| /// Decimals of the `.dbf` field for Double field `k`: as many as fit dBase's 24 characters beside | ||
| /// the field's largest whole part, at most 15. | ||
| fn dbf_decimals(ds: &Dataset, k: usize) -> usize { | ||
| let max = ds | ||
| .features | ||
| .iter() | ||
| .filter_map(|r| r.attrs.get(k).and_then(Value::as_f64)) | ||
| .filter(|v| v.is_finite()) | ||
| .fold(0.0f64, |m, v| m.max(v.abs())); | ||
| // Digits before the point, a sign and the point itself; the rest are decimals. | ||
| let int_digits = if max >= 1.0 { (max.log10().floor() as usize).saturating_add(1) } else { 1 }; | ||
| 24usize.saturating_sub(int_digits + 2).min(15) | ||
| /// Decimal places for each field, using only rows the Shapefile writes. A Double gets as many | ||
| /// as fit in 24 characters beside its largest whole part, up to 15. `check` runs before each row. | ||
| /// The writer passes one that looks at Cancel, as do the notices of a file made in memory; those | ||
| /// counted once the file is in place pass one that doesn't. | ||
| fn shapefile_decimals(ds: &Dataset, check: fn() -> Result<()>) -> Result<Vec<usize>> { | ||
| let mut decimals = vec![0; ds.fields.len()]; | ||
| let mut maxima: Vec<_> = | ||
| ds.fields.iter().enumerate().filter(|(_, field)| field.ty == FieldType::Double).map(|(k, _)| (k, 0.0_f64)).collect(); | ||
| if maxima.is_empty() { | ||
| return Ok(decimals); | ||
| } | ||
| for row in &ds.features { | ||
| check()?; | ||
| if !shapefile_keeps(row.geometry.as_ref(), ds.geometry_type) { | ||
| continue; | ||
| } | ||
| for (k, max) in &mut maxima { | ||
| if let Some(v) = row.attrs.get(*k).and_then(Value::as_f64).filter(|v| v.is_finite()) { | ||
| *max = max.max(v.abs()); | ||
| } | ||
| } | ||
| } | ||
| for (k, max) in maxima { | ||
| // Digits before the point, a sign and the point itself; the rest are decimals. | ||
| let int_digits = if max >= 1.0 { (max.log10().floor() as usize).saturating_add(1) } else { 1 }; | ||
| if let Some(d) = decimals.get_mut(k) { | ||
| *d = 24usize.saturating_sub(int_digits + 2).min(15); | ||
| } | ||
| } | ||
| Ok(decimals) | ||
| } | ||
|
|
||
| /// The number a `.dbf` numeric field of type `ty` with `d` decimals holds for `v`: none for a | ||
|
|
@@ -6830,16 +6870,13 @@ pub fn gpx_notes(ds: &Dataset, name_field: Option<usize>, target: &str) -> Resul | |
| /// of the layer's kind with something drawable (a finite point, a line part of two finite points, | ||
| /// a polygon whose outer ring has three). | ||
| fn shapefile_keeps(g: Option<&Geometry>, gt: GeometryType) -> bool { | ||
| let finite = |c: &&Coord| c.x.is_finite() && c.y.is_finite(); | ||
| let finite = |c: &Coord| c.is_finite(); | ||
| match (g, gt) { | ||
| (Some(g @ (Geometry::Point(_) | Geometry::MultiPoint(_))), GeometryType::Point) => { | ||
| let mut any = false; | ||
| g.for_each_coord(|c| any |= finite(&&c)); | ||
| any | ||
| } | ||
| (Some(Geometry::Line(parts)), GeometryType::Polyline) => parts.iter().any(|p| p.iter().filter(finite).count() >= 2), | ||
| (Some(Geometry::Point(c)), GeometryType::Point) => finite(c), | ||
| (Some(Geometry::MultiPoint(cs)), GeometryType::Point) => cs.iter().any(finite), | ||
| (Some(Geometry::Line(parts)), GeometryType::Polyline) => parts.iter().any(|p| p.iter().filter(|c| finite(c)).nth(1).is_some()), | ||
| (Some(Geometry::Polygon(polys)), GeometryType::Polygon) => { | ||
| polys.iter().any(|p| p.first().is_some_and(|r| r.iter().filter(finite).count() >= 3)) | ||
| polys.iter().any(|p| p.first().is_some_and(|r| r.iter().filter(|c| finite(c)).nth(2).is_some())) | ||
| } | ||
| _ => false, | ||
| } | ||
|
|
@@ -6984,12 +7021,12 @@ struct Spec { | |
|
|
||
| /// The column field `k` of `ds` is written to as a new file has it: numbers in 18 digits | ||
| /// (integers) or 24 characters with as many decimals as fit, text as wide as its longest value. | ||
| fn new_column(ds: &Dataset, k: usize) -> Spec { | ||
| fn new_column(ds: &Dataset, k: usize, decimals: usize) -> Spec { | ||
| let Some(f) = ds.fields.get(k) else { return Spec { ty: b'C', len: 1, decimals: 0 } }; | ||
| match f.ty { | ||
| // 18 digits: GDAL reads a wider field as a real number. | ||
| FieldType::Integer => Spec { ty: b'N', len: 18, decimals: 0 }, | ||
| FieldType::Double => Spec { ty: b'N', len: 24, decimals: u8::try_from(dbf_decimals(ds, k)).unwrap_or(15) }, | ||
| FieldType::Double => Spec { ty: b'N', len: 24, decimals: u8::try_from(decimals).unwrap_or(15) }, | ||
| FieldType::Boolean => Spec { ty: b'L', len: 1, decimals: 0 }, | ||
| FieldType::Date => Spec { ty: b'D', len: 8, decimals: 0 }, | ||
| // A `.dbf` has no date-time field that other programs read, so they're ISO text. | ||
|
|
@@ -7011,11 +7048,10 @@ impl std::fmt::Display for Spec { | |
|
|
||
| /// The column field `k` (written as `name`) is written to over a file whose `.dbf` `style` | ||
| /// describes: the file's column of that name where the field's kind and every value still fit | ||
| /// it, so the file keeps its widths and decimals; otherwise a new one ([`new_column`]), at least | ||
| /// it, so the file keeps its widths and decimals; otherwise `new` ([`new_column`]'s), at least | ||
| /// as wide as the file's, and, when a column of that name changes kind or can't | ||
| /// hold the values, what changed (`'ACRES' N(10,2) to N(24,9)`). | ||
| fn kept_column(ds: &Dataset, k: usize, name: &str, style: &DbfStyle) -> (Spec, Option<String>) { | ||
| let new = new_column(ds, k); | ||
| fn kept_column(ds: &Dataset, k: usize, name: &str, style: &DbfStyle, new: Spec) -> (Spec, Option<String>) { | ||
| let (Some(field), Some(was)) = (ds.fields.get(k), style.columns.iter().find(|c| c.name == name.as_bytes())) else { | ||
| return (new, None); | ||
| }; | ||
|
|
@@ -7088,14 +7124,16 @@ fn shapefile_parts_within( | |
| // couldn't hold their values changed. | ||
| let mut specs = Vec::with_capacity(ds.fields.len()); | ||
| let mut widened = Vec::new(); | ||
| let decimals = shapefile_decimals(ds, crate::progress::check)?; | ||
| for (k, n) in names.iter().enumerate() { | ||
| let new = new_column(ds, k, decimals.get(k).copied().unwrap_or(0)); | ||
| let spec = match style { | ||
| Some(style) => { | ||
| let (spec, changed) = kept_column(ds, k, n, style); | ||
| let (spec, changed) = kept_column(ds, k, n, style, new); | ||
| widened.extend(changed); | ||
| spec | ||
| } | ||
| None => new_column(ds, k), | ||
| None => new, | ||
| }; | ||
| table = match spec.ty { | ||
| // A float column is written as a numeric one (both hold the number as text) and | ||
|
|
@@ -7656,7 +7694,7 @@ mod tests { | |
| ldid: 0, | ||
| columns: vec![crate::dbf::Column { name: b"NOTE".to_vec(), ty: b'C', len: 255, decimals: 0 }], | ||
| }; | ||
| let (spec, changed) = kept_column(&ds, 0, "NOTE", &style); | ||
| let (spec, changed) = kept_column(&ds, 0, "NOTE", &style, new_column(&ds, 0, 0)); | ||
| assert_eq!(spec.len, 254); | ||
| assert_eq!(changed.as_deref(), Some("'NOTE' C(255) to C(254)")); | ||
| } | ||
|
|
@@ -11381,6 +11419,33 @@ mod tests { | |
| assert!(zip_shapefile_parts("RIOS_SIMPLES.shp", shp, no_dbf).unwrap_err().contains(".dbf")); | ||
| } | ||
|
|
||
| /// A large value in an omitted row must not force zero decimal places for a retained Double. | ||
| #[test] | ||
| fn an_unplaced_feature_cannot_change_the_dbf_precision() { | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This test covers the download route ( Category: quality
Member
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. The file route is covered end to end by the engine's |
||
| use crate::loss::LossCode::DroppedGeometry; | ||
| for (held_in, point, omitted, value, losses) in [ | ||
| (Crs::LonLat, Coord::new(1.0, 2.0), None, 0.0, vec![]), | ||
| ( | ||
| Crs::Epsg(32631), | ||
| Coord::new(451_000.0, 5_411_000.0), | ||
| Some(Geometry::Point(Coord::new(1e9, 5_411_500.0))), | ||
| 0.125, | ||
| vec![Some(DroppedGeometry)], | ||
| ), | ||
| ] { | ||
| let mut ds = Dataset::new("cells", GeometryType::Point, vec![Field::new("value", FieldType::Double)]); | ||
| ds.held_in = held_in; | ||
| ds.push(Some(Geometry::Point(point)), vec![Value::Float(value)]); | ||
| ds.push(omitted, vec![Value::Float(1e300)]); | ||
| let (bytes, left_out, notes, _) = write_bytes_noted(&ds, "zip", Crs::LonLat, "cells.zip").unwrap(); | ||
| assert_eq!(left_out, 1); | ||
| let (back, _) = read_bytes("cells.zip", &bytes).unwrap(); | ||
| assert_eq!(back.fields[0].ty, FieldType::Double); | ||
| assert_eq!(back.value(0, 0), &Value::Float(value)); | ||
| assert_eq!(notes.iter().map(|note| note.loss).collect::<Vec<_>>(), losses); | ||
| } | ||
| } | ||
|
|
||
| /// Typed datasets can retain incompatible cells or fractional values from dynamic sources. | ||
| #[test] | ||
| fn shapefile_notes_cover_incompatible_and_rounded_cells() { | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -475,24 +475,30 @@ fn a_date_is_its_midnight_and_equal_to_a_zoneless_midnight() { | |
| /// A literal in a clause: a full date or date-time (compares as a moment) or partial text. | ||
| #[derive(Clone, Debug)] | ||
| enum Lit { | ||
| Moment(Spec), | ||
| Moment(Spec, &'static str), | ||
| Text(&'static str), | ||
| } | ||
|
|
||
| const EPOCH: Spec = Spec { y: 1970, m: 1, d: 1, clock: None }; | ||
| // Date comparison accepts padding around a full date, so the oracle uses the day. | ||
| const PADDED_EPOCH: Lit = Lit::Moment(EPOCH, " "); | ||
|
|
||
| /// A where-clause literal: a date, a date-time, or text that isn't a full date. | ||
| fn lit() -> impl Strategy<Value = Lit> { | ||
| prop_oneof![ | ||
| 4 => valid_spec().prop_map(Lit::Moment), | ||
| 1 => prop::sample::select(vec!["2026", "2026-03", "1969", "1969-12", "0001", "9999", "2000-02", "1970-01-01 "]) | ||
| .prop_map(Lit::Text), | ||
| 4 => valid_spec().prop_map(|s| Lit::Moment(s, "")), | ||
| 1 => prop::sample::select(vec![ | ||
| Lit::Text("2026"), Lit::Text("2026-03"), Lit::Text("1969"), Lit::Text("1969-12"), | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. The Category: quality
Member
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. rustfmt leaves a macro's items as they are: |
||
| Lit::Text("0001"), Lit::Text("9999"), Lit::Text("2000-02"), PADDED_EPOCH, | ||
| ]), | ||
| ] | ||
| } | ||
|
|
||
| impl Lit { | ||
| /// The literal as it is written in a clause, quoted. | ||
| fn sql(&self) -> String { | ||
| match self { | ||
| Lit::Moment(s) => format!("'{}'", s.text()), | ||
| Lit::Moment(s, suffix) => format!("'{}{suffix}'", s.text()), | ||
| Lit::Text(t) => format!("'{t}'"), | ||
| } | ||
| } | ||
|
|
@@ -519,7 +525,7 @@ fn cell(spec: &Spec, ty: FieldType) -> Cell { | |
| fn compare(c: &Cell, op: &str, l: &Lit) -> Option<bool> { | ||
| let (us, shown) = c.shown.as_ref()?; | ||
| let ord = match l { | ||
| Lit::Moment(s) => us.cmp(&s.expected()?.0), | ||
| Lit::Moment(s, _) => us.cmp(&s.expected()?.0), | ||
| // Text that isn't a full date compares as text with the field's ISO text, ignoring case. | ||
| Lit::Text(t) => shown.to_lowercase().cmp(&t.to_lowercase()), | ||
| }; | ||
|
|
@@ -542,6 +548,15 @@ fn dataset(rows: &[(Cell, Cell)]) -> Dataset { | |
| ds | ||
| } | ||
|
|
||
| #[test] | ||
| fn a_padded_date_literal_in_an_in_list_matches_its_day() { | ||
| let rows = [(cell(&EPOCH, FieldType::Date), cell(&EPOCH, FieldType::DateTime))]; | ||
| let ds = dataset(&rows); | ||
| let clause = format!("d IN ({}, '0001-01-01')", PADDED_EPOCH.sql()); | ||
| assert_eq!(query::select(&clause, &ds), Ok(vec![0])); | ||
| assert_eq!(compare(&rows[0].0, "=", &PADDED_EPOCH), Some(true), "the oracle also matches the padded date"); | ||
| } | ||
|
|
||
| #[test] | ||
| fn where_clauses_on_dates_agree_with_the_oracle() { | ||
| let rows = prop::collection::vec((spec(), spec()), 1..6); | ||
|
|
||
Uh oh!
There was an error while loading. Please reload this page.