Skip to main content

vortex_spatial/extension/
mod.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4//! Spatial extension types and metadata shared by their Arrow plugins.
5//!
6//! Geometry types declare storage from [`SpatialMetadata`], which holds the coordinate dimension
7//! and an optional coordinate reference system. Shared metadata handling keeps these properties
8//! consistent across the GeoArrow fields used to import and export each geometry.
9
10pub(crate) mod coordinate;
11pub use coordinate::Dimension;
12
13mod linestring;
14pub use linestring::*;
15
16mod multilinestring;
17pub use multilinestring::*;
18
19mod multipoint;
20pub use multipoint::*;
21
22mod multipolygon;
23pub use multipolygon::*;
24
25mod point;
26pub use point::*;
27
28mod polygon;
29pub use polygon::*;
30
31mod rect;
32pub use rect::*;
33
34mod wkb;
35use std::fmt::Display;
36use std::sync::Arc;
37
38use ::wkb::reader::GeometryType;
39use arrow_array::BinaryArray;
40use geo_types::Geometry;
41use geoarrow::array::GenericWkbArray;
42use geoarrow::array::GeoArrowArray;
43use geoarrow::datatypes::CoordType;
44use geoarrow::datatypes::Crs;
45use geoarrow::datatypes::Dimension as GeoArrowDimension;
46use geoarrow::datatypes::GeoArrowType;
47use geoarrow::datatypes::LineStringType;
48use geoarrow::datatypes::Metadata;
49use geoarrow::datatypes::MultiLineStringType;
50use geoarrow::datatypes::MultiPointType;
51use geoarrow::datatypes::MultiPolygonType;
52use geoarrow::datatypes::PointType;
53use geoarrow::datatypes::PolygonType;
54use geoarrow::datatypes::WkbType;
55use geoarrow_cast::cast::cast;
56use prost::Message;
57use vortex_array::ArrayRef;
58use vortex_array::ExecutionCtx;
59use vortex_array::IntoArray;
60use vortex_array::VortexSessionExecute;
61use vortex_array::arrays::ConstantArray;
62use vortex_array::arrays::ExtensionArray;
63use vortex_array::arrays::ListViewArray;
64use vortex_array::arrays::StructArray;
65use vortex_array::arrays::extension::ExtensionArrayExt;
66use vortex_array::arrays::list::ListArraySlotsExt;
67use vortex_array::arrays::listview::ListViewArraySlotsExt;
68use vortex_array::arrays::listview::list_from_list_view;
69use vortex_array::builtins::ArrayBuiltins;
70use vortex_array::dtype::DType;
71use vortex_array::dtype::Nullability;
72use vortex_array::dtype::PType;
73use vortex_array::dtype::extension::ExtId;
74use vortex_array::dtype::extension::ExtVTable;
75use vortex_array::scalar::Scalar;
76use vortex_arrow::ArrowSession;
77use vortex_arrow::ArrowSessionExt;
78use vortex_buffer::Buffer;
79use vortex_error::VortexExpect;
80use vortex_error::VortexResult;
81use vortex_error::vortex_bail;
82use vortex_error::vortex_ensure;
83use vortex_error::vortex_err;
84use vortex_session::VortexSession;
85pub use wkb::*;
86
87/// Whether `dtype` is one of the native geometry extension types the spatial kernels operate on.
88pub(crate) fn is_native_geometry(dtype: &DType) -> bool {
89    dtype.as_extension_opt().is_some_and(|ext| {
90        ext.is::<Point>()
91            || ext.is::<LineString>()
92            || ext.is::<MultiPoint>()
93            || ext.is::<Polygon>()
94            || ext.is::<MultiLineString>()
95            || ext.is::<MultiPolygon>()
96            || ext.is::<Rect>()
97    })
98}
99
100/// Flatten a native geometry column into a single coordinate `Struct<x, y, ...>` containing
101/// every vertex of every geometry.
102pub(crate) fn flatten_coordinates(
103    array: &ArrayRef,
104    ctx: &mut ExecutionCtx,
105) -> VortexResult<StructArray> {
106    if !is_native_geometry(array.dtype()) {
107        vortex_bail!(
108            "spatial: operand is not a native geometry extension type, was {}",
109            array.dtype()
110        );
111    }
112    let mut node = array
113        .clone()
114        .execute::<ExtensionArray>(ctx)?
115        .storage_array()
116        .clone();
117    while node.dtype().is_list() {
118        node = node.execute::<ListViewArray>(ctx)?.elements().clone();
119    }
120    node.execute::<StructArray>(ctx)
121}
122
123/// Flatten a native geometry `storage` array to its leaf coordinates, keeping track of which
124/// row owns which coordinates.
125///
126/// Returns the flat coordinate `Struct` plus `row_offsets` (one entry per row plus a final
127/// cap): row `r`'s coordinates are `coordinates[row_offsets[r]..row_offsets[r + 1]]`, an empty
128/// range if the row has none.
129///
130/// Row boundaries are pushed down one `List` level at a time. A boundary at list `e` moves to
131/// `offsets[e]`, where that list's children start. For example, a 2-row `MultiPolygon` column —
132/// row 0 = one polygon of two rings (3 + 4 vertices), row 1 = one polygon of one ring (5
133/// vertices):
134///
135/// ```text
136/// level                offsets       row_offsets after the level
137/// rows     → polygons  [0,1,2]       [0,1,2]    row 1 starts at polygon 1
138/// polygons → rings     [0,2,3]       [0,2,3]    row 1 starts at ring 2
139/// rings    → vertices  [0,3,7,12]    [0,7,12]   row 1 starts at vertex 7
140/// ```
141pub(crate) fn flatten_row_offsets(
142    storage: ArrayRef,
143    ctx: &mut ExecutionCtx,
144) -> VortexResult<(Vec<usize>, StructArray)> {
145    let len = storage.len();
146
147    // At the outermost level, row `r` starts at element `r`; the extra entry caps the last row.
148    let mut row_offsets: Vec<usize> = (0..=len).collect();
149    let mut level = storage;
150    while level.dtype().is_list() {
151        let list = list_from_list_view(level.execute::<ListViewArray>(ctx)?, ctx)?;
152        let offsets = list
153            .offsets()
154            .clone()
155            .cast(DType::Primitive(PType::U64, Nullability::NonNullable))?
156            .execute::<Buffer<u64>>(ctx)?;
157        for row_offset in &mut row_offsets {
158            *row_offset = usize::try_from(offsets[*row_offset])
159                .map_err(|_| vortex_err!("spatial: list offset exceeds usize"))?;
160        }
161        level = list.elements().clone();
162    }
163    Ok((row_offsets, level.execute::<StructArray>(ctx)?))
164}
165
166/// Decode a native geometry column to `geo_types`. A non-geometry operand is an error.
167pub(crate) fn geometries(
168    array: &ArrayRef,
169    ctx: &mut ExecutionCtx,
170) -> VortexResult<Vec<Geometry<f64>>> {
171    let Some(ext) = array.dtype().as_extension_opt() else {
172        vortex_bail!(
173            "spatial: operand is not a geometry extension type, was {}",
174            array.dtype()
175        );
176    };
177    let storage = array
178        .clone()
179        .execute::<ExtensionArray>(ctx)?
180        .storage_array()
181        .clone();
182    if ext.is::<Point>() {
183        point_geometries(&storage, ctx)
184    } else if ext.is::<LineString>() {
185        linestring_geometries(&storage, ctx)
186    } else if ext.is::<MultiPoint>() {
187        multipoint_geometries(&storage, ctx)
188    } else if ext.is::<Polygon>() {
189        polygon_geometries(&storage, ctx)
190    } else if ext.is::<MultiLineString>() {
191        multilinestring_geometries(&storage, ctx)
192    } else if ext.is::<MultiPolygon>() {
193        multipolygon_geometries(&storage, ctx)
194    } else if ext.is::<Rect>() {
195        rect_geometries(&storage, ctx)
196    } else {
197        vortex_bail!("spatial: unsupported geometry extension {}", array.dtype())
198    }
199}
200
201/// Decode a constant operand scalar to one geometry, a constant of any
202/// supported geometry type is decoded exactly like a column.
203pub(crate) fn single_geometry(
204    scalar: &Scalar,
205    ctx: &mut ExecutionCtx,
206) -> VortexResult<Geometry<f64>> {
207    let array = ConstantArray::new(scalar.clone(), 1).into_array();
208    geometries(&array, ctx)?
209        .pop()
210        .ok_or_else(|| vortex_err!("spatial: constant operand decoded to no geometry"))
211}
212
213/// Decode a WKB geometry literal (DuckDB's wire form for `GEOMETRY` constants) to its native
214/// `Point`/`Polygon`/`MultiPolygon` scalar. `None` for unsupported types. Plan-time, one value only.
215pub fn native_geometry_scalar_from_wkb(
216    bytes: &[u8],
217    session: &VortexSession,
218) -> VortexResult<Option<Scalar>> {
219    let metadata = geoarrow_metadata(&SpatialMetadata::default());
220    let binary = BinaryArray::from(vec![Some(bytes)]);
221    let wkb = GenericWkbArray::<i32>::try_from((
222        &binary as &dyn arrow_array::Array,
223        WkbType::new(Arc::clone(&metadata)),
224    ))
225    .map_err(|e| vortex_err!("failed to read WKB literal: {e}"))?;
226
227    // Cast the WKB value to `target`, import its native storage as a Vortex array.
228    let to_storage = |target: &GeoArrowType| -> VortexResult<ArrayRef> {
229        let native =
230            cast(&wkb, target).map_err(|e| vortex_err!("failed to cast WKB literal: {e}"))?;
231        session
232            .arrow()
233            .from_arrow_array(native.to_array_ref(), false)
234    };
235
236    let scalar = match Wkb::try_from_bytes(bytes)?.geometry_type() {
237        GeometryType::Point => {
238            let target = GeoArrowType::Point(
239                PointType::new(GeoArrowDimension::XY, metadata)
240                    .with_coord_type(CoordType::Separated),
241            );
242            spatial_ext_scalar(Point, to_storage(&target)?, session)?
243        }
244        GeometryType::LineString => {
245            let target = GeoArrowType::LineString(
246                LineStringType::new(GeoArrowDimension::XY, metadata)
247                    .with_coord_type(CoordType::Separated),
248            );
249            spatial_ext_scalar(LineString, to_storage(&target)?, session)?
250        }
251        GeometryType::Polygon => {
252            let target = GeoArrowType::Polygon(
253                PolygonType::new(GeoArrowDimension::XY, metadata)
254                    .with_coord_type(CoordType::Separated),
255            );
256            spatial_ext_scalar(Polygon, to_storage(&target)?, session)?
257        }
258        GeometryType::MultiPoint => {
259            let target = GeoArrowType::MultiPoint(
260                MultiPointType::new(GeoArrowDimension::XY, metadata)
261                    .with_coord_type(CoordType::Separated),
262            );
263            spatial_ext_scalar(MultiPoint, to_storage(&target)?, session)?
264        }
265        GeometryType::MultiLineString => {
266            let target = GeoArrowType::MultiLineString(
267                MultiLineStringType::new(GeoArrowDimension::XY, metadata)
268                    .with_coord_type(CoordType::Separated),
269            );
270            spatial_ext_scalar(MultiLineString, to_storage(&target)?, session)?
271        }
272        GeometryType::MultiPolygon => {
273            let target = GeoArrowType::MultiPolygon(
274                MultiPolygonType::new(GeoArrowDimension::XY, metadata)
275                    .with_coord_type(CoordType::Separated),
276            );
277            spatial_ext_scalar(MultiPolygon, to_storage(&target)?, session)?
278        }
279        _ => return Ok(None),
280    };
281    Ok(Some(scalar))
282}
283
284/// Wrap cast-from-WKB `storage`, which has XY coordinates, in its `vtable` extension type and pull
285/// out the single scalar.
286fn spatial_ext_scalar<V: ExtVTable<StoredMetadata = SpatialStoredMetadata>>(
287    vtable: V,
288    storage: ArrayRef,
289    session: &VortexSession,
290) -> VortexResult<Scalar> {
291    ExtensionArray::try_from_storage_with_vtable(vtable, SpatialStoredMetadata::default(), storage)?
292        .into_array()
293        .execute_scalar(0, &mut session.create_execution_ctx())
294}
295
296/// Coordinate reference system stored alongside a spatial storage dtype.
297#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)]
298pub struct SpatialStoredMetadata {
299    crs: Option<String>,
300}
301
302impl SpatialStoredMetadata {
303    /// Creates stored metadata with an optional coordinate reference system.
304    pub fn new(crs: Option<String>) -> Self {
305        Self { crs }
306    }
307
308    /// Returns the coordinate reference system, if present.
309    pub fn get_crs(&self) -> Option<&str> {
310        self.crs.as_deref()
311    }
312
313    /// Decodes the coordinate reference system stored in protobuf metadata.
314    pub(crate) fn deserialize(bytes: &[u8]) -> VortexResult<Self> {
315        Ok(Self::new(SpatialMetadataProto::decode(bytes)?.crs))
316    }
317}
318
319/// Coordinate reference system (CRS) and coordinate dimension for spatial extension types.
320///
321/// Native geometry types require a dimension set by [`with_dimension`](Self::with_dimension).
322/// [`WellKnownBinary`] uses metadata without a dimension, since each WKB value encodes its own.
323/// Serialized metadata contains only the CRS. Native geometry reads recover the dimension from
324/// the stored storage dtype.
325#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)]
326pub struct SpatialMetadata {
327    pub(crate) crs: Option<String>,
328    /// The coordinate dimension of a native geometry type, and `None` for [`WellKnownBinary`].
329    ///
330    /// It is not serialized, because the storage dtype holds it. A read takes it from the stored
331    /// storage dtype.
332    pub(crate) dimension: Option<Dimension>,
333}
334
335/// The serialized form of [`SpatialMetadata`].
336#[derive(Clone, PartialEq, prost::Message)]
337struct SpatialMetadataProto {
338    #[prost(optional, string, tag = "1")]
339    crs: Option<String>,
340}
341
342impl SpatialMetadata {
343    /// Creates metadata with an optional coordinate reference system (CRS) and no coordinate
344    /// dimension, as [`WellKnownBinary`] requires.
345    pub fn new(crs: Option<String>) -> Self {
346        Self {
347            crs,
348            dimension: None,
349        }
350    }
351
352    /// Returns this metadata with the coordinate dimension that a native geometry type requires.
353    pub fn with_dimension(self, dimension: Dimension) -> Self {
354        Self {
355            dimension: Some(dimension),
356            ..self
357        }
358    }
359
360    /// Returns the coordinate reference system, or `None` for unreferenced geometry.
361    pub fn get_crs(&self) -> Option<&str> {
362        self.crs.as_deref()
363    }
364
365    /// Returns the coordinate dimension for a native geometry type, or `None` for WKB.
366    pub fn dimension(&self) -> Option<Dimension> {
367        self.dimension
368    }
369
370    /// Serializes the CRS, the only part that the storage dtype does not hold.
371    pub(crate) fn serialize(&self) -> Vec<u8> {
372        SpatialMetadataProto {
373            crs: self.crs.clone(),
374        }
375        .encode_to_vec()
376    }
377
378    /// Combines stored spatial metadata with the dimension inferred from storage.
379    pub(crate) fn from_stored_metadata(
380        stored_metadata: SpatialStoredMetadata,
381        dimension: Option<Dimension>,
382    ) -> Self {
383        Self {
384            crs: stored_metadata.crs,
385            dimension,
386        }
387    }
388
389    /// Checks that the metadata of the native geometry type `id` has a coordinate dimension.
390    pub(crate) fn validate_native(&self, id: ExtId) -> VortexResult<()> {
391        vortex_ensure!(
392            self.dimension.is_some(),
393            "{id} metadata must have a coordinate dimension, got none"
394        );
395
396        Ok(())
397    }
398
399    /// Returns the coordinate dimension of a native geometry type.
400    ///
401    /// # Panics
402    ///
403    /// Panics if there is none, which [`validate_native`](Self::validate_native) rejects.
404    pub(crate) fn native_dimension(&self) -> Dimension {
405        self.dimension
406            .vortex_expect("validate_native checks that native geometry metadata has a dimension")
407    }
408}
409
410impl Display for SpatialMetadata {
411    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
412        match self.crs.as_ref() {
413            Some(crs) => write!(f, "Geometry(crs={crs})"),
414            None => write!(f, "Geometry(unreferenced)"),
415        }
416    }
417}
418
419/// The GeoArrow [`Metadata`] equivalent of `spatial_metadata`.
420pub(crate) fn geoarrow_metadata(spatial_metadata: &SpatialMetadata) -> Arc<Metadata> {
421    Arc::new(Metadata::new(
422        spatial_metadata
423            .crs
424            .as_ref()
425            .map(|crs| Crs::from_unknown_crs_type(crs.to_string()))
426            .unwrap_or_default(),
427        None,
428    ))
429}
430
431/// Serialize a native geometry array to WKB (a `WkbView` array) via geoarrow's cast.
432/// Shared by the `to_wkb` methods on the geometry extension types.
433pub(crate) fn geoarrow_to_wkb(
434    geoarrow_array: &dyn GeoArrowArray,
435    session: &ArrowSession,
436) -> VortexResult<ArrayRef> {
437    let wkb_type =
438        GeoArrowType::WkbView(WkbType::new(geoarrow_metadata(&SpatialMetadata::default())));
439    let wkb = cast(geoarrow_array, &wkb_type)
440        .map_err(|e| vortex_err!("failed to cast geometry to WKB: {e}"))?;
441    session.from_arrow_array(wkb.to_array_ref(), false)
442}
443
444/// Recover [`SpatialMetadata`] from GeoArrow metadata.
445pub(crate) fn spatial_metadata_from_arrow(metadata: &Metadata) -> SpatialMetadata {
446    let crs = metadata.crs().crs_value().map(|value| {
447        // `Crs::from_unknown_crs_type` stores the user's string verbatim as a JSON string
448        // value, so prefer the raw string when available to round-trip cleanly. For other
449        // CRS encodings (PROJJSON object, etc.), fall back to the JSON-encoded form.
450        value
451            .as_str()
452            .map(str::to_string)
453            .unwrap_or_else(|| value.to_string())
454    });
455    SpatialMetadata::new(crs)
456}
457
458#[cfg(test)]
459mod arrow_properties;
460
461#[cfg(test)]
462mod tests {
463    use std::sync::Arc;
464    use std::sync::LazyLock;
465
466    use rstest::rstest;
467    use vortex_array::VortexSessionExecute;
468    use vortex_array::dtype::DType;
469    use vortex_array::dtype::Nullability;
470    use vortex_array::dtype::PType;
471    use vortex_array::dtype::StructFields;
472    use vortex_array::dtype::extension::ExtDType;
473    use vortex_array::dtype::extension::ExtDTypePlugin;
474    use vortex_array::dtype::extension::ExtVTable;
475    use vortex_array::dtype::proto::dtype as pb;
476    use vortex_array::dtype::proto::dtype::d_type::DtypeType;
477    use vortex_error::VortexResult;
478    use vortex_error::vortex_err;
479    use vortex_session::VortexSession;
480
481    use super::LineString;
482    use super::MultiLineString;
483    use super::MultiPoint;
484    use super::MultiPolygon;
485    use super::Point;
486    use super::Polygon;
487    use super::Rect;
488    use super::WellKnownBinary;
489    use crate::extension::SpatialMetadata;
490    use crate::extension::coordinate::Dimension;
491    use crate::extension::coordinate::coordinate_storage_dtype;
492    use crate::test_harness::spatial_session;
493
494    static SESSION: LazyLock<VortexSession> = LazyLock::new(VortexSession::empty);
495
496    /// The metadata of an unreferenced geometry with XY coordinates.
497    fn xy_metadata() -> SpatialMetadata {
498        SpatialMetadata::default().with_dimension(Dimension::Xy)
499    }
500
501    /// Test shim: decode with an explicitly constructed session.
502    fn native_geometry_scalar_from_wkb(
503        bytes: &[u8],
504    ) -> VortexResult<Option<vortex_array::scalar::Scalar>> {
505        super::native_geometry_scalar_from_wkb(bytes, &VortexSession::empty())
506    }
507
508    #[test]
509    fn test_metadata() -> VortexResult<()> {
510        let meta = SpatialMetadata::new(Some("EPSG:4326".to_string()));
511        assert_eq!(meta.to_string(), "Geometry(crs=EPSG:4326)");
512
513        // Files store the protobuf encoding of the CRS as field 1, so these bytes must not change:
514        // the key `0x0a`, the length 9, and the CRS.
515        let bytes = meta.serialize();
516        assert_eq!(bytes, b"\x0a\x09EPSG:4326");
517
518        let decoded = SpatialMetadata::from_stored_metadata(
519            super::SpatialStoredMetadata::deserialize(&bytes)?,
520            None,
521        );
522        assert_eq!(decoded, meta);
523        assert_eq!(decoded.dimension(), None);
524        assert_eq!(
525            meta.with_dimension(Dimension::Xy).dimension(),
526            Some(Dimension::Xy)
527        );
528
529        Ok(())
530    }
531
532    /// [`ExtDType::try_with_vtable`] validates the metadata before it asks for the storage
533    /// declaration, so a native geometry type without a coordinate dimension returns an error
534    /// instead of a panic. WKB metadata with a coordinate dimension is also invalid.
535    #[rstest]
536    #[case::point(
537        Point,
538        SpatialMetadata::default(),
539        "vortex.st.point metadata must have a coordinate dimension, got none"
540    )]
541    #[case::linestring(
542        LineString,
543        SpatialMetadata::default(),
544        "vortex.st.linestring metadata must have a coordinate dimension, got none"
545    )]
546    #[case::polygon(
547        Polygon,
548        SpatialMetadata::default(),
549        "vortex.st.polygon metadata must have a coordinate dimension, got none"
550    )]
551    #[case::multipoint(
552        MultiPoint,
553        SpatialMetadata::default(),
554        "vortex.st.multipoint metadata must have a coordinate dimension, got none"
555    )]
556    #[case::multilinestring(
557        MultiLineString,
558        SpatialMetadata::default(),
559        "vortex.st.multilinestring metadata must have a coordinate dimension, got none"
560    )]
561    #[case::multipolygon(
562        MultiPolygon,
563        SpatialMetadata::default(),
564        "vortex.st.multipolygon metadata must have a coordinate dimension, got none"
565    )]
566    #[case::rect(
567        Rect,
568        SpatialMetadata::default(),
569        "vortex.st.box metadata must have a coordinate dimension, got none"
570    )]
571    #[case::wkb(
572        WellKnownBinary,
573        xy_metadata(),
574        "vortex.st.wkb metadata must not have a coordinate dimension, got Xy"
575    )]
576    fn invalid_dimension_returns_error(
577        #[case] vtable: impl ExtVTable<Metadata = SpatialMetadata>,
578        #[case] metadata: SpatialMetadata,
579        #[case] expected: &str,
580    ) {
581        let result = ExtDType::try_with_vtable(vtable, metadata, Nullability::NonNullable);
582        assert!(result.is_err_and(|error| error.to_string().contains(expected)));
583    }
584
585    /// A little-endian WKB `POINT` literal decodes to the native `Point` extension scalar.
586    #[test]
587    fn decodes_wkb_point_to_native() -> VortexResult<()> {
588        let mut wkb = vec![1u8]; // little-endian byte order
589        wkb.extend_from_slice(&1u32.to_le_bytes()); // geometry type: point
590        wkb.extend_from_slice(&1.0f64.to_le_bytes()); // x
591        wkb.extend_from_slice(&2.0f64.to_le_bytes()); // y
592
593        let scalar = native_geometry_scalar_from_wkb(&wkb)?.expect("a point scalar");
594        let DType::Extension(ext) = scalar.dtype() else {
595            panic!("expected an extension dtype, got {}", scalar.dtype());
596        };
597        assert!(ext.is::<Point>());
598        assert_eq!(ext.metadata::<Point>(), &xy_metadata());
599        let mut ctx = SESSION.create_execution_ctx();
600        let expected =
601            crate::test_harness::point_column(vec![1.0], vec![2.0])?.execute_scalar(0, &mut ctx)?;
602        let actual_storage = scalar.as_extension().to_storage_scalar();
603        let expected_storage = expected.as_extension().to_storage_scalar();
604        assert_eq!(actual_storage.dtype(), expected_storage.dtype());
605        assert_eq!(actual_storage, expected_storage);
606        Ok(())
607    }
608
609    /// A little-endian WKB `POLYGON` literal decodes to the native `Polygon` extension scalar.
610    #[test]
611    fn decodes_wkb_polygon_to_native() -> VortexResult<()> {
612        let ring = [(0.0, 0.0), (1.0, 0.0), (0.0, 1.0), (0.0, 0.0)];
613        let mut wkb = vec![1u8]; // little-endian byte order
614        wkb.extend_from_slice(&3u32.to_le_bytes()); // geometry type: polygon
615        wkb.extend_from_slice(&1u32.to_le_bytes()); // one ring
616        let ring_len = u32::try_from(ring.len()).map_err(|e| vortex_err!("{e}"))?;
617        wkb.extend_from_slice(&ring_len.to_le_bytes());
618        for (x, y) in ring {
619            wkb.extend_from_slice(&f64::to_le_bytes(x));
620            wkb.extend_from_slice(&f64::to_le_bytes(y));
621        }
622
623        let scalar = native_geometry_scalar_from_wkb(&wkb)?.expect("a polygon scalar");
624        let DType::Extension(ext) = scalar.dtype() else {
625            panic!("expected an extension dtype, got {}", scalar.dtype());
626        };
627        assert!(ext.is::<Polygon>());
628        assert_eq!(ext.metadata::<Polygon>(), &xy_metadata());
629        let mut ctx = SESSION.create_execution_ctx();
630        let expected = crate::test_harness::polygon_column(vec![vec![vec![
631            (0.0, 0.0),
632            (1.0, 0.0),
633            (0.0, 1.0),
634            (0.0, 0.0),
635        ]]])?
636        .execute_scalar(0, &mut ctx)?;
637        let actual_storage = scalar.as_extension().to_storage_scalar();
638        let expected_storage = expected.as_extension().to_storage_scalar();
639        assert_eq!(actual_storage.dtype(), expected_storage.dtype());
640        assert_eq!(actual_storage, expected_storage);
641        Ok(())
642    }
643
644    /// A little-endian WKB `LINESTRING` literal decodes to the native `LineString` extension scalar.
645    #[test]
646    fn decodes_wkb_linestring_to_native() -> VortexResult<()> {
647        let points = [(0.0, 0.0), (1.0, 1.0)];
648        let mut wkb = vec![1u8]; // little-endian byte order
649        wkb.extend_from_slice(&2u32.to_le_bytes()); // geometry type: linestring
650        let len = u32::try_from(points.len()).map_err(|e| vortex_err!("{e}"))?;
651        wkb.extend_from_slice(&len.to_le_bytes());
652        for (x, y) in points {
653            wkb.extend_from_slice(&f64::to_le_bytes(x));
654            wkb.extend_from_slice(&f64::to_le_bytes(y));
655        }
656
657        let scalar = native_geometry_scalar_from_wkb(&wkb)?.expect("a linestring scalar");
658        let DType::Extension(ext) = scalar.dtype() else {
659            panic!("expected an extension dtype, got {}", scalar.dtype());
660        };
661        assert!(ext.is::<LineString>());
662        assert_eq!(ext.metadata::<LineString>(), &xy_metadata());
663        let mut ctx = SESSION.create_execution_ctx();
664        let expected = crate::test_harness::linestring_column(vec![vec![(0.0, 0.0), (1.0, 1.0)]])?
665            .execute_scalar(0, &mut ctx)?;
666        let actual_storage = scalar.as_extension().to_storage_scalar();
667        let expected_storage = expected.as_extension().to_storage_scalar();
668        assert_eq!(actual_storage.dtype(), expected_storage.dtype());
669        assert_eq!(actual_storage, expected_storage);
670        Ok(())
671    }
672
673    /// A little-endian WKB `MULTIPOINT` literal decodes to the native `MultiPoint` extension scalar.
674    #[test]
675    fn decodes_wkb_multipoint_to_native() -> VortexResult<()> {
676        let points = [(0.0, 0.0), (1.0, 1.0)];
677        let mut wkb = vec![1u8]; // little-endian byte order
678        wkb.extend_from_slice(&4u32.to_le_bytes()); // geometry type: multipoint
679        let len = u32::try_from(points.len()).map_err(|e| vortex_err!("{e}"))?;
680        wkb.extend_from_slice(&len.to_le_bytes());
681        for (x, y) in points {
682            // each member is a full WKB point
683            wkb.push(1u8);
684            wkb.extend_from_slice(&1u32.to_le_bytes());
685            wkb.extend_from_slice(&f64::to_le_bytes(x));
686            wkb.extend_from_slice(&f64::to_le_bytes(y));
687        }
688
689        let scalar = native_geometry_scalar_from_wkb(&wkb)?.expect("a multipoint scalar");
690        let DType::Extension(ext) = scalar.dtype() else {
691            panic!("expected an extension dtype, got {}", scalar.dtype());
692        };
693        assert!(ext.is::<MultiPoint>());
694        assert_eq!(ext.metadata::<MultiPoint>(), &xy_metadata());
695        let mut ctx = SESSION.create_execution_ctx();
696        let expected = crate::test_harness::multipoint_column(vec![vec![(0.0, 0.0), (1.0, 1.0)]])?
697            .execute_scalar(0, &mut ctx)?;
698        let actual_storage = scalar.as_extension().to_storage_scalar();
699        let expected_storage = expected.as_extension().to_storage_scalar();
700        assert_eq!(actual_storage.dtype(), expected_storage.dtype());
701        assert_eq!(actual_storage, expected_storage);
702        Ok(())
703    }
704
705    /// A little-endian WKB `MULTILINESTRING` literal decodes to the native `MultiLineString` scalar.
706    #[test]
707    fn decodes_wkb_multilinestring_to_native() -> VortexResult<()> {
708        let lines = [[(0.0, 0.0), (1.0, 1.0)], [(2.0, 2.0), (3.0, 3.0)]];
709        let mut wkb = vec![1u8]; // little-endian byte order
710        wkb.extend_from_slice(&5u32.to_le_bytes()); // geometry type: multilinestring
711        let num_lines = u32::try_from(lines.len()).map_err(|e| vortex_err!("{e}"))?;
712        wkb.extend_from_slice(&num_lines.to_le_bytes());
713        for line in lines {
714            // each member is a full WKB linestring
715            wkb.push(1u8);
716            wkb.extend_from_slice(&2u32.to_le_bytes());
717            let len = u32::try_from(line.len()).map_err(|e| vortex_err!("{e}"))?;
718            wkb.extend_from_slice(&len.to_le_bytes());
719            for (x, y) in line {
720                wkb.extend_from_slice(&f64::to_le_bytes(x));
721                wkb.extend_from_slice(&f64::to_le_bytes(y));
722            }
723        }
724
725        let scalar = native_geometry_scalar_from_wkb(&wkb)?.expect("a multilinestring scalar");
726        let DType::Extension(ext) = scalar.dtype() else {
727            panic!("expected an extension dtype, got {}", scalar.dtype());
728        };
729        assert!(ext.is::<MultiLineString>());
730        assert_eq!(ext.metadata::<MultiLineString>(), &xy_metadata());
731        let mut ctx = SESSION.create_execution_ctx();
732        let expected = crate::test_harness::multilinestring_column(vec![vec![
733            vec![(0.0, 0.0), (1.0, 1.0)],
734            vec![(2.0, 2.0), (3.0, 3.0)],
735        ]])?
736        .execute_scalar(0, &mut ctx)?;
737        let actual_storage = scalar.as_extension().to_storage_scalar();
738        let expected_storage = expected.as_extension().to_storage_scalar();
739        assert_eq!(actual_storage.dtype(), expected_storage.dtype());
740        assert_eq!(actual_storage, expected_storage);
741        Ok(())
742    }
743
744    /// A non-nullable `List` of `element`.
745    fn list(element: DType) -> DType {
746        DType::List(Arc::new(element), Nullability::NonNullable)
747    }
748
749    /// The non-nullable 2D coordinate `Struct`.
750    fn xy() -> DType {
751        coordinate_storage_dtype(Dimension::Xy, Nullability::NonNullable)
752    }
753
754    /// The list-based geometry types fail to read storage with a nullable inner `List` or
755    /// coordinate `Struct`, and the error reports the rejected storage.
756    #[rstest]
757    #[case::linestring_coordinates(     LineString,      list(xy().as_nullable()))]
758    #[case::multipoint_coordinates(     MultiPoint,      list(xy().as_nullable()))]
759    #[case::polygon_rings(              Polygon,         list(list(xy()).as_nullable()))]
760    #[case::polygon_coordinates(        Polygon,         list(list(xy().as_nullable())))]
761    #[case::multilinestring_lines(      MultiLineString, list(list(xy()).as_nullable()))]
762    #[case::multilinestring_coordinates(MultiLineString, list(list(xy().as_nullable())))]
763    #[case::multipolygon_polygons(      MultiPolygon,    list(list(list(xy())).as_nullable()))]
764    #[case::multipolygon_rings(         MultiPolygon,    list(list(list(xy()).as_nullable())))]
765    #[case::multipolygon_coordinates(   MultiPolygon,    list(list(list(xy().as_nullable()))))]
766    fn nullable_nested_level_is_rejected(
767        #[case] vtable: impl ExtVTable<Metadata = SpatialMetadata>,
768        #[case] storage: DType,
769    ) {
770        let result = vtable.deserialize(&[], storage.clone());
771        assert!(result.is_err_and(|error| error.to_string().contains(&format!(", got {storage}"))));
772    }
773
774    /// Malformed coordinate fields still reveal the dimension. The read error must show the
775    /// complete stored storage dtype and the declaration, including any enclosing lists.
776    #[rstest]
777    #[case::point(Point, 0)]
778    #[case::linestring(LineString, 1)]
779    #[case::multipoint(MultiPoint, 1)]
780    #[case::polygon(Polygon, 2)]
781    #[case::multilinestring(MultiLineString, 2)]
782    #[case::multipolygon(MultiPolygon, 3)]
783    #[case::rect(Rect, 0)]
784    fn read_reports_both_storage_dtypes(
785        #[case] vtable: impl ExtVTable<Metadata = SpatialMetadata>,
786        #[case] depth: usize,
787        #[values(
788            DType::Primitive(PType::F64, Nullability::Nullable),
789            DType::Primitive(PType::F32, Nullability::NonNullable)
790        )]
791        field_dtype: DType,
792    ) -> VortexResult<()> {
793        let mut expected = if vtable.id() == ExtVTable::id(&Rect) {
794            super::box_storage_dtype(Dimension::Xy, Nullability::NonNullable)
795        } else {
796            xy()
797        };
798        let DType::Struct(fields, nullability) = &expected else {
799            unreachable!("coordinate and box storage are structs");
800        };
801        let mut field_dtypes = fields.fields().collect::<Vec<_>>();
802        field_dtypes[0] = field_dtype;
803        let mut stored = DType::Struct(
804            StructFields::new(fields.names().clone(), field_dtypes),
805            *nullability,
806        );
807        for _ in 0..depth {
808            expected = list(expected);
809            stored = list(stored);
810        }
811
812        let message = format!("{} storage must be {expected}, got {stored}", vtable.id());
813        let error = vtable
814            .deserialize(&[], stored)
815            .expect_err("the coordinate field is invalid");
816        assert!(error.to_string().contains(&message), "{error}");
817
818        Ok(())
819    }
820
821    /// A serialized `vortex.st.linestring` dtype with a nullable coordinate `Struct` fails to read,
822    /// with an error that names the expected storage. No constructor builds that storage, so the
823    /// test builds the serialized extension dtype by hand.
824    #[test]
825    fn nullable_nested_level_fails_to_read() -> VortexResult<()> {
826        let serialized = pb::DType {
827            dtype_type: Some(DtypeType::Extension(Box::new(pb::Extension {
828                id: "vortex.st.linestring".to_string(),
829                storage_dtype: Some(Box::new(pb::DType::try_from(&list(xy().as_nullable()))?)),
830                metadata: None,
831            }))),
832        };
833
834        let result = DType::from_proto(&serialized, &spatial_session());
835        assert!(result.is_err_and(|error| error.to_string().contains(
836            "linestring storage must be list({x=f64, y=f64}), got list({x=f64, y=f64}?)"
837        )));
838        Ok(())
839    }
840}