Database Reference
In-Depth Information
Fixing invalid geometries
Youwilloftenfind
invalid geometries
inyourPostGISdatabase.Theseinvalidgeo-
metriescouldcompromisethefunctioningofPostGISitselfandanyexternaltoolus-
ingit,suchasQGISandMapServer.PostGIS,beingcompliantwiththeOGCSimple
Features Specification, must manage and work with valid geometries.
Luckily, PostGIS 2.0 offers you the
ST_MakeValid
function that, together with the
ST_IsValid
,
ST_IsValidReason
, and
ST_IsValidDetails
functions, is the
ideal toolkit for inspecting and fixing geometries within the database. In this recipe,
you will learn how to fix a common case of invalid geometry.
Getting ready
Unzip the
data/TM_WORLD_BORDERS-0.3.zip
file into your working direct-
ory—
working/chp3
. Import the shapefile in PostGIS with the
shp2pgsql
com-
mand, as follows:
$ shp2pgsql -s 4326 -g the_geom -W LATIN1 -I
TM_WORLD_BORDERS-0.3.shp chp03.countries >
countries.sql
$ psql -U me -d postgis_cookbook -f countries.sql
How to do it...
The steps you need toperform to complete this recipe are as follows:
1. First, investigate whether or not any geometry is invalid in the imported
table. As you can see in the following query, using the
ST_IsValid
and
ST_IsValidReason
functions,wefindfourinvalidgeometriesthatareallin-
valid for the same reason—ring self-intersection:
postgis_cookbook=# SELECT gid, name,
ST_IsValidReason(the_geom)
FROM chp03.countries
WHERE ST_IsValid(the_geom)=false;