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/mbtiles.rs b/crates/data/src/mbtiles.rs index f75f5311ce..771903bb69 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,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(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/query.rs b/crates/data/src/query.rs index 982d4e0e9e..6edc12371d 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,88 @@ 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`; past `i64::MAX`, a decimal that holds it exactly, or +/// refused. Any other literal is a +/// 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 { + if t.bytes().all(|b| b.is_ascii_digit()) { + 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}'"))?; + // 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)) +} + +/// 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 { + // 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), + 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 { + // 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'); + 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 { + // 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) + }) + } +} + /// 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 +1173,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 +1310,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 +1384,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 +1527,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..6a319de47c 100644 --- a/crates/data/src/query/tests.rs +++ b/crates/data/src/query/tests.rs @@ -66,6 +66,43 @@ 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()); + // 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", + "1.2345678901234567891e19", + // 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}"); + } + 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("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)); + 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..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)?; @@ -1573,9 +1583,17 @@ 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. -fn value(v: ValueRef<'_>, ty: FieldType, unread: &mut Vec, rounded: Option<&mut Vec>, k: usize) -> Value { +/// 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>, + not_utf8: &mut Vec, + k: usize, +) -> Value { match (v, ty) { (ValueRef::Null, _) => Value::Null, (v, FieldType::Date | FieldType::DateTime) => { @@ -1583,14 +1601,20 @@ 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::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) => 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, rounded, k), + // A blob in a text column is its text, as SQLite stores text either way. + (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); + Value::Null + } } } diff --git a/crates/data/src/source/gpkg/edit.rs b/crates/data/src/source/gpkg/edit.rs index 3b82085fd6..64ba8e863e 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, } @@ -63,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. @@ -159,6 +164,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 +189,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())); @@ -295,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(); @@ -306,7 +319,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())?))); @@ -332,16 +345,44 @@ 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 + // 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 (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() + .filter(|(i, _)| fields.get(*i).is_some_and(|f| f.ty == crate::FieldType::Double)) + .map(|&(_, c)| c) + .collect(); + 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(); - 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); + 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::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. + let before: std::collections::HashMap<(i64, usize), Sql> = current + .into_iter() + .filter(|(k, _)| updated.contains(k)) + .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(); // 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; @@ -446,11 +487,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), 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; } @@ -511,6 +553,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 483c41038d..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(()); }; @@ -320,27 +317,40 @@ 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`]). -fn value(v: &Val, ty: FieldType, unread: &mut Vec, rounded: &mut Vec, k: usize) -> Value { +/// 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, 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) - } - (Val::Blob(_), _) => Value::Null, + (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) => 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::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) => Value::parse_source(t, ty), + (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) => super::utf8_text(b, not_utf8, k), + // A blob isn't a value another attribute column holds. + (Val::Blob(_), _) => { + super::unread_date(unread, k); + Value::Null + } } } impl FeatureSource for GpkgMemSource { + /// 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 } @@ -365,7 +375,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 @@ -383,7 +393,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(()); @@ -420,7 +430,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(()) }) @@ -437,7 +447,7 @@ impl FeatureSource for GpkgMemSource { rounded_dates, null_text: Vec::new(), notes: Default::default(), - not_utf8: Vec::new(), + not_utf8, }) } @@ -494,7 +504,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) => { @@ -515,11 +525,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 3af146d1ac..fe4ba575f8 100644 --- a/crates/data/src/source/mod.rs +++ b/crates/data/src/source/mod.rs @@ -301,13 +301,76 @@ 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, + rounded: Option<&mut Vec>, + k: usize, +) -> crate::Value { + // `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); + } + // 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(['-', '+']); + // 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); + } + 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 { + 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); } /// 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); } @@ -352,14 +415,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`]). + 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)) @@ -386,6 +469,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 { @@ -394,21 +483,42 @@ 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)) } -/// 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 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!( + "{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 number was".to_string() } else { format!("{total} numbers were") }; + format!( + "{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) + ) + } + _ => { + 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..a16d9e5142 100644 --- a/crates/data/src/source/tests.rs +++ b/crates/data/src/source/tests.rs @@ -4095,6 +4095,124 @@ 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(); + // 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, 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::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())]); + 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 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)), + ] + ); + } +} + +/// 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), + // 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()), (&[][..], &[4][..])); + rounded.clear(); + 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:?}"); + // 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()); + 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/data/src/sqlite.rs b/crates/data/src/sqlite.rs index 7fd2368f4e..f22cf32aa2 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 { @@ -279,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, @@ -399,7 +415,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/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))); diff --git a/crates/engine/src/cmd/gpkg.rs b/crates/engine/src/cmd/gpkg.rs index 71f94a2cc1..4a7530369d 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); } @@ -261,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(); @@ -338,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); } @@ -401,6 +408,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"); } diff --git a/docs/user-guide/expressions.md b/docs/user-guide/expressions.md index ce69221c90..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 | +| `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"`) |