-
Notifications
You must be signed in to change notification settings - Fork 52
feat(rust/sedona-geo): Add ST_AsGeoJSON #469
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
11 commits
Select commit
Hold shift + click to select a range
c167280
feat: implement ST_AsGeoJSON
prantogg dfba3d6
clippy fix
prantogg 180047b
fmt fix
prantogg 4421184
refactor: use existing `GeoTypesExecutor`for iterating through geomet…
prantogg 9294a77
remove output type parameter
prantogg ad886bb
add integration tests
prantogg 29f333c
remove empty point test
prantogg 3660f07
pre-commit fix
prantogg 0da4fc0
Apply @petern48's suggestions from code review
prantogg 5c340db
Special case empty point and polygon
prantogg 5b092e4
fix python tests
prantogg File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Some comments aren't visible on the classic Files Changed page.
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,61 @@ | ||
| // Licensed to the Apache Software Foundation (ASF) under one | ||
| // or more contributor license agreements. See the NOTICE file | ||
| // distributed with this work for additional information | ||
| // regarding copyright ownership. The ASF licenses this file | ||
| // to you under the Apache License, Version 2.0 (the | ||
| // "License"); you may not use this file except in compliance | ||
| // with the License. You may obtain a copy of the License at | ||
| // | ||
| // http://www.apache.org/licenses/LICENSE-2.0 | ||
| // | ||
| // Unless required by applicable law or agreed to in writing, | ||
| // software distributed under the License is distributed on an | ||
| // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY | ||
| // KIND, either express or implied. See the License for the | ||
| // specific language governing permissions and limitations | ||
| // under the License. | ||
| use arrow_schema::DataType; | ||
| use datafusion_expr::{scalar_doc_sections::DOC_SECTION_OTHER, Documentation, Volatility}; | ||
| use sedona_expr::scalar_udf::SedonaScalarUDF; | ||
| use sedona_schema::{datatypes::SedonaType, matchers::ArgMatcher}; | ||
|
|
||
| /// ST_AsGeoJSON() scalar UDF implementation | ||
| /// | ||
| /// Stub function for GeoJSON conversion. | ||
| pub fn st_asgeojson_udf() -> SedonaScalarUDF { | ||
| SedonaScalarUDF::new_stub( | ||
| "st_asgeojson", | ||
| ArgMatcher::new( | ||
| vec![ArgMatcher::is_geometry_or_geography()], | ||
| SedonaType::Arrow(DataType::Utf8), | ||
| ), | ||
| Volatility::Immutable, | ||
| Some(st_asgeojson_doc()), | ||
| ) | ||
| } | ||
|
|
||
| fn st_asgeojson_doc() -> Documentation { | ||
| Documentation::builder( | ||
| DOC_SECTION_OTHER, | ||
| "Return the GeoJSON representation of a geometry", | ||
| "ST_AsGeoJSON (A: Geometry)", | ||
| ) | ||
| .with_argument("geom", "geometry: Input geometry") | ||
| .with_sql_example("SELECT ST_AsGeoJSON(ST_Point(1.0, 2.0))") | ||
| .with_related_udf("ST_GeomFromGeoJSON") | ||
| .build() | ||
| } | ||
|
|
||
| #[cfg(test)] | ||
| mod tests { | ||
| use datafusion_expr::ScalarUDF; | ||
|
|
||
| use super::*; | ||
|
|
||
| #[test] | ||
| fn udf_metadata() { | ||
| let udf: ScalarUDF = st_asgeojson_udf().into(); | ||
| assert_eq!(udf.name(), "st_asgeojson"); | ||
| assert!(udf.documentation().is_some()) | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,196 @@ | ||
| // Licensed to the Apache Software Foundation (ASF) under one | ||
| // or more contributor license agreements. See the NOTICE file | ||
| // distributed with this work for additional information | ||
| // regarding copyright ownership. The ASF licenses this file | ||
| // to you under the Apache License, Version 2.0 (the | ||
| // "License"); you may not use this file except in compliance | ||
| // with the License. You may obtain a copy of the License at | ||
| // | ||
| // http://www.apache.org/licenses/LICENSE-2.0 | ||
| // | ||
| // Unless required by applicable law or agreed to in writing, | ||
| // software distributed under the License is distributed on an | ||
| // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY | ||
| // KIND, either express or implied. See the License for the | ||
| // specific language governing permissions and limitations | ||
| // under the License. | ||
| use std::sync::Arc; | ||
|
|
||
| use arrow_array::builder::StringBuilder; | ||
| use arrow_schema::DataType; | ||
| use datafusion_common::error::{DataFusionError, Result}; | ||
| use datafusion_expr::ColumnarValue; | ||
| use geo_traits::{GeometryTrait, PointTrait, PolygonTrait}; | ||
| use sedona_expr::scalar_udf::{ScalarKernelRef, SedonaScalarKernel}; | ||
| use sedona_functions::executor::WkbExecutor; | ||
| use sedona_schema::{datatypes::SedonaType, matchers::ArgMatcher}; | ||
| use wkb::reader::Wkb; | ||
|
|
||
| use crate::to_geo::item_to_geometry; | ||
|
|
||
| /// ST_AsGeoJSON() kernel implementation using WkbExecutor | ||
| pub fn st_asgeojson_impl() -> ScalarKernelRef { | ||
| Arc::new(STAsGeoJSON {}) | ||
| } | ||
|
|
||
| #[derive(Debug)] | ||
| struct STAsGeoJSON {} | ||
|
|
||
| impl SedonaScalarKernel for STAsGeoJSON { | ||
| fn return_type(&self, args: &[SedonaType]) -> Result<Option<SedonaType>> { | ||
| let matcher = ArgMatcher::new( | ||
| vec![ArgMatcher::is_geometry()], | ||
| SedonaType::Arrow(DataType::Utf8), | ||
| ); | ||
|
|
||
| matcher.match_args(args) | ||
| } | ||
|
|
||
| fn invoke_batch( | ||
| &self, | ||
| arg_types: &[SedonaType], | ||
| args: &[ColumnarValue], | ||
| ) -> Result<ColumnarValue> { | ||
| let executor = WkbExecutor::new(arg_types, args); | ||
|
|
||
| // Estimate the minimum probable memory requirement of the output. | ||
| // GeoJSON is typically longer than WKT due to JSON formatting. | ||
| let min_probable_geojson_size = executor.num_iterations() * 33; | ||
|
|
||
| // Initialize an output builder of the appropriate type | ||
| let mut builder = | ||
| StringBuilder::with_capacity(executor.num_iterations(), min_probable_geojson_size); | ||
|
|
||
| executor.execute_wkb_void(|maybe_wkb| { | ||
| match maybe_wkb { | ||
| Some(wkb) => { | ||
| let json_str = geom_to_geojson(&wkb)?; | ||
| builder.append_value(&json_str); | ||
| } | ||
| None => builder.append_null(), | ||
| }; | ||
|
|
||
| Ok(()) | ||
| })?; | ||
|
|
||
| executor.finish(Arc::new(builder.finish())) | ||
| } | ||
| } | ||
|
|
||
| /// Convert a WKB geometry to GeoJSON string, handling special cases for empty geometries | ||
| fn geom_to_geojson(geom: &Wkb) -> Result<String> { | ||
| // Special case handling for geometries that geo_types::Geometry cannot represent | ||
| match geom.as_type() { | ||
| geo_traits::GeometryType::Point(pt) => { | ||
| if pt.coord().is_none() { | ||
| // Empty point - geo_types cannot represent this | ||
| return Ok(r#"{"type":"Point","coordinates":[]}"#.to_string()); | ||
| } | ||
| } | ||
| geo_traits::GeometryType::Polygon(poly) => { | ||
| if poly.exterior().is_none() { | ||
| // Empty polygon - to match PostGIS behavior | ||
| return Ok(r#"{"type":"Polygon","coordinates":[]}"#.to_string()); | ||
| } | ||
| } | ||
| _ => {} | ||
| } | ||
|
|
||
| // For all other geometries (including other empty geometries), convert to geo_types::Geometry | ||
| let geo_geom = item_to_geometry(geom)?; | ||
|
|
||
| let geojson_value = geojson::Value::from(&geo_geom); | ||
| let geojson_geom = geojson::Geometry::new(geojson_value); | ||
|
|
||
| serde_json::to_string(&geojson_geom).map_err(|err| DataFusionError::External(Box::new(err))) | ||
| } | ||
|
|
||
| #[cfg(test)] | ||
| mod tests { | ||
| use datafusion_common::scalar::ScalarValue; | ||
| use sedona_expr::scalar_udf::SedonaScalarUDF; | ||
| use sedona_schema::datatypes::WKB_GEOMETRY; | ||
| use sedona_testing::testers::ScalarUdfTester; | ||
|
|
||
| use super::*; | ||
|
|
||
| #[test] | ||
| fn test_simple_geojson() { | ||
| let kernel = st_asgeojson_impl(); | ||
| let udf = SedonaScalarUDF::from_kernel("st_asgeojson", kernel); | ||
| let tester = ScalarUdfTester::new(udf.into(), vec![WKB_GEOMETRY]); | ||
|
|
||
| // Test with a simple point | ||
| let result = tester.invoke_wkb_scalar(Some("POINT (1 2)")).unwrap(); | ||
| tester.assert_scalar_result_equals(result, r#"{"type":"Point","coordinates":[1.0,2.0]}"#); | ||
|
|
||
| // Test with null | ||
| let result = tester.invoke_wkb_scalar(None).unwrap(); | ||
| assert_eq!(result, ScalarValue::Utf8(None)); | ||
| } | ||
|
|
||
| #[test] | ||
| fn test_linestring() { | ||
| let kernel = st_asgeojson_impl(); | ||
| let udf = SedonaScalarUDF::from_kernel("st_asgeojson", kernel); | ||
| let tester = ScalarUdfTester::new(udf.into(), vec![WKB_GEOMETRY]); | ||
|
|
||
| let result = tester | ||
| .invoke_wkb_scalar(Some("LINESTRING (0 0, 1 1, 2 2)")) | ||
| .unwrap(); | ||
| tester.assert_scalar_result_equals( | ||
| result, | ||
| r#"{"type":"LineString","coordinates":[[0.0,0.0],[1.0,1.0],[2.0,2.0]]}"#, | ||
| ); | ||
| } | ||
|
|
||
| #[test] | ||
| fn test_polygon() { | ||
| let kernel = st_asgeojson_impl(); | ||
| let udf = SedonaScalarUDF::from_kernel("st_asgeojson", kernel); | ||
| let tester = ScalarUdfTester::new(udf.into(), vec![WKB_GEOMETRY]); | ||
|
|
||
| let result = tester | ||
| .invoke_wkb_scalar(Some("POLYGON ((0 0, 1 0, 1 1, 0 1, 0 0))")) | ||
| .unwrap(); | ||
| tester.assert_scalar_result_equals( | ||
| result, | ||
| r#"{"type":"Polygon","coordinates":[[[0.0,0.0],[1.0,0.0],[1.0,1.0],[0.0,1.0],[0.0,0.0]]]}"#, | ||
| ); | ||
| } | ||
|
|
||
| #[test] | ||
| fn test_geometry_collection() { | ||
| let kernel = st_asgeojson_impl(); | ||
| let udf = SedonaScalarUDF::from_kernel("st_asgeojson", kernel); | ||
| let tester = ScalarUdfTester::new(udf.into(), vec![WKB_GEOMETRY]); | ||
|
|
||
| let result = tester | ||
| .invoke_wkb_scalar(Some("GEOMETRYCOLLECTION(POINT(1 2), LINESTRING(0 0, 1 1))")) | ||
| .unwrap(); | ||
| tester.assert_scalar_result_equals( | ||
| result, | ||
| r#"{"type":"GeometryCollection","geometries":[{"type":"Point","coordinates":[1.0,2.0]},{"type":"LineString","coordinates":[[0.0,0.0],[1.0,1.0]]}]}"#, | ||
| ); | ||
| } | ||
|
|
||
| #[test] | ||
| fn test_empty_point() { | ||
| let kernel = st_asgeojson_impl(); | ||
| let udf = SedonaScalarUDF::from_kernel("st_asgeojson", kernel); | ||
| let tester = ScalarUdfTester::new(udf.into(), vec![WKB_GEOMETRY]); | ||
|
|
||
| let result = tester.invoke_wkb_scalar(Some("POINT EMPTY")).unwrap(); | ||
| tester.assert_scalar_result_equals(result, r#"{"type":"Point","coordinates":[]}"#); | ||
| } | ||
|
|
||
| #[test] | ||
| fn test_empty_polygon() { | ||
| let kernel = st_asgeojson_impl(); | ||
| let udf = SedonaScalarUDF::from_kernel("st_asgeojson", kernel); | ||
| let tester = ScalarUdfTester::new(udf.into(), vec![WKB_GEOMETRY]); | ||
|
|
||
| let result = tester.invoke_wkb_scalar(Some("POLYGON EMPTY")).unwrap(); | ||
| tester.assert_scalar_result_equals(result, r#"{"type":"Polygon","coordinates":[]}"#); | ||
| } | ||
| } |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
In addition to rust tests, we need integration tests in test_functions.py. Instructions for testing it locally and iterating are here.