Skip to main content

vortex_spatial/extension/
wkb.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4//! Well-known binary geometry (`vortex.st.wkb`).
5//!
6//! [`WellKnownBinary`] stores WKB bytes in binary storage. [`SpatialMetadata`] carries an optional
7//! coordinate reference system, while each WKB value encodes its geometry type and dimension.
8
9use std::fmt::Display;
10use std::ops::Deref;
11use std::sync::Arc;
12
13use arrow_array::ArrayRef as ArrowArrayRef;
14use arrow_schema::DataType;
15use arrow_schema::Field;
16use arrow_schema::extension::ExtensionType;
17use geoarrow::array::GenericWkbArray;
18use geoarrow::array::IntoArrow;
19use geoarrow::array::WkbViewArray;
20use geoarrow::datatypes::WkbType;
21use vortex_array::ArrayRef;
22use vortex_array::ExecutionCtx;
23use vortex_array::arrays::ExtensionArray;
24use vortex_array::arrays::extension::ExtensionArrayExt;
25use vortex_array::dtype::DType;
26use vortex_array::dtype::Nullability;
27use vortex_array::dtype::extension::ExtDType;
28use vortex_array::dtype::extension::ExtId;
29use vortex_array::dtype::extension::ExtVTable;
30use vortex_array::scalar::ScalarValue;
31use vortex_arrow::ArrowExport;
32use vortex_arrow::ArrowExportOptions;
33use vortex_arrow::ArrowExtVTable;
34use vortex_arrow::ArrowImport;
35use vortex_arrow::ArrowMetadataPolicy;
36use vortex_arrow::ArrowSession;
37use vortex_arrow::ExecuteArrowExt;
38use vortex_error::VortexError;
39use vortex_error::VortexResult;
40use vortex_error::vortex_bail;
41use vortex_error::vortex_ensure;
42use vortex_error::vortex_err;
43use vortex_session::registry::CachedId;
44use vortex_session::registry::Id;
45use wkb::reader::GeometryType;
46
47use crate::extension::SpatialMetadata;
48use crate::extension::geoarrow_metadata;
49use crate::extension::spatial_metadata_from_arrow;
50
51/// A typed handle to an [`ExtensionArray`] that contains WKB-encoded data.
52///
53/// You can construct this safely using `WellKnownBinaryData::try_from(ExtensionArray)`.
54#[derive(Debug, Clone)]
55pub struct WellKnownBinaryData {
56    ext: ExtensionArray,
57}
58
59impl WellKnownBinaryData {
60    /// A reference to the array that holds the Well-Known Binary scalar values.
61    pub fn wkb_values(&self) -> &ArrayRef {
62        self.ext.storage_array()
63    }
64
65    /// A reference to the [spatial metadata][SpatialMetadata].
66    pub fn spatial_metadata(&self) -> &SpatialMetadata {
67        self.ext
68            .dtype()
69            .as_extension()
70            .metadata::<WellKnownBinary>()
71    }
72}
73
74impl TryFrom<ExtensionArray> for WellKnownBinaryData {
75    type Error = VortexError;
76
77    fn try_from(ext: ExtensionArray) -> Result<Self, Self::Error> {
78        vortex_ensure!(
79            ext.ext_dtype().is::<WellKnownBinary>(),
80            "array extension dtype {} is not a WKB",
81            ext.ext_dtype()
82        );
83
84        Ok(Self { ext })
85    }
86}
87
88/// An [extension type][ExtVTable] for OGC Well-known Binary (WKB) data format.
89///
90/// This is one of the most common formats for sharing of geometry data between analytic systems,
91/// used by DuckDB, PostGIS and GeoParquet.
92#[derive(Debug, Clone, Default, PartialEq, Eq, Hash)]
93pub struct WellKnownBinary;
94
95/// A reference to a value of well-known binary encoded geometry data.
96///
97/// Interpreting this value is dependent on the [spatial metadata][SpatialMetadata] in the extension
98/// schema for the array where this scalar is taken from.
99pub struct Wkb<'a>(wkb::reader::Wkb<'a>);
100
101impl<'a> Wkb<'a> {
102    /// Attempt to decode a well-known binary value from a byte slice.
103    ///
104    /// This will not cause any data allocations or copies, but it will perform a one-pass
105    /// validation on the structure of the WKB.
106    pub fn try_from_bytes(bytes: &'a [u8]) -> VortexResult<Self> {
107        wkb::reader::Wkb::try_new(bytes)
108            .map_err(|e| vortex_err!("failed parsing WKB: {e}"))
109            .map(Wkb)
110    }
111}
112
113impl<'a> Display for Wkb<'a> {
114    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
115        let geometry_kind = match self.0.geometry_type() {
116            GeometryType::Point => "point",
117            GeometryType::LineString => "linestring",
118            GeometryType::Polygon => "polygon",
119            GeometryType::MultiPoint => "multipoint",
120            GeometryType::MultiLineString => "multilinestring",
121            GeometryType::MultiPolygon => "multipolygon",
122            GeometryType::GeometryCollection => "geometrycollection",
123            _ => "unknown",
124        };
125        // TODO(aduffy): make this more useful
126        write!(f, "WKB({geometry_kind})")
127    }
128}
129
130impl<'a> Deref for Wkb<'a> {
131    type Target = wkb::reader::Wkb<'a>;
132
133    fn deref(&self) -> &wkb::reader::Wkb<'a> {
134        &self.0
135    }
136}
137
138impl ExtVTable for WellKnownBinary {
139    type Metadata = SpatialMetadata;
140    type StoredMetadata = super::SpatialStoredMetadata;
141
142    type NativeValue<'a> = Wkb<'a>;
143
144    fn id(&self) -> ExtId {
145        static ID: CachedId = CachedId::new("vortex.st.wkb");
146        *ID
147    }
148
149    fn serialize_metadata(&self, metadata: &Self::Metadata) -> VortexResult<Vec<u8>> {
150        Ok(metadata.serialize())
151    }
152
153    fn deserialize_metadata(&self, metadata: &[u8]) -> VortexResult<Self::StoredMetadata> {
154        super::SpatialStoredMetadata::deserialize(metadata)
155    }
156
157    fn metadata_from_storage(
158        &self,
159        stored_metadata: Self::StoredMetadata,
160        _storage_dtype: &DType,
161    ) -> VortexResult<Self::Metadata> {
162        Ok(SpatialMetadata::from_stored_metadata(stored_metadata, None))
163    }
164
165    fn storage_dtype(_metadata: &Self::Metadata) -> DType {
166        DType::Binary(Nullability::NonNullable)
167    }
168
169    fn validate_metadata(metadata: &Self::Metadata) -> VortexResult<()> {
170        if let Some(dimension) = metadata.dimension {
171            vortex_bail!(
172                "vortex.st.wkb metadata must not have a coordinate dimension, got {dimension:?}"
173            );
174        }
175
176        Ok(())
177    }
178
179    fn unpack_native<'a>(
180        _ext_dtype: &'a ExtDType<Self>,
181        storage_value: &'a ScalarValue,
182    ) -> VortexResult<Self::NativeValue<'a>> {
183        Wkb::try_from_bytes(storage_value.as_binary().as_slice())
184    }
185}
186
187static ARROW_WKB: CachedId = CachedId::new(WkbType::NAME);
188
189impl ArrowExtVTable for WellKnownBinary {
190    fn metadata_policy() -> ArrowMetadataPolicy {
191        ArrowMetadataPolicy::ArrowNative
192    }
193
194    fn arrow_ext_id(&self) -> Id {
195        *ARROW_WKB
196    }
197
198    fn to_arrow_field(
199        &self,
200        name: &str,
201        ext_dtype: &ExtDType<Self>,
202        session: &ArrowSession,
203    ) -> VortexResult<Option<Field>> {
204        let spatial_metadata = ext_dtype.metadata();
205
206        let mut field = session.to_arrow_field(name, ext_dtype.storage_dtype())?;
207        field.try_with_extension_type(wkb_type(spatial_metadata))?;
208
209        Ok(Some(field))
210    }
211
212    fn execute_arrow(
213        &self,
214        array: ArrayRef,
215        target: &Field,
216        options: &ArrowExportOptions,
217        ctx: &mut ExecutionCtx,
218    ) -> VortexResult<ArrowExport> {
219        let Ok(wkb_meta) = target.try_extension_type::<WkbType>() else {
220            return Ok(ArrowExport::Unsupported(array));
221        };
222
223        let executed = array.execute::<ExtensionArray>(ctx)?;
224        let storage = executed.storage_array().clone();
225
226        let storage_field = Field::new(
227            String::new(),
228            target.data_type().clone(),
229            target.is_nullable(),
230        );
231        let arrow_storage =
232            storage.execute_arrow_with_options(Some(&storage_field), options, ctx)?;
233
234        // Round-trip through the GeoArrow WKB array types: this validates that the storage
235        // is a binary-family Arrow array and produces the canonical physical representation
236        // expected for a `WkbType` extension field.
237        let arrow_ref: ArrowArrayRef = match target.data_type() {
238            DataType::Binary => Arc::new(
239                GenericWkbArray::<i32>::try_from((arrow_storage.as_ref(), wkb_meta))
240                    .map_err(|e| vortex_err!("failed to construct WkbArray: {e}"))?
241                    .into_arrow(),
242            ),
243            DataType::LargeBinary => Arc::new(
244                GenericWkbArray::<i64>::try_from((arrow_storage.as_ref(), wkb_meta))
245                    .map_err(|e| vortex_err!("failed to construct LargeWkbArray: {e}"))?
246                    .into_arrow(),
247            ),
248            DataType::BinaryView => Arc::new(
249                WkbViewArray::try_from((arrow_storage.as_ref(), wkb_meta))
250                    .map_err(|e| vortex_err!("failed to construct WkbViewArray: {e}"))?
251                    .into_arrow(),
252            ),
253            _ => unreachable!("target data type was validated above"),
254        };
255
256        Ok(ArrowExport::Exported(arrow_ref))
257    }
258
259    fn from_arrow_field(
260        field: &Field,
261        _session: &ArrowSession,
262    ) -> VortexResult<Option<ExtDType<Self>>> {
263        let wkb_meta = field.try_extension_type::<WkbType>()?;
264
265        Ok(Some(ExtDType::try_with_vtable(
266            WellKnownBinary,
267            spatial_metadata(&wkb_meta),
268            field.is_nullable().into(),
269        )?))
270    }
271
272    fn from_arrow_array(
273        array: ArrowArrayRef,
274        _field: &Field,
275        ext_dtype: &ExtDType<Self>,
276        session: &ArrowSession,
277    ) -> VortexResult<ArrowImport> {
278        session
279            .from_arrow_storage(array, &ext_dtype.clone().erased())
280            .map(ArrowImport::Imported)
281    }
282}
283
284fn wkb_type(spatial_metadata: &SpatialMetadata) -> WkbType {
285    WkbType::new(geoarrow_metadata(spatial_metadata))
286}
287
288fn spatial_metadata(wkb_type: &WkbType) -> SpatialMetadata {
289    spatial_metadata_from_arrow(wkb_type.metadata())
290}