diff --git a/crates/data/src/query.rs b/crates/data/src/query.rs index c33beef8e2..7ddb384acb 100644 --- a/crates/data/src/query.rs +++ b/crates/data/src/query.rs @@ -1828,19 +1828,28 @@ fn like_steps_chars>(t: &[char], p: &[P], left: &mut usize) /// Whether any branch can read polygon area, including unit-converted area functions. /// Source workers use this after parsing against metadata, before evaluating actual chunks. pub fn uses_area(e: &Expr) -> bool { - let any = |es: &[Expr]| es.iter().any(uses_area); + uses_measure(e, |kind| kind == Measure::Area) +} + +/// Whether evaluating the expression can measure the feature's geometry. +pub fn uses_geometry(e: &Expr) -> bool { + uses_measure(e, |_| true) +} + +fn uses_measure(e: &Expr, measure: fn(Measure) -> bool) -> bool { + let any = |es: &[Expr]| es.iter().any(|e| uses_measure(e, measure)); match e { - Expr::Var(Var::Measure(Measure::Area, _)) => true, + Expr::Var(Var::Measure(kind, _)) => measure(*kind), Expr::And(es) | Expr::Or(es) | Expr::Concat(es) | Expr::Call(_, es) => any(es), - Expr::Not(e) | Expr::IsNullExpr { e, .. } => uses_area(e), - Expr::Compare(_, a, b) | Expr::LikeExpr { e: a, pattern: b, .. } => uses_area(a) || uses_area(b), - Expr::InExpr { e, list, .. } => uses_area(e) || any(list), - Expr::Between { e, lo, hi, .. } => uses_area(e) || uses_area(lo) || uses_area(hi), - Expr::Chain(first, rest) => uses_area(first) || rest.iter().any(|(_, e)| uses_area(e)), + Expr::Not(e) | Expr::IsNullExpr { e, .. } => uses_measure(e, measure), + Expr::Compare(_, a, b) | Expr::LikeExpr { e: a, pattern: b, .. } => uses_measure(a, measure) || uses_measure(b, measure), + Expr::InExpr { e, list, .. } => uses_measure(e, measure) || any(list), + Expr::Between { e, lo, hi, .. } => uses_measure(e, measure) || uses_measure(lo, measure) || uses_measure(hi, measure), + Expr::Chain(first, rest) => uses_measure(first, measure) || rest.iter().any(|(_, e)| uses_measure(e, measure)), Expr::Case { subject, arms, otherwise } => { - subject.as_deref().is_some_and(uses_area) - || arms.iter().any(|(w, t)| uses_area(w) || uses_area(t)) - || otherwise.as_deref().is_some_and(uses_area) + subject.as_deref().is_some_and(|e| uses_measure(e, measure)) + || arms.iter().any(|(w, t)| uses_measure(w, measure) || uses_measure(t, measure)) + || otherwise.as_deref().is_some_and(|e| uses_measure(e, measure)) } Expr::Cmp { .. } | Expr::Like { .. } | Expr::IsNull { .. } | Expr::In { .. } | Expr::Lit(_) | Expr::Field(_) | Expr::Var(_) => { false diff --git a/crates/engine/src/cmd/gp.rs b/crates/engine/src/cmd/gp.rs index d74cf53b2c..0d42cd2771 100644 --- a/crates/engine/src/cmd/gp.rs +++ b/crates/engine/src/cmd/gp.rs @@ -1349,7 +1349,7 @@ struct MapInputs<'a> { /// outputs are made in. work: Crs, /// The layers (by lowercase name) it reads only the attributes of, read as they are - /// ([`attributes_only`]); none when it works in longitude/latitude. + /// ([`attributes_only`]). unread: std::collections::HashSet, /// Import warnings from local file inputs, kept in the tool result and history. messages: Vec, @@ -1545,10 +1545,9 @@ fn inputs_of<'a>( } } let mut left_out_whole = std::collections::HashSet::new(); - let work = work_inputs(&snap.map, &snap.tables, spec, params, &mut full, &mut messages, &mut losses, &mut left_out_whole)?; + let (work, unread) = work_inputs(&snap.map, &snap.tables, spec, params, &mut full, &mut messages, &mut losses, &mut left_out_whole)?; let mut rows = env_inputs(&snap.map, &full, &snap.env, params)?; narrow_to_queries(&snap.map, spec, params, &full, &mut rows, &mut messages)?; - let unread = if work == Crs::LonLat { std::collections::HashSet::new() } else { attributes_only(spec, params) }; #[cfg(not(target_arch = "wasm32"))] let mut held = Vec::new(); #[cfg(not(target_arch = "wasm32"))] @@ -2062,24 +2061,43 @@ fn work_system( .unwrap_or(Crs::LonLat) } -/// The layers (by lowercase name) whose attributes alone a tool reads, given under a parameter -/// whose geometry it doesn't read ([`ToolSpec::reads_geometry_of`]) or one of the names it also -/// accepts for it: they are read as they are, in whatever system, so a place of theirs the system -/// it works in can't hold doesn't send it to longitude/latitude. -/// -/// [`ToolSpec::reads_geometry_of`]: rustgis_analysis::ToolSpec::reads_geometry_of -fn attributes_only(spec: Option<&rustgis_analysis::ToolSpec>, params: &Value) -> std::collections::HashSet { +/// The inputs whose geometry the tool doesn't use, by lowercase name or standalone table key. +fn attributes_only( + map: &rustgis_map::Map, + tables: &[crate::project::Table], + spec: Option<&rustgis_analysis::ToolSpec>, + params: &Value, +) -> std::collections::HashSet { let Some(spec) = spec else { return std::collections::HashSet::new() }; + // Built-in aliases have already been normalized into the declared layer parameters. + let geometry = spec + .params + .iter() + .filter(|p| p.kind == rustgis_analysis::ParamKind::Layer && spec.reads_geometry_of(p.name)) + .filter_map(|p| params.get(p.name)); + let table_id = |value: &Value| { + if let Some(name) = value.as_str() { + match project_input(map, tables, name, false) { + Some(ProjectInput::Table(t)) => Some(t.id), + _ => None, + } + } else { + value.as_u64().and_then(|n| u32::try_from(n).ok()) + } + }; + let same_input = |a: &Value, b: &Value| { + a.as_str().zip(b.as_str()).is_some_and(|(a, b)| a.eq_ignore_ascii_case(b)) || table_id(a).is_some_and(|id| table_id(b) == Some(id)) + }; spec.params .iter() .filter(|p| !spec.reads_geometry_of(p.name)) .flat_map(|p| { let aliases = rustgis_analysis::param_aliases(spec, p.name); - if aliases.is_empty() { vec![p.name] } else { aliases.to_vec() } + if aliases.is_empty() { std::slice::from_ref(&p.name) } else { aliases } }) .filter_map(|k| params.get(k)) - // A standalone table given by its number, by the key it would be converted under. - .filter_map(|v| v.as_str().map(str::to_ascii_lowercase).or_else(|| v.as_u64().and_then(|n| u32::try_from(n).ok()).map(table_key))) + .filter(|source| !geometry.clone().any(|target| same_input(source, target))) + .filter_map(|v| v.as_str().map(str::to_ascii_lowercase).or_else(|| table_id(v).map(table_key))) .collect() } @@ -2088,7 +2106,8 @@ fn attributes_only(spec: Option<&rustgis_analysis::ToolSpec>, params: &Value) -> /// longitude/latitude. An input with a place that system can't hold has the run work in /// longitude/latitude instead, and a message says so (the conversions made for the first attempt /// are dropped then, and the inputs read again in longitude/latitude, a feature with a place -/// that has none there either read without its geometry, [`inputs_in`]). Returns the system. +/// that has none there either read without its geometry, [`inputs_in`]). Returns the system +/// and the keys of the inputs read in their own coordinates for attributes alone. fn work_inputs( map: &rustgis_map::Map, tables: &[crate::project::Table], @@ -2098,7 +2117,7 @@ fn work_inputs( messages: &mut Vec, losses: &mut Vec, left_out_whole: &mut std::collections::HashSet, -) -> Result { +) -> Result<(Crs, std::collections::HashSet), String> { // A loss with its code; the rest as messages. let mut say = |said: Vec| { for note in said { @@ -2109,12 +2128,13 @@ fn work_inputs( } }; let work = work_system(map, spec, params, full); + let mut unread = attributes_only(map, tables, spec, params); if work != Crs::LonLat { - match inputs_in(map, tables, spec, params, full, work, left_out_whole) { + match inputs_in(map, tables, spec, params, full, work, &unread, left_out_whole) { Ok((converted, said)) => { full.extend(converted); say(said); - return Ok(work); + return Ok((work, unread)); } Err(e) => { // A Cancel isn't a place that can't be held. @@ -2124,10 +2144,20 @@ fn work_inputs( } } } - let (converted, said) = inputs_in(map, tables, spec, params, full, Crs::LonLat, left_out_whole)?; + // A definition query can read geometry even when the join itself doesn't. Keep the + // longitude/latitude conversion in that case, including its notice for unplaceable features. + unread.retain(|key| { + !map.layer_by_name(key).is_some_and(|layer| { + let ds = full.get(key).unwrap_or(&layer.dataset); + layer.definition_query.as_deref().is_some_and(|query| { + rustgis_data::query::parse_fields(query, ds).is_ok_and(|expr| rustgis_data::query::uses_geometry(&expr)) + }) + }) + }); + let (converted, said) = inputs_in(map, tables, spec, params, full, Crs::LonLat, &unread, left_out_whole)?; full.extend(converted); say(said); - Ok(Crs::LonLat) + Ok((Crs::LonLat, unread)) } /// Copies of the layers a tool reads converted into `work`, by lowercase name: those read whole @@ -2142,6 +2172,7 @@ fn inputs_in( params: &Value, full: &std::collections::HashMap, work: Crs, + unread: &std::collections::HashSet, left_out_whole: &mut std::collections::HashSet, ) -> Result<(std::collections::HashMap, Vec), String> { let mut converted = std::collections::HashMap::new(); @@ -2178,9 +2209,6 @@ fn inputs_in( std::borrow::Cow::Borrowed(_) => None, }) }; - // Read only for its attributes in a run in its first input's system: as it is. (The first - // input, if it is named there too, is in that system already.) - let unread = if work == Crs::LonLat { std::collections::HashSet::new() } else { attributes_only(spec, params) }; for (key, ds) in full { if unread.contains(&key.to_ascii_lowercase()) { continue; @@ -2223,15 +2251,12 @@ fn inputs_in( } } // A standalone table given by its number ([`Inputs::table`]), as one given by name: under a - // layer parameter (or a name it also accepts), the only place a number is a table's; not one - // the tool reads only the attributes of, in a run in its first input's system. + // layer parameter (or a name it also accepts), the only place a number is a table's. let mut ids = Vec::new(); if let Some(spec) = spec { use rustgis_analysis::ParamKind as K; - let layers = spec.params.iter().filter(|p| { - matches!(p.kind, K::Layer | K::PolygonLayer | K::PointLayer | K::VectorLayer | K::VectorLayers) - && (work == Crs::LonLat || spec.reads_geometry_of(p.name)) - }); + let layers = + spec.params.iter().filter(|p| matches!(p.kind, K::Layer | K::PolygonLayer | K::PointLayer | K::VectorLayer | K::VectorLayers)); for p in layers { let aliases = rustgis_analysis::param_aliases(spec, p.name); let keys: &[&str] = if aliases.is_empty() { std::slice::from_ref(&p.name) } else { aliases }; @@ -2242,12 +2267,13 @@ fn inputs_in( } } for t in tables.iter().filter(|t| ids.contains(&u64::from(t.id))) { - if t.dataset.geometry_type == rustgis_data::GeometryType::None { + let key = table_key(t.id); + if unread.contains(&key) || t.dataset.geometry_type == rustgis_data::GeometryType::None { continue; } if let Some(c) = convert(&t.dataset)? { say(&t.dataset, &c)?; - converted.insert(table_key(t.id), c); + converted.insert(key, c); } } // One notice for them all, naming each layer. diff --git a/crates/engine/src/tests/held_layers.rs b/crates/engine/src/tests/held_layers.rs index e8c95897f8..5b7192010b 100644 --- a/crates/engine/src/tests/held_layers.rs +++ b/crates/engine/src/tests/held_layers.rs @@ -1694,6 +1694,75 @@ fn a_join_tables_places_dont_decide_the_system() { assert_eq!(ds.value(0, ds.field_index("owner").unwrap()).to_string(), "far owner"); } +/// A longitude/latitude join reads the source's keys even when its geometry cannot be placed +/// there. The same source used as the target still needs conversion and its loss notice. +#[test] +fn a_lonlat_join_only_converts_geometry_it_uses() { + let mut s = session(Crs::LonLat); + let mut owners = + Dataset::new("Owners", GeometryType::Polyline, vec![Field::new("n", FieldType::Integer), Field::new("owner", FieldType::Text)]); + owners.held_in = UTM; + let place = Crs::LonLat.to(UTM).unwrap().point(Coord::new(11.5, 48.7)).unwrap(); + let line_at = |p: Coord| Some(Geometry::Line(vec![vec![p, Coord::new(p.x + 10.0, p.y)]])); + owners.push(line_at(place), vec![Cell::Int(1), Cell::Text("near owner".into())]); + owners.push(line_at(Coord::new(1e12, 1e12)), vec![Cell::Int(0), Cell::Text("far owner".into())]); + let table = s.project.add_table(owners.clone()); + let layer = s.map_mut().add_dataset(owners); + s.map_mut().layer_mut(layer).unwrap().definition_query = Some("n >= 0".into()); + let join = + json!({"tool":"joinField", "params":{"input":"Parcels", "targetField":"n", "join":"OWNERS", "fields":"owner", "output":"Owned"}}); + let mark = s.notice_mark(); + s.run("gp.run", &join).unwrap(); + let ds = &s.map().layer_by_name("Owned").unwrap().dataset; + assert_eq!(ds.value(0, ds.field_index("owner").unwrap()), &Cell::Text("far owner".into())); + assert_eq!(ds.coord_crs(), Crs::LonLat); + assert_eq!(bits(&held_coords(&s, "Owned")), bits(&held_coords(&s, "Parcels"))); + let unplaced = "1 feature(s) of 'Owners' (1) have a place that can't be given in longitude/latitude"; + let notices = s.notices_since(mark); + assert!(!notices.iter().any(|n| n.text.contains(unplaced)), "{notices:?}"); + + // The same source needs geometry when its definition query measures the features. + s.map_mut().layer_mut(layer).unwrap().definition_query = Some("line_length('m') > 0".into()); + let mark = s.notice_mark(); + let mut join = join; + join["params"]["output"] = json!("Queried owners"); + s.run("gp.run", &join).unwrap(); + let ds = &s.map().layer_by_name("Queried owners").unwrap().dataset; + assert_eq!(ds.value(0, ds.field_index("owner").unwrap()), &Cell::Null); + assert_eq!(ds.value(1, ds.field_index("owner").unwrap()), &Cell::Text("near owner".into())); + let notices = s.notices_since(mark); + assert_eq!(notices.iter().filter(|n| n.text.contains(unplaced)).count(), 1, "{notices:?}"); + + // As the target too, it is converted: a table given by its number, or a layer by its name (one + // in a geographic system, which the join doesn't work in). + let mut degrees = s.project.tables.iter().find(|t| t.id == table).unwrap().dataset.clone(); + degrees.name = "Owners in degrees".into(); + degrees.held_in = Crs::Epsg(4258); + degrees.features.set_geometry(0, Some(Geometry::Line(vec![vec![Coord::new(11.5, 48.7), Coord::new(11.6, 48.7)]]))); + s.map_mut().add_dataset(degrees); + for (target, source, name, output) in [ + (json!(table), json!(table), "Owners", "Self join"), + (json!("Owners in degrees"), json!("OWNERS IN DEGREES"), "Owners in degrees", "Self join by name"), + ] { + let mark = s.notice_mark(); + s.run( + "gp.run", + &json!({"tool":"joinField", "params":{"target":target, "targetField":"n", "joinTable":source, "fields":"owner", "output":output}}), + ) + .unwrap(); + let ds = &s.map().layer_by_name(output).unwrap().dataset; + assert_eq!(ds.coord_crs(), Crs::LonLat); + assert_eq!(ds.features.len(), 2); + let Some(Geometry::Line(parts)) = ds.features.geometry(0) else { panic!("first line was lost") }; + let first = parts.first().and_then(|part| part.first()).unwrap(); + assert!((first.x - 11.5).abs() < CLOSE && (first.y - 48.7).abs() < CLOSE, "{first:?}"); + assert!(ds.features.geometry(1).is_none()); + let notices = s.notices_since(mark); + let unplaced = unplaced.replace("'Owners'", &format!("'{name}'")); + assert_eq!(notices.iter().filter(|n| n.text.contains(&unplaced)).count(), 1, "{output}: {notices:?}"); + } +} + /// A project giving Web Mercator and longitude/latitude as their EPSG codes (`{"Epsg": 3857}`, /// `{"Epsg": 4326}`), as one written by hand or by another program may, opens with them as /// RustGIS's own Web Mercator and longitude/latitude: the layer held in Web Mercator stays off the