From 5d52710ba7f27075a8355cb92d62964fc679dfee Mon Sep 17 00:00:00 2001 From: strebdom Date: Sun, 22 Nov 2026 19:31:07 +0100 Subject: [PATCH 1/3] GDAL formats, DuckDB results and live feature services in their own coordinate system (#2032 C2f-3) --- crates/data/src/source/arcgis.rs | 79 ++++++++-- crates/data/src/source/arcgis/tests.rs | 58 ++++++- crates/data/src/source/duckdb.rs | 128 +++++++++++++--- crates/data/src/source/fgb.rs | 81 ++++++---- crates/data/src/source/gdal.rs | 199 ++++++++++++++++++++++--- crates/engine/src/cmd/layer.rs | 13 ++ crates/engine/src/tests.rs | 4 + crates/engine/src/tests/sources_own.rs | 94 ++++++++++++ docs/user-guide/data-formats.md | 5 +- docs/user-guide/data.md | 3 +- 10 files changed, 573 insertions(+), 91 deletions(-) create mode 100644 crates/engine/src/tests/sources_own.rs diff --git a/crates/data/src/source/arcgis.rs b/crates/data/src/source/arcgis.rs index c7c882c663..2043c4323b 100644 --- a/crates/data/src/source/arcgis.rs +++ b/crates/data/src/source/arcgis.rs @@ -67,6 +67,14 @@ pub struct ArcgisSource { page: std::sync::atomic::AtomicUsize, /// Whether the layer's queries take standardized SQL (`MOD`), to sample a view. sample: bool, + /// The system its features are asked for and held in: the layer's own when RustGIS reads it + /// ([`own_system`]), else longitude/latitude, as before. + held: crate::raster::Crs, + /// What places them in longitude/latitude, to test them against a view (none when held so). + to_lonlat: Option, + /// The code they are asked for by (`outSR`): the one the layer's description gave, or none for + /// longitude/latitude (4326). + out_sr: Option, } impl std::fmt::Debug for ArcgisSource { @@ -119,7 +127,7 @@ pub fn open_now(remote: Arc) -> Result { } let description = crate::ogc::arcgis_layer_url(&query); let counted = with(&query, &[("returnCountOnly", "true"), ("returnExtentOnly", "true"), ("outSR", "4326"), ("f", "json")]); - let first = with(&features_query(&query), &[("resultRecordCount", "1")]); + let first = with(&features_query(&query, None), &[("resultRecordCount", "1")]); // Asked for together: one round. let (d, c, f) = (remote.answer(&description)?, remote.answer(&counted)?, remote.answer(&first)?); let (Some(d), Some(c), Some(f)) = (d, c, f) else { return Err(remote::need()) }; @@ -139,6 +147,21 @@ pub fn open_now(remote: Arc) -> Result { // A view is chosen by geometry: a table is downloaded instead. let geometry_type = geometry_of(&d).ok_or_else(|| refuse("the layer names no geometry (it is a table)"))?; let sample = d.get("useStandardizedQueries").and_then(serde_json::Value::as_bool) == Some(true); + let (mut held, mut to_lonlat, mut out_sr) = match own_system(&d) { + Some((crs, t, code)) => (crs, Some(t), Some(code)), + None => (crate::raster::Crs::LonLat, None, None), + }; + // Asked for in that system once first: a service that answers in another (or one read by its + // definition rather than its code) is asked for in longitude/latitude, as before. + if out_sr.is_some() { + let native = with(&features_query(&query, out_sr), &[("resultRecordCount", "1")]); + let Some(answer) = remote.answer(&native)? else { return Err(remote::need()) }; + let in_it = answer.is_empty() + || crate::esripbf::read_page(&answer, "check").is_ok_and(|p| p.dataset.features.is_empty() || p.dataset.coord_crs() == held); + if !in_it { + (held, to_lonlat, out_sr) = (crate::raster::Crs::LonLat, None, None); + } + } let c = json(&remote, &counted, &c, MAX_COUNT_ANSWER, "count")?; let count = count_of(&c).ok_or_else(|| answer_error(&remote, &counted, "the count isn't a number"))?; @@ -163,7 +186,7 @@ pub fn open_now(remote: Arc) -> Result { fields: first.as_ref().map(|p| p.dataset.fields.clone()).unwrap_or_default(), extent, count: Some(count), - crs: "EPSG:4326".into(), + crs: held.label(), indexed: true, notes: Vec::new(), zm_dropped: false, @@ -177,7 +200,20 @@ pub fn open_now(remote: Arc) -> Result { if !sample { info.notes.push("its queries don't take standardized SQL, so a view holding more features than are drawn shows the first ones by object id rather than a sample of all of them".into()); } - Ok(ArcgisSource { remote, query, info, oid, oid_at, page: std::sync::atomic::AtomicUsize::new(page), sample }) + Ok(ArcgisSource { remote, query, info, oid, oid_at, page: std::sync::atomic::AtomicUsize::new(page), sample, held, to_lonlat, out_sr }) +} + +/// The layer's own coordinate system, from its description's extent (`latestWkid`, else `wkid`), +/// with what places it in longitude/latitude and the code read: `None` when it is +/// longitude/latitude or one RustGIS can't read, which is asked for in longitude/latitude instead. +fn own_system(description: &serde_json::Value) -> Option<(crate::raster::Crs, crate::raster::Transformer, u32)> { + let reference = description.pointer("/extent/spatialReference").or_else(|| description.get("sourceSpatialReference"))?; + let code = |k: &str| reference.get(k).and_then(serde_json::Value::as_u64).and_then(|c| u32::try_from(c).ok()); + let (crs, code) = [code("latestWkid"), code("wkid")].into_iter().flatten().find_map(|c| Some((crate::filegdb::crs_of_code(c)?, c)))?; + if crs == crate::raster::Crs::LonLat { + return None; + } + Some((crs, crs.transformer().ok()?, code)) } /// What a read says of the features a service counted but didn't send (none when it sent them @@ -206,11 +242,13 @@ fn with(query: &str, values: &[(&str, &str)]) -> String { values.iter().fold(query.to_string(), |q, (k, v)| crate::ogc::with_query_value(&q, k, v)) } -/// The layer's query asking for features in protocol buffers, in longitude/latitude, with every -/// field unless it names its own. -fn features_query(query: &str) -> String { +/// The layer's query asking for features in protocol buffers, in the system `out_sr` codes (none +/// for longitude/latitude), with every field unless it names its own. +fn features_query(query: &str, out_sr: Option) -> String { + // By the code the layer's description gave its own system, or 4326. + let out_sr = out_sr.unwrap_or(4326).to_string(); // With geometry, whatever the query said: a view is chosen by it. - let q = with(query, &[("outSR", "4326"), ("f", "pbf"), ("returnGeometry", "true")]); + let q = with(query, &[("outSR", &out_sr), ("f", "pbf"), ("returnGeometry", "true")]); if crate::ogc::query_value(&q, "outFields").is_some_and(|f| !f.is_empty()) { q } else { with(&q, &[("outFields", "*")]) } } @@ -289,7 +327,7 @@ fn step_for(matched: u64, limit: usize) -> u64 { impl ArcgisSource { /// The query of the features in `cell` (all of them for none), every `step`-th by object id. fn query_of(&self, cell: Option<&Extent>, step: u64) -> String { - let q = features_query(&self.query); + let q = features_query(&self.query, self.out_sr); let q = match cell { Some(c) => with( &q, @@ -350,6 +388,14 @@ impl ArcgisSource { notes } + /// Whether a feature, held in the layer's system, meets a view in longitude/latitude. + fn meets(&self, g: &crate::Geometry, view: &Extent) -> bool { + match &self.to_lonlat { + Some(t) => crate::io::lonlat_box(g, t).is_some_and(|b| b.intersects(view)), + None => g.extent().intersects(view), + } + } + /// The features a page asks for now. fn page(&self) -> usize { self.page.load(std::sync::atomic::Ordering::Relaxed) @@ -488,7 +534,7 @@ impl ArcgisSource { received = received.saturating_add(sent as u64); for f in got { let inside = match (&view, &f.geometry) { - (Some(v), Some(g)) => g.extent().intersects(v), + (Some(v), Some(g)) => self.meets(g, v), (Some(_), None) => false, (None, _) => true, }; @@ -576,6 +622,14 @@ impl ArcgisSource { "the layer's fields changed since it was added; add it again", ))); } + // In the system asked for: a page in another can't be read as if it were. + if !page.dataset.features.is_empty() && page.dataset.coord_crs() != self.held { + self.remote.forget_answer(url); + return Err(DataError::Format(crate::diagnostics::message_with_address( + &self.query, + &format!("the service answered in {}, not the {} asked for", page.dataset.coord_crs().label(), self.held.label()), + ))); + } *skipped = skipped.saturating_add(page.report.skipped); losses.add(&page.losses); let sent = page.dataset.features.len(); @@ -598,6 +652,11 @@ impl FeatureSource for ArcgisSource { &self.info } + /// The layer's own system when RustGIS reads it, else longitude/latitude. + fn coord_crs(&self) -> crate::raster::Crs { + self.held + } + fn remote(&self) -> Option> { Some(self.remote.clone()) } @@ -714,7 +773,7 @@ impl FeatureSource for ArcgisSource { let (got, more, sent) = self.page_of(url, &answer, &mut skipped, &mut losses).inspect_err(|_| forget(&urls))?; drop(answer); for f in got { - if view.as_ref().is_none_or(|v| f.geometry.as_ref().is_some_and(|g| g.extent().intersects(v))) { + if view.as_ref().is_none_or(|v| f.geometry.as_ref().is_some_and(|g| self.meets(g, v))) { visited += 1; chunks.push(f).inspect_err(|_| forget(&urls))?; } diff --git a/crates/data/src/source/arcgis/tests.rs b/crates/data/src/source/arcgis/tests.rs index d5e503088f..f013ecc374 100644 --- a/crates/data/src/source/arcgis/tests.rs +++ b/crates/data/src/source/arcgis/tests.rs @@ -56,6 +56,9 @@ struct Opts { over: usize, /// An answer of no features is no bytes at all. empty_body: bool, + /// Its layer is in Web Mercator (its description says so), and it answers in the system + /// asked for (`outSR`), Web Mercator or longitude/latitude. + mercator: bool, } impl Default for Opts { @@ -75,6 +78,7 @@ impl Default for Opts { hidden: 0, over: 0, empty_body: false, + mercator: false, } } } @@ -104,6 +108,7 @@ fn service_with(host: &str, opts: Opts) -> (String, Arc) { hidden, over, empty_body, + mercator, } = opts; let layer = format!("https://{host}/arcgis/rest/services/P/FeatureServer/0"); let asked = Arc::new(Asked::default()); @@ -117,7 +122,8 @@ fn service_with(host: &str, opts: Opts) -> (String, Arc) { Some(d) => d.as_bytes().to_vec(), None => format!( r#"{{"name":"Points","objectIdField":"OBJECTID","maxRecordCount":{page},"supportedQueryFormats":"JSON, geoJSON, PBF","geometryType":"esriGeometryPoint", - "useStandardizedQueries":{sql},"advancedQueryCapabilities":{{"supportsPagination":true}}}}"# + "useStandardizedQueries":{sql},"advancedQueryCapabilities":{{"supportsPagination":true}}{}}}"#, + if mercator { r#","extent":{"xmin":0,"ymin":0,"xmax":1,"ymax":1,"spatialReference":{"wkid":102100,"latestWkid":3857}}"# } else { "" } ) .into_bytes(), }); @@ -153,7 +159,9 @@ fn service_with(host: &str, opts: Opts) -> (String, Arc) { return Some(Vec::new()); } let geometry_too = value("returnGeometry").as_deref() != Some("false"); - let mut parts = vec![number(7, 0), lonlat(), transform(false, 0.01, 0.0, 0.0)]; + let in_mercator = mercator && value("outSR").as_deref() == Some("3857"); + let reference = if in_mercator { message(8, &number(1, 3857)) } else { lonlat() }; + let mut parts = vec![number(7, 0), reference, transform(false, 0.01, 0.0, 0.0)]; if !(sent.is_empty() && empty_without_fields) { parts.push(field("OBJECTID", 6)); if padded { @@ -171,6 +179,12 @@ fn service_with(host: &str, opts: Opts) -> (String, Arc) { } for id in sent { let (x, y) = position(id); + let (x, y) = if in_mercator { + let m = rustgis_geom::lonlat_to_merc(rustgis_geom::Coord::new(x, y)); + (m.x, m.y) + } else { + (x, y) + }; let mut at = vec![(x * 100.0).round() as i64, (y * 100.0).round() as i64]; if z { at.push(100); @@ -608,3 +622,43 @@ fn a_layer_matching_nothing_may_answer_with_no_bytes() { let b = read(&src, Request { extent: Some(small_view()), limit: 1000 }).unwrap(); assert!(b.complete && b.features.is_empty()); } + +/// A layer in a system RustGIS reads is asked for and held in it (`outSR` its code), each feature +/// as the service sends it, and a view still takes the features it holds; one in a system RustGIS +/// can't read is asked for in longitude/latitude, as before. +#[test] +fn a_layer_is_read_in_its_own_system() { + let (query, asked) = service_with("own-system.test", Opts { page: 30, mercator: true, ..Opts::default() }); + let src = open_blocking(&query).unwrap(); + assert_eq!((src.coord_crs(), src.info.crs.as_str()), (crate::raster::Crs::WebMercator, "EPSG:3857")); + let before = asked.count.load(Ordering::Relaxed); + let b = read(&src, Request { extent: Some(small_view()), limit: 1000 }).unwrap(); + let want: Vec = (3..=6).flat_map(|row| (2..=5).map(move |col| row * 20 + col + 1)).collect(); + assert_eq!(ids(&b), want); + let pages: Vec = asked.since(before).into_iter().filter(|u| u.contains("resultOffset")).collect(); + assert!(!pages.is_empty() && pages.iter().all(|u| u.contains("outSR=3857")), "{pages:?}"); + for f in &b.features { + let (x, y) = position(f.id); + let m = rustgis_geom::lonlat_to_merc(rustgis_geom::Coord::new(x, y)); + let Some(crate::Geometry::Point(c)) = &f.geometry else { panic!() }; + assert!((c.x - m.x).abs() < 0.01 && (c.y - m.y).abs() < 0.01, "{c:?} vs {m:?}"); + } + // A whole-layer read within the view takes the same features, tested in longitude/latitude. + let mut inside = Vec::new(); + src.visit_chunks(Some(small_view()), 4 << 10, &mut |c| { + inside.extend(c.iter().map(|f| f.id)); + Ok(()) + }) + .unwrap(); + inside.sort_unstable(); + assert_eq!(inside, want); + // A code RustGIS doesn't read: longitude/latitude, as before. + let description = r#"{"name":"Points","objectIdField":"OBJECTID","maxRecordCount":30,"supportedQueryFormats":"PBF","geometryType":"esriGeometryPoint", + "useStandardizedQueries":true,"advancedQueryCapabilities":{"supportsPagination":true},"extent":{"spatialReference":{"wkid":999999}}}"#; + let (query, asked) = service("unknown-system.test", 30, true, Some(description)); + let src = open_blocking(&query).unwrap(); + assert_eq!(src.coord_crs(), crate::raster::Crs::LonLat); + let b = read(&src, Request { extent: Some(small_view()), limit: 1000 }).unwrap(); + assert_eq!(ids(&b), want); + assert!(asked.since(0).iter().filter(|u| u.contains("resultOffset")).all(|u| u.contains("outSR=4326"))); +} diff --git a/crates/data/src/source/duckdb.rs b/crates/data/src/source/duckdb.rs index eff07a1b0e..64084a4add 100644 --- a/crates/data/src/source/duckdb.rs +++ b/crates/data/src/source/duckdb.rs @@ -47,9 +47,10 @@ const DIM: &str = "__rustgis_dim"; const ZM: &str = "__rustgis_zm"; /// What a converted table is written as: raised when that changes (dates as dates in 2, nanosecond -/// timestamps as timestamps in 3, the rows that lost Z or M values counted in 4), so a table -/// converted before is converted again rather than kept as it was. -const CONVERSION: u32 = 4; +/// timestamps as timestamps in 3, the rows that lost Z or M values counted in 4, kept in its own +/// coordinate system in 5), so a table converted before is converted again rather than kept as it +/// was. +const CONVERSION: u32 = 5; /// A database named by commands: DuckDB files, PostgreSQL connections (also queryable through /// DuckDB's `postgres` extension), or live-only MySQL, MariaDB and SQL Server connections. @@ -722,19 +723,34 @@ fn type_crs(ty: &str) -> Option<&str> { ty.strip_prefix("GEOMETRY('").and_then(|r| r.strip_suffix("')")).filter(|c| !c.is_empty()) } +/// The system a result's geometry is kept in rather than converted to longitude/latitude: the one +/// given or the one its type says, when RustGIS reads its EPSG code (as the GeoParquet DuckDB +/// writes says it, [`select`]). `None` for longitude/latitude or one it can't read. +fn own_system(columns: &[Column], crs: Option<&str>) -> Option { + let ty = columns.iter().find(|c| is_geometry(&c.ty)).and_then(|c| type_crs(&c.ty)); + let code = crs.or(ty)?; + let (authority, number) = code.split_once(':')?; + let crs = crate::raster::Crs::from_epsg(number.trim().parse().ok()?) + .filter(|_| authority.trim().eq_ignore_ascii_case("EPSG")) + .filter(|c| *c != crate::raster::Crs::LonLat)?; + crs.transformer().is_ok().then_some(crs) +} + /// The SELECT that turns a result into what is written: the first geometry column in -/// longitude/latitude, x and y only, other geometry columns as WKT, types the provider doesn't -/// read as text, each row's geometry family and whether its geometry had Z or M values; and the -/// geometry column's name. -fn select(columns: &[Column], crs: Option<&str>, from: &str) -> Result<(String, String)> { +/// longitude/latitude, or kept in its own system when `own` ([`own_system`]), x and y only, other +/// geometry columns as WKT, types the provider doesn't read as text, each row's geometry family and +/// whether its geometry had Z or M values; and the geometry column's name. +fn select(columns: &[Column], crs: Option<&str>, from: &str, own: bool) -> Result<(String, String)> { let geom = columns .iter() .find(|c| is_geometry(&c.ty)) .ok_or_else(|| DataError::Format("the query returns no geometry column: select one (such as ST_Point(lon, lat) AS geom)".into()))?; let g = ident(&geom.name); // A geometry that says no coordinate system (the usual case for longitude/latitude) is taken - // as it is. + // as it is. One kept in its own is given it, so the GeoParquet says it. let geom_expr = match (crs, type_crs(&geom.ty)) { + (Some(c), _) if own => format!("ST_SetCRS({g}::GEOMETRY, {})", literal(c)), + (None, Some(_)) if own => g.clone(), (Some(c), _) => format!("ST_Transform({g}::GEOMETRY, {}, 'EPSG:4326')", literal(c)), (None, Some(t)) if t.eq_ignore_ascii_case("EPSG:4326") || t.eq_ignore_ascii_case("OGC:CRS84") => g.clone(), (None, Some(_)) => format!("ST_Transform({g}, 'EPSG:4326')"), @@ -904,6 +920,13 @@ fn run_in(dir: &Path, q: &Query<'_>, confined: bool) -> Result { /// A manual table replacement keeps only its original family and permits a zero-row geometry /// column. Ordinary adds retain their existing nonempty-result behavior. fn run_selected_in(dir: &Path, q: &Query<'_>, confined: bool, selected: Option) -> Result { + run_kept_in(dir, q, confined, selected, true) +} + +/// As [`run_selected_in`]; with `keep`, a result in a system RustGIS reads is kept in it, and run +/// again in longitude/latitude, as before, when its file doesn't read back in it or the run fails +/// on a DuckDB too old to give a geometry its system. +fn run_kept_in(dir: &Path, q: &Query<'_>, confined: bool, selected: Option, keep: bool) -> Result { let sql = checked(q.sql)?; check_crs(q.crs)?; if !available() { @@ -928,7 +951,8 @@ fn run_selected_in(dir: &Path, q: &Query<'_>, confined: bool, selected: Option, confined: bool, selected: Option = Family::ALL.iter().map(|f| TempFile(Some(tmp(*f)))).collect(); let mut script = format!("{prelude} CREATE TEMP TABLE r AS {select};"); + // Rows in order along a curve over the world, or over the result's own extent in its system. + let hilbert = if own.is_some() { + format!("(SELECT ST_Extent(ST_Extent_Agg({g})) FROM r)") + } else { + "{'min_x': -180, 'min_y': -90, 'max_x': 180, 'max_y': 90}::BOX_2D".to_string() + }; for f in Family::ALL { script.push_str(&format!( - " COPY (SELECT * EXCLUDE ({DIM}, {ZM}){bbox} FROM r WHERE {DIM} = {} ORDER BY ST_Hilbert({g}, {{'min_x': -180, 'min_y': -90, 'max_x': 180, 'max_y': 90}}::BOX_2D)) TO {} (FORMAT parquet, ROW_GROUP_SIZE 16384);", + " COPY (SELECT * EXCLUDE ({DIM}, {ZM}){bbox} FROM r WHERE {DIM} = {} ORDER BY ST_Hilbert({g}, {hilbert})) TO {} (FORMAT parquet, ROW_GROUP_SIZE 16384);", dimension(f), literal(&tmp(f).display().to_string()) )); } - let counts = fetch( + let counts = match fetch( dir, &script, q.database, &format!("SELECT {DIM} AS dim, count(*)::BIGINT AS n, count_if({ZM})::BIGINT AS zm FROM r GROUP BY {DIM}"), QUERY_TIMEOUT, - )?; + ) { + Ok(counts) => counts, + // A DuckDB without `ST_SetCRS` (its error names the function): in longitude/latitude, as + // before. Any other failure is the query's own. + Err(e) if own.is_some() && q.crs.is_some() && e.to_string().to_ascii_lowercase().contains("st_setcrs") => { + drop(guards); + crate::progress::check()?; + return run_kept_in(dir, q, confined, selected, false); + } + Err(e) => return Err(e), + }; let mut out = Output::default(); for row in counts.as_array().into_iter().flatten() { @@ -999,6 +1039,18 @@ fn run_selected_in(dir: &Path, q: &Query<'_>, confined: bool, selected: Option 0).all(read_back) { + drop(guards); + crate::progress::check()?; + return run_kept_in(dir, q, confined, selected, false); + } + } // The parts take their final names; the families not in the result are removed with their // guards. for p in &out.parts { @@ -1489,7 +1541,7 @@ mod tests { fn select_list() { let cols = |v: &[(&str, &str)]| v.iter().map(|(n, t)| Column { name: n.to_string(), ty: t.to_string() }).collect::>(); // No geometry column. - let e = select(&cols(&[("a", "INTEGER")]), None, "x").unwrap_err(); + let e = select(&cols(&[("a", "INTEGER")]), None, "x", false).unwrap_err(); assert!(e.to_string().contains("no geometry column"), "{e}"); // Types the provider doesn't read become text; dates stay dates; a second geometry, WKT. let (s, g) = select( @@ -1505,6 +1557,7 @@ mod tests { ]), None, "x", + false, ) .unwrap(); assert_eq!(g, "geom"); @@ -1514,13 +1567,26 @@ mod tests { assert!(s.contains("CAST(\"s\" AS TIMESTAMP) AS \"s\""), "{s}"); assert!(s.contains(", \"n\",") && s.contains("ST_AsText(\"g2\")"), "{s}"); assert!(s.contains(&format!("(ST_HasZ(\"geom\"::GEOMETRY) OR ST_HasM(\"geom\"::GEOMETRY)) AS {ZM}")), "{s}"); - // A geometry that says its coordinate system is converted; one given is used. - let (s, _) = select(&cols(&[("g", "GEOMETRY('EPSG:3857')")]), None, "x").unwrap(); + // A geometry that says its coordinate system is kept in it when RustGIS reads it, and + // converted when not; one given is given to it, or converted from. + let typed = cols(&[("g", "GEOMETRY('EPSG:3857')")]); + assert_eq!(own_system(&typed, None), Some(crate::raster::Crs::WebMercator)); + let (s, _) = select(&typed, None, "x", true).unwrap(); + assert!(!s.contains("ST_Transform") && s.contains("ST_Force2D(\"g\")"), "{s}"); + let (s, _) = select(&typed, None, "x", false).unwrap(); assert!(s.contains("ST_Transform(\"g\", 'EPSG:4326')"), "{s}"); - let (s, _) = select(&cols(&[("g", "GEOMETRY('OGC:CRS84')")]), None, "x").unwrap(); + let (s, _) = select(&cols(&[("g", "GEOMETRY('OGC:CRS84')")]), None, "x", false).unwrap(); assert!(!s.contains("ST_Transform"), "{s}"); - let (s, _) = select(&cols(&[("g", "GEOMETRY")]), Some("EPSG:2263"), "x").unwrap(); + let plain = cols(&[("g", "GEOMETRY")]); + assert_eq!(own_system(&plain, Some("EPSG:2263")), crate::raster::Crs::from_epsg(2263)); + let (s, _) = select(&plain, Some("EPSG:2263"), "x", true).unwrap(); + assert!(s.contains("ST_SetCRS(\"g\"::GEOMETRY, 'EPSG:2263')") && !s.contains("ST_Transform"), "{s}"); + let (s, _) = select(&plain, Some("EPSG:2263"), "x", false).unwrap(); assert!(s.contains("ST_Transform(\"g\"::GEOMETRY, 'EPSG:2263', 'EPSG:4326')"), "{s}"); + // Longitude/latitude, no system, or one that isn't an EPSG code: converted as before. + assert_eq!(own_system(&plain, None), None); + assert_eq!(own_system(&cols(&[("g", "GEOMETRY('EPSG:4326')")]), None), None); + assert_eq!(own_system(&cols(&[("g", "GEOMETRY('ESRI:54008')")]), None), None); } #[test] @@ -1653,15 +1719,31 @@ mod tests { std::fs::read_dir(&cache).unwrap().flatten().map(|e| e.file_name().to_string_lossy().into_owned()).collect(); assert!(names.iter().all(|n| !n.contains(".tmp.")), "{names:?}"); - // A projected geometry that says its coordinate system comes out in longitude/latitude. + // A projected geometry that says its coordinate system is kept in it, as stored, and + // placed where it is in longitude/latitude… + let first = |path: &Path| { + let source = open(path); + let batch = source.read(&crate::source::Request { extent: None, limit: 1 }).unwrap(); + let Some(crate::Geometry::Point(c)) = batch.features.into_iter().next().unwrap().geometry else { panic!() }; + (source.coord_crs(), c, source.info().extent) + }; let out = run_in(&cache, &Query { sql: "SELECT ST_Point(1113194.9, 0)::GEOMETRY('EPSG:3857') AS g", ..Query::default() }, false).unwrap(); - let e = open(&out.parts[0].path).info().extent; + let (crs, c, e) = first(&out.parts[0].path); + assert_eq!((crs, c), (crate::raster::Crs::WebMercator, rustgis_geom::Coord::new(1113194.9, 0.0))); assert!((e.min_x - 10.0).abs() < 1e-3 && e.min_y.abs() < 1e-6, "{e:?}"); - // …and so does one given with "crs". - let q = Query { sql: "SELECT ST_Point(1113194.9, 0) AS g", crs: Some("EPSG:3857"), ..Query::default() }; - let e = open(&run_in(&cache, &q, false).unwrap().parts[0].path).info().extent; - assert!((e.min_x - 10.0).abs() < 1e-3, "{e:?}"); + // …and so is one given with "crs". + let q = Query { sql: "SELECT ST_Point(2600000, 1200000) AS g", crs: Some("EPSG:2056"), ..Query::default() }; + let (crs, c, e) = first(&run_in(&cache, &q, false).unwrap().parts[0].path); + assert_eq!((crs, c), (crate::raster::Crs::from_epsg(2056).unwrap(), rustgis_geom::Coord::new(2_600_000.0, 1_200_000.0))); + assert!((e.min_x - 7.4386).abs() < 1e-3 && (e.min_y - 46.9511).abs() < 1e-3, "{e:?}"); + // One given in longitude/latitude, or by a code RustGIS doesn't read, comes out in + // longitude/latitude, as before. + let q = Query { sql: "SELECT ST_Point(10, 20) AS g", crs: Some("EPSG:4326"), ..Query::default() }; + assert_eq!(first(&run_in(&cache, &q, false).unwrap().parts[0].path).0, crate::raster::Crs::LonLat); + let q = Query { sql: "SELECT ST_Point(1000000, 2000000) AS g", crs: Some("ESRI:54008"), ..Query::default() }; + let (crs, c, _) = first(&run_in(&cache, &q, false).unwrap().parts[0].path); + assert!(crs == crate::raster::Crs::LonLat && c.x.abs() <= 180.0 && c.y.abs() <= 90.0, "{crs:?} {c:?}"); // Invalid SQL, empty query results and non-spatial results are errors. DuckDB versions // format their diagnostics differently; their prose is not the command contract. diff --git a/crates/data/src/source/fgb.rs b/crates/data/src/source/fgb.rs index 01c371de5b..f86b33efe5 100644 --- a/crates/data/src/source/fgb.rs +++ b/crates/data/src/source/fgb.rs @@ -29,6 +29,57 @@ pub(crate) fn header_feature_count(path: &Path) -> Result { Ok(reader.header().features_count()) } +/// The system a FlatGeobuf header says, read as a GeoPackage row's is ([`super::declared_reproject`]). +fn header_reproject(header_crs: Option>, notes: &mut Vec) -> Result { + // The header's system is read as a GeoPackage row's is ([`super::declared_reproject`]): by + // its EPSG code, or by its WKT when the WKT gives another shift to WGS 84 or there is no + // EPSG code (#1855). The code is an EPSG one only when the organization is EPSG (or not + // given, which means EPSG); 0 is none. + let organization = header_crs.and_then(|c| c.org()); + let epsg_org = organization.is_none_or(|o| o.eq_ignore_ascii_case("epsg")); + let code = header_crs.map(|c| i64::from(c.code())).filter(|c| *c != 0); + let declared = super::DeclaredCrs { + what: "its coordinate system", + organization, + code, + epsg: code.and_then(|c| u32::try_from(c).ok()).filter(|_| epsg_org), + wkt1: super::defined(header_crs.and_then(|c| c.wkt())), + wkt2: None, + }; + Ok(match super::declared_reproject(declared, notes) { + Some(reproject) => reproject?, + // Nothing to read it by: longitude/latitude, said when another organization's code + // names the system, or a negative code, which can't be an EPSG one. + None => { + if !epsg_org && let Some(org) = organization { + notes.push(format!("its coordinate system is defined by {org}, not EPSG; read as longitude/latitude")); + } else if let Some(code) = code { + notes.push(format!("its coordinate system's code {code} isn't an EPSG code; read as longitude/latitude")); + } + Reproject::from_crs(Crs::LonLat, notes) + } + }) +} + +/// The system RustGIS reads a FlatGeobuf in, from its header alone (no feature is read). +#[cfg(not(target_arch = "wasm32"))] +pub(crate) fn header_coord_crs(path: &Path) -> Result { + let reader = open_reader(BufReader::new(std::fs::File::open(path)?))?; + Ok(header_reproject(reader.header().crs(), &mut Vec::new())?.crs()) +} + +/// Whether a FlatGeobuf's header says WGS 84 longitude/latitude or no system: EPSG:4326 (or no +/// organization with 4326), OGC CRS84, or a definition read as longitude/latitude. +#[cfg(not(target_arch = "wasm32"))] +pub(crate) fn header_says_wgs84(path: &Path) -> bool { + let Ok(reader) = std::fs::File::open(path).map_err(DataError::from).and_then(|f| open_reader(BufReader::new(f))) else { return false }; + let Some(crs) = reader.header().crs() else { return true }; + let org = crs.org().unwrap_or("EPSG"); + (org.eq_ignore_ascii_case("epsg") && crs.code() == 4326) + || (org.eq_ignore_ascii_case("ogc") && crs.code_string().is_some_and(|c| c.eq_ignore_ascii_case("CRS84"))) + || crs.wkt().is_some_and(|w| crate::raster::wkt::read_wkt(w).is_ok_and(|(c, _)| c == Crs::LonLat)) +} + /// A file or an upload, read and seeked. trait ReadSeek: Read + Seek {} impl ReadSeek for T {} @@ -175,35 +226,7 @@ impl FgbSource { let reader = open_reader(r)?; let h = reader.header(); let mut notes = Vec::new(); - // The header's system is read as a GeoPackage row's is ([`super::declared_reproject`]): by - // its EPSG code, or by its WKT when the WKT gives another shift to WGS 84 or there is no - // EPSG code (#1855). The code is an EPSG one only when the organization is EPSG (or not - // given, which means EPSG); 0 is none. - let header_crs = h.crs(); - let organization = header_crs.and_then(|c| c.org()); - let epsg_org = organization.is_none_or(|o| o.eq_ignore_ascii_case("epsg")); - let code = header_crs.map(|c| i64::from(c.code())).filter(|c| *c != 0); - let declared = super::DeclaredCrs { - what: "its coordinate system", - organization, - code, - epsg: code.and_then(|c| u32::try_from(c).ok()).filter(|_| epsg_org), - wkt1: super::defined(header_crs.and_then(|c| c.wkt())), - wkt2: None, - }; - let reproject = match super::declared_reproject(declared, &mut notes) { - Some(reproject) => reproject?, - // Nothing to read it by: longitude/latitude, said when another organization's code - // names the system, or a negative code, which can't be an EPSG one. - None => { - if !epsg_org && let Some(org) = organization { - notes.push(format!("its coordinate system is defined by {org}, not EPSG; read as longitude/latitude")); - } else if let Some(code) = code { - notes.push(format!("its coordinate system's code {code} isn't an EPSG code; read as longitude/latitude")); - } - Reproject::from_crs(Crs::LonLat, &mut notes) - } - }; + let reproject = header_reproject(h.crs(), &mut notes)?; let mut date_columns = Vec::new(); let mut fields = Vec::new(); let mut slots = Vec::new(); diff --git a/crates/data/src/source/gdal.rs b/crates/data/src/source/gdal.rs index 2901e6707a..1604c98dcc 100644 --- a/crates/data/src/source/gdal.rs +++ b/crates/data/src/source/gdal.rs @@ -88,6 +88,9 @@ pub struct Converted { /// GDAL couldn't reproject it (the file doesn't say its coordinate system): its coordinates /// are the file's own. pub unprojected: bool, + /// Its coordinate system is one RustGIS can't read, so GDAL converted it to longitude/latitude + /// (as every conversion did before layers kept their own system). + pub in_lonlat: bool, } /// A GDAL program (`ogr2ogr`, `ogrinfo`): from `RUSTGIS_GDAL_BIN` (a folder), else on the `PATH`. @@ -314,6 +317,7 @@ fn convert_in(dir: &Path, src: &Path, layer: Option<&str>, crs: Option<&str>) -> Ok(Some(converted)) => out.push(Converted { path: converted.path, unprojected: converted.unprojected, + in_lonlat: converted.in_lonlat, name: match family { Some(f) => format!("{} ({})", l.name, f.label()), None => l.name.clone(), @@ -402,6 +406,7 @@ pub struct FreshConverted { struct Conversion { path: PathBuf, unprojected: bool, + in_lonlat: bool, notes: Vec, empty: bool, } @@ -440,6 +445,9 @@ fn convert_one_fresh_in(dir: &Path, src: &Path, layer: &str, family: Option 0) { touch(&out); touch(&keyfile); - return Ok(Some(Conversion { path: out, unprojected: was_unprojected, notes: Vec::new(), empty: false })); + return Ok(Some(Conversion { path: out, unprojected: was_unprojected, in_lonlat: was_in_lonlat, notes: Vec::new(), empty: false })); } // Unique to this conversion, even with others of the same layer running in this process. let tmp = dir.join(format!("{tag}.{}{n:04}.tmp.fgb", std::process::id())); - // Reprojected to WGS 84 from its own coordinate system, or from the one given; a layer with - // neither is taken as it is. + // Kept in its own coordinate system, or the one given, which the FlatGeobuf says; one RustGIS + // can't read is converted to WGS 84 instead, as before. A layer with neither is taken as it + // is. let unprojected = crs.is_none() && !has_srs; - let mut c = command(ogr2ogr, drivers(&full)?); - c.args(["-f", "FlatGeobuf", "-nlt", nlt, "-dim", "XY", "-lco", "SPATIAL_INDEX=YES"]); - // Fresh replacements must fail rather than install a partial conversion. - if !fresh { - c.arg("-skipfailures"); - } - if let Some(crs) = crs { - c.args(["-s_srs", crs]); - } - if !unprojected { - c.args(["-t_srs", "EPSG:4326"]); - } - if let Some(f) = family { - c.args(["-where", f.filter()]); - } - c.arg(&tmp).arg(&full).arg(layer); + let drivers = drivers(&full)?; + let run = |to_lonlat: bool| -> std::io::Result { + let mut c = command(ogr2ogr.clone(), drivers); + c.args(["-f", "FlatGeobuf", "-nlt", nlt, "-dim", "XY", "-lco", "SPATIAL_INDEX=YES"]); + // Fresh replacements must fail rather than install a partial conversion. + if !fresh { + c.arg("-skipfailures"); + } + // The system given is assigned when kept, and converted from when not. + match (crs, to_lonlat) { + (Some(crs), false) => { + c.args(["-a_srs", crs]); + } + (Some(crs), true) => { + c.args(["-s_srs", crs, "-t_srs", "EPSG:4326"]); + } + (None, true) => { + c.args(["-t_srs", "EPSG:4326"]); + } + (None, false) => {} + } + if let Some(f) = family { + c.args(["-where", f.filter()]); + } + c.arg(&tmp).arg(&full).arg(layer); + output(c, CONVERT_TIMEOUT, &format!("GDAL conversion of {}, layer '{layer}'", full.display())) + }; // The temp file goes whatever happens, unless it becomes the conversion. let mut tmp_guard = TempFile(Some(tmp.clone())); - let res = output(c, CONVERT_TIMEOUT, &format!("GDAL conversion of {}, layer '{layer}'", full.display()))?; + let mut res = run(false)?; + let mut in_lonlat = false; + if res.status.success() && !unprojected && tmp.exists() { + let placement = placement(&tmp); + if placement != Placement::Own { + crate::progress::check()?; + // GDAL can't write over a FlatGeobuf: the first conversion goes first. + std::fs::remove_file(&tmp)?; + res = run(true)?; + in_lonlat = placement == Placement::Unreadable; + } + } if !res.status.success() { let text = String::from_utf8_lossy(&res.stderr); // The ERROR lines say what went wrong (the rest is the usage text); else the first line. @@ -615,7 +650,14 @@ fn convert_one_in(dir: &Path, src: &Path, layer: &str, request: ConversionReques std::fs::rename(&tmp, &out)?; tmp_guard.0 = None; let _ = std::fs::remove_file(&empty); - std::fs::write(&keyfile, if unprojected { format!("{key}{UNPROJECTED}") } else { key.clone() })?; + let flag = if unprojected { + UNPROJECTED + } else if in_lonlat { + IN_LONLAT + } else { + "" + }; + std::fs::write(&keyfile, format!("{key}{flag}"))?; let notes = if fresh { let mut counts = std::collections::BTreeMap::::new(); for line in String::from_utf8_lossy(&res.stderr).lines().map(str::trim).filter(|line| !line.is_empty()) { @@ -636,7 +678,47 @@ fn convert_one_in(dir: &Path, src: &Path, layer: &str, request: ConversionReques } else { Vec::new() }; - Ok(Some(Conversion { path: out, unprojected, notes, empty: !any })) + Ok(Some(Conversion { path: out, unprojected, in_lonlat, notes, empty: !any })) +} + +/// How RustGIS reads a FlatGeobuf GDAL wrote in the source's own system. +#[derive(Clone, Copy, Debug, PartialEq)] +enum Placement { + /// In that system, which it reads and converts itself (WGS 84 longitude/latitude among them). + Own, + /// A geographic system that places coordinates as WGS 84 longitude/latitude does under + /// another name (WGS 84 in 3D, whose heights the conversion drops): written in EPSG:4326, as + /// before. + LonLat, + /// A system it can't read, which it would take for longitude/latitude: converted to it. + Unreadable, +} + +/// How RustGIS reads `fgb` ([`Placement`]), from its header alone. One it reads as +/// longitude/latitude must say WGS 84 (by code or definition), and is kept as GDAL wrote it; one +/// that doesn't would have its coordinates taken for degrees. One whose header can't be read is +/// converted as before. +fn placement(fgb: &Path) -> Placement { + use crate::raster::Crs; + crate::provenance::without(|| { + let Ok(crs) = super::fgb::header_coord_crs(fgb) else { return Placement::Unreadable }; + if crs == Crs::LonLat { + return if super::fgb::header_says_wgs84(fgb) { Placement::Own } else { Placement::Unreadable }; + } + // Longitude/latitude by another name: the same places, to a nanodegree. + let same = crs.is_geographic() + && crs.to(Crs::LonLat).is_ok_and(|t| { + [(12.0, 48.0), (-120.5, -33.25), (179.0, 80.0), (0.0, 0.0)] + .into_iter() + .all(|(x, y)| t.point(rustgis_geom::Coord::new(x, y)).is_some_and(|c| (c.x - x).abs() < 1e-9 && (c.y - y).abs() < 1e-9)) + }); + if same { Placement::LonLat } else { Placement::Own } + }) +} + +/// The notice for a layer converted to longitude/latitude because its system can't be read. +pub fn in_lonlat_note(layer: &str) -> String { + format!("GDAL: '{layer}': RustGIS can't read its coordinate system, so GDAL converted it to longitude/latitude (WGS 84)") } /// Count only the other supported geometry families, not geometry-less rows. Reuse exactly the @@ -788,6 +870,75 @@ mod tests { assert_ne!(fnv1a(b"a"), fnv1a(b"b")); } + /// A layer in a system RustGIS reads is converted in it, its coordinates as the file holds + /// them; one in a system RustGIS can't read is converted to longitude/latitude, as every + /// layer was before, and said. A conversion made before is not reused for one in its own. + #[test] + fn layers_are_converted_in_their_own_system_when_gdal_is_installed() { + if !available() { + return; + } + let dir = tempfile::tempdir().unwrap(); + let made = |name: &str, (driver, ext): (&str, &str), srs: &str| { + let csv = dir.path().join(format!("{name}.csv")); + std::fs::write(&csv, "WKT,name\n\"POINT (2600000 1200000)\",Bern\n").unwrap(); + let file = dir.path().join(format!("{name}.{ext}")); + let out = Command::new(program("ogr2ogr").unwrap()).args(["-f", driver, "-a_srs", srs]).arg(&file).arg(&csv).output().unwrap(); + assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr)); + file + }; + let first = |path: &Path| { + let source = super::super::open_path(path, None).unwrap(); + let batch = source.read(&super::super::Request { extent: None, limit: 1 }).unwrap(); + let Some(crate::Geometry::Point(c)) = batch.features.into_iter().next().unwrap().geometry else { panic!() }; + (source.coord_crs(), c) + }; + let cache = dir.path().join("cache"); + let lv95 = made("lv95", ("MapInfo File", "tab"), "EPSG:2056"); + // Where GDAL itself puts the point in longitude/latitude, from the file's definition (which + // in MapInfo leaves out LV95's datum shift). + let gdal_lonlat = { + let json = dir.path().join("lv95.geojson"); + let out = Command::new(program("ogr2ogr").unwrap()) + .args(["-f", "GeoJSON", "-t_srs", "EPSG:4326"]) + .arg(&json) + .arg(&lv95) + .output() + .unwrap(); + assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr)); + let v: serde_json::Value = serde_json::from_slice(&std::fs::read(&json).unwrap()).unwrap(); + let c = &v["features"][0]["geometry"]["coordinates"]; + (c[0].as_f64().unwrap(), c[1].as_f64().unwrap()) + }; + let (converted, failed) = convert_in(&cache, &lv95, None, None).unwrap(); + assert!(failed.is_empty(), "{failed:?}"); + assert!(!converted[0].in_lonlat && !converted[0].unprojected); + // MapInfo keeps the definition, not the code: held in that system, where LV95 is. + let (crs, c) = first(&converted[0].path); + assert_ne!(crs, crate::raster::Crs::LonLat); + assert!((c.x - 2_600_000.0).abs() < 0.01 && (c.y - 1_200_000.0).abs() < 0.01, "{c:?}"); + let Some(crate::Geometry::Point(ll)) = crs.to(crate::raster::Crs::LonLat).unwrap().whole_geometry(&crate::Geometry::Point(c)) + else { + panic!() + }; + assert!((ll.x - gdal_lonlat.0).abs() < 1e-6 && (ll.y - gdal_lonlat.1).abs() < 1e-6, "{ll:?} vs {gdal_lonlat:?}"); + // Taken from the cache the same way. + let (again, _) = convert_in(&cache, &lv95, None, None).unwrap(); + assert!(!again[0].in_lonlat); + assert_eq!(first(&again[0].path).0, crs); + // A system RustGIS can't read (Nell's projection, which a GMT file keeps): converted to + // longitude/latitude, as before, and said; the same from the cache. + let nell = made("nell", ("GMT", "gmt"), "+proj=nell +datum=WGS84 +units=m"); + for _ in 0..2 { + let (converted, failed) = convert_in(&cache, &nell, None, None).unwrap(); + assert!(failed.is_empty() && converted[0].in_lonlat, "{failed:?}"); + let (crs, c) = first(&converted[0].path); + assert_eq!(crs, crate::raster::Crs::LonLat); + assert!(c.x.abs() <= 180.0 && c.y.abs() <= 90.0, "{c:?}"); + } + assert!(in_lonlat_note("nell").contains("converted it to longitude/latitude")); + } + /// A VRT renamed `.tab` isn't opened as a VRT, so the file it names isn't read. #[test] fn a_renamed_vrt_isnt_read_when_gdal_is_installed() { diff --git a/crates/engine/src/cmd/layer.rs b/crates/engine/src/cmd/layer.rs index 4b3c453743..ea2979304c 100644 --- a/crates/engine/src/cmd/layer.rs +++ b/crates/engine/src/cmd/layer.rs @@ -3520,6 +3520,7 @@ pub(crate) fn gdal_parts(mut converted: Vec 0, origin: ConvertedOrigin::Duckdb(origin(part.family)), }) @@ -4308,6 +4310,8 @@ pub(crate) struct Converted { name: String, /// Its coordinates are the source's own, in a coordinate system it doesn't say. unprojected: bool, + /// Its coordinate system is one RustGIS can't read, so it was converted to longitude/latitude. + in_lonlat: bool, /// The conversion dropped Z or M values (said as it ran), kept with the layer so an export /// says so too. zm_dropped: bool, @@ -4329,6 +4333,11 @@ pub(crate) fn add_converted(s: &mut Session, p: &Value, label: &str, original: & let parts = converted.len(); let single = parts == 1; let (mut ids, mut features, mut streamed) = (Vec::new(), 0u64, false); + let mut converted_lonlat = std::collections::HashSet::new(); + let source_layer = |o: &ConvertedOrigin| match o { + ConvertedOrigin::Gdal(g) => g.layer.clone(), + ConvertedOrigin::Duckdb(d) => d.table.clone().unwrap_or_default(), + }; for c in converted { let mut q = json!({"name": c.name}); if let Some(n) = ps(p, "name").filter(|_| single) { @@ -4382,6 +4391,10 @@ pub(crate) fn add_converted(s: &mut Session, p: &Value, label: &str, original: & // its coordinate system is unknown. let e = s.map().layer(id).map(|l| l.extent()).unwrap_or_default(); let outside = !e.is_empty() && (e.min_x < -181.0 || e.max_x > 181.0 || e.min_y < -91.0 || e.max_y > 91.0); + // Once a source layer, not once a part of it. + if c.in_lonlat && converted_lonlat.insert(source_layer(&c.origin)) { + s.notify(rustgis_data::source::gdal::in_lonlat_note(&source_layer(&c.origin)), false); + } if outside || (c.unprojected && matches!(c.origin, ConvertedOrigin::Gdal(_))) { s.notify( format!("{}: the data doesn't say its coordinate system; add it again with \"crs\" (such as EPSG:2263)", c.name), diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 016d6d5f66..ea57d21c0e 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -7,6 +7,9 @@ mod formats_out; #[cfg(not(target_arch = "wasm32"))] #[path = "tests/scene_losses.rs"] mod scene_losses; +#[cfg(not(target_arch = "wasm32"))] +#[path = "tests/sources_own.rs"] +mod sources_own; #[cfg(not(target_arch = "wasm32"))] #[path = "tests/said_not_silent.rs"] @@ -22065,6 +22068,7 @@ fn split_sources_keep_their_points_on_top() { layer: layer.to_string(), family: Some(f), unprojected: false, + in_lonlat: false, }) .collect(); let original = dir.join("file.gpx").display().to_string(); diff --git a/crates/engine/src/tests/sources_own.rs b/crates/engine/src/tests/sources_own.rs new file mode 100644 index 0000000000..b6cde3e7fe --- /dev/null +++ b/crates/engine/src/tests/sources_own.rs @@ -0,0 +1,94 @@ +//! Sources kept in their own coordinate system (#2032 C2f-3): files GDAL converts and DuckDB +//! results, held in the system they say when RustGIS reads it, and converted to longitude/latitude +//! as before, and said, when it doesn't. + +use crate::{Project, Session}; +use rustgis_data::raster::Crs; +use serde_json::json; + +/// A folder removed however the test ends. +struct Dir(std::path::PathBuf); +impl Drop for Dir { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } +} + +fn dir(name: &str) -> Dir { + let d = std::env::temp_dir().join(format!("rustgis-sources-own-{name}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&d); + std::fs::create_dir_all(&d).unwrap(); + Dir(d) +} + +fn first_point(s: &Session, id: u32) -> rustgis_geom::Coord { + let l = s.map().layer(id).unwrap(); + let Some(rustgis_data::Geometry::Point(c)) = l.dataset.features.iter().next().and_then(|f| f.geometry.clone()) else { panic!() }; + c +} + +/// A MapInfo table in LV95 added through GDAL is held in LV95 with its coordinates as stored; a +/// GMT file in a projection RustGIS can't read is converted to longitude/latitude, and said. +#[test] +fn files_gdal_reads_are_held_in_their_own_system() { + use rustgis_data::source::gdal; + if !gdal::available() { + return; + } + let d = dir("gdal"); + let made = |name: &str, driver: &str, ext: &str, srs: &str| { + let csv = d.0.join(format!("{name}.csv")); + std::fs::write(&csv, "WKT,name\n\"POINT (2600000 1200000)\",Bern\n").unwrap(); + let file = d.0.join(format!("{name}.{ext}")); + let out = std::process::Command::new(gdal::program("ogr2ogr").unwrap()) + .args(["-f", driver, "-a_srs", srs]) + .arg(&file) + .arg(&csv) + .output() + .unwrap(); + assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr)); + file + }; + let mut s = Session::new(Project::default()); + let mark = s.notice_mark(); + let r = s.run("layer.addData", &json!({"path": made("lv95", "MapInfo File", "tab", "EPSG:2056"), "stream": false})).unwrap(); + let id = r["layer"].as_u64().unwrap() as u32; + assert_ne!(s.map().layer(id).unwrap().dataset.coord_crs(), Crs::LonLat); + let c = first_point(&s, id); + assert!((c.x - 2_600_000.0).abs() < 0.01 && (c.y - 1_200_000.0).abs() < 0.01, "{c:?}"); + assert!(!s.notices_since(mark).iter().any(|n| n.text.contains("longitude/latitude (WGS 84)"))); + let mark = s.notice_mark(); + let r = + s.run("layer.addData", &json!({"path": made("nell", "GMT", "gmt", "+proj=nell +datum=WGS84 +units=m"), "stream": false})).unwrap(); + let id = r["layer"].as_u64().unwrap() as u32; + assert_eq!(s.map().layer(id).unwrap().dataset.coord_crs(), Crs::LonLat); + let c = first_point(&s, id); + assert!(c.x.abs() <= 180.0 && c.y.abs() <= 90.0, "{c:?}"); + let said = s.notices_since(mark); + assert!(said.iter().any(|n| n.text.contains("can't read its coordinate system, so GDAL converted it")), "{said:?}"); +} + +/// A DuckDB result whose geometry says its system, or is given one, is held in it with its +/// coordinates as the query gives them. +#[test] +fn duckdb_results_are_held_in_their_own_system() { + if !rustgis_data::source::duckdb::available() { + return; + } + let lv95 = Crs::from_epsg(2056).unwrap(); + let mut s = Session::new(Project::default()); + for p in [ + json!({"sql": "SELECT 'Bern' AS name, ST_Point(2600000, 1200000) AS geom", "crs": "EPSG:2056", "stream": false}), + json!({"sql": "SELECT 'Bern' AS name, ST_Point(2600000, 1200000)::GEOMETRY('EPSG:2056') AS geom", "stream": false}), + ] { + let r = s.run("layer.addSql", &p).unwrap(); + let id = r["layer"].as_u64().unwrap() as u32; + assert_eq!(s.map().layer(id).unwrap().dataset.coord_crs(), lv95, "{p}"); + assert_eq!(first_point(&s, id), rustgis_geom::Coord::new(2_600_000.0, 1_200_000.0), "{p}"); + } + // One in longitude/latitude stays so. + let r = s.run("layer.addSql", &json!({"sql": "SELECT ST_Point(7.5, 47) AS geom", "stream": false})).unwrap(); + let id = r["layer"].as_u64().unwrap() as u32; + assert_eq!(s.map().layer(id).unwrap().dataset.coord_crs(), Crs::LonLat); + assert_eq!(first_point(&s, id), rustgis_geom::Coord::new(7.5, 47.0)); +} diff --git a/docs/user-guide/data-formats.md b/docs/user-guide/data-formats.md index 904ae19226..70cf68413d 100644 --- a/docs/user-guide/data-formats.md +++ b/docs/user-guide/data-formats.md @@ -79,7 +79,8 @@ identify and run through tools like any layer; **Load All Features** loads one t With [GDAL](https://gdal.org) installed (its `ogr2ogr` and `ogrinfo` on the `PATH`, GDAL 3.8 or later), the desktop app also reads the vector formats below. Each layer is converted once into a -cached, indexed FlatGeobuf, so large ones stream too: see [Formats through +cached, indexed FlatGeobuf in its own coordinate system (or WGS 84, with a notice, when RustGIS +can't read that system), so large ones stream too: see [Formats through GDAL](data.md#formats-through-gdal). | Format | Extensions or source | Notes | @@ -647,7 +648,7 @@ databases](data.md#sql-queries-and-duckdb-databases). | Source | How to add it | Notes | | --- | --- | --- | -| SQL query | `layer.addSql` with `"sql"` | One DuckDB `SELECT` with DuckDB Spatial: Parquet, CSV, GeoParquet and `ST_Read` files, web addresses (`https://`, `s3://`). Give `"crs"` for a geometry that doesn't say its coordinate system. | +| SQL query | `layer.addSql` with `"sql"` | One DuckDB `SELECT` with DuckDB Spatial: Parquet, CSV, GeoParquet and `ST_Read` files, web addresses (`https://`, `s3://`). Give `"crs"` for a geometry that doesn't say its coordinate system. A geometry that says its system, or is given one by its EPSG code, is kept in it; others come in WGS 84. | | DuckDB database | `.duckdb`, `.ddb`: Add Data | Every table with a geometry column becomes a layer (`"layer"` picks one). Converted once, until the file changes. | ## Rasters diff --git a/docs/user-guide/data.md b/docs/user-guide/data.md index 97cf491880..c109cbcbe7 100644 --- a/docs/user-guide/data.md +++ b/docs/user-guide/data.md @@ -331,7 +331,8 @@ or the folder holding them in `RUSTGIS_GDAL_BIN`; GDAL 3.8 or later), the deskto the vector formats GDAL reads: DWG, MapInfo TAB, OpenStreetMap XML, File Geodatabases RustGIS can't read itself (compressed ones, or ones with raster fields) and more. RustGIS doesn't link to GDAL: each layer is converted once, by `ogr2ogr`, into a -FlatGeobuf with a spatial index in WGS 84 (GDAL reprojects it), kept in the cache folder +FlatGeobuf with a spatial index in the layer's own coordinate system (in WGS 84, with a notice, +when RustGIS can't read that system), kept in the cache folder (`~/.cache/rustgis/gdal` on Linux, `~/Library/Caches/RustGIS/gdal` on macOS, `%LOCALAPPDATA%\RustGIS\cache\gdal` on Windows, or `RUSTGIS_GDAL_CACHE`). Adding the file again reuses the conversion and its layer listing until the file's path, size or modification time From fbf6e6ccaa37808b1f439783e348828e5ceb856e Mon Sep 17 00:00:00 2001 From: strebdom Date: Sun, 22 Nov 2026 20:02:22 +0100 Subject: [PATCH 2/3] Review fixes: one lon/lat notice per file, probe fallbacks for feature services, no blame for an unread header (#2032 C2f-3) --- crates/data/src/source/arcgis.rs | 14 ++++++++--- crates/data/src/source/arcgis/tests.rs | 28 ++++++++++++++++++++++ crates/data/src/source/gdal.rs | 32 ++++++++++++++++++++++++-- crates/engine/src/cmd/layer.rs | 15 ++++++++---- 4 files changed, 80 insertions(+), 9 deletions(-) diff --git a/crates/data/src/source/arcgis.rs b/crates/data/src/source/arcgis.rs index 2043c4323b..b0a40b7937 100644 --- a/crates/data/src/source/arcgis.rs +++ b/crates/data/src/source/arcgis.rs @@ -155,9 +155,17 @@ pub fn open_now(remote: Arc) -> Result { // definition rather than its code) is asked for in longitude/latitude, as before. if out_sr.is_some() { let native = with(&features_query(&query, out_sr), &[("resultRecordCount", "1")]); - let Some(answer) = remote.answer(&native)? else { return Err(remote::need()) }; - let in_it = answer.is_empty() - || crate::esripbf::read_page(&answer, "check").is_ok_and(|p| p.dataset.features.is_empty() || p.dataset.coord_crs() == held); + // An answer too large to take is read in longitude/latitude, as the first one was. + let answer = match remote.answer(&native) { + Ok(Some(answer)) => Some(answer), + Ok(None) => return Err(remote::need()), + Err(e) if remote::is_too_large(&e) => None, + Err(e) => return Err(e), + }; + // In it, empty or not (a page in another system, or saying none, is read in + // longitude/latitude), or no bytes at all, which say nothing of it. + let in_it = + answer.is_some_and(|a| a.is_empty() || crate::esripbf::read_page(&a, "check").is_ok_and(|p| p.dataset.coord_crs() == held)); if !in_it { (held, to_lonlat, out_sr) = (crate::raster::Crs::LonLat, None, None); } diff --git a/crates/data/src/source/arcgis/tests.rs b/crates/data/src/source/arcgis/tests.rs index f013ecc374..a61d38c164 100644 --- a/crates/data/src/source/arcgis/tests.rs +++ b/crates/data/src/source/arcgis/tests.rs @@ -59,6 +59,12 @@ struct Opts { /// Its layer is in Web Mercator (its description says so), and it answers in the system /// asked for (`outSR`), Web Mercator or longitude/latitude. mercator: bool, + /// With `mercator`, its first feature asked for in Web Mercator is an answer too large to + /// take. + probe_too_large: bool, + /// With `mercator`, it answers the first feature asked for in Web Mercator with an empty page + /// in longitude/latitude. + probe_empty_lonlat: bool, } impl Default for Opts { @@ -79,6 +85,8 @@ impl Default for Opts { over: 0, empty_body: false, mercator: false, + probe_too_large: false, + probe_empty_lonlat: false, } } } @@ -109,6 +117,8 @@ fn service_with(host: &str, opts: Opts) -> (String, Arc) { over, empty_body, mercator, + probe_too_large, + probe_empty_lonlat, } = opts; let layer = format!("https://{host}/arcgis/rest/services/P/FeatureServer/0"); let asked = Arc::new(Asked::default()); @@ -160,6 +170,13 @@ fn service_with(host: &str, opts: Opts) -> (String, Arc) { } let geometry_too = value("returnGeometry").as_deref() != Some("false"); let in_mercator = mercator && value("outSR").as_deref() == Some("3857"); + let probe = in_mercator && value("resultRecordCount").as_deref() == Some("1") && value("resultOffset").is_none(); + if probe && probe_too_large { + return Some(vec![0; usize::try_from(remote::MAX_ANSWER).unwrap() + 1]); + } + if probe && probe_empty_lonlat { + return Some(answer(&[number(7, 0), lonlat(), transform(false, 0.01, 0.0, 0.0), field("OBJECTID", 6)])); + } let reference = if in_mercator { message(8, &number(1, 3857)) } else { lonlat() }; let mut parts = vec![number(7, 0), reference, transform(false, 0.01, 0.0, 0.0)]; if !(sent.is_empty() && empty_without_fields) { @@ -652,6 +669,17 @@ fn a_layer_is_read_in_its_own_system() { .unwrap(); inside.sort_unstable(); assert_eq!(inside, want); + // A first page in Web Mercator too large to take, or empty and in another system: asked for + // in longitude/latitude, as before. + for (host, opts) in [ + ("probe-large.test", Opts { page: 30, mercator: true, probe_too_large: true, ..Opts::default() }), + ("probe-empty.test", Opts { page: 30, mercator: true, probe_empty_lonlat: true, ..Opts::default() }), + ] { + let (query, _) = service_with(host, opts); + let src = open_blocking(&query).unwrap(); + assert_eq!(src.coord_crs(), crate::raster::Crs::LonLat, "{host}"); + assert_eq!(ids(&read(&src, Request { extent: Some(small_view()), limit: 1000 }).unwrap()), want, "{host}"); + } // A code RustGIS doesn't read: longitude/latitude, as before. let description = r#"{"name":"Points","objectIdField":"OBJECTID","maxRecordCount":30,"supportedQueryFormats":"PBF","geometryType":"esriGeometryPoint", "useStandardizedQueries":true,"advancedQueryCapabilities":{"supportsPagination":true},"extent":{"spatialReference":{"wkid":999999}}}"#; diff --git a/crates/data/src/source/gdal.rs b/crates/data/src/source/gdal.rs index 1604c98dcc..8011999574 100644 --- a/crates/data/src/source/gdal.rs +++ b/crates/data/src/source/gdal.rs @@ -701,7 +701,8 @@ enum Placement { fn placement(fgb: &Path) -> Placement { use crate::raster::Crs; crate::provenance::without(|| { - let Ok(crs) = super::fgb::header_coord_crs(fgb) else { return Placement::Unreadable }; + // A header that can't be read says nothing of the system: converted as before, unsaid. + let Ok(crs) = super::fgb::header_coord_crs(fgb) else { return Placement::LonLat }; if crs == Crs::LonLat { return if super::fgb::header_says_wgs84(fgb) { Placement::Own } else { Placement::Unreadable }; } @@ -718,7 +719,26 @@ fn placement(fgb: &Path) -> Placement { /// The notice for a layer converted to longitude/latitude because its system can't be read. pub fn in_lonlat_note(layer: &str) -> String { - format!("GDAL: '{layer}': RustGIS can't read its coordinate system, so GDAL converted it to longitude/latitude (WGS 84)") + in_lonlat_notes(&[layer]) +} + +/// One notice for the layers of a file converted to longitude/latitude because their systems +/// can't be read: their count, and their names (the first ten). +pub fn in_lonlat_notes(layers: &[&str]) -> String { + match layers { + [one] => format!("GDAL: '{one}': RustGIS can't read its coordinate system, so GDAL converted it to longitude/latitude (WGS 84)"), + _ => { + let mut named: Vec = layers.iter().take(10).map(|l| format!("'{l}'")).collect(); + if layers.len() > 10 { + named.push(format!("{} more", layers.len() - 10)); + } + format!( + "GDAL: {} layers ({}): RustGIS can't read their coordinate systems, so GDAL converted them to longitude/latitude (WGS 84)", + layers.len(), + named.join(", ") + ) + } + } } /// Count only the other supported geometry families, not geometry-less rows. Reuse exactly the @@ -937,6 +957,14 @@ mod tests { assert!(c.x.abs() <= 180.0 && c.y.abs() <= 90.0, "{c:?}"); } assert!(in_lonlat_note("nell").contains("converted it to longitude/latitude")); + // Several layers of a file: one notice, with their count and names. + let many: Vec = (1..=12).map(|i| format!("l{i}")).collect(); + let names: Vec<&str> = many.iter().map(String::as_str).collect(); + let note = in_lonlat_notes(&names); + assert!( + note.starts_with("GDAL: 12 layers ('l1', 'l2',") && note.contains("'l10', 2 more)") && note.contains("converted them"), + "{note}" + ); } /// A VRT renamed `.tab` isn't opened as a VRT, so the file it names isn't read. diff --git a/crates/engine/src/cmd/layer.rs b/crates/engine/src/cmd/layer.rs index ea2979304c..fee9d21b2a 100644 --- a/crates/engine/src/cmd/layer.rs +++ b/crates/engine/src/cmd/layer.rs @@ -4333,7 +4333,7 @@ pub(crate) fn add_converted(s: &mut Session, p: &Value, label: &str, original: & let parts = converted.len(); let single = parts == 1; let (mut ids, mut features, mut streamed) = (Vec::new(), 0u64, false); - let mut converted_lonlat = std::collections::HashSet::new(); + let mut converted_lonlat: Vec = Vec::new(); let source_layer = |o: &ConvertedOrigin| match o { ConvertedOrigin::Gdal(g) => g.layer.clone(), ConvertedOrigin::Duckdb(d) => d.table.clone().unwrap_or_default(), @@ -4391,9 +4391,12 @@ pub(crate) fn add_converted(s: &mut Session, p: &Value, label: &str, original: & // its coordinate system is unknown. let e = s.map().layer(id).map(|l| l.extent()).unwrap_or_default(); let outside = !e.is_empty() && (e.min_x < -181.0 || e.max_x > 181.0 || e.min_y < -91.0 || e.max_y > 91.0); - // Once a source layer, not once a part of it. - if c.in_lonlat && converted_lonlat.insert(source_layer(&c.origin)) { - s.notify(rustgis_data::source::gdal::in_lonlat_note(&source_layer(&c.origin)), false); + // Said once for the file below, naming each source layer once, not each part of it. + if c.in_lonlat { + let layer = source_layer(&c.origin); + if !converted_lonlat.contains(&layer) { + converted_lonlat.push(layer); + } } if outside || (c.unprojected && matches!(c.origin, ConvertedOrigin::Gdal(_))) { s.notify( @@ -4404,6 +4407,10 @@ pub(crate) fn add_converted(s: &mut Session, p: &Value, label: &str, original: & ids.push(id); } } + if !converted_lonlat.is_empty() { + let names: Vec<&str> = converted_lonlat.iter().map(String::as_str).collect(); + s.notify(rustgis_data::source::gdal::in_lonlat_notes(&names), false); + } if empty_before { let e = ids.iter().filter_map(|id| s.map().layer(*id)).fold(rustgis_geom::Extent::EMPTY, |e, l| e.union(&l.extent())); if !e.is_empty() { From 975cddecb97caf33f2cb0a8d458d91fa66aef26c Mon Sep 17 00:00:00 2001 From: strebdom Date: Sun, 22 Nov 2026 20:29:21 +0100 Subject: [PATCH 3/3] Review fixes: a refused system fails its layer saying why; an unread header converts silently (#2032 C2f-3) --- crates/data/src/source/fgb.rs | 8 +++++--- crates/data/src/source/gdal.rs | 36 +++++++++++++++++++++++++++++++--- 2 files changed, 38 insertions(+), 6 deletions(-) diff --git a/crates/data/src/source/fgb.rs b/crates/data/src/source/fgb.rs index f86b33efe5..02f28089e1 100644 --- a/crates/data/src/source/fgb.rs +++ b/crates/data/src/source/fgb.rs @@ -61,11 +61,13 @@ fn header_reproject(header_crs: Option>, notes: &mut Vec Result { +pub(crate) fn header_coord_crs(path: &Path) -> Result> { let reader = open_reader(BufReader::new(std::fs::File::open(path)?))?; - Ok(header_reproject(reader.header().crs(), &mut Vec::new())?.crs()) + Ok(header_reproject(reader.header().crs(), &mut Vec::new()).map(|r| r.crs())) } /// Whether a FlatGeobuf's header says WGS 84 longitude/latitude or no system: EPSG:4326 (or no diff --git a/crates/data/src/source/gdal.rs b/crates/data/src/source/gdal.rs index 8011999574..35a7f2c239 100644 --- a/crates/data/src/source/gdal.rs +++ b/crates/data/src/source/gdal.rs @@ -601,6 +601,11 @@ fn convert_one_in(dir: &Path, src: &Path, layer: &str, request: ConversionReques let mut in_lonlat = false; if res.status.success() && !unprojected && tmp.exists() { let placement = placement(&tmp); + // Another body's system RustGIS refuses can't go to WGS 84 either (GDAL won't convert + // between bodies): refused, saying why, rather than left out as empty. + if let Placement::Refused(why) = &placement { + return Err(DataError::Format(format!("GDAL: '{layer}': {why}"))); + } if placement != Placement::Own { crate::progress::check()?; // GDAL can't write over a FlatGeobuf: the first conversion goes first. @@ -682,7 +687,7 @@ fn convert_one_in(dir: &Path, src: &Path, layer: &str, request: ConversionReques } /// How RustGIS reads a FlatGeobuf GDAL wrote in the source's own system. -#[derive(Clone, Copy, Debug, PartialEq)] +#[derive(Clone, Debug, PartialEq)] enum Placement { /// In that system, which it reads and converts itself (WGS 84 longitude/latitude among them). Own, @@ -692,6 +697,8 @@ enum Placement { LonLat, /// A system it can't read, which it would take for longitude/latitude: converted to it. Unreadable, + /// Another body's system it refuses, and why: not converted at all. + Refused(String), } /// How RustGIS reads `fgb` ([`Placement`]), from its header alone. One it reads as @@ -701,8 +708,13 @@ enum Placement { fn placement(fgb: &Path) -> Placement { use crate::raster::Crs; crate::provenance::without(|| { - // A header that can't be read says nothing of the system: converted as before, unsaid. - let Ok(crs) = super::fgb::header_coord_crs(fgb) else { return Placement::LonLat }; + // A header that can't be read says nothing of the system: converted as before, unsaid. A + // system it says that RustGIS refuses can't be read, and is said. + let crs = match super::fgb::header_coord_crs(fgb) { + Err(_) => return Placement::LonLat, + Ok(Err(e)) => return Placement::Refused(e.to_string()), + Ok(Ok(crs)) => crs, + }; if crs == Crs::LonLat { return if super::fgb::header_says_wgs84(fgb) { Placement::Own } else { Placement::Unreadable }; } @@ -957,6 +969,24 @@ mod tests { assert!(c.x.abs() <= 180.0 && c.y.abs() <= 90.0, "{c:?}"); } assert!(in_lonlat_note("nell").contains("converted it to longitude/latitude")); + // A system RustGIS refuses (another body's, in a projection it doesn't convert) is refused, + // saying why, not converted; a header that can't be read says nothing, so is converted. + let mars = dir.path().join("mars.fgb"); + let out = Command::new(program("ogr2ogr").unwrap()) + .args(["-f", "FlatGeobuf", "-a_srs", "+proj=nell +R=3396190 +units=m +no_defs +type=crs"]) + .arg(&mars) + .arg(dir.path().join("lv95.csv")) + .output() + .unwrap(); + if out.status.success() { + assert!(matches!(placement(&mars), Placement::Refused(why) if why.contains("another body"))); + let gmt = made("mars", ("GMT", "gmt"), "+proj=nell +R=3396190 +units=m +no_defs +type=crs"); + let e = convert_in(&cache, &gmt, None, None).unwrap_err().to_string(); + assert!(e.contains("another body") && e.contains("nell"), "{e}"); + } + let broken = dir.path().join("broken.fgb"); + std::fs::write(&broken, b"not a flatgeobuf").unwrap(); + assert_eq!(placement(&broken), Placement::LonLat); // Several layers of a file: one notice, with their count and names. let many: Vec = (1..=12).map(|i| format!("l{i}")).collect(); let names: Vec<&str> = many.iter().map(String::as_str).collect();