Search code examples
postgresqlpostgis

How to add a constraint to prevent adding polygons with holes


I have a table in postgres with the following column definition:

the_geom geometry NOT NULL

I want to constraint it to only simple polygons. I have the following definition to limit it to polygons:

ADD CONSTRAINT enforce_geotype_the_geom CHECK ((geometrytype(the_geom) = 'POLYGON'::text)

And I want to also limit each polygon to prevent from having holes. Polygons with holes can be create like here. I want to prevent that. Is it possible?


Solution

  • Wouldn't this constraint solve the issue?

    ADD CONSTRAINT enforce_geotype_the_geom 
    CHECK ((ST_NumInteriorRings(the_geom) = 0))
    

    The ST_NumInteriorRings function returns null if the argument is not a polygon and the number of interiorrings > 0 if there are subrings.

    https://postgis.net/docs/ST_NumInteriorRings.html