Database Reference
In-Depth Information
Improving ST_Polygonize
Inthisshortrecipe,wewillbeusingacommoncodingpattern,inusewhengeomet-
riesarebeingconstructedwith
ST_Polygonize
,andformalizingitintoafunctionfor
re-use.
ST_Polygonize
isaveryusefulfunction.Passasetof"unioned"linesoranarray
oflinesto
ST_Polygonize
,andthefunctionwillconstructpolygonsfromtheinput.
ST_Polygonize
does so aggressively insofar as it will construct all possible poly-
gonsfromtheinputs. Onefrustrating aspectofthefunction, however,isthatitdoes
not return amultipolygon, but instead returns aGeometryCollections. GeometryCol-
lectionscanbeproblematicinthird-partytoolsforinteractingwithPostGISassomany
third-partytoolsdon'thavemechanismsinplaceforrecognizinganddisplayingGeo-
metryCollections.
Thepatternwewillformalizehereisthecommonlyrecommendedapproachforchan-
gingGeometryCollectionsintomulipolygonswhenitisappropriatetodoso.Thisap-
proach will be useful not only for
ST_Polygonize
, which we will use in the subse-
quentrecipe,butcanalsobeadaptedforothercaseswhereafunctionreturnsGeo-
metryCollectionsthatare,forallpracticalpurposes,multipolygons.Hence,thisiswhy
it merits its own dedicated recipe.
Getting ready
The basic pattern for handling GeometryCollections is to use
ST_Dump
to convert
themtoadumptype,extractthegeometryportionofthedump,collectthegeometry,
and then convert this collection into a multipolygon. The dump type is a special
PostGIS type that is a combination of the geometries and an index number for the
geometries. It's typical to use
ST_Dump
to convert from a GeometryCollection to a
dumptypeandthendofurtherprocessingonthedatafromthere.Rarelyisadump
object used directly, but it is typically an intermediate type of data.
How to do it...
We expect this function to take a geometry and return a geometry: