diff --git a/crates/analysis/src/network.rs b/crates/analysis/src/network.rs index 907f4b7150..cfa8a6d798 100644 --- a/crates/analysis/src/network.rs +++ b/crates/analysis/src/network.rs @@ -382,24 +382,96 @@ fn snap_window(p: Coord, m: f64) -> Option<[f64; 4]> { (p.x - dlon > -180.0 && p.x + dlon < 180.0).then_some([p.x - dlon, p.x + dlon, p.y - dlat, p.y + dlat]) } -/// Runs the original search on a private copy, so endpoint attachments never leak across calls. -/// Cloning the node and adjacency vectors is one step without a Cancel check inside it. +/// Per-query endpoint attachments layered over the shared [`Network`] without cloning its node or +/// adjacency vectors: at most two virtual snapped nodes (`base_n`, `base_n + 1`) and at most ten +/// extra directed edges (four per interior snap, plus two for a direct same-segment link). +struct ExtraGraph { + base_n: usize, + nodes: [Coord; 2], + node_len: usize, + edges: [(usize, Edge); 10], + edge_len: usize, + /// Base nodes (`< base_n`) that have at least one outgoing edge in `edges`. + base_sources: [usize; 6], + base_source_len: usize, +} + +impl ExtraGraph { + fn new(base_n: usize) -> Self { + Self { + base_n, + nodes: [Coord::new(0.0, 0.0); 2], + node_len: 0, + edges: [(0, (0, 0.0, 0.0, 0)); 10], + edge_len: 0, + base_sources: [0; 6], + base_source_len: 0, + } + } + + fn total_nodes(&self) -> usize { + self.base_n + self.node_len + } + + fn push_node(&mut self, c: Coord) -> Option { + let slot = self.nodes.get_mut(self.node_len)?; + *slot = c; + let id = self.base_n + self.node_len; + self.node_len += 1; + Some(id) + } + + fn push_edge(&mut self, from: usize, edge: Edge) { + if let Some(slot) = self.edges.get_mut(self.edge_len) { + *slot = (from, edge); + self.edge_len += 1; + } + if from < self.base_n + && let Some(seen) = self.base_sources.get(..self.base_source_len) + && !seen.contains(&from) + && let Some(slot) = self.base_sources.get_mut(self.base_source_len) + { + *slot = from; + self.base_source_len += 1; + } + } + + fn coord(&self, graph: &Network, id: usize) -> Option { + if id < self.base_n { + graph.nodes.get(id).copied() + } else { + let idx = id - self.base_n; + (idx < self.node_len).then(|| self.nodes.get(idx).copied()).flatten() + } + } + + fn has_edges(&self, u: usize) -> bool { + u >= self.base_n || self.base_sources.get(..self.base_source_len).is_some_and(|s| s.contains(&u)) + } + + fn edges(&self) -> &[(usize, Edge)] { + self.edges.get(..self.edge_len).unwrap_or(&[]) + } +} + +/// Searches the shared graph directly with a tiny overlay for snapped endpoints, so endpoint +/// attachments never leak across calls and the node and adjacency vectors are never cloned. fn route_on(graph: &Network, ds: &Dataset, from: Coord, to: Coord, snap_m: f64) -> Result { crate::control::check()?; - let mut nodes = graph.nodes.clone(); - let mut adj = graph.adj.clone(); let segs = &graph.segs; let skipped_segments = graph.skipped_segments; let route_error = |reason, skipped| route_error(ds, reason, skipped, graph.overflowing); - let nearest = |p: Coord, nodes: &[Coord]| nearest_segment(segs, nodes, p, None); + if segs.is_empty() { + return Err(route_error("the layer has no lines".into(), skipped_segments)); + } + let too_far = + || route_error(format!("a route end is more than {} from the network", rustgis_geom::format_distance(snap_m)), skipped_segments); + let mut extra = ExtraGraph::new(graph.nodes.len()); // Each end becomes a node on its segment, joined to the segment's two ends. - let attach = |p: Coord, nodes: &mut Vec, adj: &mut Vec>| -> Result<(usize, usize, f64), String> { - let (si, t, q, d) = nearest(p, nodes)?.ok_or_else(|| route_error("the layer has no lines".into(), skipped_segments))?; + let mut attach = |p: Coord| -> Result<(usize, usize, f64), String> { + let (si, t, q, d) = nearest_segment(segs, &graph.nodes, p, Some(snap_m))?.ok_or_else(too_far)?; if d > snap_m { - return Err(route_error( - format!("a route end is more than {} from the network", rustgis_geom::format_distance(snap_m)), - skipped_segments, - )); + return Err(too_far()); } let &(a, b, weight, row) = segs.get(si).ok_or_else(|| route_error("the layer has no lines".into(), skipped_segments))?; if t <= 0.0 { @@ -408,36 +480,26 @@ fn route_on(graph: &Network, ds: &Dataset, from: Coord, to: Coord, snap_m: f64) if t >= 1.0 { return Ok((b, si, t)); } - nodes.push(q); - adj.push(Vec::new()); - let n = nodes.len() - 1; + let n = extra.push_node(q).ok_or_else(|| route_error("the layer has no lines".into(), skipped_segments))?; for end in [a, b] { - let len = wgs84_distance_m(q, nodes.get(end).copied().unwrap_or(q)); - if let Some(v) = adj.get_mut(n) { - v.push((end, len * weight, len, row)); - } - if let Some(v) = adj.get_mut(end) { - v.push((n, len * weight, len, row)); - } + let len = wgs84_distance_m(q, graph.nodes.get(end).copied().unwrap_or(q)); + extra.push_edge(n, (end, len * weight, len, row)); + extra.push_edge(end, (n, len * weight, len, row)); } Ok((n, si, t)) }; - let (s, s_seg, s_t) = attach(from, &mut nodes, &mut adj)?; - let (t, t_seg, t_t) = attach(to, &mut nodes, &mut adj)?; + let (s, s_seg, s_t) = attach(from)?; + let (t, t_seg, t_t) = attach(to)?; // Both ends on one segment: they're joined directly along it. if s_seg == t_seg && s != t && (0.0..=1.0).contains(&s_t) && (0.0..=1.0).contains(&t_t) { - let (Some(&(_, _, weight, row)), Some(a), Some(b)) = (segs.get(s_seg), nodes.get(s).copied(), nodes.get(t).copied()) else { + let (Some(&(_, _, weight, row)), Some(a), Some(b)) = (segs.get(s_seg), extra.coord(graph, s), extra.coord(graph, t)) else { return Err(route_error("the layer has no lines".into(), skipped_segments)); }; let len = wgs84_distance_m(a, b); - if let Some(v) = adj.get_mut(s) { - v.push((t, len * weight, len, row)); - } - if let Some(v) = adj.get_mut(t) { - v.push((s, len * weight, len, row)); - } + extra.push_edge(s, (t, len * weight, len, row)); + extra.push_edge(t, (s, len * weight, len, row)); } - let n = nodes.len(); + let n = extra.total_nodes(); let mut dist = vec![f64::INFINITY; n]; let mut prev: Vec> = vec![None; n]; let mut heap = BinaryHeap::new(); @@ -446,7 +508,7 @@ fn route_on(graph: &Network, ds: &Dataset, from: Coord, to: Coord, snap_m: f64) *d = 0.0; } heap.push(State(0.0, s)); - crate::control::begin(nodes.len()); + crate::control::begin(n); let mut visited = 0; let mut pace = crate::control::Pace::default(); while let Some(State(d, u)) = heap.pop() { @@ -459,7 +521,7 @@ fn route_on(graph: &Network, ds: &Dataset, from: Coord, to: Coord, snap_m: f64) if d > dist.get(u).copied().unwrap_or(f64::INFINITY) { continue; } - for &(v, c, len, row) in adj.get(u).map(Vec::as_slice).unwrap_or(&[]) { + let mut relax = |(v, c, len, row): Edge| -> Result<(), String> { if pace.stop(4096) { return Err(crate::control::Cancelled.into()); } @@ -476,6 +538,17 @@ fn route_on(graph: &Network, ds: &Dataset, from: Coord, to: Coord, snap_m: f64) } heap.push(State(nd, v)); } + Ok(()) + }; + for &edge in graph.adj.get(u).map(Vec::as_slice).unwrap_or(&[]) { + relax(edge)?; + } + if extra.has_edges(u) { + for &(src, edge) in extra.edges() { + if src == u { + relax(edge)?; + } + } } } let cost = dist.get(t).copied().unwrap_or(f64::INFINITY); @@ -493,10 +566,10 @@ fn route_on(graph: &Network, ds: &Dataset, from: Coord, to: Coord, snap_m: f64) let mut length = 0.0; let mut used = Vec::new(); let mut at = t; - path.push(nodes.get(t).copied().unwrap_or(to)); + path.push(extra.coord(graph, t).unwrap_or(to)); while let Some(Some((p, len, row))) = prev.get(at) { crate::control::check()?; - path.push(nodes.get(*p).copied().unwrap_or(from)); + path.push(extra.coord(graph, *p).unwrap_or(from)); length += len; if used.last() != Some(row) { used.push(*row); @@ -1900,4 +1973,32 @@ mod tests { ds.push(Some(Geometry::Point(point)), vec![]); assert!(within(&ds, &[0], center, 100_000.0).is_empty()); } + + #[test] + fn route_overlay_handles_empty_far_same_segment_and_endpoint_snaps() { + let cache = Mutex::new(None); + let empty = Dataset::new("empty", GeometryType::Polyline, vec![]); + let err = shortest_route_with(&cache, &empty, &[], Coord::new(0.0, 0.0), Coord::new(0.1, 0.0), None, 100.0).unwrap_err(); + assert!(err.contains("the layer has no lines"), "{err}"); + + let mut ds = Dataset::new("roads", GeometryType::Polyline, vec![]); + ds.push(Some(Geometry::Line(vec![vec![Coord::new(0.0, 0.0), Coord::new(0.1, 0.0)]])), vec![]); + // Outside snap window: still reports the snap-distance error rather than "no lines". + let far = shortest_route_with(&cache, &ds, &[0], Coord::new(5.0, 5.0), Coord::new(0.05, 0.0), None, 50.0).unwrap_err(); + assert!(far.contains("more than"), "{far}"); + + // Reverse direction along the same segment (interior to interior) and vertex-to-interior. + let rev = shortest_route_with(&cache, &ds, &[0], Coord::new(0.07, 0.0), Coord::new(0.02, 0.0), None, 50.0).unwrap(); + let expected_rev = wgs84_distance_m(Coord::new(0.07, 0.0), Coord::new(0.02, 0.0)); + assert!((rev.length_m - expected_rev).abs() < 1e-6 && rev.path.len() == 2, "{rev:?}"); + + let v2i = shortest_route_with(&cache, &ds, &[0], Coord::new(0.0, 0.0), Coord::new(0.04, 0.0), None, 50.0).unwrap(); + let expected_v2i = wgs84_distance_m(Coord::new(0.0, 0.0), Coord::new(0.04, 0.0)); + assert!((v2i.length_m - expected_v2i).abs() < 1e-6 && v2i.path.len() == 2, "{v2i:?}"); + + // Vertex to vertex on the same segment. + let v2v = shortest_route_with(&cache, &ds, &[0], Coord::new(0.0, 0.0), Coord::new(0.1, 0.0), None, 50.0).unwrap(); + let expected_v2v = wgs84_distance_m(Coord::new(0.0, 0.0), Coord::new(0.1, 0.0)); + assert!((v2v.length_m - expected_v2v).abs() < 1e-6 && v2v.path.len() == 2, "{v2v:?}"); + } } diff --git a/crates/analysis/src/rasterops.rs b/crates/analysis/src/rasterops.rs index 1fab346287..cad7882d32 100644 --- a/crates/analysis/src/rasterops.rs +++ b/crates/analysis/src/rasterops.rs @@ -910,15 +910,18 @@ fn kmeans_on(threads: Option, r: &Raster, bands: &[usize], k: usize, iter true }; // Seeds spread across the value range of the first band. - let valid: Vec = (0..n).step_by((n / 20_000).max(1)).filter(|i| pixel(*i).is_some()).collect(); + let is_valid_pixel = |i: usize| data.iter().all(|d| d.get(i).copied().is_some_and(|v| r.is_valid(v))); + let valid: Vec = (0..n).step_by((n / 20_000).max(1)).filter(|i| is_valid_pixel(*i)).collect(); if valid.len() < k { return Err("too few valid pixels to classify".into()); } + let band0 = data.first().copied().unwrap_or(&[]); + let norm = |v: f32| if v == 0.0 { 0.0 } else { v }; let mut sorted = valid.clone(); sorted.sort_by(|a, b| { - let (va, vb) = - (pixel(*a).and_then(|p| p.first().copied()).unwrap_or(0.0), pixel(*b).and_then(|p| p.first().copied()).unwrap_or(0.0)); - va.partial_cmp(&vb).unwrap_or(std::cmp::Ordering::Equal) + let va = norm(band0.get(*a).copied().unwrap_or(0.0)); + let vb = norm(band0.get(*b).copied().unwrap_or(0.0)); + va.total_cmp(&vb) }); let mut centres: Vec> = (0..k).filter_map(|i| sorted.get((i * 2 + 1) * sorted.len() / (2 * k)).and_then(|j| pixel(*j))).collect(); @@ -929,10 +932,15 @@ fn kmeans_on(threads: Option, r: &Raster, bands: &[usize], k: usize, iter .min_by(|a, b| a.1.partial_cmp(&b.1).unwrap_or(std::cmp::Ordering::Equal)) .map_or(0, |x| x.0) }; + let mut sums = vec![vec![0.0; data.len()]; centres.len()]; + let mut counts = vec![0usize; centres.len()]; + let mut p = Vec::with_capacity(data.len()); for _ in 0..iterations.clamp(1, 50) { - let mut sums = vec![vec![0.0; data.len()]; centres.len()]; - let mut counts = vec![0usize; centres.len()]; - let mut p = Vec::with_capacity(data.len()); + crate::control::check()?; + for s in &mut sums { + s.fill(0.0); + } + counts.fill(0); for i in &valid { if pixel_into(*i, &mut p) { let c = nearest(&p, ¢res); @@ -944,7 +952,10 @@ fn kmeans_on(threads: Option, r: &Raster, bands: &[usize], k: usize, iter } for ((c, s), n) in centres.iter_mut().zip(&sums).zip(&counts) { if *n > 0 { - *c = s.iter().map(|v| v / *n as f64).collect(); + let count = *n as f64; + for (cv, sv) in c.iter_mut().zip(s) { + *cv = *sv / count; + } } } } @@ -2186,6 +2197,22 @@ mod tests { run.cancel(); let _installed = crate::control::install(Some(run)); assert_eq!(kmeans_on(Some(4), &r, &[0, 1, 2], 7, 10).unwrap_err(), crate::control::CANCELLED); + drop(_installed); + // Cancellation inside the k-means iteration loop stops before assigning rows. + let mid = crate::control::Control::cancelled_at_look(3); + let _installed = crate::control::install(Some(mid.clone())); + assert_eq!(kmeans_on(Some(1), &r, &[0, 1, 2], 7, 10).unwrap_err(), crate::control::CANCELLED); + assert_eq!(mid.looked(), 3); + } + + #[test] + fn kmeans_seed_sort_treats_negative_and_positive_zero_as_equal() { + let gt = GeoTransform { origin_x: 0.0, origin_y: 1.0, pixel_width: 1.0, pixel_height: -1.0 }; + let band0 = vec![0.0, 0.0, 0.0, 0.0, 0.0, -0.0, -0.0, -0.0]; + let band1 = vec![0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0]; + let r = Raster::new("zeros", 8, 1, vec![band0, band1], gt, Crs::LonLat, None, ColorHint::Gray, "Float32").unwrap(); + let classes = kmeans_on(Some(1), &r, &[0, 1], 2, 1).unwrap(); + assert_eq!(classes, vec![1.0, 1.0, 1.0, 1.0, 1.0, 2.0, 2.0, 2.0]); } /// Zonal means test only the cells in their zone's window (#1252), and give what testing diff --git a/crates/data/src/query.rs b/crates/data/src/query.rs index 98b9e9e2ad..fe79b5f2ac 100644 --- a/crates/data/src/query.rs +++ b/crates/data/src/query.rs @@ -50,7 +50,7 @@ pub enum Expr { }, Like { field: usize, - pattern: String, + pattern: LikePattern, negate: bool, }, IsNull { @@ -108,6 +108,32 @@ pub enum Op { Ge, } +/// Pre-lowercased `LIKE` pattern kept on [`Expr::Like`] so row evaluation avoids re-allocating +/// and re-lowercasing the constant pattern on every row. +#[derive(Clone, Debug, PartialEq)] +pub struct LikePattern { + kind: CompiledLike, +} + +#[derive(Clone, Debug, PartialEq)] +enum CompiledLike { + /// Pure ASCII pattern, already lowercased to ASCII bytes. + Ascii(Vec), + /// Pattern containing non-ASCII characters, already lowercased to `char`s. + Unicode(Vec), +} + +impl LikePattern { + fn compile(pat: &str) -> Self { + let kind = if pat.is_ascii() { + CompiledLike::Ascii(pat.bytes().map(|b| b.to_ascii_lowercase()).collect()) + } else { + CompiledLike::Unicode(pat.to_lowercase().chars().collect()) + }; + Self { kind } + } +} + #[derive(Clone, Copy, Debug, PartialEq)] pub enum Arith { Add, @@ -983,7 +1009,9 @@ impl Parser<'_> { self.note_compared_as(&l, true); let p = self.concat()?; return Ok(match (l, p) { - (Expr::Field(field), Expr::Lit(Value::Text(pattern))) => Expr::Like { field, pattern, negate }, + (Expr::Field(field), Expr::Lit(Value::Text(pattern))) => { + Expr::Like { field, pattern: LikePattern::compile(&pattern), negate } + } (e, p) => Expr::LikeExpr { e: Box::new(e), pattern: Box::new(p), negate }, }); } @@ -1478,13 +1506,17 @@ fn parse_expression(text: &str, ds: &Dataset, validate_areas: bool) -> Result bool { - if let Some((x, y)) = a.temporal_keys(b) { - return x == y; + // Fast paths for same-type text and integer values (neither is a date/date-time). + if let (Value::Text(x), Value::Text(y)) = (a, b) { + return x.eq_ignore_ascii_case(y); } // Whole numbers compare exactly: through f64, neighbours above 2^53 would be equal. if let (Value::Int(x), Value::Int(y)) = (a, b) { return x == y; } + if let Some((x, y)) = a.temporal_keys(b) { + return x == y; + } match (a.as_f64(), b.as_f64()) { // A whole number against another number: equal exactly when the order says so. (Some(_), Some(_)) if matches!(a, Value::Int(_)) || matches!(b, Value::Int(_)) => { @@ -1546,10 +1578,41 @@ fn like_within(text: &str, pat: &str, budget: &Cell) -> Option { m } +/// [`like_within`] against a pre-compiled [`LikePattern`]. +fn like_within_compiled(text: &str, pat: &LikePattern, budget: &Cell) -> Option { + let had = budget.get(); + if had == 0 { + return None; + } + let mut left = had.min(MAX_LIKE_STEPS); + let start = left; + let m = match &pat.kind { + CompiledLike::Ascii(p) if text.is_ascii() => like_steps_ascii::(text.as_bytes(), p, &mut left), + CompiledLike::Ascii(p) => { + let t: Vec = text.to_lowercase().chars().collect(); + like_steps_chars(&t, p, &mut left) + } + CompiledLike::Unicode(p) => { + let t: Vec = text.to_lowercase().chars().collect(); + like_steps_chars(&t, p, &mut left) + } + }; + budget.set(had - (start - left)); + m +} + /// [`like_within`], counting its steps down in `left`. fn like_steps(text: &str, pat: &str, left: &mut usize) -> Option { + if text.is_ascii() && pat.is_ascii() { + return like_steps_ascii::(text.as_bytes(), pat.as_bytes(), left); + } let t: Vec = text.to_lowercase().chars().collect(); let p: Vec = pat.to_lowercase().chars().collect(); + like_steps_chars(&t, &p, left) +} + +/// Zero-allocation ASCII `LIKE` matching with identical step accounting to [`like_steps_chars`]. +fn like_steps_ascii(t: &[u8], p: &[u8], left: &mut usize) -> Option { // Iterative wildcard matching with backtracking on the last '%'. let (mut ti, mut pi) = (0usize, 0usize); let (mut star, mut mark) = (None::, 0usize); @@ -1559,12 +1622,54 @@ fn like_steps(text: &str, pat: &str, left: &mut usize) -> Option { } *left -= 1; match p.get(pi) { + Some(&b'%') => { + star = Some(pi); + mark = ti; + pi += 1; + } + Some(&pc) => { + let pc = if P_LOWERED { pc } else { pc.to_ascii_lowercase() }; + if pc == b'_' || t.get(ti).is_some_and(|tb| tb.to_ascii_lowercase() == pc) { + ti += 1; + pi += 1; + } else if let Some(s) = star { + pi = s + 1; + mark += 1; + ti = mark; + } else { + return Some(false); + } + } + None => match star { + Some(s) => { + pi = s + 1; + mark += 1; + ti = mark; + } + None => return Some(false), + }, + } + } + Some(p.get(pi..).is_some_and(|rest| rest.iter().all(|c| *c == b'%'))) +} + +/// Unicode `LIKE` matching over pre-lowercased character slices. +fn like_steps_chars>(t: &[char], p: &[P], left: &mut usize) -> Option { + // Iterative wildcard matching with backtracking on the last '%'. + let (mut ti, mut pi) = (0usize, 0usize); + let (mut star, mut mark) = (None::, 0usize); + while ti < t.len() { + if *left == 0 { + return None; + } + *left -= 1; + match p.get(pi).map(|&c| c.into()) { Some('%') => { star = Some(pi); mark = ti; pi += 1; } - Some(c) if *c == '_' || Some(c) == t.get(ti) => { + Some(c) if c == '_' || Some(&c) == t.get(ti) => { ti += 1; pi += 1; } @@ -1578,7 +1683,7 @@ fn like_steps(text: &str, pat: &str, left: &mut usize) -> Option { }, } } - Some(p.get(pi..).is_some_and(|rest| rest.iter().all(|c| *c == '%'))) + Some(p.get(pi..).is_some_and(|rest| rest.iter().all(|&c| c.into() == '%'))) } /// Whether any branch can read polygon area, including unit-converted area functions. @@ -1880,7 +1985,15 @@ impl<'a> Eval<'a> { if v.is_null() || self.like_steps.get() == 0 { return None; } - like_within(&v.to_string(), pattern, &self.like_steps).map(|m| m != *negate) + let owned; + let text = match v { + Value::Text(s) => s.as_str(), + other => { + owned = other.to_string(); + owned.as_str() + } + }; + like_within_compiled(text, pattern, &self.like_steps).map(|m| m != *negate) } Expr::In { field, values, negate } => { let v = ds.value(row, *field); @@ -1902,12 +2015,27 @@ impl<'a> Eval<'a> { if v.is_null() || p.is_null() { return None; } - let p = p.to_string(); + let p_owned; + let p_str = match &*p { + Value::Text(s) => s.as_str(), + other => { + p_owned = other.to_string(); + p_owned.as_str() + } + }; // A longer pattern matches nothing, so NOT LIKE holds. - if p.chars().count() > MAX_LEN { + if p_str.chars().count() > MAX_LEN { return Some(*negate); } - like_within(&v.to_string(), &p, &self.like_steps).map(|m| m != *negate) + let v_owned; + let v_str = match &*v { + Value::Text(s) => s.as_str(), + other => { + v_owned = other.to_string(); + v_owned.as_str() + } + }; + like_within(v_str, p_str, &self.like_steps).map(|m| m != *negate) } Expr::InExpr { e, list, negate } => { let v = self.value(e); diff --git a/crates/data/src/query/tests.rs b/crates/data/src/query/tests.rs index 58e005836a..1efafa1b63 100644 --- a/crates/data/src/query/tests.rs +++ b/crates/data/src/query/tests.rs @@ -906,3 +906,32 @@ fn errors_say_why_they_are_null() { } assert_eq!(why("sqrt(0)", 0), (Value::Float(0.0), None)); } + +#[test] +fn text_equality_and_like_preserve_unicode_and_numeric_semantics() { + let mut d = Dataset::new( + "places", + GeometryType::None, + vec![Field::new("name", FieldType::Text), Field::new("code", FieldType::Text), Field::new("pop", FieldType::Integer)], + ); + d.push(None, vec![Value::Text("California".into()), Value::Text("1".into()), Value::Int(2100)]); + d.push(None, vec![Value::Text("İstanbul".into()), Value::Text("1.0".into()), Value::Int(500)]); + d.push(None, vec![Value::Text("München".into()), Value::Text("é".into()), Value::Int(230)]); + d.push(None, vec![Value::Text("New York".into()), Value::Text("2026-01-01".into()), Value::Null]); + + // Text-to-text equality is case-insensitive ASCII and never parses numbers or dates. + assert_eq!(select("name = 'california'", &d).unwrap(), vec![0]); + assert_eq!(select("code = '1.0'", &d).unwrap(), vec![1]); + assert_eq!(select("code = '1'", &d).unwrap(), vec![0]); + assert_eq!(select("code = '2026-01-01T00:00:00Z'", &d).unwrap(), Vec::::new()); + // Text against numeric literal still compares numerically. + assert_eq!(select("code = 1", &d).unwrap(), vec![0, 1]); + + // LIKE handles ASCII fast-path, ASCII pattern against Unicode text, Unicode pattern, and non-text fields. + assert_eq!(select("name LIKE '%york%'", &d).unwrap(), vec![3]); + assert_eq!(select("name LIKE '%i%'", &d).unwrap(), vec![0, 1]); + assert_eq!(select("code LIKE '_'", &d).unwrap(), vec![0, 2]); + assert_eq!(select("name LIKE 'MÜ%'", &d).unwrap(), vec![2]); + assert_eq!(select("pop LIKE '21%'", &d).unwrap(), vec![0]); + assert_eq!(select("name NOT LIKE '%york%'", &d).unwrap(), vec![0, 1, 2]); +} diff --git a/crates/data/src/row_access.rs b/crates/data/src/row_access.rs index 8ad36651fd..5a2935529f 100644 --- a/crates/data/src/row_access.rs +++ b/crates/data/src/row_access.rs @@ -216,6 +216,18 @@ impl Features { } } + /// Copies each row's id from the matching row of `other`, truncating to `other.len()` if + /// `self` has more rows. Updates in place when these rows aren't shared. + pub fn copy_ids_from(&mut self, other: &Features) { + let keep = self.rows.len().min(other.rows.len()); + self.max_id = None; + let rows = self.rows_mut(); + rows.truncate(keep); + for (dst, src) in rows.iter_mut().zip(other.rows.iter()) { + dst.id = src.id; + } + } + /// A copy of every row as a [`Feature`]: for tests and for code that needs the rows as a list, /// at the cost of building it. pub fn to_rows(&self) -> Vec { @@ -330,6 +342,27 @@ mod tests { ds.push(None, vec![]); assert_eq!(ds.features.rows().map(|r| r.id()).collect::>(), [1, 40, 41]); } + + #[test] + fn copy_ids_from_updates_in_place_when_unshared_and_truncates_to_source() { + let mut src = layer(); + src.features.truncate_rows(2); + src.features.push_row(Feature { id: 99, geometry: None, attrs: vec![Value::Text("z".into()), Value::Int(9)] }); + // `dst` is exclusively owned, so copying ids updates in place without firing the copy hook. + let mut dst = layer(); + let (_, fired) = crate::before_rows_copy(Box::new(|| {}), || dst.features.copy_ids_from(&src.features)); + assert!(!fired); + assert_eq!(dst.features.rows().map(|r| r.id()).collect::>(), [1, 2, 99]); + // `max_id` was cleared, so a new push takes an id above 99. + dst.push(None, vec![Value::Text("d".into()), Value::Int(4)]); + assert_eq!(dst.features.rows().map(|r| r.id()).collect::>(), [1, 2, 99, 100]); + // Shared `dst` copies on write and truncates when `src` has fewer rows. + let shared = dst.features.clone(); + let (_, fired) = crate::before_rows_copy(Box::new(|| {}), || dst.features.copy_ids_from(&src.features)); + assert!(fired); + assert_eq!(dst.features.len(), 3); + assert_eq!(shared.len(), 4); + } } /// With the `count-row-uses` feature, which only `cargo xtask rows` turns on, the row vector's diff --git a/crates/engine/src/cmd/publish.rs b/crates/engine/src/cmd/publish.rs index 5a866315d7..c5ca32f102 100644 --- a/crates/engine/src/cmd/publish.rs +++ b/crates/engine/src/cmd/publish.rs @@ -100,34 +100,26 @@ pub(crate) fn publish_work(s: &Session, p: &Value) -> Result = dataset.features.iter().map(|f| f.id).collect(); - held.features = published - .read - .features - .iter() - .zip(&ids) - .map(|(f, id)| rustgis_data::Feature { id: *id, ..f.clone() }) - .collect::>() - .into(); - held.fields = published.read.fields.clone(); - for field in &mut held.fields { - if let Some(was) = dataset.fields.iter().find(|was| was.name == field.name) { - field.alias = was.alias.clone(); - } - } - held.crs = published.read.crs; - // In the system the file is read in, which a layer a project saved before RustGIS - // kept a file's own coordinates (held in longitude/latitude) takes with them. - held.held_in = published.read.coord_crs(); // Already hashed before the files were placed: Cancel must not leave a successful // write without its sync record. Feature ids do not contribute to the digest. let new = rustgis_data::sync::Synced { files: published.files, rows: published.rows, native: published.native }; // Unchanged when the file reads as the layer is: compared by the digest of the kind // the new record keeps, hashed above. - let held = (of_kind(new.native.is_some()) != Some(new.digest())).then_some(held); + let held = (of_kind(new.native.is_some()) != Some(new.digest())).then(|| { + // The layer as the file now reads it, its features keeping their ids: move the + // freshly read dataset in place rather than cloning every feature. + let mut read = published.read; + read.features.copy_ids_from(&dataset.features); + for field in &mut read.fields { + if let Some(was) = dataset.fields.iter().find(|was| was.name == field.name) { + field.alias = was.alias.clone(); + } + } + // In the system the file is read in, which a layer a project saved before RustGIS + // kept a file's own coordinates (held in longitude/latitude) takes with them. + read.held_in = read.coord_crs(); + read + }); let (said, written_path) = (path.clone(), Some(path.clone())); let then: Then = Box::new(move |s: &mut Session, _: &mut Value| { let mark = s.notice_mark(); diff --git a/xtask/row-uses.txt b/xtask/row-uses.txt index 5c52ff9646..9b9e9b2c53 100644 --- a/xtask/row-uses.txt +++ b/xtask/row-uses.txt @@ -4,4 +4,4 @@ # down: new code reads and changes rows through the accessors on `Features` # (crates/data/src/row_access.rs). When a change lowers it, run `cargo xtask rows --update` and # commit this file with it. -count = 768 +count = 764