Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
58 changes: 45 additions & 13 deletions common/src/main/java/org/apache/sedona/common/Functions.java
Original file line number Diff line number Diff line change
Expand Up @@ -1169,7 +1169,16 @@ public static boolean isValid(Geometry geom, int flag) {
isValidOp.setSelfTouchingRingFormingHoleValid(false);
}

return isValidOp.isValid();
try {
return isValidOp.isValid();
} catch (RuntimeException e) {
// JTS throws on some inputs instead of reporting them invalid, e.g. coordinates near
// Double.MAX_VALUE that overflow its orientation test. A geometry that cannot be validated
// is not valid, and one bad row must not fail the query. isValidReason and isValidDetail
// report the error.
log.debug("Geometry validation failed, reporting the geometry as invalid", e);
return false;
}
}

public static boolean isValidTrajectory(Geometry geom) {
Expand Down Expand Up @@ -2955,31 +2964,54 @@ public static ValidDetail isValidDetail(Geometry geom) {
}

public static ValidDetail isValidDetail(Geometry geom, int flag) {
if (geom == null) {
return null;
}
IsValidOp isValidOp = getIsValidOpObject(geom, flag);

if (isValidOp.isValid()) {
return new ValidDetail(true, null, null);
} else {
TopologyValidationError error = isValidOp.getValidationError();
String reason = error.toString();
Geometry location = geom.getFactory().createPoint(error.getCoordinate());
return new ValidDetail(false, reason, location);
try {
if (isValidOp.isValid()) {
return new ValidDetail(true, null, null);
}
} catch (RuntimeException e) {
// The validator threw before it found a location
return new ValidDetail(false, validationFailureReason(e), null);
}
TopologyValidationError error = isValidOp.getValidationError();
String reason = error.toString();
Geometry location = geom.getFactory().createPoint(error.getCoordinate());
return new ValidDetail(false, reason, location);
}

public static String isValidReason(Geometry geom) {
return isValidReason(geom, OGC_SFS_VALIDITY);
}

public static String isValidReason(Geometry geom, int flag) {
if (geom == null) {
return null;
}
IsValidOp isValidOp = getIsValidOpObject(geom, flag);

if (isValidOp.isValid()) {
return "Valid Geometry";
} else {
TopologyValidationError error = isValidOp.getValidationError();
return error.toString();
try {
if (isValidOp.isValid()) {
return "Valid Geometry";
}
} catch (RuntimeException e) {
return validationFailureReason(e);
}
TopologyValidationError error = isValidOp.getValidationError();
return error.toString();
}

/**
* The reason reported for a geometry the validator throws on (see {@link #isValid(Geometry,
* int)}), in the form GEOS reports it, e.g. "IllegalArgumentException: Segment vertex does not
* intersect ring".
*/
private static String validationFailureReason(RuntimeException e) {
String type = e.getClass().getSimpleName();
return e.getMessage() == null ? type : type + ": " + e.getMessage();
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5929,6 +5929,61 @@ public void testAddMeasurePreservesCoordinateLayout() throws ParseException {
}
}

@Test
public void isValidValidatorErrorReturnsFalse() throws ParseException {
// Near Double.MAX_VALUE the orientation determinant overflows to NaN, so JTS places the
// hole's first vertex on the shell boundary but then cannot find the shell segment it lies on.
Geometry geom =
geomFromWKT(
"POLYGON ((-1.7e308 -10, 1.7e308 -10, 1.7e308 0, 1.7e308 10, -1.7e308 10, -1.7e308 -10),"
+ " (-1e308 0, -5e307 5, -5e307 -5, -1e308 0))",
0);
IllegalArgumentException validatorError =
assertThrows(
"fixture no longer makes the JTS validator throw",
IllegalArgumentException.class,
() -> new org.locationtech.jts.operation.valid.IsValidOp(geom).isValid());
assertEquals("Segment vertex does not intersect ring", validatorError.getMessage());

assertFalse(Functions.isValid(geom));
assertFalse(Functions.isValid(geom, 0));
assertFalse(Functions.isValid(geom, 1));

// The reason carries the validator's error, in the form GEOS reports it
String reason = "IllegalArgumentException: Segment vertex does not intersect ring";
assertEquals(reason, Functions.isValidReason(geom));
assertEquals(reason, Functions.isValidReason(geom, 0));
assertEquals(reason, Functions.isValidReason(geom, 1));
ValidDetail expectedDetail = new ValidDetail(false, reason, null);
assertTrue(expectedDetail.equals(Functions.isValidDetail(geom)));
assertTrue(expectedDetail.equals(Functions.isValidDetail(geom, 0)));
assertTrue(expectedDetail.equals(Functions.isValidDetail(geom, 1)));
}

@Test
public void isValidReasonAndDetailOfNullAreNull() {
assertNull(Functions.isValidReason(null));
assertNull(Functions.isValidReason(null, 1));
assertNull(Functions.isValidDetail(null));
assertNull(Functions.isValidDetail(null, 1));
}

@Test
public void isValidKeepsOrdinaryResults() throws ParseException {
assertTrue(Functions.isValid(geomFromWKT("POLYGON ((0 0, 10 0, 10 10, 0 10, 0 0))", 0)));
assertFalse(Functions.isValid(geomFromWKT("POLYGON ((0 0, 1 1, 0 1, 1 0, 0 0))", 0)));
assertTrue(Functions.isValid(geomFromWKT("POLYGON EMPTY", 0)));
assertTrue(Functions.isValid(geomFromWKT("GEOMETRYCOLLECTION EMPTY", 0)));
assertFalse(Functions.isValid(geomFromWKT("POINT (NaN NaN)", 0)));

// The shell touches itself at (5 10) and encloses an inverted hole: invalid under OGC,
// valid under the Esri model.
Geometry invertedHole =
geomFromWKT("POLYGON ((0 0, 10 0, 10 10, 5 10, 7 5, 3 5, 5 10, 0 10, 0 0))", 0);
assertFalse(Functions.isValid(invertedHole, 0));
assertTrue(Functions.isValid(invertedHole, 1));
}

@Test
public void testAddMeasureWithDefaultJtsCoordinates() {
// JTS's default XY coordinates carry a NaN Z slot, not an actual Z dimension.
Expand Down
2 changes: 2 additions & 0 deletions docs/api/flink/Geometry-Validation/ST_IsValid.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,8 @@ Introduction: Test if a geometry is well-formed. The function can be invoked wit
- 0 (default): Use usual OGC SFS (Simple Features Specification) validity semantics.
- 1: "ESRI flag", Accepts certain self-touching rings as valid, which are considered invalid under OGC standards.

If the validity checks cannot complete for a geometry, for example because coordinates close to the largest double value overflow them, the function returns `false` for that geometry instead of failing the query. [ST_IsValidReason](ST_IsValidReason.md) returns the error that stopped the checks.

![ST_IsValid](../../../image/ST_IsValid/ST_IsValid.svg "ST_IsValid")

Formats:
Expand Down
2 changes: 2 additions & 0 deletions docs/api/flink/Geometry-Validation/ST_IsValidReason.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,8 @@ Introduction: Returns text stating if the geometry is valid. If not, it provides
- 0 (default): Use usual OGC SFS (Simple Features Specification) validity semantics.
- 1: "ESRI flag", Accepts certain self-touching rings as valid, which are considered invalid under OGC standards.

If the validity checks cannot complete for a geometry, for example because coordinates close to the largest double value overflow them, the function returns the error that stopped them, such as `IllegalArgumentException: Segment vertex does not intersect ring`, instead of failing the query.

![ST_IsValidReason](../../../image/ST_IsValidReason/ST_IsValidReason.svg "ST_IsValidReason")

Formats:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,8 @@ Introduction: Test if a geometry is well-formed. The function can be invoked wit
- 0 (default): Use usual OGC SFS (Simple Features Specification) validity semantics.
- 1: "ESRI flag", Accepts certain self-touching rings as valid, which are considered invalid under OGC standards.

If the validity checks cannot complete for a geometry, for example because coordinates close to the largest double value overflow them, the function returns `false` for that geometry instead of failing the query. [ST_IsValidReason](ST_IsValidReason.md) returns the error that stopped the checks.

![ST_IsValid](../../../../image/ST_IsValid/ST_IsValid.svg "ST_IsValid")

Formats:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,8 @@ The flags parameter is a bitfield with the following options:
- 0: Use usual OGC SFS (Simple Features Specification) validity semantics.
- 1: "ESRI flag", Accepts certain self-touching rings as valid, which are considered invalid under OGC standards.

If the validity checks cannot complete for a geometry, for example because coordinates close to the largest double value overflow them, the function returns `false` as `valid`, the error that stopped them as `reason`, such as `IllegalArgumentException: Segment vertex does not intersect ring`, and a null `location`, instead of failing the query.

![ST_IsValidDetail](../../../../image/ST_IsValidDetail/ST_IsValidDetail.svg "ST_IsValidDetail")

Format:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,8 @@ Introduction: Returns text stating if the geometry is valid. If not, it provides
- 0 (default): Use usual OGC SFS (Simple Features Specification) validity semantics.
- 1: "ESRI flag", Accepts certain self-touching rings as valid, which are considered invalid under OGC standards.

If the validity checks cannot complete for a geometry, for example because coordinates close to the largest double value overflow them, the function returns the error that stopped them, such as `IllegalArgumentException: Segment vertex does not intersect ring`, instead of failing the query.

![ST_IsValidReason](../../../../image/ST_IsValidReason/ST_IsValidReason.svg "ST_IsValidReason")

Formats:
Expand Down
2 changes: 2 additions & 0 deletions docs/api/sql/Geometry-Validation/ST_IsValid.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,8 @@ Introduction: Test if a geometry is well-formed. The function can be invoked wit
- 0 (default): Use usual OGC SFS (Simple Features Specification) validity semantics.
- 1: "ESRI flag", Accepts certain self-touching rings as valid, which are considered invalid under OGC standards.

If the validity checks cannot complete for a geometry, for example because coordinates close to the largest double value overflow them, the function returns `false` for that geometry instead of failing the query. [ST_IsValidReason](ST_IsValidReason.md) returns the error that stopped the checks.

![ST_IsValid](../../../image/ST_IsValid/ST_IsValid.svg "ST_IsValid")

Formats:
Expand Down
2 changes: 2 additions & 0 deletions docs/api/sql/Geometry-Validation/ST_IsValidDetail.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,8 @@ The flags parameter is a bitfield with the following options:
- 0 (default): Use usual OGC SFS (Simple Features Specification) validity semantics.
- 1: "ESRI flag", Accepts certain self-touching rings as valid, which are considered invalid under OGC standards.

If the validity checks cannot complete for a geometry, for example because coordinates close to the largest double value overflow them, the function returns `false` as `valid`, the error that stopped them as `reason`, such as `IllegalArgumentException: Segment vertex does not intersect ring`, and a null `location`, instead of failing the query.

![ST_IsValidDetail](../../../image/ST_IsValidDetail/ST_IsValidDetail.svg "ST_IsValidDetail")

Formats:
Expand Down
2 changes: 2 additions & 0 deletions docs/api/sql/Geometry-Validation/ST_IsValidReason.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,8 @@ Introduction: Returns text stating if the geometry is valid. If not, it provides
- 0 (default): Use usual OGC SFS (Simple Features Specification) validity semantics.
- 1: "ESRI flag", Accepts certain self-touching rings as valid, which are considered invalid under OGC standards.

If the validity checks cannot complete for a geometry, for example because coordinates close to the largest double value overflow them, the function returns the error that stopped them, such as `IllegalArgumentException: Segment vertex does not intersect ring`, instead of failing the query.

![ST_IsValidReason](../../../image/ST_IsValidReason/ST_IsValidReason.svg "ST_IsValidReason")

Formats:
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
/*
* 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.snowflake.snowsql.udtfs;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;

import java.util.List;
import java.util.stream.Collectors;
import org.apache.sedona.common.Constructors;
import org.apache.sedona.snowflake.snowsql.GeometrySerde;
import org.junit.Test;
import org.locationtech.jts.io.ParseException;

public class ST_IsValidDetailTest {

private static ST_IsValidDetail.OutputRow process(String wkt, int flag) throws ParseException {
byte[] geometry = GeometrySerde.serialize(Constructors.geomFromWKT(wkt, 0));
List<ST_IsValidDetail.OutputRow> rows =
new ST_IsValidDetail().process(geometry, flag).collect(Collectors.toList());
assertEquals(1, rows.size());
return rows.get(0);
}

@Test
public void validatorErrorIsReportedWithoutLocation() throws ParseException {
// Near Double.MAX_VALUE the JTS validator throws instead of reporting the polygon invalid
String wkt =
"POLYGON ((-1.7e308 -10, 1.7e308 -10, 1.7e308 0, 1.7e308 10, -1.7e308 10, -1.7e308 -10),"
+ " (-1e308 0, -5e307 5, -5e307 -5, -1e308 0))";
for (int flag : new int[] {0, 1}) {
ST_IsValidDetail.OutputRow row = process(wkt, flag);
assertFalse(row.valid);
assertEquals("IllegalArgumentException: Segment vertex does not intersect ring", row.reason);
assertNull(row.location);
}
}

@Test
public void validGeometryHasNoReasonOrLocation() throws ParseException {
ST_IsValidDetail.OutputRow row = process("POLYGON ((0 0, 10 0, 10 10, 0 10, 0 0))", 0);
assertTrue(row.valid);
assertNull(row.reason);
assertNull(row.location);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -517,6 +517,9 @@ private[apache] case class ST_IsValidDetail(children: Seq[Expression])

override def eval(input: InternalRow): Any = {
val geometry = children.head.toGeometry(input)
if (geometry == null) {
return null
}
var validDetail: ValidDetail = null
if (nArgs == 1) {
validDetail = Functions.isValidDetail(geometry)
Expand All @@ -528,11 +531,10 @@ private[apache] case class ST_IsValidDetail(children: Seq[Expression])
}

try {
if (validDetail.location == null) {
return InternalRow.fromSeq(Seq(validDetail.valid, null, null))
}

val serLocation = GeometrySerializer.serialize(validDetail.location)
// A geometry the validator throws on is invalid with a reason but no location
val serLocation =
if (validDetail.location == null) null
else GeometrySerializer.serialize(validDetail.location)
InternalRow.fromSeq(
Seq(validDetail.valid, UTF8String.fromString(validDetail.reason), serLocation))
} catch {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -652,6 +652,71 @@ class functionTestScala
assert(testtable.take(1).head.get(0) == null)
}

it("ST_IsValid returns false for a geometry the validator throws on") {
// Row 3 makes JTS IsValidOp throw: near Double.MAX_VALUE its orientation test overflows.
val geoms = sparkSession
.sql("""
|SELECT id, ST_GeomFromWKT(wkt) AS geom FROM VALUES
| (1, 'POLYGON ((0 0, 10 0, 10 10, 0 10, 0 0))'),
| (2, 'POLYGON ((0 0, 1 1, 0 1, 1 0, 0 0))'),
| (3, 'POLYGON ((-1.7e308 -10, 1.7e308 -10, 1.7e308 0, 1.7e308 10, -1.7e308 10, -1.7e308 -10), (-1e308 0, -5e307 5, -5e307 -5, -1e308 0))'),
| (4, NULL),
| (5, 'POLYGON EMPTY'),
| (6, 'POLYGON ((0 0, 10 0, 10 10, 5 10, 7 5, 3 5, 5 10, 0 10, 0 0))')
| AS t(id, wkt)
|""".stripMargin)
.repartition(3, col("id"))
val actual = geoms
.selectExpr("id", "ST_IsValid(geom)", "ST_IsValid(geom, 0)", "ST_IsValid(geom, 1)")
.collect()
.map(row => row.getInt(0) -> (1 to 3).map(i => Option(row.get(i))))
.toMap
val expected = Map(
1 -> Seq(Some(true), Some(true), Some(true)),
2 -> Seq(Some(false), Some(false), Some(false)),
3 -> Seq(Some(false), Some(false), Some(false)),
4 -> Seq(None, None, None),
5 -> Seq(Some(true), Some(true), Some(true)),
6 -> Seq(Some(false), Some(false), Some(true)))
assertEquals(expected, actual)
}

it("ST_IsValidReason and ST_IsValidDetail report the error the validator throws") {
val geoms = sparkSession
.sql("""
|SELECT id, ST_GeomFromWKT(wkt) AS geom FROM VALUES
| (1, 'POLYGON ((0 0, 10 0, 10 10, 0 10, 0 0))'),
| (2, 'POLYGON ((-1.7e308 -10, 1.7e308 -10, 1.7e308 0, 1.7e308 10, -1.7e308 10, -1.7e308 -10), (-1e308 0, -5e307 5, -5e307 -5, -1e308 0))'),
| (3, NULL)
| AS t(id, wkt)
|""".stripMargin)
.repartition(3, col("id"))
val actual = geoms
.selectExpr(
"id",
"ST_IsValidReason(geom)",
"ST_IsValidReason(geom, 1)",
"ST_IsValidDetail(geom)",
"ST_IsValidDetail(geom, 1)")
.collect()
.map(row => row.getInt(0) -> (1 to 4).map(i => Option(row.get(i))))
.toMap
val reason = "IllegalArgumentException: Segment vertex does not intersect ring"
val expected = Map(
1 -> Seq(
Some("Valid Geometry"),
Some("Valid Geometry"),
Some(Row(true, null, null)),
Some(Row(true, null, null))),
2 -> Seq(
Some(reason),
Some(reason),
Some(Row(false, reason, null)),
Some(Row(false, reason, null))),
3 -> Seq(None, None, None, None))
assertEquals(expected, actual)
}

it("Passed ST_ReducePrecision") {
var testtable = sparkSession.sql("""
|SELECT ST_ReducePrecision(ST_GeomFromWKT('Point(0.1234567890123456789 0.1234567890123456789)'), 8)
Expand Down
Loading