From a95444b8d01e17f37ae39db6cb00270eb3f68d08 Mon Sep 17 00:00:00 2001 From: mavrick Date: Fri, 27 Nov 2026 14:27:47 -0600 Subject: [PATCH 01/12] fix(data): number literals in expressions are exact or refused, and GeoPackage values that don't fit a number field are said --- crates/data/src/query.rs | 36 ++++++++++-- crates/data/src/query/complete.rs | 6 +- crates/data/src/query/tests.rs | 18 ++++++ crates/data/src/source/gpkg.rs | 15 +++-- crates/data/src/source/gpkg_mem.rs | 15 +++-- crates/data/src/source/mod.rs | 89 +++++++++++++++++++++++++----- crates/data/src/source/tests.rs | 62 +++++++++++++++++++++ docs/user-guide/expressions.md | 2 +- 8 files changed, 211 insertions(+), 32 deletions(-) diff --git a/crates/data/src/query.rs b/crates/data/src/query.rs index 982d4e0e9e..08386887d1 100644 --- a/crates/data/src/query.rs +++ b/crates/data/src/query.rs @@ -590,6 +590,8 @@ enum Tok { QuotedIdent(String), Str(String), Num(f64), + /// A whole-number literal (digits only) that an `i64` holds: exact, never via a float. + Int(i64), /// A comparison operator. Op(String), Arith(Arith), @@ -777,7 +779,7 @@ fn lex_first(s: &str, tolerant: bool, most: usize) -> Result { } } let t: String = cs.get(st..i).map(|s| s.iter().collect()).unwrap_or_default(); - out.push(Tok::Num(t.parse().map_err(|_| format!("bad number '{t}'"))?)); + out.push(number_token(&t)?); } '@' | '$' => { i += 1; @@ -798,6 +800,27 @@ fn lex_first(s: &str, tolerant: bool, most: usize) -> Result { Ok(Lexed { toks: out, spans, open }) } +/// The token of a number literal, refusing one that can't be held exactly rather than rounding it. +/// A literal of digits only is an exact `i64`, or refused past `i64::MAX`. Any other literal is a +/// decimal (`f64`), refused only when it would lose its whole-number digits: it has 16 or more +/// of them and a decimal doesn't hold its digits (`9007199254740993.0`). One that merely has no +/// exact binary form (`0.1`) or many fraction digits (`0.12345678901234567891`) is read as the +/// nearest decimal, as every number written in decimal is. +fn number_token(t: &str) -> Result { + if t.bytes().all(|b| b.is_ascii_digit()) { + return t.parse::().map(Tok::Int).map_err(|_| { + format!("the whole number {t} is too large to hold exactly (the most is {}); write it as a decimal, such as 1e19", i64::MAX) + }); + } + let n: f64 = t.parse().map_err(|_| format!("bad number '{t}'"))?; + let mantissa = t.split(['e', 'E']).next().unwrap_or_default(); + let whole = mantissa.split('.').next().unwrap_or_default().trim_start_matches('0'); + if whole.len() >= 16 && n.is_finite() && Value::Text(t.to_string()).rounds_as_double() { + return Err(format!("the number {t} has more digits than a decimal number holds exactly, so it would be rounded")); + } + Ok(Tok::Num(n)) +} + /// A number literal: whole numbers are integers. fn num(n: f64) -> Value { if n.fract() == 0.0 && n.abs() < 9e15 { Value::Int(n as i64) } else { Value::Float(n) } @@ -1089,9 +1112,10 @@ impl Parser<'_> { /// `1 IN (1 IN (…))` meets the limit. fn item(&mut self) -> Result { let sign = usize::from(matches!(self.toks.get(self.pos), Some(Tok::Arith(Arith::Add | Arith::Sub)))); - let single = - matches!(self.toks.get(self.pos + sign), Some(Tok::Num(_) | Tok::Str(_) | Tok::Ident(_) | Tok::QuotedIdent(_) | Tok::Var(_))) - && matches!(self.toks.get(self.pos + sign + 1), Some(Tok::Comma | Tok::RParen)); + let single = matches!( + self.toks.get(self.pos + sign), + Some(Tok::Num(_) | Tok::Int(_) | Tok::Str(_) | Tok::Ident(_) | Tok::QuotedIdent(_) | Tok::Var(_)) + ) && matches!(self.toks.get(self.pos + sign + 1), Some(Tok::Comma | Tok::RParen)); if single { return self.unary(); } @@ -1225,7 +1249,7 @@ impl Parser<'_> { }; self.pos += 1; // A sign before a number is part of the literal and nests nothing. - let nests = !matches!(self.toks.get(self.pos), Some(Tok::Num(_))); + let nests = !matches!(self.toks.get(self.pos), Some(Tok::Num(_) | Tok::Int(_))); if nests { self.deeper()?; } @@ -1299,6 +1323,7 @@ impl Parser<'_> { // A number too large to represent (`1e999`) would be infinity, which nothing reads. Some(Tok::Num(n)) if n.is_finite() => Ok(Expr::Lit(num(n))), Some(Tok::Num(_)) => Err("the number is too large".into()), + Some(Tok::Int(i)) => Ok(Expr::Lit(Value::Int(i))), Some(Tok::Str(s)) => Ok(Expr::Lit(Value::Text(s))), Some(Tok::QuotedIdent(s)) => self.field(&s), Some(Tok::Var(v)) => match VARS.iter().find(|s| s.names.iter().any(|n| n.eq_ignore_ascii_case(&v))).map(|s| s.var) { @@ -1441,6 +1466,7 @@ fn show(t: Option<&Tok>) -> String { Some(Tok::QuotedIdent(s)) => format!("\"{s}\""), Some(Tok::Str(s)) => format!("'{s}'"), Some(Tok::Num(n)) => n.to_string(), + Some(Tok::Int(i)) => i.to_string(), Some(Tok::Op(o)) => format!("'{o}'"), Some(Tok::Arith(a)) => format!( "'{}'", diff --git a/crates/data/src/query/complete.rs b/crates/data/src/query/complete.rs index 0787ff009e..b4ca779c39 100644 --- a/crates/data/src/query/complete.rs +++ b/crates/data/src/query/complete.rs @@ -188,9 +188,9 @@ pub fn follows(text: &str) -> Follows { let joins = [Kw::And, Kw::Or, Kw::When, Kw::Then, Kw::Else, Kw::End]; let is = |word: &str, kws: &[Kw]| kws.iter().any(|k| k.word().eq_ignore_ascii_case(word)); match toks.into_iter().next() { - Some(Tok::Str(_) | Tok::QuotedIdent(_) | Tok::Num(_) | Tok::Var(_) | Tok::LParen | Tok::Arith(Arith::Add | Arith::Sub)) => { - Follows::Value - } + Some( + Tok::Str(_) | Tok::QuotedIdent(_) | Tok::Num(_) | Tok::Int(_) | Tok::Var(_) | Tok::LParen | Tok::Arith(Arith::Add | Arith::Sub), + ) => Follows::Value, Some(Tok::Op(_)) => Follows::Comparison, Some(Tok::Concat | Tok::Arith(_)) => Follows::Operator, Some(Tok::Ident(word)) if is(&word, &left_side) => Follows::Comparison, diff --git a/crates/data/src/query/tests.rs b/crates/data/src/query/tests.rs index 58e005836a..d9d751f9c7 100644 --- a/crates/data/src/query/tests.rs +++ b/crates/data/src/query/tests.rs @@ -66,6 +66,24 @@ fn v(text: &str) -> Value { value(&parse(text, &d).unwrap_or_else(|e| panic!("{text}: {e}")), &d, 0, &Env { map_scale: Some(25_000.0), ..Env::default() }) } +#[test] +fn number_literals_are_exact_or_refused() { + let d = ds(); + assert_eq!(v("9007199254740993"), Value::Int(9_007_199_254_740_993)); + assert_eq!(v(&i64::MAX.to_string()), Value::Int(i64::MAX)); + assert_eq!(v("-9007199254740993"), Value::Int(-9_007_199_254_740_993)); + assert_eq!(select("pop > 9007199254740993", &d).unwrap(), Vec::::new()); + for text in ["9223372036854775808", "99999999999999999999", "9007199254740993.0", "9007199254740993.5", "12345678901234567000.0"] { + assert!(parse(text, &d).is_err_and(|e| e.contains("exact") || e.contains("rounded")), "{text}"); + } + assert_eq!(v("0.1"), Value::Float(0.1)); + assert_eq!(v("2.5"), Value::Float(2.5)); + assert_eq!(v("1e3"), Value::Int(1000)); + assert_eq!(v("1.5e3"), Value::Int(1500)); + assert_eq!(v("9007199254740992.0"), Value::Float(9_007_199_254_740_992.0)); + assert_eq!(v("0.12345678901234567891"), Value::Float(0.123_456_789_012_345_68)); +} + fn t(s: &str) -> Value { Value::Text(s.into()) } diff --git a/crates/data/src/source/gpkg.rs b/crates/data/src/source/gpkg.rs index 106c65959a..832eeb3622 100644 --- a/crates/data/src/source/gpkg.rs +++ b/crates/data/src/source/gpkg.rs @@ -1573,8 +1573,9 @@ fn to_millisecond(t: crate::date::DateTime) -> crate::date::DateTime { } /// An attribute value of a field's type, for the field `k`. One a date field can't hold is null, -/// and counted in `unread` ([`Batch::unread_dates`]); with `rounded`, a date-time with digits past -/// the microsecond is rounded and counted there ([`Batch::rounded_dates`]), else it isn't a date. +/// and counted in `unread` ([`Batch::unread_dates`]): text that isn't a number in a number field, +/// a blob. With `rounded`, a date-time with digits past the microsecond, or a whole number past 2^53 +/// in a Double field, is rounded and counted there ([`Batch::rounded_dates`]), else the date-time isn't a date. fn value(v: ValueRef<'_>, ty: FieldType, unread: &mut Vec, rounded: Option<&mut Vec>, k: usize) -> Value { match (v, ty) { (ValueRef::Null, _) => Value::Null, @@ -1583,14 +1584,18 @@ fn value(v: ValueRef<'_>, ty: FieldType, unread: &mut Vec, rounded: Optio super::gpkg_blob::temporal(text.as_deref(), ty, unread, rounded, k) } (ValueRef::Integer(i), FieldType::Boolean) => Value::Bool(i != 0), - (ValueRef::Integer(i), FieldType::Double) => Value::Float(i as f64), + (ValueRef::Integer(i), FieldType::Double) => super::int_as_double(i, rounded, k), (ValueRef::Integer(i), _) => Value::Int(i), (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, + (ValueRef::Text(t), ty) => super::number_text(&String::from_utf8_lossy(t), ty, unread, k), + // A blob isn't a value an attribute column holds. + (ValueRef::Blob(_), _) => { + super::unread_date(unread, k); + Value::Null + } } } diff --git a/crates/data/src/source/gpkg_mem.rs b/crates/data/src/source/gpkg_mem.rs index 483c41038d..6cda37e1c7 100644 --- a/crates/data/src/source/gpkg_mem.rs +++ b/crates/data/src/source/gpkg_mem.rs @@ -320,23 +320,28 @@ impl GpkgMemSource { } /// An attribute value of a field's type, for the field `k`. One a date field can't hold is null, -/// and counted in `unread` ([`Batch::unread_dates`]); a date-time with digits past the microsecond -/// is rounded and counted in `rounded` ([`Batch::rounded_dates`]). +/// and counted in `unread` ([`Batch::unread_dates`]): text that isn't a number in a number field, +/// a blob. A date-time with digits past the microsecond, or a whole number past 2^53 in a Double +/// field, is rounded and counted in `rounded` ([`Batch::rounded_dates`]). fn value(v: &Val, ty: FieldType, unread: &mut Vec, rounded: &mut Vec, k: usize) -> Value { match (v, ty) { (Val::Null, _) => Value::Null, (v, FieldType::Date | FieldType::DateTime) => { super::gpkg_blob::temporal(if let Val::Text(t) = v { Some(t) } else { None }, ty, unread, Some(rounded), k) } - (Val::Blob(_), _) => Value::Null, (Val::Int(i), FieldType::Boolean) => Value::Bool(*i != 0), - (Val::Int(i), FieldType::Double) => Value::Float(*i as f64), + (Val::Int(i), FieldType::Double) => super::int_as_double(*i, Some(rounded), k), (Val::Int(i), _) => Value::Int(*i), (Val::Real(f), FieldType::Integer) if f.fract() == 0.0 && f.abs() < 9e15 => 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), + (Val::Text(t), ty) => super::number_text(t, ty, unread, k), + // A blob isn't a value an attribute column holds. + (Val::Blob(_), _) => { + super::unread_date(unread, k); + Value::Null + } } } diff --git a/crates/data/src/source/mod.rs b/crates/data/src/source/mod.rs index 3af146d1ac..854d3f498b 100644 --- a/crates/data/src/source/mod.rs +++ b/crates/data/src/source/mod.rs @@ -301,6 +301,29 @@ pub(crate) fn yes_no_text(text: &str, counts: &mut Vec, k: usize) -> crat v } +/// The value of the number field at `k` (`ty` Integer or Double) from a file's text +/// ([`crate::Value::parse_source`]): text that isn't a number is null, counted in `counts` +/// ([`Batch::unread_dates`]), which says it as a value that isn't a number ([`unread_dates_note`]). +/// Empty text and `` are null, uncounted. +pub(crate) fn number_text(text: &str, ty: crate::FieldType, counts: &mut Vec, k: usize) -> crate::Value { + let v = crate::Value::parse_source(text, ty); + if v.is_null() && !text.trim().is_empty() && !crate::Value::is_null_marker(text) { + unread_date(counts, k); + } + v +} + +/// The decimal value of a whole number stored in a Double field at `k`: counted in `rounded` +/// ([`Batch::rounded_dates`]) when a decimal can't hold it exactly (past 2^53). +pub(crate) fn int_as_double(i: i64, rounded: Option<&mut Vec>, k: usize) -> crate::Value { + if let Some(rounded) = rounded + && crate::Value::Int(i).rounds_as_double() + { + unread_date(rounded, k); + } + crate::Value::Float(i as f64) +} + /// 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); @@ -352,14 +375,34 @@ 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"), + // Fields of other types count values too: text that isn't yes or no ([`yes_no_text`]), text or a + // blob that isn't a number ([`number_text`]), a blob. + let mut kinds: Vec<&str> = Vec::new(); + for (f, _) in fields.iter().zip(counts).filter(|(_, n)| **n > 0) { + let kind = match f.ty { + crate::FieldType::Boolean => "yes/no values", + crate::FieldType::Integer | crate::FieldType::Double => "numbers", + // A text field counts dates a mixed column held ([`crate::sheets`]), and a blob. + crate::FieldType::Text | crate::FieldType::Date | crate::FieldType::DateTime => "dates", + }; + if !kinds.contains(&kind) { + kinds.push(kind); + } + } + // Dates first, as a read of dates alone always said, then the rest in a fixed order. + kinds.sort_by_key(|k| ["dates", "yes/no values", "numbers"].iter().position(|n| n == k)); + let what = match (kinds.as_slice(), total == 1) { + ([], true) | (["dates"], true) => "1 value isn't a date and was".to_string(), + ([], false) | (["dates"], false) => format!("{total} values aren't dates and were"), + (["yes/no values"], true) => "1 value isn't yes or no and was".to_string(), + (["yes/no values"], false) => format!("{total} values aren't yes or no and were"), + (["numbers"], true) => "1 value isn't a number and was".to_string(), + (["numbers"], false) => format!("{total} values aren't numbers and were"), + (kinds, _) => { + let (last, first) = kinds.split_last().map_or(("", &[][..]), |(l, f)| (*l, f)); + let list = if first.is_empty() { last.to_string() } else { format!("{} or {last}", first.join(", ")) }; + format!("{total} values aren't {list} 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)) @@ -399,16 +442,36 @@ pub fn not_utf8_note(fields: &[crate::Field], counts: &[usize], encoding: &str) Some(crate::loss::Note::loss(crate::loss::LossCode::ChangedEncoding, text)) } -/// What a read says of date-times it rounded to the microsecond ([`Batch::rounded_dates`]), naming -/// the first five fields. `None` when there were none. +/// What a read says of values it rounded ([`Batch::rounded_dates`]): date-times to the microsecond, +/// whole numbers past 2^53 to the nearest decimal number a Double field holds. Names the first five +/// fields. `None` when there were none. pub fn rounded_dates_note(fields: &[crate::Field], counts: &[usize]) -> Option { let total: usize = counts.iter().sum(); if total == 0 { return None; } - let what = if total == 1 { "1 date-time was".to_string() } else { format!("{total} date-times were") }; - let text = - format!("{what} rounded to the microsecond, as more digits than that aren't kept, in {}", crate::io::named_fields(fields, counts)); + let counted = |numbers: bool| fields.iter().zip(counts).any(|(f, n)| *n > 0 && (f.ty == crate::FieldType::Double) == numbers); + let (numbers, dates) = (counted(true), counted(false)); + let text = match (numbers, dates) { + (true, true) => format!( + "{total} values were rounded, date-times to the microsecond and whole numbers to the nearest decimal number, as more digits than that aren't kept, in {}", + crate::io::named_fields(fields, counts) + ), + (true, false) => { + let what = if total == 1 { "1 whole number was".to_string() } else { format!("{total} whole numbers were") }; + format!( + "{what} rounded to the nearest decimal number, as a decimal field doesn't keep more than 15 or 16 digits, in {}", + crate::io::named_fields(fields, counts) + ) + } + _ => { + let what = if total == 1 { "1 date-time was".to_string() } else { format!("{total} date-times were") }; + format!( + "{what} rounded to the microsecond, as more digits than that aren't kept, in {}", + crate::io::named_fields(fields, counts) + ) + } + }; Some(crate::loss::Note::loss(crate::loss::LossCode::ChangedRounded, text)) } diff --git a/crates/data/src/source/tests.rs b/crates/data/src/source/tests.rs index 35daae1eeb..4ad086ea0b 100644 --- a/crates/data/src/source/tests.rs +++ b/crates/data/src/source/tests.rs @@ -4095,6 +4095,68 @@ fn geopackage_writes_fine_date_time_text_as_a_date_time() { assert_eq!(stored, "2026-03-05T14:30:00.123Z"); } +/// Text or a blob another program left in a GeoPackage number column, and a whole number past 2^53 +/// in a decimal column, read as empty or rounded and said, on the desktop and in the browser; a +/// clean file says nothing. +#[test] +fn geopackage_values_that_dont_fit_a_number_field_are_said() { + let workspace = tempfile::tempdir().unwrap(); + let path = workspace.path().join("t.gpkg"); + let mut t = Dataset::new("t", GeometryType::Point, vec![Field::new("pop", FieldType::Integer), Field::new("area", FieldType::Double)]); + for (p, a) in [(1, 1.5), (2, 2.5), (3, 3.5), (4, 4.5)] { + t.push(Some(Geometry::Point(Coord::new(1.0, 2.0))), vec![Value::Int(p), Value::Float(a)]); + } + crate::io::write_path(&t, &path).unwrap(); + let read = || { + 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.clone()).collect(); + let said: Vec<_> = report.messages.iter().map(|n| (n.text.clone(), n.loss)).collect(); + (values, said) + }) + }; + for (_, said) in read() { + assert_eq!(said, []); + } + 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(); + } + // NUMERIC reads as a decimal field and keeps a whole number as one. + c.execute("ALTER TABLE t ADD COLUMN big NUMERIC", []).unwrap(); + c.execute("UPDATE t SET big = 9007199254740993 WHERE fid = 1", []).unwrap(); + c.execute("UPDATE t SET big = 5 WHERE fid = 2", []).unwrap(); + c.execute("UPDATE t SET pop = 'n/a', area = 'n/a' WHERE fid = 2", []).unwrap(); + c.execute("UPDATE t SET pop = x'00ff', area = x'00' WHERE fid = 3", []).unwrap(); + c.execute("UPDATE t SET pop = '', area = '' WHERE fid = 4", []).unwrap(); + drop(c); + for (values, said) in read() { + assert_eq!(values[0], [Value::Int(1), Value::Float(1.5), Value::Float(9_007_199_254_740_992.0)]); + assert_eq!(values[1], [Value::Null, Value::Null, Value::Float(5.0)]); + assert_eq!(values[2], [Value::Null, Value::Null, Value::Null]); + assert_eq!(values[3], [Value::Null, Value::Null, Value::Null]); + let dropped = Some(crate::loss::LossCode::DroppedValue); + let rounded = Some(crate::loss::LossCode::ChangedRounded); + assert_eq!( + said, + [ + ("t: 4 values aren't numbers and were read as empty, in 'pop', 'area'".to_string(), dropped), + ("t: 1 whole number was rounded to the nearest decimal number, as a decimal field doesn't keep more than 15 or 16 digits, in 'big'".to_string(), rounded), + ] + ); + } +} + /// 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] diff --git a/docs/user-guide/expressions.md b/docs/user-guide/expressions.md index ce69221c90..f2df711054 100644 --- a/docs/user-guide/expressions.md +++ b/docs/user-guide/expressions.md @@ -79,7 +79,7 @@ operator: write `a < b AND b < c`, not `a < b < c`. | Write | Meaning | | --- | --- | -| `42`, `3.5`, `1e6`, `.5` | Numbers; whole numbers are integers | +| `42`, `3.5`, `1e6`, `.5` | Numbers; whole numbers are integers, exact up to 9223372036854775807. A number that would be rounded (a whole number past that, or `9007199254740993.0`) is refused, not rounded | | `'text'`, `'it''s'` | Text in single quotes; two quotes stand for one | | `TRUE`, `FALSE`, `NULL` | Booleans and the missing value | | `pop_est`, `"Pop Est"`, `!Pop Est!` | A field, by name, ignoring letter case; quote a name with spaces, punctuation or the name of a keyword (`"OR"`, `"null"`) | From 7b1c758b2cd8c4ff50262d27cdd26c91b1be81df Mon Sep 17 00:00:00 2001 From: mavrick Date: Fri, 27 Nov 2026 14:39:32 -0600 Subject: [PATCH 02/12] fix(data): a GeoPackage blob in a text column is read as its text --- crates/data/src/source/gpkg.rs | 4 +++- crates/data/src/source/gpkg_mem.rs | 4 +++- crates/data/src/source/mod.rs | 2 +- crates/data/src/source/tests.rs | 11 +++++++---- 4 files changed, 14 insertions(+), 7 deletions(-) diff --git a/crates/data/src/source/gpkg.rs b/crates/data/src/source/gpkg.rs index 832eeb3622..7d92d90d75 100644 --- a/crates/data/src/source/gpkg.rs +++ b/crates/data/src/source/gpkg.rs @@ -1591,7 +1591,9 @@ fn value(v: ValueRef<'_>, ty: FieldType, unread: &mut Vec, rounded: Optio (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) => super::number_text(&String::from_utf8_lossy(t), ty, unread, k), - // A blob isn't a value an attribute column holds. + // A blob in a text column is its text, as SQLite stores text either way. + (ValueRef::Blob(b), FieldType::Text) => Value::Text(String::from_utf8_lossy(b).into_owned()), + // A blob isn't a value another attribute column holds. (ValueRef::Blob(_), _) => { super::unread_date(unread, k); Value::Null diff --git a/crates/data/src/source/gpkg_mem.rs b/crates/data/src/source/gpkg_mem.rs index 6cda37e1c7..3f2fe6a5c9 100644 --- a/crates/data/src/source/gpkg_mem.rs +++ b/crates/data/src/source/gpkg_mem.rs @@ -337,7 +337,9 @@ fn value(v: &Val, ty: FieldType, unread: &mut Vec, rounded: &mut Vec Value::Text(t.clone()), (Val::Text(t), FieldType::Boolean) => super::yes_no_text(t, unread, k), (Val::Text(t), ty) => super::number_text(t, ty, unread, k), - // A blob isn't a value an attribute column holds. + // A blob in a text column is its text, as SQLite stores text either way. + (Val::Blob(b), FieldType::Text) => Value::Text(String::from_utf8_lossy(b).into_owned()), + // A blob isn't a value another attribute column holds. (Val::Blob(_), _) => { super::unread_date(unread, k); Value::Null diff --git a/crates/data/src/source/mod.rs b/crates/data/src/source/mod.rs index 854d3f498b..f3d288eabd 100644 --- a/crates/data/src/source/mod.rs +++ b/crates/data/src/source/mod.rs @@ -382,7 +382,7 @@ pub fn unread_dates_note(fields: &[crate::Field], counts: &[usize]) -> Option "yes/no values", crate::FieldType::Integer | crate::FieldType::Double => "numbers", - // A text field counts dates a mixed column held ([`crate::sheets`]), and a blob. + // A text field counts dates a mixed column held ([`crate::sheets`]). crate::FieldType::Text | crate::FieldType::Date | crate::FieldType::DateTime => "dates", }; if !kinds.contains(&kind) { diff --git a/crates/data/src/source/tests.rs b/crates/data/src/source/tests.rs index 4ad086ea0b..8206704d84 100644 --- a/crates/data/src/source/tests.rs +++ b/crates/data/src/source/tests.rs @@ -4136,15 +4136,18 @@ fn geopackage_values_that_dont_fit_a_number_field_are_said() { c.execute("ALTER TABLE t ADD COLUMN big NUMERIC", []).unwrap(); c.execute("UPDATE t SET big = 9007199254740993 WHERE fid = 1", []).unwrap(); c.execute("UPDATE t SET big = 5 WHERE fid = 2", []).unwrap(); + // A blob in a text column is its text: nothing lost, nothing said. + c.execute("ALTER TABLE t ADD COLUMN name TEXT", []).unwrap(); + c.execute("UPDATE t SET name = x'6869' WHERE fid = 3", []).unwrap(); c.execute("UPDATE t SET pop = 'n/a', area = 'n/a' WHERE fid = 2", []).unwrap(); c.execute("UPDATE t SET pop = x'00ff', area = x'00' WHERE fid = 3", []).unwrap(); c.execute("UPDATE t SET pop = '', area = '' WHERE fid = 4", []).unwrap(); drop(c); for (values, said) in read() { - assert_eq!(values[0], [Value::Int(1), Value::Float(1.5), Value::Float(9_007_199_254_740_992.0)]); - assert_eq!(values[1], [Value::Null, Value::Null, Value::Float(5.0)]); - assert_eq!(values[2], [Value::Null, Value::Null, Value::Null]); - assert_eq!(values[3], [Value::Null, Value::Null, Value::Null]); + assert_eq!(values[0], [Value::Int(1), Value::Float(1.5), Value::Float(9_007_199_254_740_992.0), Value::Null]); + assert_eq!(values[1], [Value::Null, Value::Null, Value::Float(5.0), Value::Null]); + assert_eq!(values[2], [Value::Null, Value::Null, Value::Null, Value::Text("hi".into())]); + assert_eq!(values[3], [Value::Null, Value::Null, Value::Null, Value::Null]); let dropped = Some(crate::loss::LossCode::DroppedValue); let rounded = Some(crate::loss::LossCode::ChangedRounded); assert_eq!( From cf4350cbde89bfe96b0a35a957ee87448594d204 Mon Sep 17 00:00:00 2001 From: mavrick Date: Fri, 27 Nov 2026 15:26:52 -0600 Subject: [PATCH 03/12] fix(data): a whole-number literal past the 64-bit range is a decimal when one holds it exactly --- crates/data/src/query.rs | 15 +++++++++++---- crates/data/src/query/tests.rs | 4 +++- docs/user-guide/expressions.md | 2 +- 3 files changed, 15 insertions(+), 6 deletions(-) diff --git a/crates/data/src/query.rs b/crates/data/src/query.rs index 08386887d1..6d44f0936b 100644 --- a/crates/data/src/query.rs +++ b/crates/data/src/query.rs @@ -801,16 +801,23 @@ fn lex_first(s: &str, tolerant: bool, most: usize) -> Result { } /// The token of a number literal, refusing one that can't be held exactly rather than rounding it. -/// A literal of digits only is an exact `i64`, or refused past `i64::MAX`. Any other literal is a +/// A literal of digits only is an exact `i64`; past `i64::MAX`, a decimal that holds it exactly, or +/// refused. Any other literal is a /// decimal (`f64`), refused only when it would lose its whole-number digits: it has 16 or more /// of them and a decimal doesn't hold its digits (`9007199254740993.0`). One that merely has no /// exact binary form (`0.1`) or many fraction digits (`0.12345678901234567891`) is read as the /// nearest decimal, as every number written in decimal is. fn number_token(t: &str) -> Result { if t.bytes().all(|b| b.is_ascii_digit()) { - return t.parse::().map(Tok::Int).map_err(|_| { - format!("the whole number {t} is too large to hold exactly (the most is {}); write it as a decimal, such as 1e19", i64::MAX) - }); + if let Ok(i) = t.parse::() { + return Ok(Tok::Int(i)); + } + // Past `i64::MAX`, a whole number is a decimal when one holds it exactly (2^63 does), and + // refused when it would be rounded. + if Value::Text(t.to_string()).rounds_as_double() { + return Err(format!("the whole number {t} has more digits than a number holds exactly, so it would be rounded")); + } + return t.parse().map(Tok::Num).map_err(|_| format!("bad number '{t}'")); } let n: f64 = t.parse().map_err(|_| format!("bad number '{t}'"))?; let mantissa = t.split(['e', 'E']).next().unwrap_or_default(); diff --git a/crates/data/src/query/tests.rs b/crates/data/src/query/tests.rs index d9d751f9c7..496959bc15 100644 --- a/crates/data/src/query/tests.rs +++ b/crates/data/src/query/tests.rs @@ -73,7 +73,9 @@ fn number_literals_are_exact_or_refused() { assert_eq!(v(&i64::MAX.to_string()), Value::Int(i64::MAX)); assert_eq!(v("-9007199254740993"), Value::Int(-9_007_199_254_740_993)); assert_eq!(select("pop > 9007199254740993", &d).unwrap(), Vec::::new()); - for text in ["9223372036854775808", "99999999999999999999", "9007199254740993.0", "9007199254740993.5", "12345678901234567000.0"] { + // 2^63, past `i64::MAX`, is a decimal that holds it exactly. + assert_eq!(v("9223372036854775808"), Value::Float(9_223_372_036_854_775_808.0)); + for text in ["9223372036854775809", "99999999999999999999", "9007199254740993.0", "9007199254740993.5", "12345678901234567000.0"] { assert!(parse(text, &d).is_err_and(|e| e.contains("exact") || e.contains("rounded")), "{text}"); } assert_eq!(v("0.1"), Value::Float(0.1)); diff --git a/docs/user-guide/expressions.md b/docs/user-guide/expressions.md index f2df711054..1abbeace62 100644 --- a/docs/user-guide/expressions.md +++ b/docs/user-guide/expressions.md @@ -79,7 +79,7 @@ operator: write `a < b AND b < c`, not `a < b < c`. | Write | Meaning | | --- | --- | -| `42`, `3.5`, `1e6`, `.5` | Numbers; whole numbers are integers, exact up to 9223372036854775807. A number that would be rounded (a whole number past that, or `9007199254740993.0`) is refused, not rounded | +| `42`, `3.5`, `1e6`, `.5` | Numbers; whole numbers are integers, exact up to 9223372036854775807; past that, a decimal when one holds them exactly. A number that would be rounded (`99999999999999999999`, `9007199254740993.0`) is refused, not rounded | | `'text'`, `'it''s'` | Text in single quotes; two quotes stand for one | | `TRUE`, `FALSE`, `NULL` | Booleans and the missing value | | `pop_est`, `"Pop Est"`, `!Pop Est!` | A field, by name, ignoring letter case; quote a name with spaces, punctuation or the name of a keyword (`"OR"`, `"null"`) | From d965e077698a538ae215f2f2eb32424db1c0c801 Mon Sep 17 00:00:00 2001 From: mavrick Date: Fri, 27 Nov 2026 16:15:11 -0600 Subject: [PATCH 04/12] fix(data): refuse exponent literals that round, count number text that rounds, and say GeoPackage text that isn't UTF-8 --- crates/data/src/query.rs | 11 ++++---- crates/data/src/query/tests.rs | 10 ++++++- crates/data/src/source/gpkg.rs | 33 ++++++++++++++++------ crates/data/src/source/gpkg/edit.rs | 16 +++++++++-- crates/data/src/source/gpkg_mem.rs | 24 +++++++++------- crates/data/src/source/mod.rs | 43 +++++++++++++++++++++++++++-- crates/data/src/source/tests.rs | 28 ++++++++++++++++++- crates/engine/src/cmd/gpkg.rs | 6 ++++ 8 files changed, 140 insertions(+), 31 deletions(-) diff --git a/crates/data/src/query.rs b/crates/data/src/query.rs index 6d44f0936b..78fa6518e8 100644 --- a/crates/data/src/query.rs +++ b/crates/data/src/query.rs @@ -803,8 +803,9 @@ fn lex_first(s: &str, tolerant: bool, most: usize) -> Result { /// The token of a number literal, refusing one that can't be held exactly rather than rounding it. /// A literal of digits only is an exact `i64`; past `i64::MAX`, a decimal that holds it exactly, or /// refused. Any other literal is a -/// decimal (`f64`), refused only when it would lose its whole-number digits: it has 16 or more -/// of them and a decimal doesn't hold its digits (`9007199254740993.0`). One that merely has no +/// decimal (`f64`), refused only when it would lose whole-number digits: it is 1e15 or more, so +/// has 16 or more of them however it is written, and a decimal doesn't hold its digits +/// (`9007199254740993.0`, `1.2345678901234567891e19`). One that merely has no /// exact binary form (`0.1`) or many fraction digits (`0.12345678901234567891`) is read as the /// nearest decimal, as every number written in decimal is. fn number_token(t: &str) -> Result { @@ -820,9 +821,9 @@ fn number_token(t: &str) -> Result { return t.parse().map(Tok::Num).map_err(|_| format!("bad number '{t}'")); } let n: f64 = t.parse().map_err(|_| format!("bad number '{t}'"))?; - let mantissa = t.split(['e', 'E']).next().unwrap_or_default(); - let whole = mantissa.split('.').next().unwrap_or_default().trim_start_matches('0'); - if whole.len() >= 16 && n.is_finite() && Value::Text(t.to_string()).rounds_as_double() { + // A number of 1e15 or more has 16 or more whole-number digits, whether written out or moved + // there by an exponent: refused when a decimal wouldn't hold them. + if n.is_finite() && n.abs() >= 1e15 && Value::Text(t.to_string()).rounds_as_double() { return Err(format!("the number {t} has more digits than a decimal number holds exactly, so it would be rounded")); } Ok(Tok::Num(n)) diff --git a/crates/data/src/query/tests.rs b/crates/data/src/query/tests.rs index 496959bc15..81410cd44e 100644 --- a/crates/data/src/query/tests.rs +++ b/crates/data/src/query/tests.rs @@ -75,13 +75,21 @@ fn number_literals_are_exact_or_refused() { assert_eq!(select("pop > 9007199254740993", &d).unwrap(), Vec::::new()); // 2^63, past `i64::MAX`, is a decimal that holds it exactly. assert_eq!(v("9223372036854775808"), Value::Float(9_223_372_036_854_775_808.0)); - for text in ["9223372036854775809", "99999999999999999999", "9007199254740993.0", "9007199254740993.5", "12345678901234567000.0"] { + for text in [ + "9223372036854775809", + "99999999999999999999", + "9007199254740993.0", + "9007199254740993.5", + "12345678901234567000.0", + "1.2345678901234567891e19", + ] { assert!(parse(text, &d).is_err_and(|e| e.contains("exact") || e.contains("rounded")), "{text}"); } assert_eq!(v("0.1"), Value::Float(0.1)); assert_eq!(v("2.5"), Value::Float(2.5)); assert_eq!(v("1e3"), Value::Int(1000)); assert_eq!(v("1.5e3"), Value::Int(1500)); + assert_eq!(v("1e19"), Value::Float(1e19), "a decimal holds it exactly"); assert_eq!(v("9007199254740992.0"), Value::Float(9_007_199_254_740_992.0)); assert_eq!(v("0.12345678901234567891"), Value::Float(0.123_456_789_012_345_68)); } diff --git a/crates/data/src/source/gpkg.rs b/crates/data/src/source/gpkg.rs index 7d92d90d75..3e1c3b0b1d 100644 --- a/crates/data/src/source/gpkg.rs +++ b/crates/data/src/source/gpkg.rs @@ -471,13 +471,14 @@ impl GpkgSource { req: &Request, unread_dates: &mut Vec, rounded_dates: &mut Vec, + not_utf8: &mut Vec, ) -> rusqlite::Result { // Integer keys, negative ones too, map to distinct ids. let Some(id) = r.get::<_, Option>(0)?.map(|i| i as u64) else { return Ok(Row::Bad) }; let mut attrs = || { let mut out = Vec::with_capacity(self.info.fields.len()); for (k, f) in self.info.fields.iter().enumerate() { - out.push(match r.get_ref(k + 2).map(|v| value(v, f.ty, unread_dates, Some(&mut *rounded_dates), k)) { + out.push(match r.get_ref(k + 2).map(|v| value(v, f.ty, unread_dates, Some(&mut *rounded_dates), &mut *not_utf8, k)) { Ok(v) => v, // The select list holds a column for every field, so there is no column to miss. Err(_) => Value::Null, @@ -518,6 +519,10 @@ enum Row { } impl FeatureSource for GpkgSource { + /// Text that isn't valid UTF-8 is said as GeoPackage text ([`super::not_utf8_note`]). + fn text_encoding(&self) -> &'static str { + super::GEOPACKAGE_TEXT + } fn info(&self) -> &SourceInfo { &self.info } @@ -596,7 +601,9 @@ impl FeatureSource for GpkgSource { let mut st = conn.prepare(&sql).map_err(err)?; let mut rows = st.query(params_from_iter(chunk.iter())).map_err(err)?; while let Some(r) = rows.next().map_err(err)? { - let row = self.feature(r, native.as_ref(), req, &mut out.unread_dates, &mut out.rounded_dates).map_err(err)?; + let row = self + .feature(r, native.as_ref(), req, &mut out.unread_dates, &mut out.rounded_dates, &mut out.not_utf8) + .map_err(err)?; push(row, &mut out); } if out.features.len() >= limit { @@ -637,7 +644,10 @@ impl FeatureSource for GpkgSource { if known && !sample.wants() { continue; } - match self.feature(r, native.as_ref(), req, &mut out.unread_dates, &mut out.rounded_dates).map_err(err)? { + match self + .feature(r, native.as_ref(), req, &mut out.unread_dates, &mut out.rounded_dates, &mut out.not_utf8) + .map_err(err)? + { Row::Feature(f) if known || sample.wants() => sample.keep(f), Row::Feature(_) | Row::Skip => {} Row::Bad => out.skipped += 1, @@ -688,7 +698,7 @@ impl FeatureSource for GpkgSource { crate::progress::begin(self.progress_total()); while let Some(r) = rows.next().map_err(err)? { crate::progress::step(1)?; - match self.feature(r, native.as_ref(), &req, &mut out.unread_dates, &mut out.rounded_dates).map_err(err)? { + match self.feature(r, native.as_ref(), &req, &mut out.unread_dates, &mut out.rounded_dates, &mut out.not_utf8).map_err(err)? { Row::Feature(f) => { out.matched += 1; chunks.push(f)?; @@ -1576,7 +1586,14 @@ fn to_millisecond(t: crate::date::DateTime) -> crate::date::DateTime { /// and counted in `unread` ([`Batch::unread_dates`]): text that isn't a number in a number field, /// a blob. With `rounded`, a date-time with digits past the microsecond, or a whole number past 2^53 /// in a Double field, is rounded and counted there ([`Batch::rounded_dates`]), else the date-time isn't a date. -fn value(v: ValueRef<'_>, ty: FieldType, unread: &mut Vec, rounded: Option<&mut Vec>, k: usize) -> Value { +fn value( + v: ValueRef<'_>, + ty: FieldType, + unread: &mut Vec, + rounded: Option<&mut Vec>, + not_utf8: &mut Vec, + k: usize, +) -> Value { match (v, ty) { (ValueRef::Null, _) => Value::Null, (v, FieldType::Date | FieldType::DateTime) => { @@ -1588,11 +1605,11 @@ fn value(v: ValueRef<'_>, ty: FieldType, unread: &mut Vec, rounded: Optio (ValueRef::Integer(i), _) => Value::Int(i), (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::Text) => super::utf8_text(t, not_utf8, k), (ValueRef::Text(t), FieldType::Boolean) => super::yes_no_text(&String::from_utf8_lossy(t), unread, k), - (ValueRef::Text(t), ty) => super::number_text(&String::from_utf8_lossy(t), ty, unread, k), + (ValueRef::Text(t), ty) => super::number_text(&String::from_utf8_lossy(t), ty, unread, rounded, k), // A blob in a text column is its text, as SQLite stores text either way. - (ValueRef::Blob(b), FieldType::Text) => Value::Text(String::from_utf8_lossy(b).into_owned()), + (ValueRef::Blob(b), FieldType::Text) => super::utf8_text(b, not_utf8, k), // A blob isn't a value another attribute column holds. (ValueRef::Blob(_), _) => { super::unread_date(unread, k); diff --git a/crates/data/src/source/gpkg/edit.rs b/crates/data/src/source/gpkg/edit.rs index 3b82085fd6..3de9474a53 100644 --- a/crates/data/src/source/gpkg/edit.rs +++ b/crates/data/src/source/gpkg/edit.rs @@ -34,6 +34,8 @@ pub struct Editable { pub unread_dates: Vec, /// Date-times rounded to the microsecond, by field ([`crate::source::Batch::rounded_dates`]). pub rounded_dates: Vec, + /// Text values that aren't valid UTF-8, by field ([`crate::source::Batch::not_utf8`]). + pub not_utf8: Vec, pub writable: bool, } @@ -159,6 +161,7 @@ impl EditTable { skipped: 0, unread_dates: Vec::new(), rounded_dates: Vec::new(), + not_utf8: Vec::new(), writable: std::fs::metadata(&self.path).is_ok_and(|m| !m.permissions().readonly()), }; { @@ -183,7 +186,14 @@ impl EditTable { } let mut values = Vec::with_capacity(attrs.len()); for (k, (f, &i)) in self.info().fields.iter().zip(&attrs).enumerate() { - values.push(value(row.get_ref(i).map_err(err)?, f.ty, &mut out.unread_dates, Some(&mut out.rounded_dates), k)); + values.push(value( + row.get_ref(i).map_err(err)?, + f.ty, + &mut out.unread_dates, + Some(&mut out.rounded_dates), + &mut out.not_utf8, + k, + )); } let attrs = values; out.versions.push((id, hash.cast_signed())); @@ -306,7 +316,7 @@ impl EditTable { let attr = f.attrs.get(i).unwrap_or(&Value::Null); // A stored date that isn't one reads as null and is kept unless edited; one with // digits past the microsecond reads rounded, as the load showed it, so it is kept too. - let previous = value(ValueRef::from(old), field.ty, &mut Vec::new(), Some(&mut Vec::new()), 0); + let previous = value(ValueRef::from(old), field.ty, &mut Vec::new(), Some(&mut Vec::new()), &mut Vec::new(), 0); let same_nan = matches!((&previous, attr), (Value::Float(a), Value::Float(b)) if a.is_nan() && b.is_nan()); if previous != *attr && !same_nan { sets.push(format!("{} = ?", quote(columns.get(c).ok_or_else(|| self.shape_error())?))); @@ -447,7 +457,7 @@ impl EditTable { // trigger touched, wasn't read before, so it is said. let stored = row.get(c).ok_or_else(|| self.shape_error())?; let (mut unread, mut rounded) = (Vec::new(), Vec::new()); - let read = value(ValueRef::from(stored), field.ty, &mut unread, Some(&mut rounded), i); + let read = value(ValueRef::from(stored), field.ty, &mut unread, Some(&mut rounded), &mut Vec::new(), i); if before.get(&(k, c)) != Some(stored) { crate::source::add_unread_dates(&mut unread_dates, &unread); crate::source::add_unread_dates(&mut rounded_dates, &rounded); diff --git a/crates/data/src/source/gpkg_mem.rs b/crates/data/src/source/gpkg_mem.rs index 3f2fe6a5c9..289a67c6be 100644 --- a/crates/data/src/source/gpkg_mem.rs +++ b/crates/data/src/source/gpkg_mem.rs @@ -323,7 +323,7 @@ impl GpkgMemSource { /// and counted in `unread` ([`Batch::unread_dates`]): text that isn't a number in a number field, /// a blob. A date-time with digits past the microsecond, or a whole number past 2^53 in a Double /// field, is rounded and counted in `rounded` ([`Batch::rounded_dates`]). -fn value(v: &Val, ty: FieldType, unread: &mut Vec, rounded: &mut Vec, k: usize) -> Value { +fn value(v: &Val, ty: FieldType, unread: &mut Vec, rounded: &mut Vec, not_utf8: &mut Vec, k: usize) -> Value { match (v, ty) { (Val::Null, _) => Value::Null, (v, FieldType::Date | FieldType::DateTime) => { @@ -336,9 +336,9 @@ fn value(v: &Val, ty: FieldType, unread: &mut Vec, rounded: &mut Vec 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) => super::number_text(t, ty, unread, k), + (Val::Text(t), ty) => super::number_text(t, ty, unread, Some(rounded), k), // A blob in a text column is its text, as SQLite stores text either way. - (Val::Blob(b), FieldType::Text) => Value::Text(String::from_utf8_lossy(b).into_owned()), + (Val::Blob(b), FieldType::Text) => super::utf8_text(b, not_utf8, k), // A blob isn't a value another attribute column holds. (Val::Blob(_), _) => { super::unread_date(unread, k); @@ -348,6 +348,10 @@ fn value(v: &Val, ty: FieldType, unread: &mut Vec, rounded: &mut Vec &'static str { + super::GEOPACKAGE_TEXT + } fn info(&self) -> &SourceInfo { &self.info } @@ -372,7 +376,7 @@ impl FeatureSource for GpkgMemSource { } // A whole read knows its count; an extent, bounded natively or not, is matched as it goes. let mut sample = if req.extent.is_none() { Sampler::with_total(limit, self.info.count.unwrap_or(0)) } else { Sampler::new(limit) }; - let (mut skipped, mut unread_dates, mut rounded_dates) = (0, Vec::new(), Vec::new()); + let (mut skipped, mut unread_dates, mut rounded_dates, mut not_utf8) = (0, Vec::new(), Vec::new(), Vec::new()); let mut failed = None; crate::progress::begin(self.info.count.and_then(|n| usize::try_from(n).ok()).unwrap_or(0)); self.db @@ -390,7 +394,7 @@ impl FeatureSource for GpkgMemSource { sample.keep(Feature { id: rowid as u64, geometry: None, - attrs: self.attrs(r, &mut unread_dates, &mut rounded_dates), + attrs: self.attrs(r, &mut unread_dates, &mut rounded_dates, &mut not_utf8), }); } return ControlFlow::Continue(()); @@ -427,7 +431,7 @@ impl FeatureSource for GpkgMemSource { sample.keep(Feature { id: rowid as u64, geometry: Some(geometry), - attrs: self.attrs(r, &mut unread_dates, &mut rounded_dates), + attrs: self.attrs(r, &mut unread_dates, &mut rounded_dates, &mut not_utf8), }); ControlFlow::Continue(()) }) @@ -444,7 +448,7 @@ impl FeatureSource for GpkgMemSource { rounded_dates, null_text: Vec::new(), notes: Default::default(), - not_utf8: Vec::new(), + not_utf8, }) } @@ -501,7 +505,7 @@ impl FeatureSource for GpkgMemSource { match chunks.push(Feature { id: rowid as u64, geometry, - attrs: self.attrs(r, &mut out.unread_dates, &mut out.rounded_dates), + attrs: self.attrs(r, &mut out.unread_dates, &mut out.rounded_dates, &mut out.not_utf8), }) { Ok(()) => ControlFlow::Continue(()), Err(e) => { @@ -522,11 +526,11 @@ impl FeatureSource for GpkgMemSource { impl GpkgMemSource { /// A row's field values, in `info.fields` order, counting in `unread_dates` the dates that /// aren't ones. - fn attrs(&self, r: &[Val], unread_dates: &mut Vec, rounded_dates: &mut Vec) -> Vec { + fn attrs(&self, r: &[Val], unread_dates: &mut Vec, rounded_dates: &mut Vec, not_utf8: &mut Vec) -> Vec { let mut out = Vec::with_capacity(self.info.fields.len()); for (k, (f, &c)) in self.info.fields.iter().zip(&self.field_cols).enumerate() { out.push(match r.get(c) { - Some(v) => value(v, f.ty, unread_dates, rounded_dates, k), + Some(v) => value(v, f.ty, unread_dates, rounded_dates, not_utf8, k), None => Value::Null, }); } diff --git a/crates/data/src/source/mod.rs b/crates/data/src/source/mod.rs index f3d288eabd..89829ff58d 100644 --- a/crates/data/src/source/mod.rs +++ b/crates/data/src/source/mod.rs @@ -305,14 +305,44 @@ pub(crate) fn yes_no_text(text: &str, counts: &mut Vec, k: usize) -> crat /// ([`crate::Value::parse_source`]): text that isn't a number is null, counted in `counts` /// ([`Batch::unread_dates`]), which says it as a value that isn't a number ([`unread_dates_note`]). /// Empty text and `` are null, uncounted. -pub(crate) fn number_text(text: &str, ty: crate::FieldType, counts: &mut Vec, k: usize) -> crate::Value { +pub(crate) fn number_text( + text: &str, + ty: crate::FieldType, + counts: &mut Vec, + rounded: Option<&mut Vec>, + k: usize, +) -> crate::Value { let v = crate::Value::parse_source(text, ty); if v.is_null() && !text.trim().is_empty() && !crate::Value::is_null_marker(text) { unread_date(counts, k); } + // A number a decimal can't hold as written (`9007199254740993`) is rounded: counted in + // `rounded` ([`Batch::rounded_dates`]), as a whole number stored past 2^53 is. + if let (crate::Value::Float(_), Some(rounded)) = (&v, rounded) + && crate::Value::Text(text.trim().to_string()).rounds_as_double() + { + unread_date(rounded, k); + } v } +/// The text encoding a GeoPackage reader gives ([`FeatureSource::text_encoding`]): UTF-8, which the +/// standard requires, so [`not_utf8_note`] says why without a `.cpg` to point to. +pub const GEOPACKAGE_TEXT: &str = "UTF-8 (GeoPackage)"; + +/// A text field's value from bytes SQLite holds as text or as a blob: the text, or, when they +/// aren't valid UTF-8, the text with U+FFFD in place of what isn't, counted in `not_utf8` +/// ([`Batch::not_utf8`], said by [`not_utf8_note`]). +pub(crate) fn utf8_text(bytes: &[u8], not_utf8: &mut Vec, k: usize) -> crate::Value { + match std::str::from_utf8(bytes) { + Ok(text) => crate::Value::Text(text.to_string()), + Err(_) => { + not_utf8_at(not_utf8, k); + crate::Value::Text(String::from_utf8_lossy(bytes).into_owned()) + } + } +} + /// The decimal value of a whole number stored in a Double field at `k`: counted in `rounded` /// ([`Batch::rounded_dates`]) when a decimal can't hold it exactly (past 2^53). pub(crate) fn int_as_double(i: i64, rounded: Option<&mut Vec>, k: usize) -> crate::Value { @@ -429,6 +459,12 @@ pub fn not_utf8_note(fields: &[crate::Field], counts: &[usize], encoding: &str) if total == 0 { return None; } + // A GeoPackage's text is UTF-8 by its standard: no file chooses another. + let (encoding, cause) = if encoding == GEOPACKAGE_TEXT { + ("UTF-8", "a GeoPackage holds its text in UTF-8".to_string()) + } else { + (encoding, crate::dbf::cause(encoding)) + }; let what = if total == 1 { format!("1 text value isn't valid {encoding} and was") } else { @@ -437,7 +473,7 @@ pub fn not_utf8_note(fields: &[crate::Field], counts: &[usize], encoding: &str) let text = format!( "{what} read with U+FFFD in place of the bytes that can't be read, in {}; {}", crate::io::named_fields(fields, counts), - crate::dbf::cause(encoding) + cause ); Some(crate::loss::Note::loss(crate::loss::LossCode::ChangedEncoding, text)) } @@ -450,7 +486,8 @@ pub fn rounded_dates_note(fields: &[crate::Field], counts: &[usize]) -> Option 0 && (f.ty == crate::FieldType::Double) == numbers); + let number = |f: &crate::Field| matches!(f.ty, crate::FieldType::Integer | crate::FieldType::Double); + let counted = |numbers: bool| fields.iter().zip(counts).any(|(f, n)| *n > 0 && number(f) == numbers); let (numbers, dates) = (counted(true), counted(false)); let text = match (numbers, dates) { (true, true) => format!( diff --git a/crates/data/src/source/tests.rs b/crates/data/src/source/tests.rs index 8206704d84..9e450be8c8 100644 --- a/crates/data/src/source/tests.rs +++ b/crates/data/src/source/tests.rs @@ -4139,6 +4139,8 @@ fn geopackage_values_that_dont_fit_a_number_field_are_said() { // A blob in a text column is its text: nothing lost, nothing said. c.execute("ALTER TABLE t ADD COLUMN name TEXT", []).unwrap(); c.execute("UPDATE t SET name = x'6869' WHERE fid = 3", []).unwrap(); + // Bytes that aren't UTF-8 in a text column: read with U+FFFD in their place, and said. + c.execute("UPDATE t SET name = x'ff68' WHERE fid = 4", []).unwrap(); c.execute("UPDATE t SET pop = 'n/a', area = 'n/a' WHERE fid = 2", []).unwrap(); c.execute("UPDATE t SET pop = x'00ff', area = x'00' WHERE fid = 3", []).unwrap(); c.execute("UPDATE t SET pop = '', area = '' WHERE fid = 4", []).unwrap(); @@ -4147,7 +4149,7 @@ fn geopackage_values_that_dont_fit_a_number_field_are_said() { assert_eq!(values[0], [Value::Int(1), Value::Float(1.5), Value::Float(9_007_199_254_740_992.0), Value::Null]); assert_eq!(values[1], [Value::Null, Value::Null, Value::Float(5.0), Value::Null]); assert_eq!(values[2], [Value::Null, Value::Null, Value::Null, Value::Text("hi".into())]); - assert_eq!(values[3], [Value::Null, Value::Null, Value::Null, Value::Null]); + assert_eq!(values[3], [Value::Null, Value::Null, Value::Null, Value::Text("\u{FFFD}h".into())]); let dropped = Some(crate::loss::LossCode::DroppedValue); let rounded = Some(crate::loss::LossCode::ChangedRounded); assert_eq!( @@ -4155,11 +4157,35 @@ fn geopackage_values_that_dont_fit_a_number_field_are_said() { [ ("t: 4 values aren't numbers and were read as empty, in 'pop', 'area'".to_string(), dropped), ("t: 1 whole number was rounded to the nearest decimal number, as a decimal field doesn't keep more than 15 or 16 digits, in 'big'".to_string(), rounded), + ("t: 1 text value isn't valid UTF-8 and was read with U+FFFD in place of the bytes that can't be read, in 'name'; a GeoPackage holds its text in UTF-8".to_string(), Some(crate::loss::LossCode::ChangedEncoding)), ] ); } } +/// Number text a decimal can't hold as written is counted as rounded, and text or a blob that isn't +/// UTF-8 as not valid in it; numbers that fit and UTF-8 text are counted as nothing. +#[test] +fn number_text_that_rounds_and_text_that_isnt_utf8_are_counted() { + let (mut unread, mut rounded) = (Vec::new(), Vec::new()); + for (text, ty) in + [("9007199254740993", FieldType::Double), ("9223372036854775809", FieldType::Integer), ("9007199254740993.0", FieldType::Double)] + { + assert!(matches!(super::number_text(text, ty, &mut unread, Some(&mut rounded), 0), Value::Float(_)), "{text}"); + } + assert_eq!((unread.as_slice(), rounded.as_slice()), (&[][..], &[3][..])); + rounded.clear(); + for (text, ty) in [("2.5", FieldType::Double), ("0.1", FieldType::Double), ("12", FieldType::Integer), ("1e3", FieldType::Double)] { + super::number_text(text, ty, &mut unread, Some(&mut rounded), 0); + } + assert!(unread.is_empty() && rounded.is_empty(), "{unread:?} {rounded:?}"); + let mut not_utf8 = Vec::new(); + assert_eq!(super::utf8_text(b"hi", &mut not_utf8, 0), Value::Text("hi".into())); + assert!(not_utf8.is_empty()); + assert_eq!(super::utf8_text(b"\xffh", &mut not_utf8, 1), Value::Text("\u{FFFD}h".into())); + assert_eq!(not_utf8, [0, 1]); +} + /// 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] diff --git a/crates/engine/src/cmd/gpkg.rs b/crates/engine/src/cmd/gpkg.rs index 71f94a2cc1..8616ddbffa 100644 --- a/crates/engine/src/cmd/gpkg.rs +++ b/crates/engine/src/cmd/gpkg.rs @@ -113,6 +113,9 @@ fn add_layer(s: &mut Session, p: &Value) -> CmdResult { if let Some(note) = rustgis_data::source::rounded_dates_note(&info.fields, &editable.rounded_dates) { s.say(note.prefixed(&name)); } + if let Some(note) = rustgis_data::source::not_utf8_note(&info.fields, &editable.not_utf8, rustgis_data::source::GEOPACKAGE_TEXT) { + s.say(note.prefixed(&name)); + } if !editable.writable { s.notify(format!("{name}: the file is read-only, so edits can't be saved to it"), false); } @@ -401,6 +404,9 @@ pub(super) fn read_candidate(name: &str, edit: &rustgis_map::source::GpkgEdit) - if let Some(note) = rustgis_data::source::rounded_dates_note(&info.fields, &editable.rounded_dates) { notes.push(note); } + if let Some(note) = rustgis_data::source::not_utf8_note(&info.fields, &editable.not_utf8, rustgis_data::source::GEOPACKAGE_TEXT) { + notes.push(note); + } if !editable.writable { notes.push("the file is read-only, so edits can't be saved to it"); } From 3edb5cc19ad442b4665583ec7dd7e9a29f8b5b2c Mon Sep 17 00:00:00 2001 From: mavrick Date: Fri, 27 Nov 2026 16:46:49 -0600 Subject: [PATCH 05/12] fix(data): only whole-number digits of a literal are kept from rounding; the UTF-8 counter builds for the browser --- crates/data/src/export/tests.rs | 2 +- crates/data/src/query.rs | 41 +++++++++++++++++++++++++++++---- crates/data/src/query/tests.rs | 2 ++ crates/data/src/source/mod.rs | 1 - docs/user-guide/expressions.md | 2 +- 5 files changed, 40 insertions(+), 8 deletions(-) diff --git a/crates/data/src/export/tests.rs b/crates/data/src/export/tests.rs index 9ab87de52f..111d91bb38 100644 --- a/crates/data/src/export/tests.rs +++ b/crates/data/src/export/tests.rs @@ -245,7 +245,7 @@ fn a_streamed_export_writes_what_a_whole_export_writes() { rounded_dates: Vec::new(), null_text: Vec::new(), not_utf8: Vec::new(), - not_utf8_in: "UTF-8", + not_utf8_in: src.text_encoding(), utc_dates, fine_dates: if ext == "gpkg" { crate::io::fine_dates(whole.features.iter(), &whole.fields) } else { Vec::new() }, written_values: if ext == "fgb" { crate::io::written_values(whole.features.iter(), &whole.fields) } else { Vec::new() }, diff --git a/crates/data/src/query.rs b/crates/data/src/query.rs index 78fa6518e8..6410460fab 100644 --- a/crates/data/src/query.rs +++ b/crates/data/src/query.rs @@ -804,8 +804,8 @@ fn lex_first(s: &str, tolerant: bool, most: usize) -> Result { /// A literal of digits only is an exact `i64`; past `i64::MAX`, a decimal that holds it exactly, or /// refused. Any other literal is a /// decimal (`f64`), refused only when it would lose whole-number digits: it is 1e15 or more, so -/// has 16 or more of them however it is written, and a decimal doesn't hold its digits -/// (`9007199254740993.0`, `1.2345678901234567891e19`). One that merely has no +/// has 16 or more of them however it is written, and a decimal doesn't hold them +/// (`9007199254740993.0`, `1.2345678901234567891e19`); its fraction digits round as any do. One that merely has no /// exact binary form (`0.1`) or many fraction digits (`0.12345678901234567891`) is read as the /// nearest decimal, as every number written in decimal is. fn number_token(t: &str) -> Result { @@ -822,13 +822,44 @@ fn number_token(t: &str) -> Result { } let n: f64 = t.parse().map_err(|_| format!("bad number '{t}'"))?; // A number of 1e15 or more has 16 or more whole-number digits, whether written out or moved - // there by an exponent: refused when a decimal wouldn't hold them. - if n.is_finite() && n.abs() >= 1e15 && Value::Text(t.to_string()).rounds_as_double() { - return Err(format!("the number {t} has more digits than a decimal number holds exactly, so it would be rounded")); + // there by an exponent: refused when a decimal wouldn't hold them. Its fraction digits, past + // them, are read as the nearest decimal, as any fraction is. + if n.is_finite() && n.abs() >= 1e15 && whole_digits_round(t) { + return Err(format!("the number {t} has more whole-number digits than a decimal number holds exactly, so it would be rounded")); } Ok(Tok::Num(n)) } +/// Whether a decimal literal's whole-number digits, its exponent applied, would be rounded: digits +/// written out (`9007199254740993.0`, `1.2345678901234567891e19`) must be held exactly; zeros an +/// exponent adds past them (`1e307`) weren't written, so only the written digits need holding. +/// `false` for one that isn't written in digits. +fn whole_digits_round(t: &str) -> bool { + let (mantissa, exp) = match t.split_once(['e', 'E']) { + Some((m, e)) => match e.parse::() { + Ok(e) => (m, e), + Err(_) => return false, + }, + None => (t, 0), + }; + let (int, frac) = mantissa.split_once('.').unwrap_or((mantissa, "")); + if !int.bytes().chain(frac.bytes()).all(|b| b.is_ascii_digit()) { + return false; + } + let digits = format!("{int}{frac}"); + // Where the point falls in `digits`, the exponent moving it. + let Some(point) = i64::try_from(int.len()).ok().and_then(|n| n.checked_add(exp)).and_then(|p| usize::try_from(p).ok()) else { + return false; + }; + let written: String = digits.chars().take(point).collect(); + let added = point.saturating_sub(digits.len()); + if added == 0 { + !crate::io::double_holds(written.trim_start_matches('0')) + } else { + !crate::io::double_holds(&format!("{written}e{added}")) + } +} + /// A number literal: whole numbers are integers. fn num(n: f64) -> Value { if n.fract() == 0.0 && n.abs() < 9e15 { Value::Int(n as i64) } else { Value::Float(n) } diff --git a/crates/data/src/query/tests.rs b/crates/data/src/query/tests.rs index 81410cd44e..6a37cb9ab7 100644 --- a/crates/data/src/query/tests.rs +++ b/crates/data/src/query/tests.rs @@ -90,6 +90,8 @@ fn number_literals_are_exact_or_refused() { assert_eq!(v("1e3"), Value::Int(1000)); assert_eq!(v("1.5e3"), Value::Int(1500)); assert_eq!(v("1e19"), Value::Float(1e19), "a decimal holds it exactly"); + // Only whole-number digits are kept from rounding: a fraction past them reads as the nearest decimal. + assert_eq!(v("1000000000000000.123456789"), Value::Float(1_000_000_000_000_000.1)); assert_eq!(v("9007199254740992.0"), Value::Float(9_007_199_254_740_992.0)); assert_eq!(v("0.12345678901234567891"), Value::Float(0.123_456_789_012_345_68)); } diff --git a/crates/data/src/source/mod.rs b/crates/data/src/source/mod.rs index 89829ff58d..861196e053 100644 --- a/crates/data/src/source/mod.rs +++ b/crates/data/src/source/mod.rs @@ -360,7 +360,6 @@ pub(crate) fn null_text_at(counts: &mut Vec, k: usize) { } /// Counts one more text value that isn't valid in its encoding in the field at `k` ([`Batch::not_utf8`]). -#[cfg(not(target_arch = "wasm32"))] pub(crate) fn not_utf8_at(counts: &mut Vec, k: usize) { unread_dates_by(counts, k, 1); } diff --git a/docs/user-guide/expressions.md b/docs/user-guide/expressions.md index 1abbeace62..7776c45127 100644 --- a/docs/user-guide/expressions.md +++ b/docs/user-guide/expressions.md @@ -79,7 +79,7 @@ operator: write `a < b AND b < c`, not `a < b < c`. | Write | Meaning | | --- | --- | -| `42`, `3.5`, `1e6`, `.5` | Numbers; whole numbers are integers, exact up to 9223372036854775807; past that, a decimal when one holds them exactly. A number that would be rounded (`99999999999999999999`, `9007199254740993.0`) is refused, not rounded | +| `42`, `3.5`, `1e6`, `.5` | Numbers; whole numbers are integers, exact up to 9223372036854775807; past that, a decimal when one holds them exactly. A number whose whole-number digits would be rounded (`99999999999999999999`, `9007199254740993.0`, `1.2345678901234567891e19`) is refused, not rounded; digits after the point read as the nearest decimal, as in `0.1` | | `'text'`, `'it''s'` | Text in single quotes; two quotes stand for one | | `TRUE`, `FALSE`, `NULL` | Booleans and the missing value | | `pop_est`, `"Pop Est"`, `!Pop Est!` | A field, by name, ignoring letter case; quote a name with spaces, punctuation or the name of a keyword (`"OR"`, `"null"`) | From de2939aac5e2628169176945b6e02bc0ea24d06d Mon Sep 17 00:00:00 2001 From: mavrick Date: Fri, 27 Nov 2026 17:37:29 -0600 Subject: [PATCH 06/12] fix(data): the browser reader counts text that isn't UTF-8, a long fraction isn't a rounded whole number, and a save's read-back counts bad text --- crates/data/src/mbtiles.rs | 5 +++-- crates/data/src/query.rs | 6 ++++-- crates/data/src/source/gpkg/edit.rs | 11 ++++++++--- crates/data/src/source/gpkg_mem.rs | 15 +++++++-------- crates/data/src/source/mod.rs | 8 +++++--- crates/data/src/source/tests.rs | 20 +++++++++++++++----- crates/data/src/sqlite.rs | 23 ++++++++++++++++++++++- crates/engine/src/cmd/gpkg.rs | 4 ++++ 8 files changed, 68 insertions(+), 24 deletions(-) diff --git a/crates/data/src/mbtiles.rs b/crates/data/src/mbtiles.rs index f75f5311ce..a6e812d6be 100644 --- a/crates/data/src/mbtiles.rs +++ b/crates/data/src/mbtiles.rs @@ -173,6 +173,7 @@ fn key(v: Option<&Val>) -> Option { match v? { Val::Int(i) => Some(Key::Int(*i)), Val::Text(t) => Some(Key::Text(t.clone())), + Val::BadText(b) => Some(Key::Text(String::from_utf8_lossy(b).into_owned())), Val::Blob(b) => Some(Key::Blob(b.clone())), _ => None, } @@ -192,8 +193,8 @@ pub fn read_bytes(bytes: &[u8]) -> Result { && let (Some(n), Some(v)) = (col(m, "name"), col(m, "value")) { db.rows(m, |_, r| { - if let (Some(Val::Text(n)), Some(Val::Text(v))) = (r.get(n), r.get(v)) { - meta.push((n.clone(), v.clone())); + if let (Some(n), Some(v)) = (r.get(n).and_then(Val::text), r.get(v).and_then(Val::text)) { + meta.push((n.into_owned(), v.into_owned())); } if meta.len() >= 1000 { ControlFlow::Break(()) } else { ControlFlow::Continue(()) } })?; diff --git a/crates/data/src/query.rs b/crates/data/src/query.rs index 6410460fab..7893b1a52f 100644 --- a/crates/data/src/query.rs +++ b/crates/data/src/query.rs @@ -834,7 +834,7 @@ fn number_token(t: &str) -> Result { /// written out (`9007199254740993.0`, `1.2345678901234567891e19`) must be held exactly; zeros an /// exponent adds past them (`1e307`) weren't written, so only the written digits need holding. /// `false` for one that isn't written in digits. -fn whole_digits_round(t: &str) -> bool { +pub(crate) fn whole_digits_round(t: &str) -> bool { let (mantissa, exp) = match t.split_once(['e', 'E']) { Some((m, e)) => match e.parse::() { Ok(e) => (m, e), @@ -854,7 +854,9 @@ fn whole_digits_round(t: &str) -> bool { let written: String = digits.chars().take(point).collect(); let added = point.saturating_sub(digits.len()); if added == 0 { - !crate::io::double_holds(written.trim_start_matches('0')) + // No whole-number digits but zeros (`0.1`): a zero, which every decimal holds. + let written = written.trim_start_matches('0'); + !crate::io::double_holds(if written.is_empty() { "0" } else { written }) } else { !crate::io::double_holds(&format!("{written}e{added}")) } diff --git a/crates/data/src/source/gpkg/edit.rs b/crates/data/src/source/gpkg/edit.rs index 3de9474a53..31930f7371 100644 --- a/crates/data/src/source/gpkg/edit.rs +++ b/crates/data/src/source/gpkg/edit.rs @@ -65,6 +65,9 @@ pub struct SavedRows { /// the save: the load said those. A row only a trigger touched wasn't read before the save, so /// its rounded values are counted even when unchanged, and may be said again. pub rounded_dates: Vec, + /// Per supplied field, text read back that isn't valid UTF-8 ([`crate::source::not_utf8_note`]), + /// counted as [`SavedRows::rounded_dates`] is. + pub not_utf8: Vec, } /// An existing feature table; its read connection is never reused for writes. @@ -305,7 +308,7 @@ impl EditTable { let mut spatial_changed = !edits.inserts.is_empty() || !edits.deletes.is_empty(); let mut utc_dates = vec![0usize; fields.len()]; let mut fine_dates = vec![0usize; fields.len()]; - let (mut unread_dates, mut rounded_dates) = (Vec::new(), Vec::new()); + let (mut unread_dates, mut rounded_dates, mut not_utf8) = (Vec::new(), Vec::new(), Vec::new()); for (f, _) in &edits.updates { let row = current.get(&f.id.cast_signed()).ok_or_else(|| self.shape_error())?; let mut sets = Vec::new(); @@ -456,11 +459,12 @@ impl EditTable { // before the save, which the load already said; an inserted row, or one only a // trigger touched, wasn't read before, so it is said. let stored = row.get(c).ok_or_else(|| self.shape_error())?; - let (mut unread, mut rounded) = (Vec::new(), Vec::new()); - let read = value(ValueRef::from(stored), field.ty, &mut unread, Some(&mut rounded), &mut Vec::new(), i); + let (mut unread, mut rounded, mut bad_text) = (Vec::new(), Vec::new(), Vec::new()); + let read = value(ValueRef::from(stored), field.ty, &mut unread, Some(&mut rounded), &mut bad_text, i); if before.get(&(k, c)) != Some(stored) { crate::source::add_unread_dates(&mut unread_dates, &unread); crate::source::add_unread_dates(&mut rounded_dates, &rounded); + crate::source::add_unread_dates(&mut not_utf8, &bad_text); } *attr = read; } @@ -521,6 +525,7 @@ impl EditTable { fine_dates, unread_dates, rounded_dates, + not_utf8, })) } diff --git a/crates/data/src/source/gpkg_mem.rs b/crates/data/src/source/gpkg_mem.rs index 289a67c6be..2ad9bbedc1 100644 --- a/crates/data/src/source/gpkg_mem.rs +++ b/crates/data/src/source/gpkg_mem.rs @@ -56,10 +56,7 @@ fn get<'a>(row: &'a [(String, Val)], col: &str) -> Option<&'a Val> { } fn text(v: Option<&Val>) -> Option { - match v? { - Val::Text(s) => Some(s.clone()), - _ => None, - } + v?.text().map(std::borrow::Cow::into_owned) } /// An integer value, exactly (an id, a code). @@ -119,7 +116,7 @@ pub fn unsupported_table_counts(bytes: Shared) -> Result> { let mut invalid = 0u64; // Count in place: the contents catalog can be large without materializing its rows. db.rows(table, |_, row| { - let (Some(Val::Text(kind)), Some(Val::Text(name))) = (row.get(kind_col), row.get(name_col)) else { + let (Some(kind), Some(name)) = (row.get(kind_col).and_then(Val::text), row.get(name_col).and_then(Val::text)) else { invalid = invalid.saturating_add(1); return ControlFlow::Continue(()); }; @@ -326,15 +323,17 @@ impl GpkgMemSource { fn value(v: &Val, ty: FieldType, unread: &mut Vec, rounded: &mut Vec, not_utf8: &mut Vec, k: usize) -> Value { match (v, ty) { (Val::Null, _) => Value::Null, - (v, FieldType::Date | FieldType::DateTime) => { - super::gpkg_blob::temporal(if let Val::Text(t) = v { Some(t) } else { None }, ty, unread, Some(rounded), k) - } + (v, FieldType::Date | FieldType::DateTime) => super::gpkg_blob::temporal(v.text().as_deref(), ty, unread, Some(rounded), k), (Val::Int(i), FieldType::Boolean) => Value::Bool(*i != 0), (Val::Int(i), FieldType::Double) => super::int_as_double(*i, Some(rounded), k), (Val::Int(i), _) => Value::Int(*i), (Val::Real(f), FieldType::Integer) if f.fract() == 0.0 && f.abs() < 9e15 => Value::Int(*f as i64), (Val::Real(f), _) => Value::Float(*f), (Val::Text(t), FieldType::Text) => Value::Text(t.clone()), + (Val::BadText(b), FieldType::Text) => super::utf8_text(b, not_utf8, k), + // Elsewhere it reads as its text with U+FFFD, which no number, date or yes/no word holds. + (Val::BadText(b), FieldType::Boolean) => super::yes_no_text(&String::from_utf8_lossy(b), unread, k), + (Val::BadText(b), ty) => super::number_text(&String::from_utf8_lossy(b), ty, unread, Some(rounded), k), (Val::Text(t), FieldType::Boolean) => super::yes_no_text(t, unread, k), (Val::Text(t), ty) => super::number_text(t, ty, unread, Some(rounded), k), // A blob in a text column is its text, as SQLite stores text either way. diff --git a/crates/data/src/source/mod.rs b/crates/data/src/source/mod.rs index 861196e053..e73ef56ee6 100644 --- a/crates/data/src/source/mod.rs +++ b/crates/data/src/source/mod.rs @@ -316,10 +316,12 @@ pub(crate) fn number_text( if v.is_null() && !text.trim().is_empty() && !crate::Value::is_null_marker(text) { unread_date(counts, k); } - // A number a decimal can't hold as written (`9007199254740993`) is rounded: counted in - // `rounded` ([`Batch::rounded_dates`]), as a whole number stored past 2^53 is. + // A number whose whole-number digits a decimal can't hold (`9007199254740993`) is rounded: + // counted in `rounded` ([`Batch::rounded_dates`]), as a whole number stored past 2^53 is. A + // fraction past what a decimal holds reads as the nearest decimal, as a stored one does. + let trimmed = text.trim().trim_start_matches(['-', '+']); if let (crate::Value::Float(_), Some(rounded)) = (&v, rounded) - && crate::Value::Text(text.trim().to_string()).rounds_as_double() + && crate::query::whole_digits_round(trimmed) { unread_date(rounded, k); } diff --git a/crates/data/src/source/tests.rs b/crates/data/src/source/tests.rs index 9e450be8c8..6fbd0d8ff4 100644 --- a/crates/data/src/source/tests.rs +++ b/crates/data/src/source/tests.rs @@ -4139,14 +4139,16 @@ fn geopackage_values_that_dont_fit_a_number_field_are_said() { // A blob in a text column is its text: nothing lost, nothing said. c.execute("ALTER TABLE t ADD COLUMN name TEXT", []).unwrap(); c.execute("UPDATE t SET name = x'6869' WHERE fid = 3", []).unwrap(); - // Bytes that aren't UTF-8 in a text column: read with U+FFFD in their place, and said. - c.execute("UPDATE t SET name = x'ff68' WHERE fid = 4", []).unwrap(); + // Bytes that aren't UTF-8 in a text column, stored as text and as a blob: read with U+FFFD in + // their place, and said. + c.execute("UPDATE t SET name = CAST(x'ff68' AS TEXT) WHERE fid = 4", []).unwrap(); + c.execute("UPDATE t SET name = x'ff69' WHERE fid = 1", []).unwrap(); c.execute("UPDATE t SET pop = 'n/a', area = 'n/a' WHERE fid = 2", []).unwrap(); c.execute("UPDATE t SET pop = x'00ff', area = x'00' WHERE fid = 3", []).unwrap(); c.execute("UPDATE t SET pop = '', area = '' WHERE fid = 4", []).unwrap(); drop(c); for (values, said) in read() { - assert_eq!(values[0], [Value::Int(1), Value::Float(1.5), Value::Float(9_007_199_254_740_992.0), Value::Null]); + assert_eq!(values[0], [Value::Int(1), Value::Float(1.5), Value::Float(9_007_199_254_740_992.0), Value::Text("\u{FFFD}i".into())]); assert_eq!(values[1], [Value::Null, Value::Null, Value::Float(5.0), Value::Null]); assert_eq!(values[2], [Value::Null, Value::Null, Value::Null, Value::Text("hi".into())]); assert_eq!(values[3], [Value::Null, Value::Null, Value::Null, Value::Text("\u{FFFD}h".into())]); @@ -4157,7 +4159,7 @@ fn geopackage_values_that_dont_fit_a_number_field_are_said() { [ ("t: 4 values aren't numbers and were read as empty, in 'pop', 'area'".to_string(), dropped), ("t: 1 whole number was rounded to the nearest decimal number, as a decimal field doesn't keep more than 15 or 16 digits, in 'big'".to_string(), rounded), - ("t: 1 text value isn't valid UTF-8 and was read with U+FFFD in place of the bytes that can't be read, in 'name'; a GeoPackage holds its text in UTF-8".to_string(), Some(crate::loss::LossCode::ChangedEncoding)), + ("t: 2 text values aren't valid UTF-8 and were read with U+FFFD in place of the bytes that can't be read, in 'name'; a GeoPackage holds its text in UTF-8".to_string(), Some(crate::loss::LossCode::ChangedEncoding)), ] ); } @@ -4175,7 +4177,15 @@ fn number_text_that_rounds_and_text_that_isnt_utf8_are_counted() { } assert_eq!((unread.as_slice(), rounded.as_slice()), (&[][..], &[3][..])); rounded.clear(); - for (text, ty) in [("2.5", FieldType::Double), ("0.1", FieldType::Double), ("12", FieldType::Integer), ("1e3", FieldType::Double)] { + for (text, ty) in [ + ("2.5", FieldType::Double), + ("0.1", FieldType::Double), + ("12", FieldType::Integer), + ("1e3", FieldType::Double), + // A long fraction reads as the nearest decimal: no whole-number digit is lost. + ("0.12345678901234567891", FieldType::Double), + ("1.00000000000000001", FieldType::Double), + ] { super::number_text(text, ty, &mut unread, Some(&mut rounded), 0); } assert!(unread.is_empty() && rounded.is_empty(), "{unread:?} {rounded:?}"); diff --git a/crates/data/src/sqlite.rs b/crates/data/src/sqlite.rs index 7fd2368f4e..d540625a5d 100644 --- a/crates/data/src/sqlite.rs +++ b/crates/data/src/sqlite.rs @@ -16,9 +16,23 @@ pub enum Val { Int(i64), Real(f64), Text(String), + /// Text whose bytes aren't valid UTF-8, kept as they are: a reader that says so can count it + /// ([`Val::text`] reads it with U+FFFD in their place). + BadText(Vec), Blob(Vec), } +impl Val { + /// The text this holds, a [`Val::BadText`]'s with U+FFFD in place of the bytes that aren't UTF-8. + pub fn text(&self) -> Option> { + match self { + Val::Text(t) => Some(std::borrow::Cow::Borrowed(t)), + Val::BadText(b) => Some(String::from_utf8_lossy(b)), + _ => None, + } + } +} + /// A column of a table, as its `CREATE TABLE` declares it. #[derive(Clone, Debug, PartialEq)] pub struct Column { @@ -399,7 +413,14 @@ fn record(p: &[u8]) -> Result, String> { t => { let n = usize::try_from((t - 12) / 2).map_err(|_| bad("record"))?; let s = p.get(body..body.checked_add(n).ok_or_else(|| bad("record"))?).ok_or_else(|| bad("a record past its payload"))?; - (if t % 2 == 0 { Val::Blob(s.to_vec()) } else { Val::Text(String::from_utf8_lossy(s).into_owned()) }, n) + ( + match (t % 2 == 0, std::str::from_utf8(s)) { + (true, _) => Val::Blob(s.to_vec()), + (false, Ok(text)) => Val::Text(text.to_string()), + (false, Err(_)) => Val::BadText(s.to_vec()), + }, + n, + ) } }; body += len; diff --git a/crates/engine/src/cmd/gpkg.rs b/crates/engine/src/cmd/gpkg.rs index 8616ddbffa..4a7530369d 100644 --- a/crates/engine/src/cmd/gpkg.rs +++ b/crates/engine/src/cmd/gpkg.rs @@ -264,6 +264,7 @@ fn save_edits(s: &mut Session, p: &Value) -> CmdResult { let utc_dates = saved_rows.utc_dates; let fine_dates = saved_rows.fine_dates; let rounded_dates = saved_rows.rounded_dates; + let not_utf8 = saved_rows.not_utf8; let unread_dates = saved_rows.unread_dates; let mut stored: std::collections::HashMap<_, _> = saved_rows.features.into_iter().map(|f| (f.id, f)).collect(); let versions = saved.versions.iter().copied().collect(); @@ -341,6 +342,9 @@ fn save_edits(s: &mut Session, p: &Value) -> CmdResult { if let Some(note) = rustgis_data::source::rounded_dates_note(&fields, &rounded_dates) { s.say(note.map_text(|note| format!("{}: {note}, when read back after the save", super::saved_target(&name, table)))); } + if let Some(note) = rustgis_data::source::not_utf8_note(&fields, ¬_utf8, rustgis_data::source::GEOPACKAGE_TEXT) { + s.say(note.map_text(|note| format!("{}: {note}, when read back after the save", super::saved_target(&name, table)))); + } if let Some(note) = rustgis_data::io::utc_dates_note(&fields, &utc_dates, &super::saved_target(&name, table)) { s.say(note); } From eefe5f45a4e74950e016100cac76e3657bc304c0 Mon Sep 17 00:00:00 2001 From: mavrick Date: Fri, 27 Nov 2026 18:17:14 -0600 Subject: [PATCH 07/12] fix(data): a fraction that rounds into the whole number is caught, the rounding notice says numbers, and the guide tells digit-only literals from decimals --- crates/data/src/query.rs | 12 ++++++++---- crates/data/src/query/tests.rs | 2 ++ crates/data/src/source/mod.rs | 6 +++--- crates/data/src/source/tests.rs | 14 +++++++++----- docs/user-guide/expressions.md | 2 +- 5 files changed, 23 insertions(+), 13 deletions(-) diff --git a/crates/data/src/query.rs b/crates/data/src/query.rs index 7893b1a52f..5b168a7054 100644 --- a/crates/data/src/query.rs +++ b/crates/data/src/query.rs @@ -830,8 +830,9 @@ fn number_token(t: &str) -> Result { Ok(Tok::Num(n)) } -/// Whether a decimal literal's whole-number digits, its exponent applied, would be rounded: digits -/// written out (`9007199254740993.0`, `1.2345678901234567891e19`) must be held exactly; zeros an +/// Whether a decimal literal's whole-number digits, its exponent applied, would be changed: digits +/// written out (`9007199254740993.0`, `1.2345678901234567891e19`) must be read back as written, +/// a fraction rounding up into them (`1000000000000000.99`) included; zeros an /// exponent adds past them (`1e307`) weren't written, so only the written digits need holding. /// `false` for one that isn't written in digits. pub(crate) fn whole_digits_round(t: &str) -> bool { @@ -854,9 +855,12 @@ pub(crate) fn whole_digits_round(t: &str) -> bool { let written: String = digits.chars().take(point).collect(); let added = point.saturating_sub(digits.len()); if added == 0 { - // No whole-number digits but zeros (`0.1`): a zero, which every decimal holds. + // The whole part of the decimal read must be the one written: a decimal that can't hold + // those digits (`9007199254740993.0`) changes them, and so does a fraction that rounds up + // into them (`1000000000000000.99` reads as 1000000000000001). let written = written.trim_start_matches('0'); - !crate::io::double_holds(if written.is_empty() { "0" } else { written }) + let written = if written.is_empty() { "0" } else { written }; + !t.parse::().is_ok_and(|x| x.is_finite() && format!("{:.0}", x.abs().trunc()) == written) } else { !crate::io::double_holds(&format!("{written}e{added}")) } diff --git a/crates/data/src/query/tests.rs b/crates/data/src/query/tests.rs index 6a37cb9ab7..c3b8dd5cff 100644 --- a/crates/data/src/query/tests.rs +++ b/crates/data/src/query/tests.rs @@ -82,6 +82,8 @@ fn number_literals_are_exact_or_refused() { "9007199254740993.5", "12345678901234567000.0", "1.2345678901234567891e19", + // A fraction that rounds up into the whole number changes it. + "1000000000000000.99", ] { assert!(parse(text, &d).is_err_and(|e| e.contains("exact") || e.contains("rounded")), "{text}"); } diff --git a/crates/data/src/source/mod.rs b/crates/data/src/source/mod.rs index e73ef56ee6..1cc146ea8c 100644 --- a/crates/data/src/source/mod.rs +++ b/crates/data/src/source/mod.rs @@ -492,13 +492,13 @@ pub fn rounded_dates_note(fields: &[crate::Field], counts: &[usize]) -> Option format!( - "{total} values were rounded, date-times to the microsecond and whole numbers to the nearest decimal number, as more digits than that aren't kept, in {}", + "{total} values were rounded, date-times to the microsecond and numbers to the nearest decimal number, as more digits than that aren't kept, in {}", crate::io::named_fields(fields, counts) ), (true, false) => { - let what = if total == 1 { "1 whole number was".to_string() } else { format!("{total} whole numbers were") }; + let what = if total == 1 { "1 number was".to_string() } else { format!("{total} numbers were") }; format!( - "{what} rounded to the nearest decimal number, as a decimal field doesn't keep more than 15 or 16 digits, in {}", + "{what} rounded to the nearest decimal number, changing digits before the point, as a decimal field doesn't keep more than 15 or 16 digits, in {}", crate::io::named_fields(fields, counts) ) } diff --git a/crates/data/src/source/tests.rs b/crates/data/src/source/tests.rs index 6fbd0d8ff4..e0828c00df 100644 --- a/crates/data/src/source/tests.rs +++ b/crates/data/src/source/tests.rs @@ -4158,7 +4158,7 @@ fn geopackage_values_that_dont_fit_a_number_field_are_said() { said, [ ("t: 4 values aren't numbers and were read as empty, in 'pop', 'area'".to_string(), dropped), - ("t: 1 whole number was rounded to the nearest decimal number, as a decimal field doesn't keep more than 15 or 16 digits, in 'big'".to_string(), rounded), + ("t: 1 number was rounded to the nearest decimal number, changing digits before the point, as a decimal field doesn't keep more than 15 or 16 digits, in 'big'".to_string(), rounded), ("t: 2 text values aren't valid UTF-8 and were read with U+FFFD in place of the bytes that can't be read, in 'name'; a GeoPackage holds its text in UTF-8".to_string(), Some(crate::loss::LossCode::ChangedEncoding)), ] ); @@ -4170,12 +4170,16 @@ fn geopackage_values_that_dont_fit_a_number_field_are_said() { #[test] fn number_text_that_rounds_and_text_that_isnt_utf8_are_counted() { let (mut unread, mut rounded) = (Vec::new(), Vec::new()); - for (text, ty) in - [("9007199254740993", FieldType::Double), ("9223372036854775809", FieldType::Integer), ("9007199254740993.0", FieldType::Double)] - { + for (text, ty) in [ + ("9007199254740993", FieldType::Double), + ("9223372036854775809", FieldType::Integer), + ("9007199254740993.0", FieldType::Double), + // A fraction that rounds up into the whole number changes it. + ("2.99999999999999999", FieldType::Double), + ] { assert!(matches!(super::number_text(text, ty, &mut unread, Some(&mut rounded), 0), Value::Float(_)), "{text}"); } - assert_eq!((unread.as_slice(), rounded.as_slice()), (&[][..], &[3][..])); + assert_eq!((unread.as_slice(), rounded.as_slice()), (&[][..], &[4][..])); rounded.clear(); for (text, ty) in [ ("2.5", FieldType::Double), diff --git a/docs/user-guide/expressions.md b/docs/user-guide/expressions.md index 7776c45127..c9fc8237c2 100644 --- a/docs/user-guide/expressions.md +++ b/docs/user-guide/expressions.md @@ -79,7 +79,7 @@ operator: write `a < b AND b < c`, not `a < b < c`. | Write | Meaning | | --- | --- | -| `42`, `3.5`, `1e6`, `.5` | Numbers; whole numbers are integers, exact up to 9223372036854775807; past that, a decimal when one holds them exactly. A number whose whole-number digits would be rounded (`99999999999999999999`, `9007199254740993.0`, `1.2345678901234567891e19`) is refused, not rounded; digits after the point read as the nearest decimal, as in `0.1` | +| `42`, `3.5`, `1e6`, `.5` | Numbers. Written in digits only (`9007199254740993`), a whole number is an exact integer up to 9223372036854775807, and past that a decimal when one holds it exactly. Written with a point or an exponent (`9007199254740993.0`, `1e6`), a number is a decimal. Either way, one whose whole-number digits would change (`99999999999999999999`, `9007199254740993.0`, `1.2345678901234567891e19`, `1000000000000000.99`) is refused, not rounded; digits after the point read as the nearest decimal, as in `0.1` | | `'text'`, `'it''s'` | Text in single quotes; two quotes stand for one | | `TRUE`, `FALSE`, `NULL` | Booleans and the missing value | | `pop_est`, `"Pop Est"`, `!Pop Est!` | A field, by name, ignoring letter case; quote a name with spaces, punctuation or the name of a keyword (`"OR"`, `"null"`) | From aece224bfc7910682a91a7422f3bc1acddbd10b7 Mon Sep 17 00:00:00 2001 From: mavrick Date: Fri, 27 Nov 2026 19:37:03 -0600 Subject: [PATCH 08/12] fix(data): literals of any size and written exponent digits are checked, schema rows with bad text stay listed, and an edit's read-back baseline covers every column --- crates/data/src/mbtiles.rs | 5 +++-- crates/data/src/query.rs | 32 +++++++++++++++++++++-------- crates/data/src/query/tests.rs | 7 ++++++- crates/data/src/source/gpkg/edit.rs | 11 ++++------ crates/data/src/source/mod.rs | 4 +++- crates/data/src/source/tests.rs | 2 ++ crates/data/src/sqlite.rs | 8 +++++--- 7 files changed, 47 insertions(+), 22 deletions(-) diff --git a/crates/data/src/mbtiles.rs b/crates/data/src/mbtiles.rs index a6e812d6be..56ffee3048 100644 --- a/crates/data/src/mbtiles.rs +++ b/crates/data/src/mbtiles.rs @@ -193,8 +193,9 @@ pub fn read_bytes(bytes: &[u8]) -> Result { && let (Some(n), Some(v)) = (col(m, "name"), col(m, "value")) { db.rows(m, |_, r| { - if let (Some(n), Some(v)) = (r.get(n).and_then(Val::text), r.get(v).and_then(Val::text)) { - meta.push((n.into_owned(), v.into_owned())); + // A metadata row that isn't UTF-8 is passed over, as before. + if let (Some(Val::Text(n)), Some(Val::Text(v))) = (r.get(n), r.get(v)) { + meta.push((n.clone(), v.clone())); } if meta.len() >= 1000 { ControlFlow::Break(()) } else { ControlFlow::Continue(()) } })?; diff --git a/crates/data/src/query.rs b/crates/data/src/query.rs index 5b168a7054..6edc12371d 100644 --- a/crates/data/src/query.rs +++ b/crates/data/src/query.rs @@ -803,9 +803,9 @@ fn lex_first(s: &str, tolerant: bool, most: usize) -> Result { /// The token of a number literal, refusing one that can't be held exactly rather than rounding it. /// A literal of digits only is an exact `i64`; past `i64::MAX`, a decimal that holds it exactly, or /// refused. Any other literal is a -/// decimal (`f64`), refused only when it would lose whole-number digits: it is 1e15 or more, so -/// has 16 or more of them however it is written, and a decimal doesn't hold them -/// (`9007199254740993.0`, `1.2345678901234567891e19`); its fraction digits round as any do. One that merely has no +/// decimal (`f64`), refused only when the decimal read would have other whole-number digits than +/// written (`9007199254740993.0`, `1.2345678901234567891e19`, `2.99999999999999999`); its +/// fraction digits round as any do. One that merely has no /// exact binary form (`0.1`) or many fraction digits (`0.12345678901234567891`) is read as the /// nearest decimal, as every number written in decimal is. fn number_token(t: &str) -> Result { @@ -821,10 +821,10 @@ fn number_token(t: &str) -> Result { return t.parse().map(Tok::Num).map_err(|_| format!("bad number '{t}'")); } let n: f64 = t.parse().map_err(|_| format!("bad number '{t}'"))?; - // A number of 1e15 or more has 16 or more whole-number digits, whether written out or moved - // there by an exponent: refused when a decimal wouldn't hold them. Its fraction digits, past - // them, are read as the nearest decimal, as any fraction is. - if n.is_finite() && n.abs() >= 1e15 && whole_digits_round(t) { + // Refused when the decimal read has other whole-number digits than written: a decimal can't + // hold them, or the fraction rounds up into them (`2.99999999999999999` reads as 3). Its + // fraction digits read as the nearest decimal, as any fraction does. + if n.is_finite() && whole_digits_round(t) { return Err(format!("the number {t} has more whole-number digits than a decimal number holds exactly, so it would be rounded")); } Ok(Tok::Num(n)) @@ -836,6 +836,11 @@ fn number_token(t: &str) -> Result { /// exponent adds past them (`1e307`) weren't written, so only the written digits need holding. /// `false` for one that isn't written in digits. pub(crate) fn whole_digits_round(t: &str) -> bool { + // An ordinary number, with at most 15 digits in all and no exponent, a decimal holds exactly, + // fraction included, so it can't round into the whole part. + if !t.contains(['e', 'E']) && t.trim_start_matches(['0', '.']).bytes().filter(u8::is_ascii_digit).count() <= 15 { + return false; + } let (mantissa, exp) = match t.split_once(['e', 'E']) { Some((m, e)) => match e.parse::() { Ok(e) => (m, e), @@ -862,7 +867,18 @@ pub(crate) fn whole_digits_round(t: &str) -> bool { let written = if written.is_empty() { "0" } else { written }; !t.parse::().is_ok_and(|x| x.is_finite() && format!("{:.0}", x.abs().trunc()) == written) } else { - !crate::io::double_holds(&format!("{written}e{added}")) + // Every digit written counts, trailing zeros too (`100000000000000000000000e1`): the decimal + // read, to as many significant digits, must give them back. The zeros the exponent adds + // weren't written, so `1e24` needs only its `1`. + let written = written.trim_start_matches('0'); + if written.is_empty() { + return false; + } + let precision = written.len() - 1; + !t.parse::().is_ok_and(|x| { + let shown = format!("{:.*e}", precision, x.abs()); + x.is_finite() && shown.split(['e', 'E']).next().is_some_and(|m| m.replace('.', "") == written) + }) } } diff --git a/crates/data/src/query/tests.rs b/crates/data/src/query/tests.rs index c3b8dd5cff..6a319de47c 100644 --- a/crates/data/src/query/tests.rs +++ b/crates/data/src/query/tests.rs @@ -82,8 +82,12 @@ fn number_literals_are_exact_or_refused() { "9007199254740993.5", "12345678901234567000.0", "1.2345678901234567891e19", - // A fraction that rounds up into the whole number changes it. + // A fraction that rounds up into the whole number changes it, at any size. "1000000000000000.99", + "2.99999999999999999", + "99999999999999.99999999", + // Zeros written before an exponent count as digits. + "100000000000000000000000e1", ] { assert!(parse(text, &d).is_err_and(|e| e.contains("exact") || e.contains("rounded")), "{text}"); } @@ -92,6 +96,7 @@ fn number_literals_are_exact_or_refused() { assert_eq!(v("1e3"), Value::Int(1000)); assert_eq!(v("1.5e3"), Value::Int(1500)); assert_eq!(v("1e19"), Value::Float(1e19), "a decimal holds it exactly"); + assert_eq!(v("1e24"), Value::Float(1e24), "only its written 1 needs holding"); // Only whole-number digits are kept from rounding: a fraction past them reads as the nearest decimal. assert_eq!(v("1000000000000000.123456789"), Value::Float(1_000_000_000_000_000.1)); assert_eq!(v("9007199254740992.0"), Value::Float(9_007_199_254_740_992.0)); diff --git a/crates/data/src/source/gpkg/edit.rs b/crates/data/src/source/gpkg/edit.rs index 31930f7371..60e80f7645 100644 --- a/crates/data/src/source/gpkg/edit.rs +++ b/crates/data/src/source/gpkg/edit.rs @@ -345,13 +345,10 @@ impl EditTable { tx.execute(&format!("UPDATE {table} SET {} WHERE {pk} = ?", sets.join(", ")), params_from_iter(args)).map_err(err)? as u64; saved.updated += 1; } - // What the date columns of the updated rows held before the save, to tell a value the save - // changed from one the load already said; the rest of the rows isn't kept. - let dated: Vec = snapshot_columns - .iter() - .filter(|(i, _)| fields.get(*i).is_some_and(|f| matches!(f.ty, crate::FieldType::Date | crate::FieldType::DateTime))) - .map(|&(_, c)| c) - .collect(); + // What the columns of the updated rows held before the save, to tell a value the save changed + // from one the load already said (a date that isn't one, a number that isn't, text that isn't + // UTF-8); the rest of the rows isn't kept. + let dated: Vec = snapshot_columns.iter().map(|&(_, c)| c).collect(); let before: std::collections::HashMap<(i64, usize), Sql> = current.iter().flat_map(|(k, row)| dated.iter().filter_map(move |&c| row.get(c).map(|v| ((*k, c), v.clone())))).collect(); drop(current); diff --git a/crates/data/src/source/mod.rs b/crates/data/src/source/mod.rs index 1cc146ea8c..8e995d9ad6 100644 --- a/crates/data/src/source/mod.rs +++ b/crates/data/src/source/mod.rs @@ -320,7 +320,9 @@ pub(crate) fn number_text( // counted in `rounded` ([`Batch::rounded_dates`]), as a whole number stored past 2^53 is. A // fraction past what a decimal holds reads as the nearest decimal, as a stored one does. let trimmed = text.trim().trim_start_matches(['-', '+']); - if let (crate::Value::Float(_), Some(rounded)) = (&v, rounded) + // Text past a decimal's range reads as infinity: an overflow, not a rounding. + if let (crate::Value::Float(f), Some(rounded)) = (&v, rounded) + && f.is_finite() && crate::query::whole_digits_round(trimmed) { unread_date(rounded, k); diff --git a/crates/data/src/source/tests.rs b/crates/data/src/source/tests.rs index e0828c00df..3122c706c3 100644 --- a/crates/data/src/source/tests.rs +++ b/crates/data/src/source/tests.rs @@ -4189,6 +4189,8 @@ fn number_text_that_rounds_and_text_that_isnt_utf8_are_counted() { // A long fraction reads as the nearest decimal: no whole-number digit is lost. ("0.12345678901234567891", FieldType::Double), ("1.00000000000000001", FieldType::Double), + // Past a decimal's range: infinity, an overflow, not counted as rounded. + ("1e400", FieldType::Double), ] { super::number_text(text, ty, &mut unread, Some(&mut rounded), 0); } diff --git a/crates/data/src/sqlite.rs b/crates/data/src/sqlite.rs index d540625a5d..f22cf32aa2 100644 --- a/crates/data/src/sqlite.rs +++ b/crates/data/src/sqlite.rs @@ -293,16 +293,18 @@ impl> Db { let mut out = Vec::new(); let mut err = None; self.scan(1, |_, row| { - if let [Val::Text(kind), Val::Text(name), _, Val::Int(root), Val::Text(sql), ..] = row.as_slice() + // Text that isn't UTF-8 reads with U+FFFD, as it always did: such a table is still listed. + if let [kind, name, _, Val::Int(root), sql, ..] = row.as_slice() + && let (Some(kind), Some(name), Some(sql)) = (kind.text(), name.text(), sql.text()) && kind == "table" { // Unparsable tables are passed over; another may be wanted. - if let Ok(p) = parse_table(sql) { + if let Ok(p) = parse_table(&sql) { match u32::try_from(*root) { // A virtual table (an R-tree index, say) has no pages of its own. Ok(0) => {} Ok(root) => out.push(Table { - name: name.clone(), + name: name.to_string(), root, columns: p.columns, rowid_column: p.rowid_column, From 79f8bdf492159f76ea52e4f330d9cae644f78a3b Mon Sep 17 00:00:00 2001 From: mavrick Date: Fri, 27 Nov 2026 20:34:39 -0600 Subject: [PATCH 09/12] fix(data): MBTiles metadata keeps bad text as before, the save baseline keeps only cells a read can say, and field packages say text that isn't UTF-8 --- crates/data/src/mbtiles.rs | 6 +++--- crates/data/src/source/gpkg/edit.rs | 23 +++++++++++++++++------ crates/engine/src/cmd/field.rs | 1 + 3 files changed, 21 insertions(+), 9 deletions(-) diff --git a/crates/data/src/mbtiles.rs b/crates/data/src/mbtiles.rs index 56ffee3048..771903bb69 100644 --- a/crates/data/src/mbtiles.rs +++ b/crates/data/src/mbtiles.rs @@ -193,9 +193,9 @@ pub fn read_bytes(bytes: &[u8]) -> Result { && let (Some(n), Some(v)) = (col(m, "name"), col(m, "value")) { db.rows(m, |_, r| { - // A metadata row that isn't UTF-8 is passed over, as before. - if let (Some(Val::Text(n)), Some(Val::Text(v))) = (r.get(n), r.get(v)) { - meta.push((n.clone(), v.clone())); + // Text that isn't UTF-8 reads with U+FFFD, as it always did. + if let (Some(n), Some(v)) = (r.get(n).and_then(Val::text), r.get(v).and_then(Val::text)) { + meta.push((n.into_owned(), v.into_owned())); } if meta.len() >= 1000 { ControlFlow::Break(()) } else { ControlFlow::Continue(()) } })?; diff --git a/crates/data/src/source/gpkg/edit.rs b/crates/data/src/source/gpkg/edit.rs index 60e80f7645..a0233680f9 100644 --- a/crates/data/src/source/gpkg/edit.rs +++ b/crates/data/src/source/gpkg/edit.rs @@ -345,12 +345,23 @@ impl EditTable { tx.execute(&format!("UPDATE {table} SET {} WHERE {pk} = ?", sets.join(", ")), params_from_iter(args)).map_err(err)? as u64; saved.updated += 1; } - // What the columns of the updated rows held before the save, to tell a value the save changed - // from one the load already said (a date that isn't one, a number that isn't, text that isn't - // UTF-8); the rest of the rows isn't kept. - let dated: Vec = snapshot_columns.iter().map(|&(_, c)| c).collect(); - let before: std::collections::HashMap<(i64, usize), Sql> = - current.iter().flat_map(|(k, row)| dated.iter().filter_map(move |&c| row.get(c).map(|v| ((*k, c), v.clone())))).collect(); + // What the updated rows held before the save, to tell a value the save changed from one the + // load already said. Only a value a read can say something of is kept: text or a blob (a + // date that isn't one, a number that isn't, text that isn't UTF-8) or a whole number in a + // decimal field; the deleted rows and the rest of each row aren't. + let updated: std::collections::HashSet = edits.updates.iter().map(|(f, _)| f.id.cast_signed()).collect(); + let decimal: std::collections::HashSet = snapshot_columns + .iter() + .filter(|(i, _)| fields.get(*i).is_some_and(|f| f.ty == crate::FieldType::Double)) + .map(|&(_, c)| c) + .collect(); + let said = |c: usize, v: &Sql| matches!(v, Sql::Text(_) | Sql::Blob(_)) || matches!(v, Sql::Integer(_)) && decimal.contains(&c); + let columns_kept: Vec = snapshot_columns.iter().map(|&(_, c)| c).collect(); + let before: std::collections::HashMap<(i64, usize), Sql> = current + .iter() + .filter(|(k, _)| updated.contains(k)) + .flat_map(|(k, row)| columns_kept.iter().filter_map(move |&c| row.get(c).filter(|v| said(c, v)).map(|v| ((*k, c), v.clone())))) + .collect(); drop(current); // Reserve the loaded baseline as well as live and historical keys. A deleted source row // can still be present in the layer, so SQLite's ordinary rowid allocation is not enough. diff --git a/crates/engine/src/cmd/field.rs b/crates/engine/src/cmd/field.rs index 52ac809cd6..38a3b3c2d9 100644 --- a/crates/engine/src/cmd/field.rs +++ b/crates/engine/src/cmd/field.rs @@ -850,6 +850,7 @@ fn copy_stream( source::unread_dates_note(&info.fields, &batch.unread_dates), source::rounded_dates_note(&info.fields, &batch.rounded_dates), source::null_text_note(&info.fields, &batch.null_text), + source::not_utf8_note(&info.fields, &batch.not_utf8, src.text_encoding()), ]; losses.extend(info.notes.iter().chain(&batch.notes).cloned().map(|note| note.prefixed(&layer.name))); losses.extend(counted.into_iter().flatten().map(|note| note.prefixed(&layer.name))); From b8e716833968d8ca14db4c717be4989181b58348 Mon Sep 17 00:00:00 2001 From: mavrick Date: Fri, 27 Nov 2026 21:23:43 -0600 Subject: [PATCH 10/12] fix(data): the save baseline keeps every cell of a date column, as before --- crates/data/src/source/gpkg/edit.rs | 16 ++++++++++++---- 1 file changed, 12 insertions(+), 4 deletions(-) diff --git a/crates/data/src/source/gpkg/edit.rs b/crates/data/src/source/gpkg/edit.rs index a0233680f9..2e9f22469a 100644 --- a/crates/data/src/source/gpkg/edit.rs +++ b/crates/data/src/source/gpkg/edit.rs @@ -346,16 +346,24 @@ impl EditTable { saved.updated += 1; } // What the updated rows held before the save, to tell a value the save changed from one the - // load already said. Only a value a read can say something of is kept: text or a blob (a - // date that isn't one, a number that isn't, text that isn't UTF-8) or a whole number in a - // decimal field; the deleted rows and the rest of each row aren't. + // load already said. Only a value a read can say something of is kept: any value of a date + // column, text or a blob (a number that isn't one, text that isn't UTF-8) or a whole number + // in a decimal field; the deleted rows and the rest of each row aren't. let updated: std::collections::HashSet = edits.updates.iter().map(|(f, _)| f.id.cast_signed()).collect(); let decimal: std::collections::HashSet = snapshot_columns .iter() .filter(|(i, _)| fields.get(*i).is_some_and(|f| f.ty == crate::FieldType::Double)) .map(|&(_, c)| c) .collect(); - let said = |c: usize, v: &Sql| matches!(v, Sql::Text(_) | Sql::Blob(_)) || matches!(v, Sql::Integer(_)) && decimal.contains(&c); + let dated: std::collections::HashSet = snapshot_columns + .iter() + .filter(|(i, _)| fields.get(*i).is_some_and(|f| matches!(f.ty, crate::FieldType::Date | crate::FieldType::DateTime))) + .map(|&(_, c)| c) + .collect(); + // A date column's every cell, as before (a number there isn't a date either). + let said = |c: usize, v: &Sql| { + dated.contains(&c) || matches!(v, Sql::Text(_) | Sql::Blob(_)) || matches!(v, Sql::Integer(_)) && decimal.contains(&c) + }; let columns_kept: Vec = snapshot_columns.iter().map(|&(_, c)| c).collect(); let before: std::collections::HashMap<(i64, usize), Sql> = current .iter() From 6cbfa935563a885a636aa540c19d8d07c44f6a12 Mon Sep 17 00:00:00 2001 From: mavrick Date: Fri, 27 Nov 2026 22:07:38 -0600 Subject: [PATCH 11/12] fix(data): a number past a decimal's range reads as empty and is said, NaN and infinity words are kept, and the save baseline moves its cells --- crates/data/src/source/gpkg/edit.rs | 10 ++++++---- crates/data/src/source/mod.rs | 9 ++++++++- crates/data/src/source/tests.rs | 15 +++++++++++++-- 3 files changed, 27 insertions(+), 7 deletions(-) diff --git a/crates/data/src/source/gpkg/edit.rs b/crates/data/src/source/gpkg/edit.rs index 2e9f22469a..82dfe8343e 100644 --- a/crates/data/src/source/gpkg/edit.rs +++ b/crates/data/src/source/gpkg/edit.rs @@ -364,13 +364,15 @@ impl EditTable { let said = |c: usize, v: &Sql| { dated.contains(&c) || matches!(v, Sql::Text(_) | Sql::Blob(_)) || matches!(v, Sql::Integer(_)) && decimal.contains(&c) }; - let columns_kept: Vec = snapshot_columns.iter().map(|&(_, c)| c).collect(); + let columns_kept: std::collections::HashSet = snapshot_columns.iter().map(|&(_, c)| c).collect(); + // Moved out of the rows read, which aren't needed past here: no second copy. let before: std::collections::HashMap<(i64, usize), Sql> = current - .iter() + .into_iter() .filter(|(k, _)| updated.contains(k)) - .flat_map(|(k, row)| columns_kept.iter().filter_map(move |&c| row.get(c).filter(|v| said(c, v)).map(|v| ((*k, c), v.clone())))) + .flat_map(|(k, row)| { + row.into_iter().enumerate().filter(|(c, v)| columns_kept.contains(c) && said(*c, v)).map(move |(c, v)| ((k, c), v)) + }) .collect(); - drop(current); // Reserve the loaded baseline as well as live and historical keys. A deleted source row // can still be present in the layer, so SQLite's ordinary rowid allocation is not enough. let mut high_water = 0; diff --git a/crates/data/src/source/mod.rs b/crates/data/src/source/mod.rs index 8e995d9ad6..fe4ba575f8 100644 --- a/crates/data/src/source/mod.rs +++ b/crates/data/src/source/mod.rs @@ -312,7 +312,14 @@ pub(crate) fn number_text( rounded: Option<&mut Vec>, k: usize, ) -> crate::Value { - let v = crate::Value::parse_source(text, ty); + // `NaN` and `inf` written as words are kept as they are (a field holds them, and a save writes + // them back); a number in digits past a decimal's range (`1e400`) would be infinity, which it + // isn't: empty, and said as text that isn't a number. + let words = |t: &str| matches!(t.trim().trim_start_matches(['-', '+']).to_ascii_lowercase().as_str(), "nan" | "inf" | "infinity"); + let v = match crate::Value::parse_source(text, ty) { + crate::Value::Float(f) if !f.is_finite() && !words(text) => crate::Value::Null, + v => v, + }; if v.is_null() && !text.trim().is_empty() && !crate::Value::is_null_marker(text) { unread_date(counts, k); } diff --git a/crates/data/src/source/tests.rs b/crates/data/src/source/tests.rs index 3122c706c3..a16d9e5142 100644 --- a/crates/data/src/source/tests.rs +++ b/crates/data/src/source/tests.rs @@ -4189,12 +4189,23 @@ fn number_text_that_rounds_and_text_that_isnt_utf8_are_counted() { // A long fraction reads as the nearest decimal: no whole-number digit is lost. ("0.12345678901234567891", FieldType::Double), ("1.00000000000000001", FieldType::Double), - // Past a decimal's range: infinity, an overflow, not counted as rounded. - ("1e400", FieldType::Double), ] { super::number_text(text, ty, &mut unread, Some(&mut rounded), 0); } assert!(unread.is_empty() && rounded.is_empty(), "{unread:?} {rounded:?}"); + // NaN and infinity written as words are kept, uncounted; a number in digits past a decimal's + // range is empty, and counted. + for text in ["nan", "inf", "-Infinity"] { + assert!( + matches!(super::number_text(text, FieldType::Double, &mut unread, Some(&mut rounded), 0), Value::Float(f) if !f.is_finite()), + "{text}" + ); + } + assert!(unread.is_empty() && rounded.is_empty(), "{unread:?} {rounded:?}"); + for text in ["1e400", "-1e400"] { + assert_eq!(super::number_text(text, FieldType::Double, &mut unread, Some(&mut rounded), 0), Value::Null, "{text}"); + } + assert_eq!((unread.as_slice(), rounded.as_slice()), (&[2][..], &[][..])); let mut not_utf8 = Vec::new(); assert_eq!(super::utf8_text(b"hi", &mut not_utf8, 0), Value::Text("hi".into())); assert!(not_utf8.is_empty()); From dfefb1c9e3e5e3fd4ba6a22fb3ba48a9bf277321 Mon Sep 17 00:00:00 2001 From: mavrick Date: Fri, 27 Nov 2026 23:17:16 -0600 Subject: [PATCH 12/12] fix(data): the save baseline keeps no text cells of a text column, which no read says anything of --- crates/data/src/source/gpkg/edit.rs | 20 +++++++++++++++----- 1 file changed, 15 insertions(+), 5 deletions(-) diff --git a/crates/data/src/source/gpkg/edit.rs b/crates/data/src/source/gpkg/edit.rs index 82dfe8343e..64ba8e863e 100644 --- a/crates/data/src/source/gpkg/edit.rs +++ b/crates/data/src/source/gpkg/edit.rs @@ -346,9 +346,8 @@ impl EditTable { saved.updated += 1; } // What the updated rows held before the save, to tell a value the save changed from one the - // load already said. Only a value a read can say something of is kept: any value of a date - // column, text or a blob (a number that isn't one, text that isn't UTF-8) or a whole number - // in a decimal field; the deleted rows and the rest of each row aren't. + // load already said. Only a value a read can say something of is kept (see `said`); the + // deleted rows and the rest of each row aren't. let updated: std::collections::HashSet = edits.updates.iter().map(|(f, _)| f.id.cast_signed()).collect(); let decimal: std::collections::HashSet = snapshot_columns .iter() @@ -360,9 +359,20 @@ impl EditTable { .filter(|(i, _)| fields.get(*i).is_some_and(|f| matches!(f.ty, crate::FieldType::Date | crate::FieldType::DateTime))) .map(|&(_, c)| c) .collect(); - // A date column's every cell, as before (a number there isn't a date either). + let text: std::collections::HashSet = snapshot_columns + .iter() + .filter(|(i, _)| fields.get(*i).is_some_and(|f| f.ty == crate::FieldType::Text)) + .map(|&(_, c)| c) + .collect(); + // A date column's every cell, as before (a number there isn't a date either); text in a + // number or yes/no column; a blob anywhere (in a text column, its bytes may not be UTF-8); + // a whole number in a decimal column. Text in a text column was read as UTF-8 here + // already, so nothing is said of it and it isn't kept. let said = |c: usize, v: &Sql| { - dated.contains(&c) || matches!(v, Sql::Text(_) | Sql::Blob(_)) || matches!(v, Sql::Integer(_)) && decimal.contains(&c) + dated.contains(&c) + || matches!(v, Sql::Blob(_)) + || matches!(v, Sql::Text(_)) && !text.contains(&c) + || matches!(v, Sql::Integer(_)) && decimal.contains(&c) }; let columns_kept: std::collections::HashSet = snapshot_columns.iter().map(|&(_, c)| c).collect(); // Moved out of the rows read, which aren't needed past here: no second copy.