1

I am working on postgis and was ran below query but i have my doubts

Is the below representation valid ?

As far as I know the polygon must have 4 coordinates.

SELECT  ST_GeometryType  ( ST_GeomFromGeoJSON('{
        "type": "Polygon",
        "coordinates": [
            [
                [
                    10.798460841178894,
                    27.7146573614866
                ],
                [
                    18.005492091178894,
                    23.112072196617056
                ]
            ]
        ]
    }'));

enter image description here

enter image description here

What can be work around for the validation ?

Can we throw error before insert in such case ?

Abhijit Gujar
  • 2,750
  • 3
  • 29
  • 43
  • 1
    A "valid" polygon must have at least four points - which forms a triangle. The first and last points must be the same. – Ralph Tee Apr 10 '18 at 10:05
  • 1
    Your coordinates are asserting a precision deep into the subatomic structure. If you aren't mapping superstrings, you can lose all but the first six places in the coordinates. – Vince Apr 10 '18 at 10:52
  • @Vince +1 for superstrings. time to implement ST_11DDistance... – geozelot Apr 10 '18 at 11:00

2 Answers2

2

You can test the validity of any Geometry by using the ST_IsValid geometry accessor.

For more detail on the reason you can then use ST_IsValidReason which in your case, as Ralph points out, will tell you it needs more points.

P.S. If you have the opportunity, you can additionally avoid sending invalid GeoJSON to the DB from further up your stack (e.g. within a web form) by using https://github.com/mapbox/geojsonhint. This would save your DB having to do the expensive ST_GeomFromGeoJSON on invalid data.

Guy
  • 1,678
  • 11
  • 13
1

Additionally and to address your second question (remember: only one distinct question per post!), you can always try using ST_MakeValid on invalid geometries; the function has it's limits, though, and can return GEOMETRYCOLLECTIONs with lower dimension geometries.

To prevent the insert of invalid geometries in the first place (usually a very good idea for all tables), you can easily implement table/row constraints (see this answer), or even triggers.

geozelot
  • 30,050
  • 4
  • 32
  • 56