From 4093d9707efadc75910b515cdcbb69fcfedc9e64 Mon Sep 17 00:00:00 2001 From: mavrick Date: Thu, 26 Nov 2026 13:45:17 -0600 Subject: [PATCH 1/6] fix(engine): yes/no text that isn't yes or no is said or refused, not read as no (#2371) Value::parse read any text other than true/yes/1/y as false in a yes/no field. It now reads false/f/no/n/0 as false, true/t as true, and other text as null, which Paste, Calculate Field and Update already count as values their field can't hold. edit.setValue refuses it, as it refuses dates. Template and subtype defaults, domain codes and contingent combinations a field can't hold as given (2.7 in a whole-number field, maybe in a yes/no one) are refused when set, not cut silently. A subtype default saved before that check is left out of a new feature and said. Update says the fractions it cuts and the whole numbers past 2^53 it rounds. --- crates/analysis/src/tools.rs | 109 +++++++++++++++++++++++++++++--- crates/data/src/value.rs | 21 +++++- crates/engine/src/cmd/design.rs | 65 +++++++++++-------- crates/engine/src/cmd/edit.rs | 47 ++++++++++++-- crates/engine/src/tests.rs | 109 ++++++++++++++++++++++++++++++++ crates/ui-egui/src/table.rs | 2 +- 6 files changed, 308 insertions(+), 45 deletions(-) diff --git a/crates/analysis/src/tools.rs b/crates/analysis/src/tools.rs index 185dc12d63..9f8c555f2d 100644 --- a/crates/analysis/src/tools.rs +++ b/crates/analysis/src/tools.rs @@ -2838,7 +2838,8 @@ fn symmetrical_difference(inp: &dyn Inputs, p: &Json) -> Result Value { match (v, ty) { (Value::Int(_), FieldType::Integer) @@ -2859,6 +2860,9 @@ fn converted(v: &Value, ty: FieldType) -> Value { (Value::Float(_), FieldType::Integer) => Value::Null, (Value::Float(f), FieldType::Text) => Value::Text(f.to_string()), (Value::Bool(b), FieldType::Integer) => Value::Int(i64::from(*b)), + // A whole number is yes when it isn't 0, as a shapefile writes it. + (Value::Int(i), FieldType::Boolean) => Value::Bool(*i != 0), + (Value::Float(f), FieldType::Boolean) if f.fract() == 0.0 => Value::Bool(*f != 0.0), (Value::Bool(b), FieldType::Double) => Value::Float(if *b { 1.0 } else { 0.0 }), // Text that reads as an integer is one; text that reads as another number goes as that // float would, so one out of range (or not a number) is empty, not clamped. @@ -2922,9 +2926,9 @@ fn update_on(inp: &dyn Inputs, p: &Json, threads: Option) -> Result) -> Result` text asks for null: no loss. - *n += usize::from(c.is_null() && !v.asks_null()); - *days += usize::from(matches!(v, Value::DateTime(t) if f.ty == FieldType::Date && !t.is_date())); + unfit.add(v, &c, f.ty); c }) .collect(); @@ -2951,7 +2953,7 @@ fn update_on(inp: &dyn Inputs, p: &Json, threads: Option) -> Result = Vec::new(); messages.extend(left_out.notes("Update", &up.name)); let features = |n: usize| if n == 1 { "1 update feature".to_string() } else { format!("{n} update features") }; - for (f, (n, days)) in ds.fields.iter().zip(unfit) { + for (f, Unfit { nulls: n, days, fractions, rounded }) in ds.fields.iter().zip(unfit) { if n > 0 { losses.push(rustgis_data::loss::LossMessage { code: rustgis_data::loss::LossCode::DroppedValue, @@ -2965,10 +2967,59 @@ fn update_on(inp: &dyn Inputs, p: &Json, threads: Option) -> Result 0 { + let their = if fractions == 1 { "its" } else { "their" }; + losses.push(rustgis_data::loss::LossMessage { + code: rustgis_data::loss::LossCode::ChangedTruncated, + text: format!("Update: '{}' holds whole numbers, so {} lost {their} fraction", f.name, features(fractions)), + }); + } + if rounded > 0 { + losses.push(rustgis_data::loss::LossMessage { + code: rustgis_data::loss::LossCode::ChangedRounded, + text: format!("Update: '{}' holds decimals, so whole numbers past 2^53 in {} were rounded", f.name, features(rounded)), + }); + } } Ok(ToolResult { losses, output: Output::Layer(out), messages }) } +/// What [`converted`] lost of one input field's update values, counted for one notice per kind. +#[derive(Clone, Copy, Debug, Default)] +struct Unfit { + /// Values its type couldn't hold, written as null. + nulls: usize, + /// Date-times a date field kept only the day of. + days: usize, + /// Numbers with a fraction a whole-number field cut. + fractions: usize, + /// Whole numbers past 2^53 a decimal field rounded. + rounded: usize, +} + +impl Unfit { + /// Counts what converting `v` to `c` in a `ty` field lost. + fn add(&mut self, v: &Value, c: &Value, ty: FieldType) { + // Empty or `` text asks for null: no loss. + self.nulls += usize::from(c.is_null() && !v.asks_null()); + self.days += usize::from(matches!(v, Value::DateTime(t) if ty == FieldType::Date && !t.is_date())); + let decimal = match v { + Value::Float(f) => Some(*f), + Value::Text(t) if t.trim().parse::().is_err() => t.trim().parse::().ok(), + _ => None, + }; + self.fractions += usize::from(matches!(c, Value::Int(_)) && decimal.is_some_and(|f| f.fract() != 0.0)); + let whole = match v { + Value::Int(i) => Some(*i), + Value::Text(t) => t.trim().parse::().ok(), + _ => None, + }; + // i128 holds both exactly: a whole number past 2^53 its decimal doesn't. + self.rounded += + usize::from(ty == FieldType::Double && matches!(c, Value::Float(f) if whole.is_some_and(|i| *f as i128 != i128::from(i)))); + } +} + /// The most split areas (split polygons, or values of the split field) Split takes: more is an /// error before anything is clipped, not thousands of layers. Areas that come out empty count too. const MAX_SPLIT_AREAS: usize = 1000; @@ -14543,6 +14594,41 @@ mod tests { ); } + #[test] + fn update_says_the_fractions_it_cuts_the_numbers_it_rounds_and_the_words_that_arent_yes_or_no() { + let fields = vec![Field::new("n", FieldType::Integer), Field::new("x", FieldType::Double), Field::new("b", FieldType::Boolean)]; + let mut parcels = Dataset::new("parcels", GeometryType::Polygon, fields); + parcels.push(Some(sq(0.0, 0.0, 1.0)), vec![Value::Null, Value::Null, Value::Null]); + let fields = vec![Field::new("n", FieldType::Double), Field::new("x", FieldType::Integer), Field::new("b", FieldType::Text)]; + let mut zones = Dataset::new("zones", GeometryType::Polygon, fields); + let m = |zones: &Dataset| Map(HashMap::from([("parcels".to_string(), parcels.clone()), ("zones".to_string(), zones.clone())])); + let run = |zones: &Dataset| crate::run("update", &m(zones), &serde_json::json!({"input": "parcels", "update": "zones"})).unwrap(); + // Whole numbers, numbers a decimal holds, and yes/no words lose nothing. + zones.push(Some(sq(5.0, 0.0, 1.0)), vec![Value::Float(2.0), Value::Int(1 << 53), Value::Text(" No ".into())]); + assert_eq!(said(&run(&zones))[1..], [] as [&str; 0]); + zones.push(Some(sq(7.0, 0.0, 1.0)), vec![Value::Float(-2.7), Value::Int((1 << 53) + 1), Value::Text("maybe".into())]); + let lossy = [ + "ChangedTruncated: Update: 'n' holds whole numbers, so 1 update feature lost its fraction", + "ChangedRounded: Update: 'x' holds decimals, so whole numbers past 2^53 in 1 update feature were rounded", + "DroppedValue: Update: 'b' is null in 1 update feature, whose value isn't a Boolean value", + ]; + let res = run(&zones); + assert_eq!(said(&res)[1..], lossy); + let out = layer(res); + let last = out.features.last().unwrap(); + assert_eq!(last.attrs, [Value::Int(-2), Value::Float(9_007_199_254_740_992.0), Value::Null]); + // Written as text, the same. + let fields = vec![Field::new("n", FieldType::Text), Field::new("x", FieldType::Text), Field::new("b", FieldType::Text)]; + let mut zones = Dataset::new("zones", GeometryType::Polygon, fields); + zones.push(Some(sq(5.0, 0.0, 1.0)), vec![Value::Text("2".into()), Value::Text("1e3".into()), Value::Text("yes".into())]); + assert_eq!(said(&run(&zones))[1..], [] as [&str; 0]); + zones.push( + Some(sq(7.0, 0.0, 1.0)), + vec![Value::Text("-2.7".into()), Value::Text("9007199254740993".into()), Value::Text("maybe".into())], + ); + assert_eq!(said(&run(&zones))[1..], lossy); + } + #[test] fn converted_keeps_fitting_values_and_converts_the_rest() { let third = 1.0 / 3.0; @@ -14570,6 +14656,11 @@ mod tests { } assert_eq!(converted(&Value::Bool(true), FieldType::Double), Value::Float(1.0)); assert_eq!(converted(&Value::Int(5), FieldType::Text), Value::Text("5".into())); + // A whole number is yes when it isn't 0; a fraction or a word that isn't yes or no is neither. + assert_eq!(converted(&Value::Int(2), FieldType::Boolean), Value::Bool(true)); + assert_eq!(converted(&Value::Float(0.0), FieldType::Boolean), Value::Bool(false)); + assert_eq!(converted(&Value::Float(0.5), FieldType::Boolean), Value::Null); + assert_eq!(converted(&Value::Text("maybe".into()), FieldType::Boolean), Value::Null); assert_eq!(converted(&Value::Text("x".into()), FieldType::Double), Value::Null); assert_eq!(converted(&Value::Null, FieldType::Text), Value::Null); // A date-time into a date field is its day; a date into a date-time field, its midnight. diff --git a/crates/data/src/value.rs b/crates/data/src/value.rs index 5b904998c8..f1c00f0ec6 100644 --- a/crates/data/src/value.rs +++ b/crates/data/src/value.rs @@ -229,9 +229,20 @@ impl Value { } } + /// The yes/no value text says, ignoring case and spaces around it: `true`, `t`, `yes`, `y` and + /// `1` are true; `false`, `f`, `no`, `n` and `0` are false; other text is neither. + pub fn yes_no(text: &str) -> Option { + match text.trim().to_ascii_lowercase().as_str() { + "true" | "t" | "yes" | "y" | "1" => Some(true), + "false" | "f" | "no" | "n" | "0" => Some(false), + _ => None, + } + } + /// Parses user text into a value of `ty` (empty → Null). Text a number field can't hold, /// including a non-finite Double (`NaN`, `inf`), is Null. Dates are ISO 8601: `YYYY-MM-DD` /// for a date; that, a time and an optional zone for a date-time. Text that isn't one is Null. + /// A yes/no field takes the words of [`yes_no`](Value::yes_no); other text is Null, not false. pub fn parse(text: &str, ty: FieldType) -> Value { let t = text.trim(); if t.is_empty() || t.eq_ignore_ascii_case("") { @@ -244,7 +255,7 @@ impl Value { .or_else(|| t.parse::().ok().filter(|f| f.is_finite()).map(|f| f as i64)) .map_or(Value::Null, Value::Int), FieldType::Double => t.parse::().ok().filter(|f| f.is_finite()).map_or(Value::Null, Value::Float), - FieldType::Boolean => Value::Bool(matches!(t.to_ascii_lowercase().as_str(), "true" | "yes" | "1" | "y")), + FieldType::Boolean => Value::yes_no(t).map_or(Value::Null, Value::Bool), FieldType::Text => Value::Text(t.to_string()), FieldType::Date => Date::parse(t).map(Value::Date).unwrap_or(Value::Null), FieldType::DateTime => DateTime::parse(t).map(Value::DateTime).unwrap_or(Value::Null), @@ -672,6 +683,14 @@ mod tests { assert!(matches!(Value::parse_source(text, FieldType::Integer), Value::Float(f) if !f.is_finite())); assert!(matches!(Value::parse_source(text, FieldType::Double), Value::Float(f) if !f.is_finite())); } + for (text, said) in [(" Yes ", Some(true)), ("T", Some(true)), ("1", Some(true)), ("n", Some(false)), ("FALSE", Some(false))] { + assert_eq!(Value::yes_no(text), said, "{text}"); + assert_eq!(Value::parse(text, FieldType::Boolean), Value::Bool(said.unwrap_or_default()), "{text}"); + } + for text in ["maybe", "2", "on", "yess"] { + assert_eq!(Value::yes_no(text), None, "{text}"); + assert_eq!(Value::parse(text, FieldType::Boolean), Value::Null, "{text} is neither, not no"); + } assert_eq!(Value::parse("2.5", FieldType::Double), Value::Float(2.5)); assert_eq!(Value::parse("2.5", FieldType::Integer), Value::Int(2)); assert_eq!(Value::parse("1e3", FieldType::Integer), Value::Int(1000)); diff --git a/crates/engine/src/cmd/design.rs b/crates/engine/src/cmd/design.rs index 13515b5621..7fddebbb39 100644 --- a/crates/engine/src/cmd/design.rs +++ b/crates/engine/src/cmd/design.rs @@ -195,7 +195,10 @@ pub(crate) fn apply_with>(s: &mut Session, id: u32, changes: zs.push((*r, z)); } let l = s.map_mut().layer_mut(id).ok_or("no such layer")?; - // New features: subtype defaults fill empty fields; elevation goes in `z`. + // New features: subtype defaults fill empty fields; elevation goes in `z`. A default its field + // can't hold as given (one saved before it was checked, or for a field retyped since) is left + // out, and said, by field, once the edit is kept; one that isn't finite refuses the edit. + let mut unheld: Vec<(String, usize)> = Vec::new(); if let Some(st) = l.design.subtypes.clone() && let Some(sfi) = l.dataset.field_index(&st.field) { @@ -208,10 +211,17 @@ pub(crate) fn apply_with>(s: &mut Session, id: u32, changes: && let Some(cell) = l.dataset.features.get_mut(*r).and_then(|f| f.attrs.get_mut(fi)) && cell.is_null() { + // One that isn't finite refuses the edit, as it always has: no cell takes it. if super::edit::non_finite_input(v, ty) { return Err(format!("field '{field}' requires a finite number")); } - *cell = super::edit::coerce(v.clone(), ty); + match super::edit::held_default(field, v, ty) { + Ok(held) => *cell = held, + Err(_) => match unheld.iter_mut().find(|(f, _)| f == field) { + Some((_, n)) => *n += 1, + None => unheld.push((field.clone(), 1)), + }, + } } } } @@ -323,6 +333,13 @@ pub(crate) fn apply_with>(s: &mut Session, id: u32, changes: s.notify_loss(code, notice); } } + for (field, n) in unheld { + let features = if n == 1 { "1 new feature".to_string() } else { format!("{n} new features") }; + s.notify_loss( + rustgis_data::loss::LossCode::DroppedValue, + format!("{layer}: field '{field}' left empty in {features}, as it can't hold its subtype default as given").into(), + ); + } if !unread.is_empty() { s.notify( format!( @@ -2219,15 +2236,16 @@ fn domain(s: &mut Session, p: &Json) -> CmdResult { return Ok(Json::Null); } let kind = if let Some(codes) = p.get("coded").and_then(Json::as_array) { - let pairs: Vec<(Value, String)> = codes - .iter() - .take(10_000) - .filter_map(|c| { - let code = super::edit::coerce(Value::from_json(c.get(0)?), ty); - let desc = c.get(1).and_then(Json::as_str).map(String::from).unwrap_or_else(|| code.to_string()); - (!code.is_null()).then_some((code, desc)) - }) - .collect(); + // A code its field can't hold as given is refused, not cut to another or left out. + let mut pairs: Vec<(Value, String)> = Vec::new(); + for c in codes.iter().take(10_000) { + let Some(given) = c.get(0) else { continue }; + let code = super::edit::held_default(&fname, &Value::from_json(given), ty)?; + let desc = c.get(1).and_then(Json::as_str).map(String::from).unwrap_or_else(|| code.to_string()); + if !code.is_null() { + pairs.push((code, desc)); + } + } if pairs.is_empty() { return Err("coded is a list of [code, description] pairs".into()); } @@ -2275,16 +2293,14 @@ fn subtypes(s: &mut Session, p: &Json) -> CmdResult { for v in list { let code = v.get("code").and_then(Json::as_i64).ok_or("each subtype has an integer code")?; let name = super::within("name", "a subtype's name", v.get("name").and_then(Json::as_str).ok_or("each subtype has a name")?, 200)?; - let defaults: Vec<(String, Value)> = v + let mut defaults: Vec<(String, Value)> = v .get("defaults") .and_then(Json::as_object) .map(|o| o.iter().map(|(k, v)| (k.clone(), Value::from_json(v))).collect()) .unwrap_or_default(); - for (field, value) in &defaults { - if let Some(ty) = l.dataset.field_index(field).and_then(|i| l.dataset.fields.get(i)).map(|f| f.ty) - && super::edit::non_finite_input(value, ty) - { - return Err(format!("field '{field}' requires a finite number")); + for (field, value) in &mut defaults { + if let Some(ty) = l.dataset.field_index(field).and_then(|i| l.dataset.fields.get(i)).map(|f| f.ty) { + *value = super::edit::held_default(field, value, ty)?; } } if subs.iter().any(|x: &Subtype| x.code == code) { @@ -2418,7 +2434,8 @@ fn contingent(s: &mut Session, p: &Json) -> CmdResult { .take(100_000) .map(|c| { let vals = c.as_array().filter(|a| a.len() == fields.len()).ok_or("each combination has one value per field")?; - Ok(vals.iter().zip(&fields).map(|(v, (_, ty))| super::edit::coerce(Value::from_json(v), *ty)).collect()) + // A value its field can't hold as given is refused, not cut to another. + vals.iter().zip(&fields).map(|(v, (name, ty))| super::edit::held_default(name, &Value::from_json(v), *ty)).collect() }) .collect::>()?; let l = s.map_mut().layer_mut(id).ok_or("no such layer")?; @@ -2572,7 +2589,7 @@ fn related(s: &mut Session, p: &Json) -> CmdResult { Ok(json!({"related": total, "layers": names})) } -/// Validates defaults before replacing a template; a refused numeric value leaves it intact. +/// Validates defaults before replacing a template; a refused value leaves it intact. fn template(s: &mut Session, p: &Json) -> CmdResult { let id = s.layer_id(p)?; let name = ps(p, "name").map(str::trim).filter(|n| !n.is_empty()).ok_or("name is required")?.to_string(); @@ -2587,15 +2604,7 @@ fn template(s: &mut Session, p: &Json) -> CmdResult { for (k, v) in o { let fi = l.dataset.field_index(k).ok_or_else(|| format!("no field named '{k}'"))?; let ty = l.dataset.fields.get(fi).map(|f| f.ty).unwrap_or(FieldType::Text); - let value = Value::from_json(v); - if super::edit::non_finite_input(&value, ty) { - return Err(format!("field '{k}' requires a finite number")); - } - let coerced = super::edit::coerce(value.clone(), ty); - // A default a date field can't hold is refused, as edit.addFeature refuses the value. - if ty.is_temporal() && coerced.is_null() && !value.asks_null() { - return Err(format!("field '{k}': '{value}' isn't a {} value", ty.label())); - } + let coerced = super::edit::held_default(k, &Value::from_json(v), ty)?; defaults.push((l.dataset.fields.get(fi).map(|f| f.name.clone()).unwrap_or_default(), coerced)); } } diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index 825b1d9afa..0d790eb72f 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -780,6 +780,34 @@ pub(crate) fn non_finite_input(value: &Value, ty: FieldType) -> bool { } } +/// A value set once for a field and used again (a template's or subtype's default, a domain's +/// code, a contingent combination) as a `ty` field holds it, refused when holding it would lose +/// any of it: one that isn't finite or isn't a value of the field's type, or that the field would +/// cut, clamp or round. It is checked when it is set, as no later edit could say what was lost. +pub(crate) fn held_default(field: &str, value: &Value, ty: FieldType) -> Result { + if non_finite_input(value, ty) { + return Err(format!("field '{field}' requires a finite number")); + } + let coerced = coerce(value.clone(), ty); + if coerced.is_null() && !value.asks_null() { + return Err(format!("field '{field}': '{value}' isn't a {} value", ty.label())); + } + let whole = match value { + Value::Int(i) => Some(*i), + Value::Text(t) => t.trim().parse::().ok(), + _ => None, + }; + // i128 holds both exactly: a whole number past 2^53 its decimal doesn't. + let rounded = ty == FieldType::Double && matches!(coerced, Value::Float(f) if whole.is_some_and(|i| f as i128 != i128::from(i))); + if numeric_loss(value, &coerced, ty).is_some() + || rounded + || matches!(value, Value::DateTime(t) if ty == FieldType::Date && !t.is_date()) + { + return Err(format!("field '{field}': a {} field can't hold '{value}' as given", ty.label())); + } + Ok(coerced) +} + /// Whether a number, or a number written as text, is an infinity (not NaN). fn infinite(value: &Value) -> bool { match value { @@ -818,6 +846,9 @@ fn convert(v: Value, ty: FieldType) -> (Value, Cut, Option) { _ => (Value::parse(&t, ty), Cut::None, None), }, }, + // A whole number is yes when it isn't 0, as a shapefile writes it. + (Value::Int(i), FieldType::Boolean) => (Value::Bool(i != 0), Cut::None, None), + (Value::Float(f), FieldType::Boolean) if f.fract() == 0.0 => (Value::Bool(f != 0.0), Cut::None, None), // Uncounted coercion retains source numbers until output can explain any loss. (Value::Text(t), _) => (Value::parse_source(&t, ty), Cut::None, None), (other, _) => (Value::parse(&other.to_string(), ty), Cut::None, None), @@ -964,8 +995,8 @@ fn set_value(s: &mut Session, p: &Json) -> CmdResult { Ok(Json::Null) } -/// `raw` (an `edit.setValue` value) as a value of a `ty` field. A number that isn't finite, and a -/// value a date field can't hold, are refused. +/// `raw` (an `edit.setValue` value) as a value of a `ty` field. A number that isn't finite, a +/// value a date field can't hold, and text that isn't a yes/no word in a yes/no field, are refused. fn typed(raw: Json, ty: FieldType) -> Result { Ok(match raw { // A number that isn't finite (NaN, infinity) is no value a number field holds, nor one a @@ -973,16 +1004,20 @@ fn typed(raw: Json, ty: FieldType) -> Result { Json::String(t) if ty.is_numeric() && t.trim().parse::().is_ok_and(|f| !f.is_finite()) => { return Err(format!("'{}' isn't a finite number, which a {} field holds", t.trim(), ty.label())); } - // Text a date field can't hold (`soon`) is refused, not stored as null. + // Text a date or yes/no field can't hold (`soon`, `maybe`) is refused, not stored as null. Json::String(t) => match Value::parse(&t, ty) { - Value::Null if ty.is_temporal() && !t.trim().is_empty() && !t.trim().eq_ignore_ascii_case("") => { + Value::Null + if (ty.is_temporal() || ty == FieldType::Boolean) && !t.trim().is_empty() && !t.trim().eq_ignore_ascii_case("") => + { return Err(format!("'{}' isn't a {} value", t.trim(), ty.label())); } v => v, }, - // So is any other value a date field can't hold (`20260305`). + // So is any other value a date or yes/no field can't hold (`20260305`, `0.5`). other => match coerce(Value::from_json(&other), ty) { - Value::Null if ty.is_temporal() && !other.is_null() => return Err(format!("'{other}' isn't a {} value", ty.label())), + Value::Null if (ty.is_temporal() || ty == FieldType::Boolean) && !other.is_null() => { + return Err(format!("'{other}' isn't a {} value", ty.label())); + } v => v, }, }) diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index a0e3bd7fe2..197393b053 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -1521,6 +1521,115 @@ fn set_value_says_what_a_whole_number_field_took_with_its_code() { } } +#[test] +fn yes_no_text_that_isnt_yes_or_no_is_refused_or_said_never_read_as_no() { + use rustgis_data::{Value as V, loss::LossCode}; + let mut s = world(); + s.run("edit.addField", &json!({"layer": "Cities", "name": "flag", "type": "boolean"})).unwrap(); + let cell = |s: &Session, row: usize| { + let ds = &s.map().layer_by_name("Cities").unwrap().dataset; + ds.value(row, ds.field_index("flag").unwrap()).clone() + }; + // The yes/no words go in, and a whole number is yes when it isn't 0; anything else is refused. + for (value, held) in [(json!(" No "), false), (json!("t"), true), (json!(2), true), (json!(0), false)] { + s.run("edit.setValue", &json!({"layer": "Cities", "row": 0, "field": "flag", "value": value})).unwrap(); + assert_eq!(cell(&s, 0), V::Bool(held), "{value}"); + } + let err = s.run("edit.setValue", &json!({"layer": "Cities", "row": 0, "field": "flag", "value": "maybe"})).unwrap_err(); + assert_eq!(err, "'maybe' isn't a Boolean value"); + let err = s.run("edit.setValue", &json!({"layer": "Cities", "row": 0, "field": "flag", "value": 0.5})).unwrap_err(); + assert_eq!(err, "'0.5' isn't a Boolean value"); + assert_eq!(cell(&s, 0), V::Bool(false), "a refused value leaves the cell as it was"); + // Calculate Field writes null for a result that isn't yes or no, and says so; clean results say nothing. + let mark = s.notice_mark(); + s.run("edit.calculateField", &json!({"layer": "Cities", "field": "flag", "expression": "'yes'"})).unwrap(); + assert!(s.notices_since(mark).iter().all(|n| !n.text.contains("Calculate Field")), "{:?}", s.notices_since(mark)); + let mark = s.notice_mark(); + s.run("edit.calculateField", &json!({"layer": "Cities", "field": "flag", "expression": "'maybe'"})).unwrap(); + let said: Vec<_> = s.notices_since(mark).iter().filter(|n| n.text.contains("'flag' is null in")).map(|n| n.loss()).collect(); + assert_eq!(said, [Some(LossCode::DroppedValue)], "{:?}", s.notices_since(mark)); + assert_eq!(cell(&s, 0), V::Null); + // Paste: the same. + let point = json!({"type": "Point", "coordinates": [0.0, 0.0]}); + let pasted = |flags: &[&str]| { + let features: Vec = flags.iter().map(|f| json!({"type": "Feature", "geometry": point, "properties": {"flag": f}})).collect(); + json!({"layer": "Cities", "text": json!({"type": "FeatureCollection", "features": features}).to_string()}) + }; + let mark = s.notice_mark(); + s.run("edit.paste", &pasted(&["yes", "N", ""])).unwrap(); + assert!(s.notices_since(mark).iter().all(|n| !n.text.contains("is null in")), "{:?}", s.notices_since(mark)); + s.run("edit.undo", &Value::Null).unwrap(); + let mark = s.notice_mark(); + s.run("edit.paste", &pasted(&["yes", "maybe", "later"])).unwrap(); + let said: Vec<_> = s.notices_since(mark).iter().filter(|n| n.text.contains("'flag' is null in 2 features")).map(|n| n.loss()).collect(); + assert_eq!(said, [Some(LossCode::DroppedValue)], "{:?}", s.notices_since(mark)); + s.run("edit.undo", &Value::Null).unwrap(); +} + +#[test] +fn a_default_its_field_cant_hold_as_given_is_refused_when_set() { + use rustgis_data::Value as V; + let mut s = world(); + s.run("edit.addField", &json!({"layer": "Cities", "name": "n", "type": "long"})).unwrap(); + s.run("edit.addField", &json!({"layer": "Cities", "name": "flag", "type": "boolean"})).unwrap(); + s.run("edit.addField", &json!({"layer": "Cities", "name": "x", "type": "double"})).unwrap(); + s.run("edit.addField", &json!({"layer": "Cities", "name": "kind", "type": "long"})).unwrap(); + for (field, value) in [("n", json!(2.7)), ("n", json!("seven")), ("n", json!(1e30)), ("flag", json!("maybe"))] { + let defaults = json!({field: value}); + let err = s.run("edit.template", &json!({"layer": "Cities", "name": "T", "defaults": defaults})).unwrap_err(); + assert!(err.starts_with(&format!("field '{field}': ")) && (err.contains("isn't a") || err.contains("as given")), "{value}: {err}"); + let subtypes = json!([{"code": 1, "name": "One", "defaults": defaults}]); + let err = s.run("data.subtypes", &json!({"layer": "Cities", "field": "kind", "subtypes": subtypes})).unwrap_err(); + assert!(err.starts_with(&format!("field '{field}': ")), "{value}: {err}"); + } + let err = s.run("edit.template", &json!({"layer": "Cities", "name": "T", "defaults": {"x": 9_007_199_254_740_993_i64}})).unwrap_err(); + assert_eq!(err, "field 'x': a Double field can't hold '9007199254740993' as given"); + let err = s.run("data.contingentValues", &json!({"layer": "Cities", "name": "C", "fields": ["n", "flag"], "combos": [[2.5, true]]})); + assert_eq!(err.unwrap_err(), "field 'n': a Long field can't hold '2.5' as given"); + let err = s.run("data.domain", &json!({"layer": "Cities", "field": "flag", "coded": [[true, "Yes"], ["maybe", "Maybe"]]})).unwrap_err(); + assert_eq!(err, "field 'flag': 'maybe' isn't a Boolean value"); + assert!(s.map().layer_by_name("Cities").unwrap().design.templates.is_empty(), "a refused template isn't added"); + // Defaults the fields hold as given are kept, and fill new features with nothing to say. + s.run("edit.template", &json!({"layer": "Cities", "name": "T", "defaults": {"n": 2.0, "flag": "yes"}})).unwrap(); + let mark = s.notice_mark(); + let point = json!({"type": "Point", "coordinates": [0.0, 0.0]}); + let row = s.run("edit.addFeature", &json!({"layer": "Cities", "geometry": point, "template": "T"})).unwrap()["row"].as_u64().unwrap(); + assert!(s.notices_since(mark).iter().all(|n| n.loss().is_none()), "{:?}", s.notices_since(mark)); + let ds = &s.map().layer_by_name("Cities").unwrap().dataset; + let row = row as usize; + assert_eq!((ds.value(row, ds.field_index("n").unwrap()), ds.value(row, ds.field_index("flag").unwrap())), (&V::Int(2), &V::Bool(true))); + s.run("edit.undo", &Value::Null).unwrap(); + // A subtype's defaults fill a new feature of its code. One saved before defaults were + // checked, that its field can't hold as given, is left out and said. + let subtypes = json!([{"code": 1, "name": "One", "defaults": {"n": "7", "flag": "no"}}]); + s.run("data.subtypes", &json!({"layer": "Cities", "field": "kind", "subtypes": subtypes, "symbolize": false})).unwrap(); + let new = |s: &mut Session| { + let mark = s.notice_mark(); + let row = s.run("edit.addFeature", &json!({"layer": "Cities", "geometry": point, "attributes": {"kind": 1}})).unwrap()["row"] + .as_u64() + .unwrap(); + let ds = &s.map().layer_by_name("Cities").unwrap().dataset; + let held = + (ds.value(row as usize, ds.field_index("n").unwrap()).clone(), ds.value(row as usize, ds.field_index("flag").unwrap()).clone()); + let said: Vec<_> = s.notices_since(mark).iter().filter(|n| n.loss().is_some()).map(|n| (n.text.clone(), n.loss())).collect(); + s.run("edit.undo", &Value::Null).unwrap(); + (held, said) + }; + assert_eq!(new(&mut s), ((V::Int(7), V::Bool(false)), vec![])); + let cities = s.map_mut().layers.iter_mut().find(|l| l.name == "Cities").unwrap(); + let defaults = &mut cities.design.subtypes.as_mut().unwrap().subtypes[0].defaults; + defaults.iter_mut().find(|(f, _)| f == "n").unwrap().1 = V::Float(2.7); + let (held, said) = new(&mut s); + assert_eq!(held, (V::Null, V::Bool(false))); + assert_eq!( + said, + [( + "Cities: field 'n' left empty in 1 new feature, as it can't hold its subtype default as given".to_string(), + Some(rustgis_data::loss::LossCode::DroppedValue) + )] + ); +} + /// A date field is added, edited as ISO text, compared in a where clause, calculated, offered to /// the time slider, and kept as dates through a project save; arithmetic on it is an error, and /// text that isn't a date is reported, not quietly stored as null. diff --git a/crates/ui-egui/src/table.rs b/crates/ui-egui/src/table.rs index d413721370..4154e44a96 100644 --- a/crates/ui-egui/src/table.rs +++ b/crates/ui-egui/src/table.rs @@ -976,7 +976,7 @@ fn fits(text: &str, ty: rustgis_engine::data::FieldType) -> bool { t.parse::().is_ok() || t.parse::().is_ok_and(|f| f.fract() == 0.0 && f >= i64::MIN as f64 && f < i64::MAX as f64) } T::Double => t.parse::().is_ok_and(f64::is_finite), - T::Boolean => matches!(t.to_ascii_lowercase().as_str(), "true" | "false" | "yes" | "no" | "1" | "0" | "y" | "n"), + T::Boolean => rustgis_engine::data::Value::yes_no(t).is_some(), // ISO 8601: `2026-03-05`; for a date-time, that and `14:30`, with or without a zone. T::Date => rustgis_engine::data::Date::parse(t).is_some(), T::DateTime => rustgis_engine::data::DateTime::parse(t).is_some(), From 59ddeccf8d366e56b8dda50c8316381e58fff969 Mon Sep 17 00:00:00 2001 From: mavrick Date: Thu, 26 Nov 2026 15:20:44 -0600 Subject: [PATCH 2/6] fix(engine): rounding in text forms, yes/no fractions and GeoPackage yes/no text are said A default or Update value rounded by a decimal field is caught when written as 9007199254740993.0 or past the 64-bit range, through one shared check (Value::rounds_as_double). A fraction into a yes/no field is refused or counted, not read through the six-decimal text it shows. The GeoPackage readers say text in a yes/no column that isn't yes or no. Subtype defaults left out are said in one notice. --- crates/analysis/src/tools.rs | 24 +++++++-------- crates/data/src/io.rs | 2 +- crates/data/src/source/gpkg.rs | 1 + crates/data/src/source/gpkg_mem.rs | 1 + crates/data/src/source/mod.rs | 26 ++++++++++++++-- crates/data/src/source/tests.rs | 48 ++++++++++++++++++++++++++++++ crates/data/src/value.rs | 12 ++++++++ crates/engine/src/cmd/design.rs | 24 +++++++++------ crates/engine/src/cmd/edit.rs | 11 ++----- crates/engine/src/tests.rs | 11 +++++-- 10 files changed, 125 insertions(+), 35 deletions(-) diff --git a/crates/analysis/src/tools.rs b/crates/analysis/src/tools.rs index 9f8c555f2d..43cfed14e4 100644 --- a/crates/analysis/src/tools.rs +++ b/crates/analysis/src/tools.rs @@ -2863,6 +2863,8 @@ fn converted(v: &Value, ty: FieldType) -> Value { // A whole number is yes when it isn't 0, as a shapefile writes it. (Value::Int(i), FieldType::Boolean) => Value::Bool(*i != 0), (Value::Float(f), FieldType::Boolean) if f.fract() == 0.0 => Value::Bool(*f != 0.0), + // A fraction is no yes/no value: null, not the text it's shown as (`0.0000001` shows `0`). + (Value::Float(_), FieldType::Boolean) => Value::Null, (Value::Bool(b), FieldType::Double) => Value::Float(if *b { 1.0 } else { 0.0 }), // Text that reads as an integer is one; text that reads as another number goes as that // float would, so one out of range (or not a number) is empty, not clamped. @@ -2977,7 +2979,11 @@ fn update_on(inp: &dyn Inputs, p: &Json, threads: Option) -> Result 0 { losses.push(rustgis_data::loss::LossMessage { code: rustgis_data::loss::LossCode::ChangedRounded, - text: format!("Update: '{}' holds decimals, so whole numbers past 2^53 in {} were rounded", f.name, features(rounded)), + text: format!( + "Update: '{}' holds decimals, so the numbers of {} were rounded to the digits it holds", + f.name, + features(rounded) + ), }); } } @@ -2993,7 +2999,7 @@ struct Unfit { days: usize, /// Numbers with a fraction a whole-number field cut. fractions: usize, - /// Whole numbers past 2^53 a decimal field rounded. + /// Numbers a decimal field rounded: whole numbers past 2^53, and text with more digits than it holds. rounded: usize, } @@ -3009,14 +3015,7 @@ impl Unfit { _ => None, }; self.fractions += usize::from(matches!(c, Value::Int(_)) && decimal.is_some_and(|f| f.fract() != 0.0)); - let whole = match v { - Value::Int(i) => Some(*i), - Value::Text(t) => t.trim().parse::().ok(), - _ => None, - }; - // i128 holds both exactly: a whole number past 2^53 its decimal doesn't. - self.rounded += - usize::from(ty == FieldType::Double && matches!(c, Value::Float(f) if whole.is_some_and(|i| *f as i128 != i128::from(i)))); + self.rounded += usize::from(ty == FieldType::Double && matches!(c, Value::Float(_)) && v.rounds_as_double()); } } @@ -14609,7 +14608,7 @@ mod tests { zones.push(Some(sq(7.0, 0.0, 1.0)), vec![Value::Float(-2.7), Value::Int((1 << 53) + 1), Value::Text("maybe".into())]); let lossy = [ "ChangedTruncated: Update: 'n' holds whole numbers, so 1 update feature lost its fraction", - "ChangedRounded: Update: 'x' holds decimals, so whole numbers past 2^53 in 1 update feature were rounded", + "ChangedRounded: Update: 'x' holds decimals, so the numbers of 1 update feature were rounded to the digits it holds", "DroppedValue: Update: 'b' is null in 1 update feature, whose value isn't a Boolean value", ]; let res = run(&zones); @@ -14624,7 +14623,7 @@ mod tests { assert_eq!(said(&run(&zones))[1..], [] as [&str; 0]); zones.push( Some(sq(7.0, 0.0, 1.0)), - vec![Value::Text("-2.7".into()), Value::Text("9007199254740993".into()), Value::Text("maybe".into())], + vec![Value::Text("-2.7".into()), Value::Text("9007199254740993.0".into()), Value::Text("maybe".into())], ); assert_eq!(said(&run(&zones))[1..], lossy); } @@ -14660,6 +14659,7 @@ mod tests { assert_eq!(converted(&Value::Int(2), FieldType::Boolean), Value::Bool(true)); assert_eq!(converted(&Value::Float(0.0), FieldType::Boolean), Value::Bool(false)); assert_eq!(converted(&Value::Float(0.5), FieldType::Boolean), Value::Null); + assert_eq!(converted(&Value::Float(1e-7), FieldType::Boolean), Value::Null, "not the 0 it shows as"); assert_eq!(converted(&Value::Text("maybe".into()), FieldType::Boolean), Value::Null); assert_eq!(converted(&Value::Text("x".into()), FieldType::Double), Value::Null); assert_eq!(converted(&Value::Null, FieldType::Text), Value::Null); diff --git a/crates/data/src/io.rs b/crates/data/src/io.rs index aca286b276..81a6101322 100644 --- a/crates/data/src/io.rs +++ b/crates/data/src/io.rs @@ -3391,7 +3391,7 @@ impl TextColumn { /// `0.10000000000000001` (0.1 to 17 digits) and `0.00000000023283064365386962890625` (2^-32 /// exactly) are; `12345678901234567891` and `0.12345678901234567891` aren't. No Double's exact /// value has more than 767 significant digits, so longer text isn't one, and isn't formatted. -fn double_holds(v: &str) -> bool { +pub fn double_holds(v: &str) -> bool { /// The digits of a number's mantissa without leading or trailing zeros. fn digits(s: &str) -> String { let mantissa = s.split(['e', 'E']).next().unwrap_or_default(); diff --git a/crates/data/src/source/gpkg.rs b/crates/data/src/source/gpkg.rs index 404f313fc8..e6d0fcc0f8 100644 --- a/crates/data/src/source/gpkg.rs +++ b/crates/data/src/source/gpkg.rs @@ -1509,6 +1509,7 @@ fn value(v: ValueRef<'_>, ty: FieldType, unread: &mut Vec, rounded: Optio (ValueRef::Real(f), FieldType::Integer) if f.fract() == 0.0 && f.abs() < 9e15 => Value::Int(f as i64), (ValueRef::Real(f), _) => Value::Float(f), (ValueRef::Text(t), FieldType::Text) => Value::Text(String::from_utf8_lossy(t).into_owned()), + (ValueRef::Text(t), FieldType::Boolean) => super::yes_no_text(&String::from_utf8_lossy(t), unread, k), (ValueRef::Text(t), ty) => Value::parse_source(&String::from_utf8_lossy(t), ty), (ValueRef::Blob(_), _) => Value::Null, } diff --git a/crates/data/src/source/gpkg_mem.rs b/crates/data/src/source/gpkg_mem.rs index bea415d8a0..f90c216e44 100644 --- a/crates/data/src/source/gpkg_mem.rs +++ b/crates/data/src/source/gpkg_mem.rs @@ -326,6 +326,7 @@ fn value(v: &Val, ty: FieldType, unread: &mut Vec, rounded: &mut Vec Value::Int(*f as i64), (Val::Real(f), _) => Value::Float(*f), (Val::Text(t), FieldType::Text) => Value::Text(t.clone()), + (Val::Text(t), FieldType::Boolean) => super::yes_no_text(t, unread, k), (Val::Text(t), ty) => Value::parse_source(t, ty), } } diff --git a/crates/data/src/source/mod.rs b/crates/data/src/source/mod.rs index b514c6543d..81e6ed83d5 100644 --- a/crates/data/src/source/mod.rs +++ b/crates/data/src/source/mod.rs @@ -257,8 +257,9 @@ pub struct Batch { pub complete: bool, /// Rows that couldn't be read. pub skipped: usize, - /// Values in date fields that weren't dates and are read as null, counted for each field by - /// its position; empty when there were none. Said by [`unread_dates_note`]. + /// Values in date fields that weren't dates, and text in yes/no fields that was neither yes nor + /// no ([`yes_no_text`]), read as null, counted for each field by its position; empty when there + /// were none. Said by [`unread_dates_note`]. pub unread_dates: Vec, /// Date-times of date fields that had digits past the microsecond, rounded to it, counted for /// each field by its position. Said by [`rounded_dates_note`]. @@ -281,6 +282,17 @@ pub(crate) fn unread_date(counts: &mut Vec, k: usize) { unread_dates_by(counts, k, 1); } +/// The value of the yes/no field at `k` from a file's text ([`crate::Value::yes_no`]): text that +/// is neither yes nor no is null, counted in `counts` ([`Batch::unread_dates`]), which says it as a +/// value that isn't yes or no ([`unread_dates_note`]). Empty text and `` are null, uncounted. +pub(crate) fn yes_no_text(text: &str, counts: &mut Vec, k: usize) -> crate::Value { + let v = crate::Value::parse(text, crate::FieldType::Boolean); + if v.is_null() && !crate::Value::Text(text.to_string()).asks_null() { + unread_date(counts, k); + } + v +} + /// Counts one more text value `` read as null in the field at `k` ([`Batch::null_text`]). pub(crate) fn null_text_at(counts: &mut Vec, k: usize) { unread_dates_by(counts, k, 1); @@ -332,7 +344,15 @@ pub fn unread_dates_note(fields: &[crate::Field], counts: &[usize]) -> Option 0 && (f.ty == crate::FieldType::Boolean) == boolean); + let what = match (counted(false), counted(true), total == 1) { + (false, true, true) => "1 value isn't yes or no and was".to_string(), + (false, true, false) => format!("{total} values aren't yes or no and were"), + (true, true, _) => format!("{total} values aren't dates or yes/no values and were"), + (_, _, true) => "1 value isn't a date and was".to_string(), + _ => format!("{total} values aren't dates and were"), + }; let text = format!("{what} read as empty, in {}", crate::io::named_fields(fields, counts)); Some(crate::loss::Note::loss(crate::loss::LossCode::DroppedValue, text)) } diff --git a/crates/data/src/source/tests.rs b/crates/data/src/source/tests.rs index 5519c4649d..0d430efe91 100644 --- a/crates/data/src/source/tests.rs +++ b/crates/data/src/source/tests.rs @@ -4049,6 +4049,54 @@ fn geopackage_writes_fine_date_time_text_as_a_date_time() { assert_eq!(stored, "2026-03-05T14:30:00.123Z"); } +/// Text another program left in a GeoPackage yes/no column reads as yes or no when it is a yes/no +/// word; other text reads as empty, and is said, on the desktop and in the browser. +#[test] +fn geopackage_yes_no_text_that_isnt_yes_or_no_is_said() { + let workspace = tempfile::tempdir().unwrap(); + let path = workspace.path().join("gates.gpkg"); + let mut gates = Dataset::new("gates", GeometryType::Point, vec![Field::new("open", FieldType::Boolean)]); + for v in [Value::Bool(true), Value::Null, Value::Null, Value::Null] { + gates.push(Some(Geometry::Point(Coord::new(1.0, 2.0))), vec![v]); + } + crate::io::write_path(&gates, &path).unwrap(); + let read = |odd: &str| { + let c = rusqlite::Connection::open(&path).unwrap(); + // The spatial index's triggers call functions only SpatiaLite has; the geometry stays. + let triggers: Vec = c + .prepare("SELECT name FROM sqlite_master WHERE type = 'trigger'") + .unwrap() + .query_map([], |r| r.get(0)) + .unwrap() + .map(|n| n.unwrap()) + .collect(); + for t in triggers { + c.execute(&format!("DROP TRIGGER \"{t}\""), []).unwrap(); + } + c.execute("UPDATE gates SET open = 'No' WHERE fid = 2", []).unwrap(); + c.execute("UPDATE gates SET open = ?1 WHERE fid = 3", [odd]).unwrap(); + c.execute("UPDATE gates SET open = '' WHERE fid = 4", []).unwrap(); + drop(c); + let desktop = open_path(&path, None).unwrap(); + let browser = gpkg_mem::GpkgMemSource::open_shared(Shared(Arc::new(std::fs::read(&path).unwrap())), None).unwrap(); + [desktop.as_ref(), &browser as &dyn FeatureSource].map(|src| { + let (ds, report) = materialize(src).unwrap(); + let values: Vec = ds.features.iter().map(|f| f.attrs[0].clone()).collect(); + let said: Vec<_> = report.messages.iter().filter(|n| n.text.contains("yes or no")).map(|n| (n.text.clone(), n.loss)).collect(); + (values, said) + }) + }; + for (values, said) in read("maybe") { + assert_eq!(values, [Value::Bool(true), Value::Bool(false), Value::Null, Value::Null]); + let code = Some(crate::loss::LossCode::DroppedValue); + assert_eq!(said, [("gates: 1 value isn't yes or no and was read as empty, in 'open'".to_string(), code)]); + } + for (values, said) in read("t") { + assert_eq!(values, [Value::Bool(true), Value::Bool(false), Value::Bool(true), Value::Null]); + assert!(said.is_empty(), "{said:?}"); + } +} + /// A GeoPackage export writes DATE and DATETIME columns, as GeoPackage gives them: a date-time with /// a zone in UTC with `Z` (its other offset said), one without a zone without, milliseconds always. /// The desktop and browser readers read them back as dates; a value that isn't one, as null, said diff --git a/crates/data/src/value.rs b/crates/data/src/value.rs index f1c00f0ec6..ade75c6ede 100644 --- a/crates/data/src/value.rs +++ b/crates/data/src/value.rs @@ -229,6 +229,18 @@ impl Value { } } + /// Whether this value, put in a decimal (Double) field, comes out rounded: a whole number past + /// 2^53, or a number written as text with more digits than a decimal holds + /// ([`double_holds`](crate::io::double_holds): `9007199254740993.0` is, `0.1` and `1e3` aren't). + pub fn rounds_as_double(&self) -> bool { + match self { + // i128 holds both exactly. + Value::Int(i) => (*i as f64) as i128 != i128::from(*i), + Value::Text(t) => t.trim().parse::().is_ok_and(f64::is_finite) && !crate::io::double_holds(t.trim()), + _ => false, + } + } + /// The yes/no value text says, ignoring case and spaces around it: `true`, `t`, `yes`, `y` and /// `1` are true; `false`, `f`, `no`, `n` and `0` are false; other text is neither. pub fn yes_no(text: &str) -> Option { diff --git a/crates/engine/src/cmd/design.rs b/crates/engine/src/cmd/design.rs index 7fddebbb39..41a9996947 100644 --- a/crates/engine/src/cmd/design.rs +++ b/crates/engine/src/cmd/design.rs @@ -197,12 +197,13 @@ pub(crate) fn apply_with>(s: &mut Session, id: u32, changes: let l = s.map_mut().layer_mut(id).ok_or("no such layer")?; // New features: subtype defaults fill empty fields; elevation goes in `z`. A default its field // can't hold as given (one saved before it was checked, or for a field retyped since) is left - // out, and said, by field, once the edit is kept; one that isn't finite refuses the edit. - let mut unheld: Vec<(String, usize)> = Vec::new(); + // out, and said once the edit is kept, naming its fields; one that isn't finite refuses the edit. + let (mut unheld, mut unheld_rows): (Vec, usize) = (Vec::new(), 0); if let Some(st) = l.design.subtypes.clone() && let Some(sfi) = l.dataset.field_index(&st.field) { for r in &new_rows { + let mut left_out = false; let code = l.dataset.value(*r, sfi).as_f64().map(|v| v as i64); let Some(sub) = code.and_then(|c| st.subtypes.iter().find(|x| x.code == c)) else { continue }; for (field, v) in &sub.defaults { @@ -217,13 +218,16 @@ pub(crate) fn apply_with>(s: &mut Session, id: u32, changes: } match super::edit::held_default(field, v, ty) { Ok(held) => *cell = held, - Err(_) => match unheld.iter_mut().find(|(f, _)| f == field) { - Some((_, n)) => *n += 1, - None => unheld.push((field.clone(), 1)), - }, + Err(_) => { + left_out = true; + if !unheld.contains(field) { + unheld.push(field.clone()); + } + } } } } + unheld_rows += usize::from(left_out); } } if elevation != Elevation::None && !zs.is_empty() { @@ -333,11 +337,13 @@ pub(crate) fn apply_with>(s: &mut Session, id: u32, changes: s.notify_loss(code, notice); } } - for (field, n) in unheld { - let features = if n == 1 { "1 new feature".to_string() } else { format!("{n} new features") }; + if unheld_rows > 0 { + let features = if unheld_rows == 1 { "1 new feature".to_string() } else { format!("{unheld_rows} new features") }; + let fields: Vec = unheld.iter().map(|f| format!("'{f}'")).collect(); s.notify_loss( rustgis_data::loss::LossCode::DroppedValue, - format!("{layer}: field '{field}' left empty in {features}, as it can't hold its subtype default as given").into(), + format!("{layer}: subtype defaults left out of {features}, as their fields can't hold them as given: {}", fields.join(", ")) + .into(), ); } if !unread.is_empty() { diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index 0d790eb72f..470162b639 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -792,15 +792,8 @@ pub(crate) fn held_default(field: &str, value: &Value, ty: FieldType) -> Result< if coerced.is_null() && !value.asks_null() { return Err(format!("field '{field}': '{value}' isn't a {} value", ty.label())); } - let whole = match value { - Value::Int(i) => Some(*i), - Value::Text(t) => t.trim().parse::().ok(), - _ => None, - }; - // i128 holds both exactly: a whole number past 2^53 its decimal doesn't. - let rounded = ty == FieldType::Double && matches!(coerced, Value::Float(f) if whole.is_some_and(|i| f as i128 != i128::from(i))); if numeric_loss(value, &coerced, ty).is_some() - || rounded + || (ty == FieldType::Double && matches!(coerced, Value::Float(_)) && value.rounds_as_double()) || matches!(value, Value::DateTime(t) if ty == FieldType::Date && !t.is_date()) { return Err(format!("field '{field}': a {} field can't hold '{value}' as given", ty.label())); @@ -849,6 +842,8 @@ fn convert(v: Value, ty: FieldType) -> (Value, Cut, Option) { // A whole number is yes when it isn't 0, as a shapefile writes it. (Value::Int(i), FieldType::Boolean) => (Value::Bool(i != 0), Cut::None, None), (Value::Float(f), FieldType::Boolean) if f.fract() == 0.0 => (Value::Bool(f != 0.0), Cut::None, None), + // A fraction is no yes/no value: null, not the text it's shown as (`0.0000001` shows `0`). + (Value::Float(_), FieldType::Boolean) => (Value::Null, Cut::None, None), // Uncounted coercion retains source numbers until output can explain any loss. (Value::Text(t), _) => (Value::parse_source(&t, ty), Cut::None, None), (other, _) => (Value::parse(&other.to_string(), ty), Cut::None, None), diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 197393b053..755bb5fe90 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -1539,6 +1539,8 @@ fn yes_no_text_that_isnt_yes_or_no_is_refused_or_said_never_read_as_no() { assert_eq!(err, "'maybe' isn't a Boolean value"); let err = s.run("edit.setValue", &json!({"layer": "Cities", "row": 0, "field": "flag", "value": 0.5})).unwrap_err(); assert_eq!(err, "'0.5' isn't a Boolean value"); + let err = s.run("edit.setValue", &json!({"layer": "Cities", "row": 0, "field": "flag", "value": 1e-7})).unwrap_err(); + assert!(err.ends_with("isn't a Boolean value"), "not the 0 it shows as: {err}"); assert_eq!(cell(&s, 0), V::Bool(false), "a refused value leaves the cell as it was"); // Calculate Field writes null for a result that isn't yes or no, and says so; clean results say nothing. let mark = s.notice_mark(); @@ -1584,13 +1586,18 @@ fn a_default_its_field_cant_hold_as_given_is_refused_when_set() { } let err = s.run("edit.template", &json!({"layer": "Cities", "name": "T", "defaults": {"x": 9_007_199_254_740_993_i64}})).unwrap_err(); assert_eq!(err, "field 'x': a Double field can't hold '9007199254740993' as given"); + for text in ["9007199254740993.0", "12345678901234567890"] { + let err = s.run("edit.template", &json!({"layer": "Cities", "name": "T", "defaults": {"x": text}})).unwrap_err(); + assert!(err.contains("can't hold"), "{text}: {err}"); + } let err = s.run("data.contingentValues", &json!({"layer": "Cities", "name": "C", "fields": ["n", "flag"], "combos": [[2.5, true]]})); assert_eq!(err.unwrap_err(), "field 'n': a Long field can't hold '2.5' as given"); let err = s.run("data.domain", &json!({"layer": "Cities", "field": "flag", "coded": [[true, "Yes"], ["maybe", "Maybe"]]})).unwrap_err(); assert_eq!(err, "field 'flag': 'maybe' isn't a Boolean value"); assert!(s.map().layer_by_name("Cities").unwrap().design.templates.is_empty(), "a refused template isn't added"); // Defaults the fields hold as given are kept, and fill new features with nothing to say. - s.run("edit.template", &json!({"layer": "Cities", "name": "T", "defaults": {"n": 2.0, "flag": "yes"}})).unwrap(); + s.run("edit.template", &json!({"layer": "Cities", "name": "T", "defaults": {"n": 2.0, "flag": "yes", "x": "9007199254740992.0"}})) + .unwrap(); let mark = s.notice_mark(); let point = json!({"type": "Point", "coordinates": [0.0, 0.0]}); let row = s.run("edit.addFeature", &json!({"layer": "Cities", "geometry": point, "template": "T"})).unwrap()["row"].as_u64().unwrap(); @@ -1624,7 +1631,7 @@ fn a_default_its_field_cant_hold_as_given_is_refused_when_set() { assert_eq!( said, [( - "Cities: field 'n' left empty in 1 new feature, as it can't hold its subtype default as given".to_string(), + "Cities: subtype defaults left out of 1 new feature, as their fields can't hold them as given: 'n'".to_string(), Some(rustgis_data::loss::LossCode::DroppedValue) )] ); From 5c11a7e0dd4388faf80267b138eb0fb16abfa570 Mon Sep 17 00:00:00 2001 From: mavrick Date: Thu, 26 Nov 2026 16:14:06 -0600 Subject: [PATCH 3/6] fix(engine): decimals into text fields in full, text fractions and .0 whole numbers counted A decimal default for a text field, and edit.setValue's number into one, keep all their digits instead of the six places a decimal is shown to. Update counts a fraction a decimal parse rounds away (2.0000000000000001), and says its cuts and roundings in one notice per kind. A whole number written with .0 is held in a decimal field only exactly, as one without it. --- crates/analysis/src/tools.rs | 64 ++++++++++++++++++++++------------- crates/data/src/value.rs | 33 ++++++++++++++++-- crates/engine/src/cmd/edit.rs | 6 ++++ crates/engine/src/tests.rs | 10 ++++-- 4 files changed, 84 insertions(+), 29 deletions(-) diff --git a/crates/analysis/src/tools.rs b/crates/analysis/src/tools.rs index 43cfed14e4..881259600b 100644 --- a/crates/analysis/src/tools.rs +++ b/crates/analysis/src/tools.rs @@ -2838,8 +2838,8 @@ fn symmetrical_difference(inp: &dyn Inputs, p: &Json) -> Result Value { match (v, ty) { (Value::Int(_), FieldType::Integer) @@ -2955,6 +2955,8 @@ fn update_on(inp: &dyn Inputs, p: &Json, threads: Option) -> Result = Vec::new(); messages.extend(left_out.notes("Update", &up.name)); let features = |n: usize| if n == 1 { "1 update feature".to_string() } else { format!("{n} update features") }; + // The cuts and roundings are said one notice per kind, naming their fields. + let (mut cut, mut round): (Vec<(&str, usize)>, Vec<(&str, usize)>) = (Vec::new(), Vec::new()); for (f, Unfit { nulls: n, days, fractions, rounded }) in ds.fields.iter().zip(unfit) { if n > 0 { losses.push(rustgis_data::loss::LossMessage { @@ -2970,23 +2972,32 @@ fn update_on(inp: &dyn Inputs, p: &Json, threads: Option) -> Result 0 { - let their = if fractions == 1 { "its" } else { "their" }; - losses.push(rustgis_data::loss::LossMessage { - code: rustgis_data::loss::LossCode::ChangedTruncated, - text: format!("Update: '{}' holds whole numbers, so {} lost {their} fraction", f.name, features(fractions)), - }); + cut.push((&f.name, fractions)); } if rounded > 0 { - losses.push(rustgis_data::loss::LossMessage { - code: rustgis_data::loss::LossCode::ChangedRounded, - text: format!( - "Update: '{}' holds decimals, so the numbers of {} were rounded to the digits it holds", - f.name, - features(rounded) - ), - }); + round.push((&f.name, rounded)); } } + let named = |fields: &[(&str, usize)]| { + let total: usize = fields.iter().map(|(_, n)| n).sum(); + let values = if total == 1 { "1 update value".to_string() } else { format!("{total} update values") }; + let (its, was) = if total == 1 { ("its", "was") } else { ("their", "were") }; + (values, its, was, fields.iter().map(|(f, _)| format!("'{f}'")).collect::>().join(", ")) + }; + if !cut.is_empty() { + let (values, its, _, fields) = named(&cut); + losses.push(rustgis_data::loss::LossMessage { + code: rustgis_data::loss::LossCode::ChangedTruncated, + text: format!("Update: {values} lost {its} fraction in fields that hold whole numbers: {fields}"), + }); + } + if !round.is_empty() { + let (values, _, was, fields) = named(&round); + losses.push(rustgis_data::loss::LossMessage { + code: rustgis_data::loss::LossCode::ChangedRounded, + text: format!("Update: {values} {was} rounded to the digits a decimal holds, in {fields}"), + }); + } Ok(ToolResult { losses, output: Output::Layer(out), messages }) } @@ -3009,12 +3020,17 @@ impl Unfit { // Empty or `` text asks for null: no loss. self.nulls += usize::from(c.is_null() && !v.asks_null()); self.days += usize::from(matches!(v, Value::DateTime(t) if ty == FieldType::Date && !t.is_date())); - let decimal = match v { - Value::Float(f) => Some(*f), - Value::Text(t) if t.trim().parse::().is_err() => t.trim().parse::().ok(), - _ => None, + let fraction = match v { + Value::Float(f) => f.fract() != 0.0, + // A decimal written out is read from its digits, which a decimal can round away: + // `2.0000000000000001` has a fraction, `2.000` hasn't. + Value::Text(t) => match t.trim().split_once('.') { + Some((_, digits)) if digits.bytes().all(|b| b.is_ascii_digit()) => digits.bytes().any(|b| b != b'0'), + _ => t.trim().parse::().is_err() && t.trim().parse::().is_ok_and(|f| f.fract() != 0.0), + }, + _ => false, }; - self.fractions += usize::from(matches!(c, Value::Int(_)) && decimal.is_some_and(|f| f.fract() != 0.0)); + self.fractions += usize::from(matches!(c, Value::Int(_)) && fraction); self.rounded += usize::from(ty == FieldType::Double && matches!(c, Value::Float(_)) && v.rounds_as_double()); } } @@ -14607,9 +14623,9 @@ mod tests { assert_eq!(said(&run(&zones))[1..], [] as [&str; 0]); zones.push(Some(sq(7.0, 0.0, 1.0)), vec![Value::Float(-2.7), Value::Int((1 << 53) + 1), Value::Text("maybe".into())]); let lossy = [ - "ChangedTruncated: Update: 'n' holds whole numbers, so 1 update feature lost its fraction", - "ChangedRounded: Update: 'x' holds decimals, so the numbers of 1 update feature were rounded to the digits it holds", "DroppedValue: Update: 'b' is null in 1 update feature, whose value isn't a Boolean value", + "ChangedTruncated: Update: 1 update value lost its fraction in fields that hold whole numbers: 'n'", + "ChangedRounded: Update: 1 update value was rounded to the digits a decimal holds, in 'x'", ]; let res = run(&zones); assert_eq!(said(&res)[1..], lossy); @@ -14619,11 +14635,11 @@ mod tests { // Written as text, the same. let fields = vec![Field::new("n", FieldType::Text), Field::new("x", FieldType::Text), Field::new("b", FieldType::Text)]; let mut zones = Dataset::new("zones", GeometryType::Polygon, fields); - zones.push(Some(sq(5.0, 0.0, 1.0)), vec![Value::Text("2".into()), Value::Text("1e3".into()), Value::Text("yes".into())]); + zones.push(Some(sq(5.0, 0.0, 1.0)), vec![Value::Text("2.000".into()), Value::Text("1e3".into()), Value::Text("yes".into())]); assert_eq!(said(&run(&zones))[1..], [] as [&str; 0]); zones.push( Some(sq(7.0, 0.0, 1.0)), - vec![Value::Text("-2.7".into()), Value::Text("9007199254740993.0".into()), Value::Text("maybe".into())], + vec![Value::Text("2.0000000000000001".into()), Value::Text("9007199254740993.0".into()), Value::Text("maybe".into())], ); assert_eq!(said(&run(&zones))[1..], lossy); } diff --git a/crates/data/src/value.rs b/crates/data/src/value.rs index ade75c6ede..e1393d36b9 100644 --- a/crates/data/src/value.rs +++ b/crates/data/src/value.rs @@ -230,13 +230,28 @@ impl Value { } /// Whether this value, put in a decimal (Double) field, comes out rounded: a whole number past - /// 2^53, or a number written as text with more digits than a decimal holds - /// ([`double_holds`](crate::io::double_holds): `9007199254740993.0` is, `0.1` and `1e3` aren't). + /// 2^53, written as digits (with or without `.0`) and held only exactly, or a number written as + /// text with more significant digits than a decimal holds ([`double_holds`](crate::io::double_holds)): + /// `9007199254740993.0` and `12345678901234567000.0` are; `0.1`, `1e3` and + /// `1.2345678901234567e19`, which says only its 17 digits, aren't. pub fn rounds_as_double(&self) -> bool { match self { // i128 holds both exactly. Value::Int(i) => (*i as f64) as i128 != i128::from(*i), - Value::Text(t) => t.trim().parse::().is_ok_and(f64::is_finite) && !crate::io::double_holds(t.trim()), + Value::Text(t) => { + let t = t.trim(); + if !t.parse::().is_ok_and(f64::is_finite) { + return false; + } + // A whole number written with a decimal point (`12345678901234567000.0`) is held + // only exactly, as one written without it is. + match t.split_once('.') { + Some((whole, zeros)) if whole.bytes().any(|b| b.is_ascii_digit()) && zeros.bytes().all(|b| b == b'0') => { + !crate::io::double_holds(whole) + } + _ => !crate::io::double_holds(t), + } + } _ => false, } } @@ -699,6 +714,18 @@ mod tests { assert_eq!(Value::yes_no(text), said, "{text}"); assert_eq!(Value::parse(text, FieldType::Boolean), Value::Bool(said.unwrap_or_default()), "{text}"); } + for (text, rounded) in [ + ("9007199254740993.0", true), + ("12345678901234567000.0", true), + ("12345678901234567890", true), + ("9007199254740992.0", false), + ("0.1", false), + ("1e3", false), + ("1.2345678901234567e19", false), + ] { + assert_eq!(Value::Text(text.into()).rounds_as_double(), rounded, "{text}"); + } + assert!(Value::Int((1 << 53) + 1).rounds_as_double() && !Value::Int(1 << 53).rounds_as_double()); for text in ["maybe", "2", "on", "yess"] { assert_eq!(Value::yes_no(text), None, "{text}"); assert_eq!(Value::parse(text, FieldType::Boolean), Value::Null, "{text} is neither, not no"); diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index 470162b639..e21218e8e0 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -788,6 +788,10 @@ pub(crate) fn held_default(field: &str, value: &Value, ty: FieldType) -> Result< if non_finite_input(value, ty) { return Err(format!("field '{field}' requires a finite number")); } + // A decimal goes into a text field in full, not as the six places it's shown to. + if ty == FieldType::Text && matches!(value, Value::Float(_)) { + return Ok(Value::Text(value.to_file_text())); + } let coerced = coerce(value.clone(), ty); if coerced.is_null() && !value.asks_null() { return Err(format!("field '{field}': '{value}' isn't a {} value", ty.label())); @@ -1008,6 +1012,8 @@ fn typed(raw: Json, ty: FieldType) -> Result { } v => v, }, + // A number goes into a text field in full, not as the six decimals it's shown to. + Json::Number(n) if ty == FieldType::Text => Value::Text(Value::from_json(&Json::Number(n)).to_file_text()), // So is any other value a date or yes/no field can't hold (`20260305`, `0.5`). other => match coerce(Value::from_json(&other), ty) { Value::Null if (ty.is_temporal() || ty == FieldType::Boolean) && !other.is_null() => { diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 755bb5fe90..2a85231abb 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -1596,8 +1596,9 @@ fn a_default_its_field_cant_hold_as_given_is_refused_when_set() { assert_eq!(err, "field 'flag': 'maybe' isn't a Boolean value"); assert!(s.map().layer_by_name("Cities").unwrap().design.templates.is_empty(), "a refused template isn't added"); // Defaults the fields hold as given are kept, and fill new features with nothing to say. - s.run("edit.template", &json!({"layer": "Cities", "name": "T", "defaults": {"n": 2.0, "flag": "yes", "x": "9007199254740992.0"}})) - .unwrap(); + s.run("edit.addField", &json!({"layer": "Cities", "name": "note", "type": "text"})).unwrap(); + let defaults = json!({"n": 2.0, "flag": "yes", "x": "9007199254740992.0", "note": 0.1234567}); + s.run("edit.template", &json!({"layer": "Cities", "name": "T", "defaults": defaults})).unwrap(); let mark = s.notice_mark(); let point = json!({"type": "Point", "coordinates": [0.0, 0.0]}); let row = s.run("edit.addFeature", &json!({"layer": "Cities", "geometry": point, "template": "T"})).unwrap()["row"].as_u64().unwrap(); @@ -1605,6 +1606,11 @@ fn a_default_its_field_cant_hold_as_given_is_refused_when_set() { let ds = &s.map().layer_by_name("Cities").unwrap().dataset; let row = row as usize; assert_eq!((ds.value(row, ds.field_index("n").unwrap()), ds.value(row, ds.field_index("flag").unwrap())), (&V::Int(2), &V::Bool(true))); + assert_eq!(ds.value(row, ds.field_index("note").unwrap()), &V::Text("0.1234567".into()), "in full, not to six places"); + s.run("edit.undo", &Value::Null).unwrap(); + s.run("edit.setValue", &json!({"layer": "Cities", "row": 0, "field": "note", "value": 0.1234567})).unwrap(); + let ds = &s.map().layer_by_name("Cities").unwrap().dataset; + assert_eq!(ds.value(0, ds.field_index("note").unwrap()), &V::Text("0.1234567".into()), "edit.setValue too"); s.run("edit.undo", &Value::Null).unwrap(); // A subtype's defaults fill a new feature of its code. One saved before defaults were // checked, that its field can't hold as given, is left out and said. From 3696b84e346e42a9c80e9dc62bdfbcf120f7729a Mon Sep 17 00:00:00 2001 From: mavrick Date: Thu, 26 Nov 2026 17:03:45 -0600 Subject: [PATCH 4/6] fix(engine): exponent fractions, setValue rounding and decimals into text are said or kept A fraction written in exponent form (2.0000000000000000001e0) is read from its digits (Value::text_has_fraction), so whole-number fields say the cut in every edit path and Update. edit.setValue and adding a feature say a number a decimal field rounds. Paste and Calculate Field put a decimal into a text field in full, as defaults and edit.setValue now do. Refusals name the value as given. --- crates/analysis/src/tools.rs | 22 ++++++++---------- crates/data/src/value.rs | 44 +++++++++++++++++++++++++++++++++++ crates/engine/src/cmd/edit.rs | 32 ++++++++++++------------- crates/engine/src/tests.rs | 27 ++++++++++++++++++--- 4 files changed, 94 insertions(+), 31 deletions(-) diff --git a/crates/analysis/src/tools.rs b/crates/analysis/src/tools.rs index 881259600b..e063a03a49 100644 --- a/crates/analysis/src/tools.rs +++ b/crates/analysis/src/tools.rs @@ -3020,17 +3020,15 @@ impl Unfit { // Empty or `` text asks for null: no loss. self.nulls += usize::from(c.is_null() && !v.asks_null()); self.days += usize::from(matches!(v, Value::DateTime(t) if ty == FieldType::Date && !t.is_date())); - let fraction = match v { - Value::Float(f) => f.fract() != 0.0, - // A decimal written out is read from its digits, which a decimal can round away: - // `2.0000000000000001` has a fraction, `2.000` hasn't. - Value::Text(t) => match t.trim().split_once('.') { - Some((_, digits)) if digits.bytes().all(|b| b.is_ascii_digit()) => digits.bytes().any(|b| b != b'0'), - _ => t.trim().parse::().is_err() && t.trim().parse::().is_ok_and(|f| f.fract() != 0.0), - }, - _ => false, - }; - self.fractions += usize::from(matches!(c, Value::Int(_)) && fraction); + // Text is read from its digits, which a decimal can round away: `2.0000000000000001` has a + // fraction, `2.000` hasn't. + let fraction = matches!(c, Value::Int(_)) + && match v { + Value::Float(f) => f.fract() != 0.0, + Value::Text(t) => Value::text_has_fraction(t), + _ => false, + }; + self.fractions += usize::from(fraction); self.rounded += usize::from(ty == FieldType::Double && matches!(c, Value::Float(_)) && v.rounds_as_double()); } } @@ -14639,7 +14637,7 @@ mod tests { assert_eq!(said(&run(&zones))[1..], [] as [&str; 0]); zones.push( Some(sq(7.0, 0.0, 1.0)), - vec![Value::Text("2.0000000000000001".into()), Value::Text("9007199254740993.0".into()), Value::Text("maybe".into())], + vec![Value::Text("2.0000000000000000001e0".into()), Value::Text("9007199254740993.0".into()), Value::Text("maybe".into())], ); assert_eq!(said(&run(&zones))[1..], lossy); } diff --git a/crates/data/src/value.rs b/crates/data/src/value.rs index e1393d36b9..eea3dcf490 100644 --- a/crates/data/src/value.rs +++ b/crates/data/src/value.rs @@ -256,6 +256,32 @@ impl Value { } } + /// Whether a number written as text has a fraction, read from its digits (not from the + /// decimal it parses to, which can round one away): `2.5`, `2.0000000000000001` and + /// `2.0000000000000000001e0` have; `2`, `2.000` and `1e3` haven't. Text that isn't a number + /// written out in digits (`inf`, `x`) has none. + pub fn text_has_fraction(text: &str) -> bool { + let t = text.trim().trim_start_matches(['-', '+']); + let (mantissa, exp) = match t.split_once(['e', 'E']) { + Some((m, e)) => (m, e.parse::().ok()), + None => (t, Some(0)), + }; + let Some(exp) = exp else { return false }; + let (whole, frac) = mantissa.split_once('.').unwrap_or((mantissa, "")); + if !whole.bytes().chain(frac.bytes()).all(|b| b.is_ascii_digit()) || whole.len() + frac.len() == 0 { + return false; + } + // The digits past the point once the exponent moves it: a fraction when any isn't 0. + let digits = format!("{whole}{frac}"); + let past = i64::try_from(frac.len()).unwrap_or(i64::MAX).saturating_sub(exp); + let kept = i64::try_from(digits.len()).unwrap_or(0).saturating_sub(past.max(0)); + match usize::try_from(kept) { + Ok(kept) => digits.get(kept..).is_some_and(|f| f.bytes().any(|b| b != b'0')), + // The point moves past every digit: all of them are fraction. + Err(_) => digits.bytes().any(|b| b != b'0'), + } + } + /// The yes/no value text says, ignoring case and spaces around it: `true`, `t`, `yes`, `y` and /// `1` are true; `false`, `f`, `no`, `n` and `0` are false; other text is neither. pub fn yes_no(text: &str) -> Option { @@ -726,6 +752,24 @@ mod tests { assert_eq!(Value::Text(text.into()).rounds_as_double(), rounded, "{text}"); } assert!(Value::Int((1 << 53) + 1).rounds_as_double() && !Value::Int(1 << 53).rounds_as_double()); + for (text, fraction) in [ + ("2.5", true), + ("-2.7", true), + ("2.0000000000000001", true), + ("2.0000000000000000001e0", true), + ("25e-1", true), + ("5e-1", true), + (".5", true), + ("2", false), + ("2.000", false), + ("1e3", false), + ("1.5e1", false), + ("2.50e1", false), + ("inf", false), + ("x", false), + ] { + assert_eq!(Value::text_has_fraction(text), fraction, "{text}"); + } for text in ["maybe", "2", "on", "yess"] { assert_eq!(Value::yes_no(text), None, "{text}"); assert_eq!(Value::parse(text, FieldType::Boolean), Value::Null, "{text} is neither, not no"); diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index e21218e8e0..8e83768bdb 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -492,9 +492,8 @@ pub(crate) fn validate(g: &Geometry) -> Result<(), String> { /// text it shows (which rounds a decimal to six places); a decimal, or text written as one, into a /// whole-number field loses its fraction (toward zero); a whole number past 2^53 into a decimal /// field is the nearest decimal. Not a number, and an infinity in a whole-number field, are null. -/// Other values go through their text (a -/// decimal into a text field as it's shown, to six places), and what the field can't hold is -/// null. A number past the 64-bit range is held at the range's end, as it was; [`coerce_cut`], for +/// A decimal goes into a text field in full, as a file writes it. Other values go through their +/// text, and what the field can't hold is null. A number past the 64-bit range is held at the range's end, as it was; [`coerce_cut`], for /// callers that say what was cut, makes it null instead. pub(crate) fn coerce(v: Value, ty: FieldType) -> Value { match convert(v, ty) { @@ -788,19 +787,14 @@ pub(crate) fn held_default(field: &str, value: &Value, ty: FieldType) -> Result< if non_finite_input(value, ty) { return Err(format!("field '{field}' requires a finite number")); } - // A decimal goes into a text field in full, not as the six places it's shown to. - if ty == FieldType::Text && matches!(value, Value::Float(_)) { - return Ok(Value::Text(value.to_file_text())); - } let coerced = coerce(value.clone(), ty); + // Named as given, not as shown (which rounds a decimal to six places). + let given = value.to_file_text(); if coerced.is_null() && !value.asks_null() { - return Err(format!("field '{field}': '{value}' isn't a {} value", ty.label())); + return Err(format!("field '{field}': '{given}' isn't a {} value", ty.label())); } - if numeric_loss(value, &coerced, ty).is_some() - || (ty == FieldType::Double && matches!(coerced, Value::Float(_)) && value.rounds_as_double()) - || matches!(value, Value::DateTime(t) if ty == FieldType::Date && !t.is_date()) - { - return Err(format!("field '{field}': a {} field can't hold '{value}' as given", ty.label())); + if numeric_loss(value, &coerced, ty).is_some() || matches!(value, Value::DateTime(t) if ty == FieldType::Date && !t.is_date()) { + return Err(format!("field '{field}': a {} field can't hold '{given}' as given", ty.label())); } Ok(coerced) } @@ -837,12 +831,18 @@ fn convert(v: Value, ty: FieldType) -> (Value, Cut, Option) { (Some((v, cut)), Ok(f)) => (v, cut, Some(f)), // A word the decimal reader takes ("inf", "NaN") isn't a number written as text: // null, and said so, as not a number. - (None, Ok(f)) if f.is_finite() || t.bytes().any(|b| b.is_ascii_digit()) => whole(f), + // A fraction the decimal rounded away (`2.0000000000000000001e0`) is still one. + (None, Ok(f)) if f.is_finite() || t.bytes().any(|b| b.is_ascii_digit()) => match whole(f) { + (v @ Value::Int(_), Cut::None, x) if Value::text_has_fraction(&t) => (v, Cut::Fraction, x), + held => held, + }, (None, Ok(f)) if f.is_infinite() => (Value::Null, Cut::NotFinite, None), (None, Ok(_)) => (Value::Null, Cut::NotANumber, None), _ => (Value::parse(&t, ty), Cut::None, None), }, }, + // A decimal goes into a text field in full, not as the six places it's shown to. + (Value::Float(f), FieldType::Text) if f.is_finite() => (Value::Text(Value::Float(f).to_file_text()), Cut::None, None), // A whole number is yes when it isn't 0, as a shapefile writes it. (Value::Int(i), FieldType::Boolean) => (Value::Bool(i != 0), Cut::None, None), (Value::Float(f), FieldType::Boolean) if f.fract() == 0.0 => (Value::Bool(f != 0.0), Cut::None, None), @@ -936,6 +936,8 @@ fn numeric_loss(input: &Value, v: &Value, ty: FieldType) -> Option { } _ => None, } + } else if ty == FieldType::Double && matches!(v, Value::Float(_)) && input.rounds_as_double() { + Some(("{layer}, field '{field}', row {row}: 1 attribute value was rounded to the digits a decimal holds", LossCode::ChangedRounded)) } else { None } @@ -1012,8 +1014,6 @@ fn typed(raw: Json, ty: FieldType) -> Result { } v => v, }, - // A number goes into a text field in full, not as the six decimals it's shown to. - Json::Number(n) if ty == FieldType::Text => Value::Text(Value::from_json(&Json::Number(n)).to_file_text()), // So is any other value a date or yes/no field can't hold (`20260305`, `0.5`). other => match coerce(Value::from_json(&other), ty) { Value::Null if (ty.is_temporal() || ty == FieldType::Boolean) && !other.is_null() => { diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 2a85231abb..990736e950 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -1541,6 +1541,8 @@ fn yes_no_text_that_isnt_yes_or_no_is_refused_or_said_never_read_as_no() { assert_eq!(err, "'0.5' isn't a Boolean value"); let err = s.run("edit.setValue", &json!({"layer": "Cities", "row": 0, "field": "flag", "value": 1e-7})).unwrap_err(); assert!(err.ends_with("isn't a Boolean value"), "not the 0 it shows as: {err}"); + let err = s.run("edit.template", &json!({"layer": "Cities", "name": "T", "defaults": {"flag": 1e-7}})).unwrap_err(); + assert_eq!(err, "field 'flag': '0.0000001' isn't a Boolean value", "named as given"); assert_eq!(cell(&s, 0), V::Bool(false), "a refused value leaves the cell as it was"); // Calculate Field writes null for a result that isn't yes or no, and says so; clean results say nothing. let mark = s.notice_mark(); @@ -1586,9 +1588,24 @@ fn a_default_its_field_cant_hold_as_given_is_refused_when_set() { } let err = s.run("edit.template", &json!({"layer": "Cities", "name": "T", "defaults": {"x": 9_007_199_254_740_993_i64}})).unwrap_err(); assert_eq!(err, "field 'x': a Double field can't hold '9007199254740993' as given"); - for text in ["9007199254740993.0", "12345678901234567890"] { - let err = s.run("edit.template", &json!({"layer": "Cities", "name": "T", "defaults": {"x": text}})).unwrap_err(); - assert!(err.contains("can't hold"), "{text}: {err}"); + for (field, text) in [("x", "9007199254740993.0"), ("x", "12345678901234567890"), ("n", "1.00000000000000001e0")] { + let err = s.run("edit.template", &json!({"layer": "Cities", "name": "T", "defaults": {field: text}})).unwrap_err(); + assert_eq!(err, format!("field '{field}': a {} field can't hold '{text}' as given", if field == "n" { "Long" } else { "Double" })); + } + // edit.setValue keeps such values, and says what holding them lost; exact ones say nothing. + for (field, value, said) in [ + ("x", json!(9_007_199_254_740_993_i64), Some(rustgis_data::loss::LossCode::ChangedRounded)), + ("x", json!("9007199254740993.0"), Some(rustgis_data::loss::LossCode::ChangedRounded)), + ("x", json!("9007199254740992.0"), None), + ("x", json!(0.1), None), + ("n", json!("2.0000000000000000001e0"), Some(rustgis_data::loss::LossCode::ChangedTruncated)), + ("n", json!("1e3"), None), + ] { + let mark = s.notice_mark(); + s.run("edit.setValue", &json!({"layer": "Cities", "row": 0, "field": field, "value": value})).unwrap(); + let codes: Vec<_> = s.notices_since(mark).iter().filter_map(|n| n.loss()).collect(); + assert_eq!(codes, said.into_iter().collect::>(), "{value}"); + s.run("edit.undo", &Value::Null).unwrap(); } let err = s.run("data.contingentValues", &json!({"layer": "Cities", "name": "C", "fields": ["n", "flag"], "combos": [[2.5, true]]})); assert_eq!(err.unwrap_err(), "field 'n': a Long field can't hold '2.5' as given"); @@ -1612,6 +1629,10 @@ fn a_default_its_field_cant_hold_as_given_is_refused_when_set() { let ds = &s.map().layer_by_name("Cities").unwrap().dataset; assert_eq!(ds.value(0, ds.field_index("note").unwrap()), &V::Text("0.1234567".into()), "edit.setValue too"); s.run("edit.undo", &Value::Null).unwrap(); + s.run("edit.calculateField", &json!({"layer": "Cities", "field": "note", "expression": "0.1234567"})).unwrap(); + let ds = &s.map().layer_by_name("Cities").unwrap().dataset; + assert_eq!(ds.value(0, ds.field_index("note").unwrap()), &V::Text("0.1234567".into()), "Calculate Field too"); + s.run("edit.undo", &Value::Null).unwrap(); // A subtype's defaults fill a new feature of its code. One saved before defaults were // checked, that its field can't hold as given, is left out and said. let subtypes = json!([{"code": 1, "name": "One", "defaults": {"n": "7", "flag": "no"}}]); From f08a9ecdd2e68df88bc0d79a657478e081cc0dad Mon Sep 17 00:00:00 2001 From: mavrick Date: Thu, 26 Nov 2026 18:06:42 -0600 Subject: [PATCH 5/6] fix(engine): rounding into a decimal or whole-number field is said in every edit Cut::Rounded marks a number with more digits than its field holds: a whole number past 2^53 into a decimal field, or text such as 9007199254740993.0 or 9007199254740993e0. Calculate Field, Paste, calculation rules, edit.setValue, adding a feature and the defaults say it as changed.rounded, and the Calculate Field preview names it. --- crates/data/src/source/mod.rs | 2 +- crates/engine/src/cmd/edit.rs | 35 +++++++++++++++++++++++++++++++---- crates/engine/src/tests.rs | 26 +++++++++++++++++++++++++- crates/ui-egui/src/dialogs.rs | 1 + 4 files changed, 58 insertions(+), 6 deletions(-) diff --git a/crates/data/src/source/mod.rs b/crates/data/src/source/mod.rs index 81e6ed83d5..9e587ba986 100644 --- a/crates/data/src/source/mod.rs +++ b/crates/data/src/source/mod.rs @@ -287,7 +287,7 @@ pub(crate) fn unread_date(counts: &mut Vec, k: usize) { /// value that isn't yes or no ([`unread_dates_note`]). Empty text and `` are null, uncounted. pub(crate) fn yes_no_text(text: &str, counts: &mut Vec, k: usize) -> crate::Value { let v = crate::Value::parse(text, crate::FieldType::Boolean); - if v.is_null() && !crate::Value::Text(text.to_string()).asks_null() { + if v.is_null() && !text.trim().is_empty() && !crate::Value::is_null_marker(text) { unread_date(counts, k); } v diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index 8e83768bdb..9070f2437a 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -488,8 +488,9 @@ pub(crate) fn validate(g: &Geometry) -> Result<(), String> { } } -/// `v` as a value of a `ty` field. A date-time into a date field is the day it shows. A number goes into a number field as it is, not through the -/// text it shows (which rounds a decimal to six places); a decimal, or text written as one, into a +/// `v` as a value of a `ty` field. A date-time into a date field is the day it shows. A number +/// goes into a number field as it is, not through the text it shows (which rounds a decimal to six +/// places); a decimal, or text written as one, into a /// whole-number field loses its fraction (toward zero); a whole number past 2^53 into a decimal /// field is the nearest decimal. Not a number, and an infinity in a whole-number field, are null. /// A decimal goes into a text field in full, as a file writes it. Other values go through their @@ -519,6 +520,10 @@ pub(crate) enum Cut { NotFinite, /// A date-time's time of day or zone: a date field keeps its day. Time, + /// Digits past those a decimal holds: a whole number past 2^53 in a decimal field, or text + /// with more significant digits than the decimal it is read through + /// ([`Value::rounds_as_double`], [`double_holds`](rustgis_data::io::double_holds)). + Rounded, } /// How many of a field's results [`coerce_cut`] cut, of each kind, for one notice per kind. @@ -529,6 +534,7 @@ pub(crate) struct Cuts { not_numbers: usize, not_finite: usize, times: usize, + rounded: usize, } impl Cuts { @@ -540,6 +546,7 @@ impl Cuts { Cut::NotANumber => self.not_numbers += 1, Cut::NotFinite => self.not_finite += 1, Cut::Time => self.times += 1, + Cut::Rounded => self.rounded += 1, } } @@ -576,6 +583,10 @@ impl Cuts { let their = if self.times == 1 { "its" } else { "their" }; out.push((LossCode::DroppedTime, format!("{by}: '{field}' holds dates, so {} kept only {their} day", results(self.times)))); } + if self.rounded > 0 { + let were = if self.rounded == 1 { "was" } else { "were" }; + out.push((LossCode::ChangedRounded, format!("{by}: {} {were} rounded to the digits '{field}' holds", results(self.rounded)))); + } out } } @@ -618,6 +629,7 @@ impl Loss { Loss::Cut(Cut::NotANumber) => PreviewLoss::NotANumber, Loss::Cut(Cut::NotFinite) => PreviewLoss::NotFinite, Loss::Cut(Cut::Time) => PreviewLoss::Time, + Loss::Cut(Cut::Rounded) => PreviewLoss::Rounded, Loss::Unread => PreviewLoss::Unheld, Loss::Error(fault) => PreviewLoss::Error(fault), }) @@ -637,6 +649,8 @@ pub enum PreviewLoss { NotFinite, /// A date field keeps a date-time's day. Time, + /// Digits past those the field holds are rounded. + Rounded, /// A result the field can't hold (text that isn't a number or a date) is null. Unheld, /// The expression's error made it null. @@ -715,6 +729,7 @@ impl WriteLosses { (cuts.not_numbers, PreviewLoss::NotANumber), (cuts.not_finite, PreviewLoss::NotFinite), (cuts.times, PreviewLoss::Time), + (cuts.rounded, PreviewLoss::Rounded), ] .into_iter() .find_map(|(n, loss)| (n > 0).then_some(loss)) @@ -816,7 +831,9 @@ fn convert(v: Value, ty: FieldType) -> (Value, Cut, Option) { (Value::Float(f), FieldType::Integer) if f.is_infinite() => (Value::Null, Cut::NotFinite, None), (Value::Float(f), FieldType::Integer) => whole(f), (Value::Float(f), FieldType::Double) => (Value::Float(f), Cut::None, None), - (Value::Int(i), FieldType::Double) => (Value::Float(i as f64), Cut::None, None), + (Value::Int(i), FieldType::Double) => { + (Value::Float(i as f64), if Value::Int(i).rounds_as_double() { Cut::Rounded } else { Cut::None }, None) + } // A date-time into a date field is the day it shows, and said so when it had a time or zone. (Value::DateTime(t), FieldType::Date) => (Value::Date(t.date()), if t.is_date() { Cut::None } else { Cut::Time }, None), // A date is no number or yes/no: null (and said by the caller), not read as false. @@ -832,8 +849,11 @@ fn convert(v: Value, ty: FieldType) -> (Value, Cut, Option) { // A word the decimal reader takes ("inf", "NaN") isn't a number written as text: // null, and said so, as not a number. // A fraction the decimal rounded away (`2.0000000000000000001e0`) is still one. + // A fraction the decimal rounded away (`2.0000000000000000001e0`) is still one, and + // digits past those it holds (`9007199254740993e0`) are rounded. (None, Ok(f)) if f.is_finite() || t.bytes().any(|b| b.is_ascii_digit()) => match whole(f) { (v @ Value::Int(_), Cut::None, x) if Value::text_has_fraction(&t) => (v, Cut::Fraction, x), + (v @ Value::Int(_), Cut::None, x) if !rustgis_data::io::double_holds(t.trim()) => (v, Cut::Rounded, x), held => held, }, (None, Ok(f)) if f.is_infinite() => (Value::Null, Cut::NotFinite, None), @@ -848,6 +868,10 @@ fn convert(v: Value, ty: FieldType) -> (Value, Cut, Option) { (Value::Float(f), FieldType::Boolean) if f.fract() == 0.0 => (Value::Bool(f != 0.0), Cut::None, None), // A fraction is no yes/no value: null, not the text it's shown as (`0.0000001` shows `0`). (Value::Float(_), FieldType::Boolean) => (Value::Null, Cut::None, None), + (Value::Text(t), FieldType::Double) => match Value::parse_source(&t, ty) { + v @ Value::Float(_) if Value::Text(t).rounds_as_double() => (v, Cut::Rounded, None), + v => (v, Cut::None, None), + }, // Uncounted coercion retains source numbers until output can explain any loss. (Value::Text(t), _) => (Value::parse_source(&t, ty), Cut::None, None), (other, _) => (Value::parse(&other.to_string(), ty), Cut::None, None), @@ -931,12 +955,15 @@ fn numeric_loss(input: &Value, v: &Value, ty: FieldType) -> Option { "{layer}, field '{field}', row {row}: 1 attribute value was clamped to the 64-bit integer range", LossCode::DroppedValue, )), + Cut::Rounded => { + Some(("{layer}, field '{field}', row {row}: 1 attribute value lost integer precision", LossCode::ChangedRounded)) + } Cut::None if &exact != v => { Some(("{layer}, field '{field}', row {row}: 1 attribute value lost integer precision", LossCode::ChangedRounded)) } _ => None, } - } else if ty == FieldType::Double && matches!(v, Value::Float(_)) && input.rounds_as_double() { + } else if ty == FieldType::Double && matches!(v, Value::Float(_)) && coerce_cut(input.clone(), ty).1 == Cut::Rounded { Some(("{layer}, field '{field}', row {row}: 1 attribute value was rounded to the digits a decimal holds", LossCode::ChangedRounded)) } else { None diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 990736e950..dd78009f98 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -1588,7 +1588,9 @@ fn a_default_its_field_cant_hold_as_given_is_refused_when_set() { } let err = s.run("edit.template", &json!({"layer": "Cities", "name": "T", "defaults": {"x": 9_007_199_254_740_993_i64}})).unwrap_err(); assert_eq!(err, "field 'x': a Double field can't hold '9007199254740993' as given"); - for (field, text) in [("x", "9007199254740993.0"), ("x", "12345678901234567890"), ("n", "1.00000000000000001e0")] { + for (field, text) in + [("x", "9007199254740993.0"), ("x", "12345678901234567890"), ("n", "1.00000000000000001e0"), ("n", "9007199254740993e0")] + { let err = s.run("edit.template", &json!({"layer": "Cities", "name": "T", "defaults": {field: text}})).unwrap_err(); assert_eq!(err, format!("field '{field}': a {} field can't hold '{text}' as given", if field == "n" { "Long" } else { "Double" })); } @@ -1600,6 +1602,8 @@ fn a_default_its_field_cant_hold_as_given_is_refused_when_set() { ("x", json!(0.1), None), ("n", json!("2.0000000000000000001e0"), Some(rustgis_data::loss::LossCode::ChangedTruncated)), ("n", json!("1e3"), None), + ("n", json!("9007199254740993e0"), Some(rustgis_data::loss::LossCode::ChangedRounded)), + ("n", json!("9007199254740992e0"), None), ] { let mark = s.notice_mark(); s.run("edit.setValue", &json!({"layer": "Cities", "row": 0, "field": field, "value": value})).unwrap(); @@ -1629,6 +1633,26 @@ fn a_default_its_field_cant_hold_as_given_is_refused_when_set() { let ds = &s.map().layer_by_name("Cities").unwrap().dataset; assert_eq!(ds.value(0, ds.field_index("note").unwrap()), &V::Text("0.1234567".into()), "edit.setValue too"); s.run("edit.undo", &Value::Null).unwrap(); + // Calculate Field and Paste say what a decimal field rounds; exact values say nothing. + // (A number written in an expression is read as a decimal when it is parsed, so text stands in.) + for (expression, said) in + [("'9007199254740993.0'", true), ("'9007199254740993'", true), ("'9007199254740992.0'", false), ("0.1", false)] + { + let mark = s.notice_mark(); + s.run("edit.calculateField", &json!({"layer": "Cities", "field": "x", "expression": expression})).unwrap(); + let codes: Vec<_> = s.notices_since(mark).iter().filter_map(|n| n.loss()).collect(); + assert_eq!(codes.contains(&rustgis_data::loss::LossCode::ChangedRounded), said, "{expression}: {:?}", s.notices_since(mark)); + s.run("edit.undo", &Value::Null).unwrap(); + } + for (x, said) in [(json!(9_007_199_254_740_993_i64), true), (json!(0.1), false)] { + let feature = json!({"type": "Feature", "geometry": {"type": "Point", "coordinates": [0.0, 0.0]}, "properties": {"x": x}}); + let text = json!({"type": "FeatureCollection", "features": [feature]}).to_string(); + let mark = s.notice_mark(); + s.run("edit.paste", &json!({"layer": "Cities", "text": text})).unwrap(); + let codes: Vec<_> = s.notices_since(mark).iter().filter_map(|n| n.loss()).collect(); + assert_eq!(codes.contains(&rustgis_data::loss::LossCode::ChangedRounded), said, "{x}: {:?}", s.notices_since(mark)); + s.run("edit.undo", &Value::Null).unwrap(); + } s.run("edit.calculateField", &json!({"layer": "Cities", "field": "note", "expression": "0.1234567"})).unwrap(); let ds = &s.map().layer_by_name("Cities").unwrap().dataset; assert_eq!(ds.value(0, ds.field_index("note").unwrap()), &V::Text("0.1234567".into()), "Calculate Field too"); diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 9d0f895cb4..11eacb6133 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -3480,6 +3480,7 @@ fn calculation_preview(rows: &[rustgis_engine::cmd::edit::CalculationPreview]) - PreviewLoss::NotANumber => tl_raw!("not a number"), PreviewLoss::NotFinite => tl_raw!("not a finite number"), PreviewLoss::Time => tl_raw!("time dropped"), + PreviewLoss::Rounded => tl_raw!("rounded"), PreviewLoss::Unheld => tl_raw!("not a value the field holds"), // The phrases the run's notices give for the same errors. PreviewLoss::Error(fault) => tl_raw!(fault.describe()), From ce68c0755cf6dcbe7b662ef5a417046ad029ff25 Mon Sep 17 00:00:00 2001 From: mavrick Date: Thu, 26 Nov 2026 19:26:26 -0600 Subject: [PATCH 6/6] fix(data): a GeoPackage export writes yes/no fields as yes or no, and says the rest Value::as_yes_no reads any value as a yes/no field holds it: a whole number is yes unless it is 0, text a yes/no word. The GeoPackage writer writes a yes/no field's values by it, so 2.0 is yes rather than empty, and an export says the values that are neither (0.5, maybe), written empty, as dropped.value. --- crates/data/src/io.rs | 27 +++++++++++++++++++++++++++ crates/data/src/source/gpkg.rs | 3 +++ crates/data/src/source/tests.rs | 20 ++++++++++++++++++++ crates/data/src/value.rs | 13 +++++++++++++ crates/engine/src/cmd/share.rs | 14 +++++++++++--- 5 files changed, 74 insertions(+), 3 deletions(-) diff --git a/crates/data/src/io.rs b/crates/data/src/io.rs index 81a6101322..d84245a2e6 100644 --- a/crates/data/src/io.rs +++ b/crates/data/src/io.rs @@ -4911,6 +4911,33 @@ pub fn text_in_dates<'a>(features: impl IntoIterator, counts } +/// For each field, how many values a GeoPackage export writes empty in a yes/no field, as they +/// aren't yes or no ([`Value::as_yes_no`]): `0.5`, `maybe`, a date. Null and empty text aren't counted. +pub fn unheld_yes_no(ds: &Dataset) -> Vec { + let mut counts = vec![0usize; ds.fields.len()]; + for f in &ds.features { + for ((n, field), v) in counts.iter_mut().zip(&ds.fields).zip(&f.attrs) { + *n += usize::from(field.ty == FieldType::Boolean && !v.asks_null() && v.as_yes_no().is_none()); + } + } + counts +} + +/// What a GeoPackage export to `target` says of the values it wrote empty in yes/no fields +/// ([`unheld_yes_no`]). `None` when there was none. +pub fn unheld_yes_no_note(fields: &[Field], counts: &[usize], target: &str) -> Option { + let total: usize = counts.iter().sum(); + if total == 0 { + return None; + } + let target: String = target.chars().map(dbf_notice_char).collect(); + let what = if total == 1 { "1 value isn't yes or no and was".to_string() } else { format!("{total} values aren't yes or no and were") }; + Some(crate::loss::Note::loss( + crate::loss::LossCode::DroppedValue, + format!("{target}: {what} written empty, in {}", named_fields(fields, counts)), + )) +} + /// What a GeoPackage export to `target` says of the text it wrote in date fields /// ([`text_in_dates`]). `None` when there was none. pub fn text_in_dates_note(fields: &[Field], counts: &[usize], target: &str) -> Option { diff --git a/crates/data/src/source/gpkg.rs b/crates/data/src/source/gpkg.rs index e6d0fcc0f8..1f1819b37a 100644 --- a/crates/data/src/source/gpkg.rs +++ b/crates/data/src/source/gpkg.rs @@ -1429,6 +1429,9 @@ fn sql_value(v: &Value, ty: FieldType) -> rusqlite::types::Value { use rusqlite::types::Value as Sql; match (v, ty) { (Value::Null, _) => Sql::Null, + // A yes/no field holds a yes/no value, read as a yes/no field reads one; other values are + // null, as `io::unheld_yes_no` counts them. + (v, FieldType::Boolean) => v.as_yes_no().map_or(Sql::Null, |b| Sql::Integer(i64::from(b))), (Value::Int(x), _) => Sql::Integer(*x), (Value::Float(x), _) if x.is_finite() => Sql::Real(*x), (Value::Float(_), _) => Sql::Null, diff --git a/crates/data/src/source/tests.rs b/crates/data/src/source/tests.rs index 0d430efe91..c40118737b 100644 --- a/crates/data/src/source/tests.rs +++ b/crates/data/src/source/tests.rs @@ -4091,6 +4091,26 @@ fn geopackage_yes_no_text_that_isnt_yes_or_no_is_said() { let code = Some(crate::loss::LossCode::DroppedValue); assert_eq!(said, [("gates: 1 value isn't yes or no and was read as empty, in 'open'".to_string(), code)]); } + // An export writes a yes/no field's values as a yes/no field reads them, and counts the rest. + let mut odd = Dataset::new("odd", GeometryType::Point, vec![Field::new("open", FieldType::Boolean)]); + for v in [Value::Float(2.0), Value::Float(0.5), Value::Text("no".into()), Value::Text("maybe".into()), Value::Null] { + odd.push(Some(Geometry::Point(Coord::new(1.0, 2.0))), vec![v]); + } + let counts = crate::io::unheld_yes_no(&odd); + assert_eq!( + crate::io::unheld_yes_no_note(&odd.fields, &counts, "odd.gpkg").map(|n| (n.text, n.loss)), + Some(( + "odd.gpkg: 2 values aren't yes or no and were written empty, in 'open'".to_string(), + Some(crate::loss::LossCode::DroppedValue) + )) + ); + let clean = crate::io::unheld_yes_no(&gates); + assert_eq!(crate::io::unheld_yes_no_note(&gates.fields, &clean, "gates.gpkg"), None); + let odd_path = workspace.path().join("odd.gpkg"); + crate::io::write_path(&odd, &odd_path).unwrap(); + let (ds, _) = materialize(open_path(&odd_path, None).unwrap().as_ref()).unwrap(); + let values: Vec = ds.features.iter().map(|f| f.attrs[0].clone()).collect(); + assert_eq!(values, [Value::Bool(true), Value::Null, Value::Bool(false), Value::Null, Value::Null]); for (values, said) in read("t") { assert_eq!(values, [Value::Bool(true), Value::Bool(false), Value::Bool(true), Value::Null]); assert!(said.is_empty(), "{said:?}"); diff --git a/crates/data/src/value.rs b/crates/data/src/value.rs index eea3dcf490..0d73521ce8 100644 --- a/crates/data/src/value.rs +++ b/crates/data/src/value.rs @@ -282,6 +282,19 @@ impl Value { } } + /// The yes/no value this value is, as a yes/no field holds it: a yes/no as it is, a whole + /// number yes unless it is 0, text one of the [`yes_no`](Value::yes_no) words; anything else + /// (`0.5`, `maybe`, a date, null) is neither. + pub fn as_yes_no(&self) -> Option { + match self { + Value::Bool(b) => Some(*b), + Value::Int(i) => Some(*i != 0), + Value::Float(f) if f.is_finite() && f.fract() == 0.0 => Some(*f != 0.0), + Value::Text(t) => Value::yes_no(t), + _ => None, + } + } + /// The yes/no value text says, ignoring case and spaces around it: `true`, `t`, `yes`, `y` and /// `1` are true; `false`, `f`, `no`, `n` and `0` are false; other text is neither. pub fn yes_no(text: &str) -> Option { diff --git a/crates/engine/src/cmd/share.rs b/crates/engine/src/cmd/share.rs index 23e32916bb..68ff574617 100644 --- a/crates/engine/src/cmd/share.rs +++ b/crates/engine/src/cmd/share.rs @@ -665,10 +665,13 @@ pub fn coalesce_read_zm(notes: &mut rustgis_data::loss::Notes, file: &str, ds: & } /// What a GeoPackage export of `ds` says of its dates: date-times written in UTC, and text in -/// date fields that isn't a date, and rounded to the millisecond; for a FlatGeobuf, its date fields with no values. Nothing for +/// date fields that isn't a date, and rounded to the millisecond, and of values in yes/no fields +/// that aren't yes or no, written empty; for a FlatGeobuf, its date fields with no values. Nothing for /// another format, or when there was none. pub fn gpkg_dates_note(ds: &rustgis_data::Dataset, ext: &str, path: &str) -> Vec { - use rustgis_data::io::{fine_dates, fine_dates_note, offset_dates, text_in_dates, text_in_dates_note, utc_dates_note}; + use rustgis_data::io::{ + fine_dates, fine_dates_note, offset_dates, text_in_dates, text_in_dates_note, unheld_yes_no, unheld_yes_no_note, utc_dates_note, + }; if ext == "fgb" { return rustgis_data::io::fgb_empty_dates_note(&ds.fields, &rustgis_data::io::written_values(ds.features.iter(), &ds.fields), path) .map(rustgis_data::loss::Note::plain) @@ -680,7 +683,12 @@ pub fn gpkg_dates_note(ds: &rustgis_data::Dataset, ext: &str, path: &str) -> Vec } let utc = utc_dates_note(&ds.fields, &offset_dates(ds.features.iter(), &ds.fields), path); let fine = fine_dates_note(&ds.fields, &fine_dates(ds.features.iter(), &ds.fields), path); - utc.into_iter().chain(fine).chain(text_in_dates_note(&ds.fields, &text_in_dates(ds.features.iter(), &ds.fields), path)).collect() + let yes_no = unheld_yes_no_note(&ds.fields, &unheld_yes_no(ds), path); + utc.into_iter() + .chain(fine) + .chain(text_in_dates_note(&ds.fields, &text_in_dates(ds.features.iter(), &ds.fields), path)) + .chain(yes_no) + .collect() } /// Writes layer `l` to `path`, in `asked` or the system the format defaults to (the project's,