The goal of this recipe is identical to the previous two recipes, but it covers how to perform the process with data in a PostGIS database. You will use it to turn points into lines, and lines into polygons.
Not all methods are available; for those not available, you can use the previous recipe. It will also work on a database layer; it just doesn't save the results to the database. So, the results will need to be imported to the database after completion.
You need to load a vector layer of points with a numeric ID indicating order, and an identifier of unique lines or polygons that is shared between points of the same geometry. For example, you can use census_wake_2000_points loaded into PostGIS with the geometry field called geom. (Refer to Chapter 1, Data Input and Output, the Loading Vector Data into PostGIS recipe to see how to load data into PostGIS.)
Using DB Manager Plugin (this comes with QGIS and is in the Database menu) or an alternate PostGIS SQL application (command line—pgsql or GUI—pgadmin III), the following SQL examples will perform the conversions between vector types.
To test the creation of new geometries, wrap the queries in CREATE VIEW, as demonstrated in Chapter 2, Data Management. If the data is large or you are happy with the results, you can swap in CREATE TABLE to make a new table for more permanent storage.
CREATE VIEW line2poly AS SELECT id,stfid,ST_MakePolygon(geom) as geom FROM pts2line;
CREATE VIEW pts AS SELECT ROW_NUMBER() over (order by a.id_0) as id,id_0 as grpid,(a.a_geom).path[2] as path, ST_GeometryType((a.a_geom).geom), ((a.a_geom).geom) as geom FROM (SELECT id_0,(ST_DumpPoints(geom)) as a_geom FROM "census_wake2000") as a;
Based on the common identifier specified in GROUP BY, the SQL statement aggregates multiple points into a new geometry of the specified type.
When dumping geometries to points, PostGIS actually dumps an array, including ID information. This is why the example query is actually a nested set of queries. The first is to dump the array of geometry information, and the second to extract the relevant parts of the results in the format that we want them in.
PostGIS has a few dump functions with different purposes in mind. Splitting geometries is apparently a difficult concept for databases because aggregation is usually the only direction functions can logically go. Disaggregation is claimed by some to be counter to how SQL conceptually works and would require non-SQL logic.
ST_Dump, ST_DumpPoints, and ST_DumpRings), refer to the PostGIS manual at http://postgis.net/docs/manual-2.1/reference.html