Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion crates/data/src/export/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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() },
Expand Down
6 changes: 4 additions & 2 deletions crates/data/src/mbtiles.rs
Original file line number Diff line number Diff line change
Expand Up @@ -173,6 +173,7 @@ fn key(v: Option<&Val>) -> Option<Key> {
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,
}
Expand All @@ -192,8 +193,9 @@ pub fn read_bytes(bytes: &[u8]) -> Result<Archive, String> {
&& 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(()) }
})?;
Expand Down
97 changes: 92 additions & 5 deletions crates/data/src/query.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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),
Expand Down Expand Up @@ -777,7 +779,7 @@ fn lex_first(s: &str, tolerant: bool, most: usize) -> Result<Lexed, String> {
}
}
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;
Expand All @@ -798,6 +800,88 @@ fn lex_first(s: &str, tolerant: bool, most: usize) -> Result<Lexed, String> {
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<Tok, String> {
if t.bytes().all(|b| b.is_ascii_digit()) {
if let Ok(i) = t.parse::<i64>() {
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::<i64>() {
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();
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
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::<f64>().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::<f64>().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) }
Expand Down Expand Up @@ -1089,9 +1173,10 @@ impl Parser<'_> {
/// `1 IN (1 IN (…))` meets the limit.
fn item(&mut self) -> Result<Expr, String> {
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();
}
Expand Down Expand Up @@ -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()?;
}
Expand Down Expand Up @@ -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) {
Expand Down Expand Up @@ -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!(
"'{}'",
Expand Down
6 changes: 3 additions & 3 deletions crates/data/src/query/complete.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
37 changes: 37 additions & 0 deletions crates/data/src/query/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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::<usize>::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())
}
Expand Down
46 changes: 35 additions & 11 deletions crates/data/src/source/gpkg.rs
Original file line number Diff line number Diff line change
Expand Up @@ -471,13 +471,14 @@ impl GpkgSource {
req: &Request,
unread_dates: &mut Vec<usize>,
rounded_dates: &mut Vec<usize>,
not_utf8: &mut Vec<usize>,
) -> rusqlite::Result<Row> {
// Integer keys, negative ones too, map to distinct ids.
let Some(id) = r.get::<_, Option<i64>>(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,
Expand Down Expand Up @@ -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
}
Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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)?;
Expand Down Expand Up @@ -1573,24 +1583,38 @@ 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<usize>, rounded: Option<&mut Vec<usize>>, 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<usize>,
rounded: Option<&mut Vec<usize>>,
not_utf8: &mut Vec<usize>,
k: usize,
) -> Value {
match (v, ty) {
(ValueRef::Null, _) => Value::Null,
(v, FieldType::Date | FieldType::DateTime) => {
let text = if let ValueRef::Text(t) = v { Some(String::from_utf8_lossy(t)) } else { None };
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
}
}
}

Expand Down
Loading
Loading