Skip to main content

vortex_spatial/extension/
multilinestring.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4//! The [`MultiLineString`] extension type (`vortex.st.multilinestring`), stored as
5//! `List<List<Struct<x, y[, z][, m]>>>` (line strings → coordinates) and tagged with
6//! [`SpatialMetadata`]. The storage layout matches [`Polygon`](super::Polygon); the two are
7//! distinguished by their GeoArrow extension name, not their shape.
8
9use std::sync::Arc;
10
11use arrow_array::ArrayRef as ArrowArrayRef;
12use arrow_schema::DataType;
13use arrow_schema::Field;
14use arrow_schema::extension::ExtensionType;
15use geo_traits::to_geo::ToGeoGeometry;
16use geo_types::Geometry;
17use geoarrow::array::GeoArrowArrayAccessor;
18use geoarrow::array::IntoArrow;
19use geoarrow::array::MultiLineStringArray;
20use geoarrow::datatypes::CoordType;
21use geoarrow::datatypes::MultiLineStringType;
22use prost::Message;
23use vortex_array::ArrayRef;
24use vortex_array::ExecutionCtx;
25use vortex_array::IntoArray;
26use vortex_array::arrays::ExtensionArray;
27use vortex_array::arrays::extension::ExtensionArrayExt;
28use vortex_array::dtype::DType;
29use vortex_array::dtype::Nullability;
30use vortex_array::dtype::extension::ExtDType;
31use vortex_array::dtype::extension::ExtId;
32use vortex_array::dtype::extension::ExtVTable;
33use vortex_array::scalar::ScalarValue;
34use vortex_arrow::ArrowExport;
35use vortex_arrow::ArrowExportOptions;
36use vortex_arrow::ArrowExportVTable;
37use vortex_arrow::ArrowImport;
38use vortex_arrow::ArrowImportVTable;
39use vortex_arrow::ArrowSession;
40use vortex_arrow::ArrowSessionExt;
41use vortex_error::VortexError;
42use vortex_error::VortexResult;
43use vortex_error::vortex_bail;
44use vortex_error::vortex_ensure;
45use vortex_error::vortex_ensure_eq;
46use vortex_error::vortex_err;
47use vortex_session::registry::CachedId;
48use vortex_session::registry::Id;
49
50use super::SpatialMetadata;
51use super::coordinate::Dimension;
52use super::coordinate::coordinate_dimension;
53use super::coordinate::coordinate_storage_dtype;
54use super::geoarrow_metadata;
55use super::geoarrow_to_wkb;
56use super::spatial_metadata_from_arrow;
57
58/// A multilinestring: `geoarrow.multilinestring`, stored as `List<List<Struct<x, y[, z][, m]>>>`
59/// (line strings of vertices).
60#[derive(Debug, Clone, Default, PartialEq, Eq, Hash)]
61pub struct MultiLineString;
62
63impl ExtVTable for MultiLineString {
64    type Metadata = SpatialMetadata;
65    // No cheap owned value like Point's `Coordinate`; expose the raw storage scalar.
66    type NativeValue<'a> = &'a ScalarValue;
67
68    fn id(&self) -> ExtId {
69        static ID: CachedId = CachedId::new("vortex.st.multilinestring");
70        *ID
71    }
72
73    fn serialize_metadata(&self, metadata: &Self::Metadata) -> VortexResult<Vec<u8>> {
74        Ok(metadata.encode_to_vec())
75    }
76
77    fn deserialize_metadata(&self, metadata: &[u8]) -> VortexResult<Self::Metadata> {
78        Ok(SpatialMetadata::decode(metadata)?)
79    }
80
81    fn validate_dtype(ext_dtype: &ExtDType<Self>) -> VortexResult<()> {
82        multilinestring_dimension(ext_dtype.storage_dtype()).map(|_| ())
83    }
84
85    fn unpack_native<'a>(
86        _ext_dtype: &'a ExtDType<Self>,
87        storage_value: &'a ScalarValue,
88    ) -> VortexResult<&'a ScalarValue> {
89        Ok(storage_value)
90    }
91}
92
93/// Canonical multilinestring storage: an outer list of line strings, each a list of the coordinate
94/// `Struct`.
95pub(crate) fn multilinestring_storage_dtype(dim: Dimension, nullability: Nullability) -> DType {
96    let coords = coordinate_storage_dtype(dim, Nullability::NonNullable);
97    let line = DType::List(Arc::new(coords), Nullability::NonNullable);
98    DType::List(Arc::new(line), nullability)
99}
100
101/// Validate that `dtype` equals [`multilinestring_storage_dtype`] for its [`Dimension`] and
102/// top-level nullability, and return that dimension. As in GeoArrow, only the outer `List` can be
103/// nullable.
104pub(crate) fn multilinestring_dimension(dtype: &DType) -> VortexResult<Dimension> {
105    let DType::List(line, _) = dtype else {
106        vortex_bail!("multilinestring storage must be a List of line strings, was {dtype}");
107    };
108    let DType::List(coords, _) = line.as_ref() else {
109        vortex_bail!("multilinestring line storage must be a List of coordinates, was {line}");
110    };
111    let dimension = coordinate_dimension(coords)?;
112
113    vortex_ensure_eq!(
114        *dtype,
115        multilinestring_storage_dtype(dimension, dtype.nullability()),
116        "multilinestring storage can be nullable only at its outer List"
117    );
118
119    Ok(dimension)
120}
121
122static ARROW_MULTILINESTRING: CachedId = CachedId::new(MultiLineStringType::NAME);
123
124/// The `geoarrow.multilinestring` type for `dimension`, with separated (struct) coordinates.
125fn multilinestring_type(
126    spatial_metadata: &SpatialMetadata,
127    dimension: Dimension,
128) -> MultiLineStringType {
129    MultiLineStringType::new(dimension.into(), geoarrow_metadata(spatial_metadata))
130}
131
132/// Decode storage to `geo_types` for the spatial scalar functions (CRS is irrelevant to planar ops).
133pub(crate) fn multilinestring_geometries(
134    storage: &ArrayRef,
135    ctx: &mut ExecutionCtx,
136) -> VortexResult<Vec<Geometry<f64>>> {
137    multilinestring_array(storage, ctx)?
138        .iter()
139        .map(|geometry| -> VortexResult<Geometry<f64>> {
140            Ok(geometry
141                .ok_or_else(|| vortex_err!("spatial: null geometry is not supported"))?
142                .map_err(|e| vortex_err!("spatial: geometry access failed: {e}"))?
143                .to_geometry())
144        })
145        .collect()
146}
147
148/// Build a geoarrow `MultiLineStringArray` from the `MultiLineString` storage.
149fn multilinestring_array(
150    storage: &ArrayRef,
151    ctx: &mut ExecutionCtx,
152) -> VortexResult<MultiLineStringArray> {
153    let multilinestring_type = multilinestring_type(
154        &SpatialMetadata::default(),
155        multilinestring_dimension(storage.dtype())?,
156    );
157    let session = ctx.session().clone();
158    let arrow = session.arrow().execute_arrow(storage.clone(), None, ctx)?;
159    MultiLineStringArray::try_from((arrow.as_ref(), multilinestring_type))
160        .map_err(|e| vortex_err!("failed to construct MultiLineStringArray: {e}"))
161}
162
163/// A validated `MultiLineString` array (`try_from` checks the extension type).
164pub struct MultiLineStringData(ExtensionArray);
165
166impl TryFrom<ExtensionArray> for MultiLineStringData {
167    type Error = VortexError;
168
169    fn try_from(ext: ExtensionArray) -> Result<Self, Self::Error> {
170        vortex_ensure!(
171            ext.ext_dtype().is::<MultiLineString>(),
172            "expected a MultiLineString extension array"
173        );
174        Ok(MultiLineStringData(ext))
175    }
176}
177
178impl MultiLineStringData {
179    /// Serialize multilinestrings to WKB (a view array) — the form DuckDB `GEOMETRY` takes.
180    pub fn to_wkb(&self, ctx: &mut ExecutionCtx) -> VortexResult<ArrayRef> {
181        geoarrow_to_wkb(
182            &multilinestring_array(self.0.storage_array(), ctx)?,
183            &ctx.session().arrow(),
184        )
185    }
186}
187
188impl ArrowExportVTable for MultiLineString {
189    fn arrow_ext_id(&self) -> Id {
190        *ARROW_MULTILINESTRING
191    }
192
193    fn vortex_id(&self) -> Id {
194        self.id()
195    }
196
197    fn to_arrow_field(
198        &self,
199        name: &str,
200        dtype: &DType,
201        session: &ArrowSession,
202    ) -> VortexResult<Option<Field>> {
203        let ext_type = dtype.as_extension();
204        let spatial_metadata = ext_type.metadata::<MultiLineString>();
205        let dimension = multilinestring_dimension(ext_type.storage_dtype())?;
206
207        let mut field = session.to_arrow_field(name, ext_type.storage_dtype())?;
208        field.try_with_extension_type(multilinestring_type(spatial_metadata, dimension))?;
209
210        Ok(Some(field))
211    }
212
213    fn execute_arrow(
214        &self,
215        array: ArrayRef,
216        target: &Field,
217        options: &ArrowExportOptions,
218        ctx: &mut ExecutionCtx,
219    ) -> VortexResult<ArrowExport> {
220        let is_multilinestring = array
221            .dtype()
222            .as_extension_opt()
223            .map(|ext| ext.is::<MultiLineString>())
224            .unwrap_or(false);
225        if !is_multilinestring {
226            return Ok(ArrowExport::Unsupported(array));
227        }
228
229        let Ok(multilinestring_meta) = target.try_extension_type::<MultiLineStringType>() else {
230            return Ok(ArrowExport::Unsupported(array));
231        };
232        if multilinestring_meta.coord_type() != CoordType::Separated {
233            return Ok(ArrowExport::Unsupported(array));
234        }
235
236        let executed = array.execute::<ExtensionArray>(ctx)?;
237        let storage = executed.storage_array().clone();
238
239        let storage_field = Field::new(
240            String::new(),
241            target.data_type().clone(),
242            target.is_nullable(),
243        );
244        let session = ctx.session().clone();
245        let arrow_storage =
246            session
247                .arrow()
248                .exporter(options)
249                .execute_arrow(storage, Some(&storage_field), ctx)?;
250
251        let multilinestrings =
252            MultiLineStringArray::try_from((arrow_storage.as_ref(), multilinestring_meta))
253                .map_err(|e| vortex_err!("failed to construct MultiLineStringArray: {e}"))?;
254
255        Ok(ArrowExport::Exported(Arc::new(
256            multilinestrings.into_arrow(),
257        )))
258    }
259}
260
261impl ArrowImportVTable for MultiLineString {
262    fn arrow_ext_id(&self) -> Id {
263        *ARROW_MULTILINESTRING
264    }
265
266    /// Import a `geoarrow.multilinestring` field (matched by GeoArrow name). Accepts the full
267    /// `MultiLineStringType`, or a metadata-less literal (name only), inferring the dimension.
268    fn from_arrow_field(
269        &self,
270        field: &Field,
271        session: &ArrowSession,
272    ) -> VortexResult<Option<DType>> {
273        let (dimension, metadata) =
274            if let Ok(multilinestring_meta) = field.try_extension_type::<MultiLineStringType>() {
275                vortex_ensure!(
276                    multilinestring_meta.coord_type() == CoordType::Separated,
277                    "geoarrow.multilinestring with interleaved coordinates is not supported; \
278             re-encode with separated (struct) coordinates"
279                );
280                (
281                    multilinestring_meta.dimension().into(),
282                    spatial_metadata_from_arrow(multilinestring_meta.metadata()),
283                )
284            } else {
285                // Literal: peel the two `List` layers to the coordinate struct and read its dimension
286                // from the field names (the canonical check rejects nullable coordinates).
287                if field.extension_type_name() != Some(MultiLineStringType::NAME) {
288                    return Ok(None);
289                }
290                let Ok(DType::List(line, _)) =
291                    session.from_arrow_datatype(field.data_type(), field.is_nullable().into())
292                else {
293                    return Ok(None);
294                };
295                let DType::List(coords, _) = line.as_ref() else {
296                    return Ok(None);
297                };
298                let DType::Struct(fields, _) = coords.as_ref() else {
299                    return Ok(None);
300                };
301                let Ok(dimension) = Dimension::from_field_names(fields.names()) else {
302                    return Ok(None);
303                };
304                (dimension, SpatialMetadata::default())
305            };
306
307        let storage_dtype = multilinestring_storage_dtype(dimension, field.is_nullable().into());
308        Ok(Some(DType::Extension(
309            ExtDType::try_with_vtable(MultiLineString, metadata, storage_dtype)?.erased(),
310        )))
311    }
312
313    fn from_arrow_array(
314        &self,
315        array: ArrowArrayRef,
316        field: &Field,
317        dtype: &DType,
318        session: &ArrowSession,
319    ) -> VortexResult<ArrowImport> {
320        let Some(ext_dtype) = dtype.as_extension_opt() else {
321            return Ok(ArrowImport::Unsupported(array));
322        };
323        if !ext_dtype.is::<MultiLineString>()
324            || field.try_extension_type::<MultiLineStringType>().is_err()
325            || !matches!(array.data_type(), DataType::List(_))
326        {
327            return Ok(ArrowImport::Unsupported(array));
328        }
329
330        let storage = session.from_arrow_array(array, field.is_nullable())?;
331        Ok(ArrowImport::Imported(
332            ExtensionArray::try_new(ext_dtype.clone(), storage)?.into_array(),
333        ))
334    }
335}
336
337#[cfg(test)]
338mod tests {
339    use std::sync::Arc;
340
341    use rstest::rstest;
342    use vortex_array::dtype::DType;
343    use vortex_array::dtype::Nullability;
344    use vortex_array::dtype::PType;
345    use vortex_array::dtype::extension::ExtDType;
346    use vortex_error::VortexResult;
347
348    use super::MultiLineString;
349    use super::multilinestring_storage_dtype;
350    use crate::extension::SpatialMetadata;
351    use crate::extension::coordinate::Dimension;
352    use crate::extension::coordinate::coordinate_storage_dtype;
353
354    fn spatial_meta() -> SpatialMetadata {
355        SpatialMetadata {
356            crs: Some("EPSG:4326".to_string()),
357        }
358    }
359
360    /// `MultiLineString` accepts the canonical `List<List<coordinate-struct>>` storage of every
361    /// dimension.
362    #[rstest]
363    #[case::xy(Dimension::Xy)]
364    #[case::xyz(Dimension::Xyz)]
365    #[case::xym(Dimension::Xym)]
366    #[case::xyzm(Dimension::Xyzm)]
367    fn multilinestring_validates_every_dimension(#[case] dim: Dimension) -> VortexResult<()> {
368        let storage = multilinestring_storage_dtype(dim, Nullability::NonNullable);
369        ExtDType::<MultiLineString>::try_new(spatial_meta(), storage)?;
370        Ok(())
371    }
372
373    /// Non-multilinestring storage is rejected: a bare coordinate struct (point) fails.
374    #[test]
375    fn multilinestring_rejects_invalid_storage() -> VortexResult<()> {
376        let primitive = DType::Primitive(PType::F64, Nullability::NonNullable);
377        assert!(ExtDType::<MultiLineString>::try_new(spatial_meta(), primitive).is_err());
378
379        // A bare list of coordinates is a single line string, not a multilinestring.
380        let coords = coordinate_storage_dtype(Dimension::Xy, Nullability::NonNullable);
381        let line = DType::List(Arc::new(coords), Nullability::NonNullable);
382        assert!(ExtDType::<MultiLineString>::try_new(spatial_meta(), line).is_err());
383        Ok(())
384    }
385}