Skip to main content

waratah_geo/
materialize.rs

1//! WKT / WKB materialization: native term → output literal lexical form.
2//!
3//! **Locked (plan §1):** `geo:wktLiteral` output does NOT emit internal
4//! CRS84. PROJ (or a pure axis swap) transforms back to the ingest `CrsId`
5//! and that CRS's WKT axis order is restored. Non-CRS84 CRSs emit the
6//! GeoSPARQL literal as `<crs-uri> WKT` with the **serialize-default** URI
7//! (alias spellings are not stored on the term); CRS84 emits bare WKT with
8//! no prefix, because it is the GeoSPARQL default CRS and
9//! `parse_geometry_literal` treats an absent prefix as CRS84, so the form
10//! round-trips. `geo:wkbLiteral` output emits EWKB hex, lon/lat coordinate
11//! order always (datum-normalized for non-CRS84/4326 CRSs), SRID per
12//! [`crate::encode::wkb_srid`], SRID-less for CRS84.
13//! The native term's spike-reduction flag is execution-only and deliberately
14//! ignored here, so materialization renders the original canonical blob.
15//!
16//! **Locked `geo:wkbLiteral` literal contract (owner decision):** output is
17//! hex **EWKB** with the SRID from [`crate::encode::wkb_srid`] — SRID-less
18//! for CRS84, `Some(epsg)` otherwise — so every materialized wkbLiteral
19//! re-ingests through [`crate::encode::parse_geometry_literal`] as the same
20//! CRS (round-trip). Input accepts hex EWKB always, plus hex OGC WKB when
21//! the flag-bit sniff finds no EWKB flag bits. The binary payload is ALWAYS
22//! lon/lat (x = longitude) regardless of SRID — the SRID is CRS identity
23//! metadata only (the de-facto WKB ecosystem convention: PostGIS, GDAL,
24//! GEOS); MySQL 8, which reorders WKB coordinates per the EPSG axis
25//! definition, is the accepted, documented incompatibility.
26//!
27//! **Z / M blobs** keep their extra coordinate values on BOTH output paths:
28//! the payload's dims are read from its WKB header and Z/M payloads
29//! re-stream through `canonical`'s forwarding chain (datum transform on
30//! x/y only, z/m passthrough). The wktLiteral path emits dimension markers
31//! (`POINT Z(...)`, `POLYGON Z((...))`) — geozero's `WktWriter` cannot — so
32//! every materialized Z/M lexical re-ingests as the same canonical blob.
33
34use geo::Geometry;
35use waratah_storage::{CrsId, EncodedTerm, GeoDatatype};
36
37use crate::encode::{GeoError, transform_from_crs84, transform_geometry_from_crs84_normalized};
38
39/// Render the lexical form of a native geo term.
40///
41/// `payload` is the CRS84 EWKB for blob-backed terms (`None` for inline
42/// points). Returns `None` when the term is not a native geo term.
43pub fn materialize_lexical(
44    term: &EncodedTerm,
45    payload: Option<&[u8]>,
46) -> Option<Result<String, GeoError>> {
47    match term {
48        EncodedTerm::LiteralPoint {
49            x,
50            y,
51            crs,
52            geo_datatype,
53        } => Some(render_point(*x, *y, *crs, *geo_datatype)),
54        EncodedTerm::LiteralGeometry {
55            crs, geo_datatype, ..
56        } => {
57            let Some(payload) = payload else {
58                return Some(Err(GeoError::Parse(
59                    "geometry term requires its blob payload to materialize".into(),
60                )));
61            };
62            Some(render_geometry(payload, *crs, *geo_datatype))
63        }
64        _ => None,
65    }
66}
67
68/// Point dispatcher: builds the point geometry once, then takes the same
69/// datatype leaf as blob-backed geometries.
70fn render_point(
71    lon: f64,
72    lat: f64,
73    crs: CrsId,
74    geo_datatype: GeoDatatype,
75) -> Result<String, GeoError> {
76    let geometry = Geometry::Point(geo::Point::new(lon, lat));
77    if geo_datatype == GeoDatatype::WkbLiteral {
78        // Points materialize through the same WKB path as geometries.
79        render_wkb_hex(&geometry, crs)
80    } else {
81        render_wkt_text(&geometry, crs)
82    }
83}
84
85/// Geometry dispatcher over the blob payload.
86///
87/// The payload's dims are read from its WKB header (one sniff): 2D blobs
88/// take the unchanged 2D paths below; Z/M blobs re-stream through
89/// `canonical`'s forwarding chain, which preserves their z / m values —
90/// the 2D `to_geo` projection used by [`crate::relate::candidate_from_ewkb`]
91/// would drop them.
92fn render_geometry(
93    crs84_ewkb: &[u8],
94    crs: CrsId,
95    geo_datatype: GeoDatatype,
96) -> Result<String, GeoError> {
97    let header = crate::encode::read_wkb_dialect_header(crs84_ewkb);
98    let carries_zm = header.has_z || header.has_m;
99    if geo_datatype == GeoDatatype::WktLiteral {
100        if carries_zm {
101            // geozero's WktWriter never emits dimension markers, so Z/M
102            // output goes through the marker-aware emitter in `canonical`;
103            // re-ingesting the lexical reproduces the same canonical blob.
104            let dims = crate::canonical::dims_from_flags(header.has_z, header.has_m);
105            let wkt = crate::canonical::crs84_zm_blob_to_marked_wkt(crs84_ewkb, crs, dims)?;
106            return Ok(with_crs_prefix(wkt, crs));
107        }
108        let geometry = crate::relate::candidate_from_ewkb(crs84_ewkb)?;
109        render_wkt_text(&geometry, crs)
110    } else {
111        if carries_zm {
112            let dims = crate::canonical::dims_from_flags(header.has_z, header.has_m);
113            let wkb = crate::canonical::crs84_zm_blob_to_ewkb(crs84_ewkb, crs, dims)?;
114            return Ok(wkb.iter().map(|byte| format!("{byte:02x}")).collect());
115        }
116        let geometry = crate::relate::candidate_from_ewkb(crs84_ewkb)?;
117        render_wkb_hex(&geometry, crs)
118    }
119}
120
121/// Prepend the canonical `<crs-uri> ` prefix for non-CRS84 CRSs (bare WKT
122/// is the GeoSPARQL default form for CRS84).
123fn with_crs_prefix(wkt: String, crs: CrsId) -> String {
124    if matches!(crs, CrsId::Crs84) {
125        return wkt;
126    }
127    format!("<{}> {wkt}", CrsId::canonical_uri(crs))
128}
129
130/// WKT leaf: transform back to the ingest CRS, restore its WKT axis order,
131/// and emit bare WKT for CRS84 (the GeoSPARQL default) or
132/// `<crs-uri> WKT` with the canonical URI otherwise.
133fn render_wkt_text(geometry: &Geometry<f64>, crs: CrsId) -> Result<String, GeoError> {
134    let transformed = transform_geometry_back(geometry, crs)?;
135    let wkt = geometry_to_wkt(&transformed)?;
136    if matches!(crs, CrsId::Crs84) {
137        return Ok(wkt);
138    }
139    Ok(format!("<{}> {wkt}", CrsId::canonical_uri(crs)))
140}
141
142/// WKB leaf: rebuild at materialize time from the CRS84 geometry + ingest
143/// CRS, emit EWKB hex-encoded in lon/lat order ALWAYS (the binary-format
144/// convention — only the datum normalizes for non-CRS84/4326 CRSs; no axis
145/// reorder). The EWKB SRID names the ingest CRS per
146/// [`crate::encode::wkb_srid`], which carries the CRS84-is-SRID-less
147/// round-trip rule.
148fn render_wkb_hex(geometry: &Geometry<f64>, crs: CrsId) -> Result<String, GeoError> {
149    let transformed = transform_geometry_from_crs84_normalized(geometry, crs)?;
150    use geozero::CoordDimensions;
151    use geozero::ToWkb;
152    let srid = crate::encode::wkb_srid(crs);
153    let wkb = transformed
154        .to_ewkb(CoordDimensions::xy(), srid)
155        .map_err(|error| GeoError::Parse(error.to_string()))?;
156    Ok(wkb.iter().map(|byte| format!("{byte:02x}")).collect())
157}
158
159fn transform_geometry_back(
160    geometry: &Geometry<f64>,
161    crs: CrsId,
162) -> Result<Geometry<f64>, GeoError> {
163    // WKT path only: the WKB leaf uses
164    // `transform_geometry_from_crs84_normalized` (binary is lon/lat always,
165    // no text-order restore).
166    if matches!(crs, CrsId::Crs84) {
167        return Ok(geometry.clone());
168    }
169    use geo::MapCoords;
170    geometry.try_map_coords(|coord| -> Result<geo::Coord<f64>, GeoError> {
171        // `transform_from_crs84` returns the target CRS's WKT text order —
172        // (lat, lon) for EPSG geographic CRSs, (lon, lat) for CRS84. geozero
173        // prints Coord.x first, so the text order maps straight into (x, y).
174        let (a, b) = transform_from_crs84(crs, coord.x, coord.y)?;
175        Ok(geo::Coord { x: a, y: b })
176    })
177}
178
179/// geo_types → WKT string via geozero (feature `with-wkt`).
180fn geometry_to_wkt(geometry: &Geometry<f64>) -> Result<String, GeoError> {
181    use geozero::ToWkt;
182    geometry
183        .to_wkt()
184        .map_err(|error| GeoError::Parse(error.to_string()))
185}
186
187#[cfg(test)]
188mod tests {
189    use super::*;
190    use pretty_assertions::assert_eq;
191
192    fn point_term(lon: f64, lat: f64, crs: CrsId) -> EncodedTerm {
193        EncodedTerm::LiteralPoint {
194            x: lon,
195            y: lat,
196            crs,
197            geo_datatype: GeoDatatype::WktLiteral,
198        }
199    }
200
201    #[test]
202    fn crs84_out_omits_the_default_crs_prefix() {
203        let out = materialize_lexical(&point_term(153.025, -27.47, CrsId::Crs84), None)
204            .unwrap()
205            .unwrap();
206        assert_eq!(out, "POINT(153.025 -27.47)");
207    }
208
209    #[test]
210    fn epsg4326_out_restores_lat_lon_axis() {
211        let out = materialize_lexical(&point_term(153.025, -27.47, CrsId::Epsg4326), None)
212            .unwrap()
213            .unwrap();
214        assert_eq!(
215            out,
216            "<http://www.opengis.net/def/crs/EPSG/0/4326> POINT(-27.47 153.025)"
217        );
218    }
219
220    #[test]
221    fn epsg4326_round_trip_through_ingest() {
222        // Ingest lat/lon → CRS84 stored → materialize back to lat/lon.
223        let prepared = crate::encode::prepare_geometry_literal(&oxrdf::Literal::new_typed_literal(
224            "<http://www.opengis.net/def/crs/EPSG/0/4326> POINT(-27.47 153.025)",
225            oxrdf::NamedNode::new_unchecked(crate::encode::GEO_WKT_LITERAL),
226        ))
227        .unwrap();
228        let out = materialize_lexical(&prepared.term, None).unwrap().unwrap();
229        assert_eq!(
230            out,
231            "<http://www.opengis.net/def/crs/EPSG/0/4326> POINT(-27.47 153.025)"
232        );
233    }
234
235    #[test]
236    fn alias_spelling_normalizes_to_the_default_uri() {
237        // An `urn:ogc:def:crs:EPSG::4326` alias stores CrsId::Epsg4326 and
238        // serializes with the canonical opengis.net URI.
239        let prepared = crate::encode::prepare_geometry_literal(&oxrdf::Literal::new_typed_literal(
240            "<urn:ogc:def:crs:EPSG::4326> POINT(-27.47 153.025)",
241            oxrdf::NamedNode::new_unchecked(crate::encode::GEO_WKT_LITERAL),
242        ))
243        .unwrap();
244        let out = materialize_lexical(&prepared.term, None).unwrap().unwrap();
245        assert!(
246            out.starts_with("<http://www.opengis.net/def/crs/EPSG/0/4326>"),
247            "{out}"
248        );
249    }
250
251    #[test]
252    fn polygon_wkt_out_restores_axis_order_and_prefix() {
253        // Blob-backed non-point WKT: ingest an EPSG:4326 polygon (lat/lon
254        // axis order) and materialize it back through its CRS84 blob.
255        let prepared = crate::encode::prepare_geometry_literal(&oxrdf::Literal::new_typed_literal(
256            "<http://www.opengis.net/def/crs/EPSG/0/4326> POLYGON((-28.0 152.5, -28.0 153.5, -27.0 153.5, -27.0 152.5, -28.0 152.5))",
257            oxrdf::NamedNode::new_unchecked(crate::encode::GEO_WKT_LITERAL),
258        ))
259        .unwrap();
260        assert!(prepared.is_native(), "polygon must mint a native term");
261        let payload = &prepared.blobs[0].1;
262        let out = materialize_lexical(&prepared.term, Some(payload))
263            .unwrap()
264            .unwrap();
265        assert_eq!(
266            out,
267            "<http://www.opengis.net/def/crs/EPSG/0/4326> POLYGON((-28 152.5,-28 153.5,-27 153.5,-27 152.5,-28 152.5))"
268        );
269
270        // The same polygon under CRS84 emits bare WKT: no `<crs-uri>` prefix.
271        let crs84 = crate::encode::prepare_geometry_literal(&oxrdf::Literal::new_typed_literal(
272            "POLYGON((152.5 -28.0, 153.5 -28.0, 153.5 -27.0, 152.5 -27.0, 152.5 -28.0))",
273            oxrdf::NamedNode::new_unchecked(crate::encode::GEO_WKT_LITERAL),
274        ))
275        .unwrap();
276        let crs84_payload = &crs84.blobs[0].1;
277        let crs84_out = materialize_lexical(&crs84.term, Some(crs84_payload))
278            .unwrap()
279            .unwrap();
280        assert_eq!(
281            crs84_out,
282            "POLYGON((152.5 -28,153.5 -28,153.5 -27,152.5 -27,152.5 -28))"
283        );
284    }
285
286    /// Little-endian POINT (E)WKB hex, with an optional EWKB SRID flag.
287    fn point_ewkb_hex(x: f64, y: f64, srid: Option<i32>) -> String {
288        let mut bytes = vec![1u8]; // little-endian
289        match srid {
290            Some(srid) => {
291                bytes.extend_from_slice(&0x2000_0001u32.to_le_bytes()); // SRID flag | POINT
292                bytes.extend_from_slice(&srid.to_le_bytes());
293            }
294            None => bytes.extend_from_slice(&1u32.to_le_bytes()), // POINT
295        }
296        bytes.extend_from_slice(&x.to_le_bytes());
297        bytes.extend_from_slice(&y.to_le_bytes());
298        bytes.iter().map(|byte| format!("{byte:02x}")).collect()
299    }
300
301    #[test]
302    fn wkb_literal_point_materializes_as_hex_and_round_trips() {
303        // CRS84 hex (no SRID): materialize must produce hex EWKB, NOT WKT
304        // text, and the hex must re-parse to the same point and CRS. The
305        // flagless form sniffs as OGC WKB on ingest and still round-trips
306        // byte-identically (flagless EWKB is byte-identical to OGC WKB); the
307        // SRID'd EPSG:4326 form round-trips through the EWKB reader (see
308        // `wkb_literal_srid4326_round_trips` in `encode.rs`).
309        let hex = point_ewkb_hex(153.025, -27.47, None);
310        let prepared = crate::encode::prepare_geometry_literal(&oxrdf::Literal::new_typed_literal(
311            hex.clone(),
312            oxrdf::NamedNode::new_unchecked(crate::encode::GEO_WKB_LITERAL),
313        ))
314        .unwrap();
315        let EncodedTerm::LiteralPoint {
316            crs, geo_datatype, ..
317        } = prepared.term
318        else {
319            panic!("expected LiteralPoint, got {:?}", prepared.term);
320        };
321        assert_eq!(geo_datatype, GeoDatatype::WkbLiteral);
322        assert_eq!(crs, CrsId::Crs84);
323        let out = materialize_lexical(&prepared.term, None).unwrap().unwrap();
324        assert_eq!(out, hex, "wkbLiteral point stays hex EWKB");
325        let (geometry, reparsed_crs) =
326            crate::encode::parse_geometry_literal(&oxrdf::Literal::new_typed_literal(
327                &out,
328                oxrdf::NamedNode::new_unchecked(crate::encode::GEO_WKB_LITERAL),
329            ))
330            .unwrap();
331        assert_eq!(reparsed_crs, CrsId::Crs84);
332        let Geometry::Point(point) = geometry else {
333            panic!("expected a point, got {geometry:?}");
334        };
335        assert_eq!(point.x(), 153.025);
336        assert_eq!(point.y(), -27.47);
337    }
338}