diff --git a/pom.xml b/pom.xml
index 343dbc76c25..5f3fe53f4e4 100644
--- a/pom.xml
+++ b/pom.xml
@@ -75,6 +75,7 @@
2.13.4
1.20.0
1.21.0-datasyslab-3
+ udt
0.16.1
0.8
@@ -686,6 +687,13 @@
+
+ src/main/scala/**/*.scala
+ src/test/scala/**/*.scala
+ src/main/scala/**/*.sc
+ src/test/scala/**/*.sc
+ spark/shared/src/main/**/*.scala
+
3.7.5
tools/maven/scalafmt.conf
diff --git a/spark/common/pom.xml b/spark/common/pom.xml
index 4e6701518ce..6ebafdb4de2 100644
--- a/spark/common/pom.xml
+++ b/spark/common/pom.xml
@@ -310,6 +310,7 @@
src/main/scala-spark-${spark.major.version}
+ src/main/scala-spatial-${sedona.spatial.type.impl}
@@ -334,6 +335,27 @@
org.scalastyle
scalastyle-maven-plugin
+
+
+ ${project.basedir}/src/main/scala
+ ${project.basedir}/src/main/scala-spatial-${sedona.spatial.type.impl}
+
+
+
+
+ com.diffplug.spotless
+ spotless-maven-plugin
+
+
+
+ src/main/scala/**/*.scala
+ src/test/scala/**/*.scala
+ src/main/scala/**/*.sc
+ src/test/scala/**/*.sc
+ src/main/scala-spatial-${sedona.spatial.type.impl}/**/*.scala
+
+
+
diff --git a/spark/common/src/main/scala-spatial-udt/org/apache/spark/sql/sedona_sql/types/SpatialTypeSupport.scala b/spark/common/src/main/scala-spatial-udt/org/apache/spark/sql/sedona_sql/types/SpatialTypeSupport.scala
new file mode 100644
index 00000000000..50c84476e0c
--- /dev/null
+++ b/spark/common/src/main/scala-spatial-udt/org/apache/spark/sql/sedona_sql/types/SpatialTypeSupport.scala
@@ -0,0 +1,35 @@
+/*
+ * 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.
+ */
+package org.apache.spark.sql.sedona_sql.types
+
+import org.apache.spark.sql.catalyst.expressions.SpecializedGetters
+import org.apache.spark.sql.sedona_sql.UDT.GeometryUDT
+import org.apache.spark.sql.types.DataType
+import org.locationtech.jts.geom.Geometry
+
+/** Version-selected geometry boundary used by the DataFrame/RDD adapters. */
+object SpatialTypeSupport {
+ def geometryType: DataType = GeometryUDT()
+ def isGeometry(dataType: DataType): Boolean = dataType.isInstanceOf[GeometryUDT]
+ def externalGeometry(value: Geometry): Any = value
+ def externalGeometry(value: Geometry, dataType: DataType): Any = value
+ def fromExternalGeometry(value: Any): Geometry = value.asInstanceOf[Geometry]
+ def readGeometry(row: SpecializedGetters, ordinal: Int, dataType: DataType): Geometry =
+ if (row.isNullAt(ordinal)) null else GeometryUDT.deserialize(row.get(ordinal, dataType))
+}
diff --git a/spark/common/src/main/scala/org/apache/sedona/sql/utils/Adapter.scala b/spark/common/src/main/scala/org/apache/sedona/sql/utils/Adapter.scala
index 732fb1272d7..f75e2ea77f0 100644
--- a/spark/common/src/main/scala/org/apache/sedona/sql/utils/Adapter.scala
+++ b/spark/common/src/main/scala/org/apache/sedona/sql/utils/Adapter.scala
@@ -23,7 +23,7 @@ import org.apache.sedona.core.spatialRDD.SpatialRDD
import java.sql.{Date, Timestamp}
import org.apache.spark.api.java.JavaPairRDD
import org.apache.spark.rdd.RDD
-import org.apache.spark.sql.sedona_sql.UDT.GeometryUDT
+import org.apache.spark.sql.sedona_sql.types.SpatialTypeSupport
import org.apache.spark.sql.types._
import org.apache.spark.sql.{DataFrame, Row, SparkSession}
import org.apache.spark.sql.catalyst.expressions.GenericRowWithSchema
@@ -141,9 +141,12 @@ object Adapter {
sparkSession: SparkSession): DataFrame = {
val rowRdd = spatialRDD.rawSpatialRDD.rdd.map[Row](geom => {
val stringRow = extractUserData(geom)
- Row.fromSeq(stringRow)
+ Row.fromSeq(stringRow.map {
+ case geometry: Geometry => SpatialTypeSupport.externalGeometry(geometry)
+ case value => value
+ })
})
- var cols: Seq[StructField] = Seq(StructField("geometry", GeometryUDT()))
+ var cols: Seq[StructField] = Seq(StructField("geometry", SpatialTypeSupport.geometryType))
if (fieldNames != null && fieldNames.nonEmpty) {
cols = cols ++ fieldNames.map(f => StructField(f, StringType))
}
@@ -193,12 +196,15 @@ object Adapter {
row = f,
leftFieldnames = leftFieldnames,
rightFieldnames = rightFieldNames)
- Row.fromSeq(stringRow)
+ Row.fromSeq(stringRow.map {
+ case geometry: Geometry => SpatialTypeSupport.externalGeometry(geometry)
+ case value => value
+ })
})
- var cols: Seq[StructField] = Seq(StructField("leftgeometry", GeometryUDT()))
+ var cols: Seq[StructField] = Seq(StructField("leftgeometry", SpatialTypeSupport.geometryType))
if (leftFieldnames != null && leftFieldnames.nonEmpty)
cols = cols ++ leftFieldnames.map(fName => StructField(fName, StringType))
- cols = cols ++ Seq(StructField("rightgeometry", GeometryUDT()))
+ cols = cols ++ Seq(StructField("rightgeometry", SpatialTypeSupport.geometryType))
if (rightFieldNames != null && rightFieldNames.nonEmpty)
cols = cols ++ rightFieldNames.map(fName => StructField(fName, StringType))
val schema = StructType(cols)
@@ -292,7 +298,7 @@ object Adapter {
private def toRdd(dataFrame: DataFrame, geometryColId: Int): RDD[Geometry] = {
dataFrame.rdd.map[Geometry](f => {
- var geometry = f.get(geometryColId).asInstanceOf[Geometry]
+ val geometry = SpatialTypeSupport.fromExternalGeometry(f.get(geometryColId))
var fieldSize = f.size
var userData: String = null
if (fieldSize > 1) {
@@ -333,7 +339,9 @@ object Adapter {
val parsedRow = stringRow.zipWithIndex.map { case (value, idx) =>
val desiredDataType = schema(idx).dataType
// Don't convert geometry data, only user data
- if (desiredDataType == GeometryUDT) value else parseString(value.toString, desiredDataType)
+ if (SpatialTypeSupport.isGeometry(desiredDataType))
+ SpatialTypeSupport.externalGeometry(value.asInstanceOf[Geometry], desiredDataType)
+ else parseString(value.toString, desiredDataType)
}
Row.fromSeq(parsedRow)
diff --git a/spark/common/src/main/scala/org/apache/sedona/util/DfUtils.scala b/spark/common/src/main/scala/org/apache/sedona/util/DfUtils.scala
index 5b2bea21806..e232e534a35 100644
--- a/spark/common/src/main/scala/org/apache/sedona/util/DfUtils.scala
+++ b/spark/common/src/main/scala/org/apache/sedona/util/DfUtils.scala
@@ -18,12 +18,12 @@
*/
package org.apache.sedona.util
-import org.apache.spark.sql.sedona_sql.UDT.GeometryUDT
+import org.apache.spark.sql.sedona_sql.types.SpatialTypeSupport
import org.apache.spark.sql.types.StructType
object DfUtils {
def getGeometryColumnName(schema: StructType): String = {
- val geomFields = schema.fields.filter(_.dataType == GeometryUDT)
+ val geomFields = schema.fields.filter(field => SpatialTypeSupport.isGeometry(field.dataType))
if (geomFields.isEmpty)
throw new IllegalArgumentException(
diff --git a/spark/common/src/main/scala/org/apache/spark/sql/sedona_sql/adapters/StructuredAdapter.scala b/spark/common/src/main/scala/org/apache/spark/sql/sedona_sql/adapters/StructuredAdapter.scala
index 4046f38fe97..7b92460661d 100644
--- a/spark/common/src/main/scala/org/apache/spark/sql/sedona_sql/adapters/StructuredAdapter.scala
+++ b/spark/common/src/main/scala/org/apache/spark/sql/sedona_sql/adapters/StructuredAdapter.scala
@@ -20,7 +20,6 @@ package org.apache.spark.sql.sedona_sql.adapters
import org.apache.sedona.core.spatialPartitioning.GenericUniquePartitioner
import org.apache.sedona.core.spatialRDD.SpatialRDD
-import org.apache.sedona.sql.utils.GeometrySerializer
import org.apache.sedona.util.DfUtils
import org.apache.spark.api.java.JavaPairRDD
import org.apache.spark.rdd.RDD
@@ -28,7 +27,8 @@ import org.apache.spark.sql.catalyst.InternalRow
import org.apache.spark.sql.types.{DataType, StructType}
import org.apache.spark.sql.{DataFrame, Row, SparkSession}
import org.apache.spark.sql.sedona_sql.DataFrameShims
-import org.locationtech.jts.geom.Geometry
+import org.apache.spark.sql.sedona_sql.types.SpatialTypeSupport
+import org.locationtech.jts.geom.{Geometry, GeometryFactory}
import org.slf4j.{Logger, LoggerFactory}
/**
@@ -53,7 +53,7 @@ object StructuredAdapter {
} else spatialRDD.schema = rdd.first().schema
spatialRDD.rawSpatialRDD = rdd
.map(row => {
- val geom = row.getAs[Geometry](geometryFieldName)
+ val geom = SpatialTypeSupport.fromExternalGeometry(row.getAs[Any](geometryFieldName))
geom.setUserData(row.copy())
geom
})
@@ -108,9 +108,12 @@ object StructuredAdapter {
val spatialRDD = new SpatialRDD[Geometry]
spatialRDD.schema = schema
val ordinal = spatialRDD.schema.fieldIndex(geometryFieldName)
+ val geometryType = schema(ordinal).dataType
spatialRDD.rawSpatialRDD = rdd
.map(row => {
- val geom = GeometrySerializer.deserialize(row.getBinary(ordinal))
+ // Keep the existing empty carrier for null internal geometry; user data retains the null.
+ val geom = Option(SpatialTypeSupport.readGeometry(row, ordinal, geometryType))
+ .getOrElse(new GeometryFactory().createGeometryCollection())
geom.setUserData(row.copy())
geom
})
diff --git a/spark/common/src/test/scala/org/apache/sedona/sql/SpatialAdapterBoundaryTest.scala b/spark/common/src/test/scala/org/apache/sedona/sql/SpatialAdapterBoundaryTest.scala
new file mode 100644
index 00000000000..af784e66ec9
--- /dev/null
+++ b/spark/common/src/test/scala/org/apache/sedona/sql/SpatialAdapterBoundaryTest.scala
@@ -0,0 +1,120 @@
+/*
+ * 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.
+ */
+package org.apache.sedona.sql
+
+import org.apache.sedona.common.S2Geography.WKBGeography
+import org.apache.sedona.core.spatialRDD.SpatialRDD
+import org.apache.sedona.sql.utils.Adapter
+import org.apache.sedona.util.DfUtils
+import org.apache.spark.sql.Row
+import org.apache.spark.sql.sedona_sql.UDT.{GeographyUDT, GeometryUDT}
+import org.apache.spark.sql.sedona_sql.adapters.StructuredAdapter
+import org.apache.spark.sql.types._
+import org.locationtech.jts.geom.{Coordinate, Geometry, GeometryFactory, PrecisionModel}
+
+class SpatialAdapterBoundaryTest extends TestBaseScala {
+ private def point(x: Double): Geometry =
+ new GeometryFactory(new PrecisionModel(), 4326).createPoint(new Coordinate(x, 2))
+
+ describe("spatial adapter boundaries") {
+ it("preserves the default geometry schema and string attributes through Adapter") {
+ val geometry = point(1)
+ geometry.setUserData("alpha\t")
+ val spatialRDD = new SpatialRDD[Geometry]
+ spatialRDD.rawSpatialRDD = sc.parallelize(Seq(geometry)).toJavaRDD()
+ val frame = Adapter.toDf(spatialRDD, Seq("label", "empty"), sparkSession)
+ assert(
+ frame.schema == StructType(
+ Seq(
+ StructField("geometry", GeometryUDT()),
+ StructField("label", StringType),
+ StructField("empty", StringType))))
+ val row = frame.head()
+ assert(row.getAs[Geometry](0).getSRID == 4326)
+ assert(row.getString(1) == "alpha")
+ assert(row.getString(2) == "")
+ val restored = Adapter.toSpatialRdd(frame, "geometry").rawSpatialRDD.first()
+ assert(restored.equalsExact(geometry))
+ assert(restored.getUserData == "alpha\t")
+ assert(geometry.getUserData == "alpha\t")
+ }
+
+ it("preserves an explicitly requested GeometryUDT schema") {
+ val geometry = point(3)
+ geometry.setUserData("7")
+ val spatialRDD = new SpatialRDD[Geometry]
+ spatialRDD.rawSpatialRDD = sc.parallelize(Seq(geometry)).toJavaRDD()
+ val schema =
+ StructType(Seq(StructField("shape", GeometryUDT()), StructField("number", IntegerType)))
+ val frame = Adapter.toDf(spatialRDD, schema, sparkSession)
+ assert(frame.schema == schema)
+ assert(frame.head().getAs[Geometry](0).equalsExact(geometry))
+ assert(frame.head().getInt(1) == 7)
+ }
+
+ it("keeps full rows and geography values through StructuredAdapter") {
+ val geometry = point(4)
+ val geography = WKBGeography.fromJTS(point(5))
+ val schema = StructType(
+ Seq(
+ StructField("id", IntegerType, nullable = false),
+ StructField("shape", GeometryUDT()),
+ StructField("globe", GeographyUDT()),
+ StructField("label", StringType)))
+ val source = sparkSession.createDataFrame(
+ sc.parallelize(Seq(Row(7, geometry, geography, null))),
+ schema)
+ val spatialRDD = StructuredAdapter.toSpatialRdd(source)
+ val converted = StructuredAdapter.toDf(spatialRDD, sparkSession)
+ assert(converted.schema == schema)
+ val row = converted.head()
+ assert(row.getInt(0) == 7)
+ assert(row.getAs[Geometry](1).equalsExact(geometry))
+ assert(row.getAs[WKBGeography](2).getSRID == 4326)
+ assert(row.getAs[WKBGeography](2).getWKBBytes.sameElements(geography.getWKBBytes))
+ assert(row.isNullAt(3))
+ val fromRows = StructuredAdapter.toSpatialRdd(source.rdd, "shape")
+ val restoredRow = StructuredAdapter.toRowRdd(fromRows).first()
+ assert(restoredRow.schema == schema)
+ assert(restoredRow.getAs[Geometry]("shape").equalsExact(geometry))
+ }
+
+ it("retains null internal geometry as an empty carrier and restores the original null") {
+ val schema =
+ StructType(Seq(StructField("geometry", GeometryUDT()), StructField("id", IntegerType)))
+ val source = sparkSession.createDataFrame(sc.parallelize(Seq(Row(null, 9))), schema)
+ val spatialRDD = StructuredAdapter.toSpatialRdd(source)
+ assert(spatialRDD.rawSpatialRDD.first().isEmpty)
+ val restored = StructuredAdapter.toDf(spatialRDD, sparkSession).head()
+ assert(restored.isNullAt(0))
+ assert(restored.getInt(1) == 9)
+ }
+
+ it("detects geometry columns without selecting geography or hiding ambiguity") {
+ def schema(names: String*): StructType = StructType(
+ Seq(StructField("globe", GeographyUDT())) ++ names.map(StructField(_, GeometryUDT())))
+ assert(DfUtils.getGeometryColumnName(schema("shape")) == "shape")
+ assert(DfUtils.getGeometryColumnName(schema("left", "geometry")) == "geometry")
+ intercept[IllegalArgumentException] { DfUtils.getGeometryColumnName(schema()) }
+ intercept[IllegalArgumentException] {
+ DfUtils.getGeometryColumnName(schema("left", "right"))
+ }
+ }
+ }
+}
diff --git a/spark/spark-4.1/src/main/scala/org/apache/spark/sql/udf/SedonaArrowEvalPython.scala b/spark/common/src/test/scala/org/apache/sedona/sql/SpatialTestValues.scala
similarity index 60%
rename from spark/spark-4.1/src/main/scala/org/apache/spark/sql/udf/SedonaArrowEvalPython.scala
rename to spark/common/src/test/scala/org/apache/sedona/sql/SpatialTestValues.scala
index 7600ece5079..e2aa25f9858 100644
--- a/spark/spark-4.1/src/main/scala/org/apache/spark/sql/udf/SedonaArrowEvalPython.scala
+++ b/spark/common/src/test/scala/org/apache/sedona/sql/SpatialTestValues.scala
@@ -16,17 +16,17 @@
* specific language governing permissions and limitations
* under the License.
*/
-package org.apache.spark.sql.udf
+package org.apache.sedona.sql
-import org.apache.spark.sql.catalyst.expressions.{Attribute, PythonUDF}
-import org.apache.spark.sql.catalyst.plans.logical.{BaseEvalPython, LogicalPlan}
+import org.apache.spark.sql.Row
+import org.apache.spark.sql.sedona_sql.types.SpatialTypeSupport
+import org.locationtech.jts.geom.Geometry
-case class SedonaArrowEvalPython(
- udfs: Seq[PythonUDF],
- resultAttrs: Seq[Attribute],
- child: LogicalPlan,
- evalType: Int)
- extends BaseEvalPython {
- override protected def withNewChildInternal(newChild: LogicalPlan): SedonaArrowEvalPython =
- copy(child = newChild)
+/** Geometry result access for semantic tests across external SQL representations. */
+object SpatialTestValues {
+ def geometry(value: Any): Geometry = SpatialTypeSupport.fromExternalGeometry(value)
+
+ def geometry(row: Row, ordinal: Int): Geometry = geometry(row.get(ordinal))
+
+ def geometry(row: Row, field: String): Geometry = geometry(row, row.fieldIndex(field))
}
diff --git a/spark/common/src/test/scala/org/apache/sedona/sql/SpatialTestValuesTest.scala b/spark/common/src/test/scala/org/apache/sedona/sql/SpatialTestValuesTest.scala
new file mode 100644
index 00000000000..eee61b681db
--- /dev/null
+++ b/spark/common/src/test/scala/org/apache/sedona/sql/SpatialTestValuesTest.scala
@@ -0,0 +1,85 @@
+/*
+ * 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.
+ */
+package org.apache.sedona.sql
+
+import org.apache.spark.sql.Row
+import org.apache.spark.sql.catalyst.expressions.GenericRowWithSchema
+import org.apache.spark.sql.sedona_sql.types.SpatialTypeSupport
+import org.apache.spark.sql.types.{IntegerType, StructField, StructType}
+import org.locationtech.jts.geom.{Coordinate, CoordinateXYZM, Geometry, GeometryFactory, LineString, Point, PrecisionModel}
+import org.scalatest.funsuite.AnyFunSuite
+
+class SpatialTestValuesTest extends AnyFunSuite {
+ private val factory = new GeometryFactory(new PrecisionModel(), 3857)
+ private val point = factory.createPoint(new Coordinate(1, 2))
+
+ test("legacy geometry values retain identity and null results remain null") {
+ assert(SpatialTestValues.geometry(point) eq point)
+ assert(SpatialTestValues.geometry(Row(point), 0) eq point)
+ assert(SpatialTestValues.geometry(null) == null)
+ assert(SpatialTestValues.geometry(Row(null), 0) == null)
+ }
+
+ test("default external geometry rows retain SRID and support index and field access") {
+ val value = SpatialTypeSupport.externalGeometry(point)
+ val schema = StructType(
+ Seq(
+ StructField("id", IntegerType),
+ StructField("a.geom`name", SpatialTypeSupport.geometryType)))
+ val row = new GenericRowWithSchema(Array[Any](7, value), schema)
+ if (!value.isInstanceOf[Geometry]) {
+ // The previous direct JTS cast cannot read Spark's external native value.
+ intercept[ClassCastException](row.getAs[Geometry](1).getSRID)
+ }
+ Seq(SpatialTestValues.geometry(row, 1), SpatialTestValues.geometry(row, "a.geom`name"))
+ .foreach { actual =>
+ assert(actual.equalsExact(point))
+ assert(actual.getSRID == 3857)
+ assert(actual.getFactory.getSRID == 3857)
+ }
+ val nullRow = new GenericRowWithSchema(Array[Any](7, null), schema)
+ assert(SpatialTestValues.geometry(nullRow, "a.geom`name") == null)
+ }
+
+ test("external result access preserves ZM coordinates and typed empty sequences") {
+ val line = factory.createLineString(
+ Array[Coordinate](new CoordinateXYZM(1, 2, 3, 4), new CoordinateXYZM(5, 6, 7, 8)))
+ val result = SpatialTestValues
+ .geometry(SpatialTypeSupport.externalGeometry(line))
+ .asInstanceOf[LineString]
+ assert(result.getSRID == 3857)
+ assert(result.getCoordinateSequence.getDimension == 4)
+ assert(result.getCoordinateSequence.getMeasures == 1)
+ assert(result.getCoordinateSequence.getZ(1) == 7d)
+ assert(result.getCoordinateSequence.getM(1) == 8d)
+ val empty = factory.createPoint(factory.getCoordinateSequenceFactory.create(0, 4, 1))
+ val emptyResult = SpatialTestValues
+ .geometry(SpatialTypeSupport.externalGeometry(empty))
+ .asInstanceOf[Point]
+ assert(emptyResult.isEmpty)
+ assert(emptyResult.getSRID == 3857)
+ assert(emptyResult.getCoordinateSequence.getDimension == 4)
+ assert(emptyResult.getCoordinateSequence.getMeasures == 1)
+ }
+
+ test("geometry result access does not reinterpret binary or scalar values") {
+ intercept[RuntimeException](SpatialTestValues.geometry(Array[Byte](1, 2, 3)))
+ intercept[RuntimeException](SpatialTestValues.geometry("POINT (1 2)"))
+ }
+}
diff --git a/spark/common/src/test/scala/org/apache/sedona/sql/TestBaseScala.scala b/spark/common/src/test/scala/org/apache/sedona/sql/TestBaseScala.scala
index 0068da6060f..dddfaed0ea6 100644
--- a/spark/common/src/test/scala/org/apache/sedona/sql/TestBaseScala.scala
+++ b/spark/common/src/test/scala/org/apache/sedona/sql/TestBaseScala.scala
@@ -210,10 +210,10 @@ trait TestBaseScala extends FunSpec with BeforeAndAfterAll {
val input = buildPointLonLatDf.limit(sampleCount).collect()
input
.map(row => {
- val point1 = row.getAs[org.locationtech.jts.geom.Point](0)
+ val point1 = SpatialTestValues.geometry(row, 0)
input
.map(row => {
- val point2 = row.getAs[org.locationtech.jts.geom.Point](0)
+ val point2 = SpatialTestValues.geometry(row, 0)
if (Spheroid.distance(point1, point2) <= distance) 1 else 0
})
.sum
@@ -225,10 +225,10 @@ trait TestBaseScala extends FunSpec with BeforeAndAfterAll {
val input = buildPointLonLatDf.limit(sampleCount).collect()
input
.map(row => {
- val point1 = row.getAs[org.locationtech.jts.geom.Point](0)
+ val point1 = SpatialTestValues.geometry(row, 0)
input
.map(row => {
- val point2 = row.getAs[org.locationtech.jts.geom.Point](0)
+ val point2 = SpatialTestValues.geometry(row, 0)
if (Haversine.distance(point1, point2) <= distance) 1 else 0
})
.sum
@@ -245,10 +245,10 @@ trait TestBaseScala extends FunSpec with BeforeAndAfterAll {
val inputPoint = buildPointDf.limit(sampleCount).collect()
inputPoint
.map(row => {
- val point = row.getAs[org.locationtech.jts.geom.Point](0)
+ val point = SpatialTestValues.geometry(row, 0)
inputPolygon
.map(row => {
- val polygon = row.getAs[org.locationtech.jts.geom.Polygon](0)
+ val polygon = SpatialTestValues.geometry(row, 0)
if (densityFrac == 0) {
if (intersects)
if (hausdorffDistance(point, polygon) <= distance) 1 else 0
@@ -274,10 +274,10 @@ trait TestBaseScala extends FunSpec with BeforeAndAfterAll {
val inputPoint = buildPointDf.limit(sampleCount).collect()
inputPoint
.map(row => {
- val point = row.getAs[org.locationtech.jts.geom.Point](0)
+ val point = SpatialTestValues.geometry(row, 0)
inputPolygon
.map(row => {
- val polygon = row.getAs[org.locationtech.jts.geom.Polygon](0)
+ val polygon = SpatialTestValues.geometry(row, 0)
if (intersects)
if (frechetDistance(point, polygon) <= distance) 1 else 0
else if (frechetDistance(point, polygon) < distance) 1
@@ -294,10 +294,10 @@ trait TestBaseScala extends FunSpec with BeforeAndAfterAll {
inputPoint
.map(row => {
- val point = row.getAs[org.locationtech.jts.geom.Point](0)
+ val point = SpatialTestValues.geometry(row, 0)
inputPolygon
.map(row => {
- val polygon = row.getAs[org.locationtech.jts.geom.Polygon](0)
+ val polygon = SpatialTestValues.geometry(row, 0)
if (dWithin(point, polygon, distance, false)) 1 else 0
})
.sum
@@ -311,10 +311,10 @@ trait TestBaseScala extends FunSpec with BeforeAndAfterAll {
val sphericalDf2Collected = sphericalDf2.collect()
sphericalDf1Collected
.map(row => {
- val geom1 = row.get(2).asInstanceOf[org.locationtech.jts.geom.Point]
+ val geom1 = SpatialTestValues.geometry(row, 2)
sphericalDf2Collected
.map(row => {
- val geom2 = row.get(2).asInstanceOf[org.locationtech.jts.geom.Point]
+ val geom2 = SpatialTestValues.geometry(row, 2)
if (dWithin(geom1, geom2, distance, true)) 1 else 0
})
.sum
diff --git a/spark/common/src/test/scala/org/apache/sedona/sql/functionTestScala.scala b/spark/common/src/test/scala/org/apache/sedona/sql/functionTestScala.scala
index b2150b7f7e7..6b2d067a0b1 100644
--- a/spark/common/src/test/scala/org/apache/sedona/sql/functionTestScala.scala
+++ b/spark/common/src/test/scala/org/apache/sedona/sql/functionTestScala.scala
@@ -1628,17 +1628,17 @@ class functionTestScala
val points = pointDF
.selectExpr("ST_StartPoint(geom) as geom")
.filter("geom IS NOT NULL")
- .toSeq[Geometry]
+ .toGeometrySeq
val polygons = polygonDF
.selectExpr("ST_StartPoint(geom) as geom")
.filter("geom IS NOT NULL")
- .toSeq[Geometry]
+ .toGeometrySeq
val linestrings = lineStringDF
.selectExpr("ST_StartPoint(geom) as geom")
.filter("geom IS NOT NULL")
- .toSeq[Geometry]
+ .toGeometrySeq
Then("Linestring should result in list of points")
linestrings should contain theSameElementsAs expectedStartingPoints.map(_.toGeom)
diff --git a/spark/common/src/test/scala/org/apache/sedona/sql/implicits.scala b/spark/common/src/test/scala/org/apache/sedona/sql/implicits.scala
index a05fcb4a35f..42e30b94d15 100644
--- a/spark/common/src/test/scala/org/apache/sedona/sql/implicits.scala
+++ b/spark/common/src/test/scala/org/apache/sedona/sql/implicits.scala
@@ -25,6 +25,9 @@ import org.locationtech.jts.io.WKTReader
object implicits {
implicit class DataFrameEnhancer(df: DataFrame) {
+ def toGeometrySeq: Seq[Geometry] =
+ df.collect().toSeq.map(row => SpatialTestValues.geometry(row, 0)).toList
+
def toSeq[T]: Seq[T] =
df.collect().toSeq.map(element => element(0).asInstanceOf[T]).toList
diff --git a/spark/spark-4.1/src/main/scala/org/apache/sedona/sql/parser/SedonaSqlParser.scala b/spark/shared/src/main/scala-spark-4.1/org/apache/sedona/sql/parser/SedonaSqlParser.scala
similarity index 100%
rename from spark/spark-4.1/src/main/scala/org/apache/sedona/sql/parser/SedonaSqlParser.scala
rename to spark/shared/src/main/scala-spark-4.1/org/apache/sedona/sql/parser/SedonaSqlParser.scala
diff --git a/spark/spark-4.0/src/main/scala/org/apache/spark/sql/udf/ExtractSedonaUDFRule.scala b/spark/shared/src/main/scala-spark-4/org/apache/spark/sql/udf/ExtractSedonaUDFRule.scala
similarity index 100%
rename from spark/spark-4.0/src/main/scala/org/apache/spark/sql/udf/ExtractSedonaUDFRule.scala
rename to spark/shared/src/main/scala-spark-4/org/apache/spark/sql/udf/ExtractSedonaUDFRule.scala
diff --git a/spark/spark-4.0/src/main/scala/org/apache/spark/sql/udf/SedonaArrowEvalPython.scala b/spark/shared/src/main/scala-spark-4/org/apache/spark/sql/udf/SedonaArrowEvalPython.scala
similarity index 100%
rename from spark/spark-4.0/src/main/scala/org/apache/spark/sql/udf/SedonaArrowEvalPython.scala
rename to spark/shared/src/main/scala-spark-4/org/apache/spark/sql/udf/SedonaArrowEvalPython.scala
diff --git a/spark/spark-4.0/src/main/scala/org/apache/spark/sql/udf/SedonaArrowStrategy.scala b/spark/shared/src/main/scala-spark-4/org/apache/spark/sql/udf/SedonaArrowStrategy.scala
similarity index 100%
rename from spark/spark-4.0/src/main/scala/org/apache/spark/sql/udf/SedonaArrowStrategy.scala
rename to spark/shared/src/main/scala-spark-4/org/apache/spark/sql/udf/SedonaArrowStrategy.scala
diff --git a/spark/spark-4.0/pom.xml b/spark/spark-4.0/pom.xml
index 09ea7df39c3..6d069556ff4 100644
--- a/spark/spark-4.0/pom.xml
+++ b/spark/spark-4.0/pom.xml
@@ -168,6 +168,25 @@
src/main/scala
+
+ org.codehaus.mojo
+ build-helper-maven-plugin
+ 3.2.0
+
+
+ add-shared-spark-source
+ generate-sources
+
+ add-source
+
+
+
+ ${project.basedir}/../shared/src/main/scala-spark-4
+
+
+
+
+
net.alchim31.maven
scala-maven-plugin
@@ -179,6 +198,12 @@
org.scalastyle
scalastyle-maven-plugin
+
+
+ ${project.basedir}/src/main/scala
+ ${project.basedir}/../shared/src/main/scala-spark-4
+
+
diff --git a/spark/spark-4.1/pom.xml b/spark/spark-4.1/pom.xml
index feb9091c8cb..fdff917c0de 100644
--- a/spark/spark-4.1/pom.xml
+++ b/spark/spark-4.1/pom.xml
@@ -168,6 +168,26 @@
src/main/scala
+
+ org.codehaus.mojo
+ build-helper-maven-plugin
+ 3.2.0
+
+
+ add-shared-spark-source
+ generate-sources
+
+ add-source
+
+
+
+ ${project.basedir}/../shared/src/main/scala-spark-4
+ ${project.basedir}/../shared/src/main/scala-spark-4.1
+
+
+
+
+
net.alchim31.maven
scala-maven-plugin
@@ -179,6 +199,13 @@
org.scalastyle
scalastyle-maven-plugin
+
+
+ ${project.basedir}/src/main/scala
+ ${project.basedir}/../shared/src/main/scala-spark-4
+ ${project.basedir}/../shared/src/main/scala-spark-4.1
+
+
diff --git a/spark/spark-4.1/src/main/scala/org/apache/spark/sql/udf/ExtractSedonaUDFRule.scala b/spark/spark-4.1/src/main/scala/org/apache/spark/sql/udf/ExtractSedonaUDFRule.scala
deleted file mode 100644
index 3d3301580cc..00000000000
--- a/spark/spark-4.1/src/main/scala/org/apache/spark/sql/udf/ExtractSedonaUDFRule.scala
+++ /dev/null
@@ -1,185 +0,0 @@
-/*
- * 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.
- */
-package org.apache.spark.sql.udf
-
-import org.apache.sedona.sql.UDF.PythonEvalType
-import org.apache.spark.internal.Logging
-import org.apache.spark.sql.catalyst.expressions.{AttributeReference, Expression, ExpressionSet, PythonUDF}
-import org.apache.spark.sql.catalyst.plans.logical.{LogicalPlan, Project, Subquery}
-import org.apache.spark.sql.catalyst.rules.Rule
-import org.apache.spark.sql.catalyst.trees.TreePattern.PYTHON_UDF
-
-import scala.collection.mutable
-
-// That rule extracts scalar Python UDFs, currently Apache Spark has
-// assert on types which blocks using the vectorized udfs with geometry type
-class ExtractSedonaUDFRule extends Rule[LogicalPlan] with Logging {
-
- private def hasScalarPythonUDF(e: Expression): Boolean = {
- e.exists(PythonUDF.isScalarPythonUDF)
- }
-
- @scala.annotation.tailrec
- private def canEvaluateInPython(e: PythonUDF): Boolean = {
- e.children match {
- case Seq(u: PythonUDF) => e.evalType == u.evalType && canEvaluateInPython(u)
- case children => !children.exists(hasScalarPythonUDF)
- }
- }
-
- def isScalarPythonUDF(e: Expression): Boolean = {
- e.isInstanceOf[PythonUDF] && e
- .asInstanceOf[PythonUDF]
- .evalType == PythonEvalType.SQL_SCALAR_SEDONA_UDF
- }
-
- private def collectEvaluableUDFsFromExpressions(
- expressions: Seq[Expression]): Seq[PythonUDF] = {
-
- var firstVisitedScalarUDFEvalType: Option[Int] = None
-
- def canChainUDF(evalType: Int): Boolean = {
- evalType == firstVisitedScalarUDFEvalType.get
- }
-
- def collectEvaluableUDFs(expr: Expression): Seq[PythonUDF] = expr match {
- case udf: PythonUDF
- if isScalarPythonUDF(udf) && canEvaluateInPython(udf)
- && firstVisitedScalarUDFEvalType.isEmpty =>
- firstVisitedScalarUDFEvalType = Some(udf.evalType)
- Seq(udf)
- case udf: PythonUDF
- if isScalarPythonUDF(udf) && canEvaluateInPython(udf)
- && canChainUDF(udf.evalType) =>
- Seq(udf)
- case e => e.children.flatMap(collectEvaluableUDFs)
- }
-
- expressions.flatMap(collectEvaluableUDFs)
- }
-
- private var hasFailedBefore: Boolean = false
-
- def apply(plan: LogicalPlan): LogicalPlan = plan match {
- case s: Subquery if s.correlated => plan
-
- case _ =>
- try {
- plan.transformUpWithPruning(_.containsPattern(PYTHON_UDF)) {
- case p: SedonaArrowEvalPython => p
-
- case plan: LogicalPlan => extract(plan)
- }
- } catch {
- case e: Throwable =>
- if (!hasFailedBefore) {
- log.warn(
- s"Vectorized UDF feature won't be available due to plan transformation error.")
- log.warn(
- s"Failed to extract Sedona UDFs from plan: ${plan.treeString}\n" +
- s"Exception: ${e.getMessage}",
- e)
- hasFailedBefore = true
- }
- plan
- }
- }
-
- private def canonicalizeDeterministic(u: PythonUDF) = {
- if (u.deterministic) {
- u.canonicalized.asInstanceOf[PythonUDF]
- } else {
- u
- }
- }
-
- private def extract(plan: LogicalPlan): LogicalPlan = {
- val udfs = ExpressionSet(collectEvaluableUDFsFromExpressions(plan.expressions))
- .filter(udf => udf.references.subsetOf(plan.inputSet))
- .toSeq
- .asInstanceOf[Seq[PythonUDF]]
-
- udfs match {
- case Seq() => plan
- case _ => resolveUDFs(plan, udfs)
- }
- }
-
- def resolveUDFs(plan: LogicalPlan, udfs: Seq[PythonUDF]): LogicalPlan = {
- val attributeMap = mutable.HashMap[PythonUDF, Expression]()
-
- val newChildren = adjustAttributeMap(plan, udfs, attributeMap)
-
- udfs.map(canonicalizeDeterministic).filterNot(attributeMap.contains).foreach { udf =>
- throw new IllegalStateException(
- s"Invalid PythonUDF $udf, requires attributes from more than one child.")
- }
-
- val rewritten = plan.withNewChildren(newChildren).transformExpressions { case p: PythonUDF =>
- attributeMap.getOrElse(canonicalizeDeterministic(p), p)
- }
-
- val newPlan = extract(rewritten)
- if (newPlan.output != plan.output) {
- Project(plan.output, newPlan)
- } else {
- newPlan
- }
- }
-
- def adjustAttributeMap(
- plan: LogicalPlan,
- udfs: Seq[PythonUDF],
- attributeMap: mutable.HashMap[PythonUDF, Expression]): Seq[LogicalPlan] = {
- plan.children.map { child =>
- val validUdfs = udfs.filter { udf =>
- udf.references.subsetOf(child.outputSet)
- }
-
- if (validUdfs.nonEmpty) {
- require(
- validUdfs.forall(isScalarPythonUDF),
- "Can only extract scalar vectorized udf or sql batch udf")
-
- val resultAttrs = validUdfs.zipWithIndex.map { case (u, i) =>
- AttributeReference(s"pythonUDF$i", u.dataType)()
- }
-
- val evalTypes = validUdfs.map(_.evalType).toSet
- if (evalTypes.size != 1) {
- throw new IllegalStateException(
- "Expected udfs have the same evalType but got different evalTypes: " +
- evalTypes.mkString(","))
- }
- val evalType = evalTypes.head
- val evaluation = evalType match {
- case PythonEvalType.SQL_SCALAR_SEDONA_UDF =>
- SedonaArrowEvalPython(validUdfs, resultAttrs, child, evalType)
- case _ =>
- throw new IllegalStateException("Unexpected UDF evalType")
- }
-
- attributeMap ++= validUdfs.map(canonicalizeDeterministic).zip(resultAttrs)
- evaluation
- } else {
- child
- }
- }
- }
-}
diff --git a/spark/spark-4.1/src/main/scala/org/apache/spark/sql/udf/SedonaArrowStrategy.scala b/spark/spark-4.1/src/main/scala/org/apache/spark/sql/udf/SedonaArrowStrategy.scala
deleted file mode 100644
index 21e389ee567..00000000000
--- a/spark/spark-4.1/src/main/scala/org/apache/spark/sql/udf/SedonaArrowStrategy.scala
+++ /dev/null
@@ -1,43 +0,0 @@
-/*
- * 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.
- */
-package org.apache.spark.sql.udf
-
-import org.apache.sedona.sql.UDF.PythonEvalType
-import org.apache.spark.api.python.ChainedPythonFunctions
-import org.apache.spark.{JobArtifactSet, TaskContext}
-import org.apache.spark.sql.catalyst.InternalRow
-import org.apache.spark.sql.catalyst.expressions.{Attribute, PythonUDF}
-import org.apache.spark.sql.catalyst.plans.logical.LogicalPlan
-import org.apache.spark.sql.execution.{SparkPlan, SparkStrategy}
-import org.apache.spark.sql.execution.metric.SQLMetric
-import org.apache.spark.sql.execution.python.SedonaArrowEvalPythonExec
-import org.apache.spark.sql.types.StructType
-
-import scala.collection.JavaConverters.asScalaIteratorConverter
-
-// We use custom Strategy to avoid Apache Spark assert on types, we
-// can consider extending this to support other engines working with
-// arrow data
-class SedonaArrowStrategy extends SparkStrategy {
- override def apply(plan: LogicalPlan): Seq[SparkPlan] = plan match {
- case SedonaArrowEvalPython(udfs, output, child, evalType) =>
- SedonaArrowEvalPythonExec(udfs, output, planLater(child), evalType) :: Nil
- case _ => Nil
- }
-}