Top 5 Recent Articles
ARTICLES CATEGORIES
- Algorithms (22)
- All (399)
- Biography (1)
- Blog (44)
- Business Requirements (1)
- Commentary (1)
- Conversion (2)
- Customers (2)
- Data Models (1)
- Education (2)
- GeoRaptor (13)
- GPS (1)
- Image Processing (2)
- Import Export (8)
- Licensing (2)
- LiDAR (1)
- Linear Referencing (4)
- Manifold GIS (3)
- Mapping (1)
- MySQL Spatial (7)
- Networking and Routing (including Optimization) (5)
- Open Source (18)
- Oracle Spatial and Locator (194)
- Partitioning (1)
- PostGIS (36)
- Projections (1)
- Published Articles (1)
- qGIS (1)
- Recommendations (1)
- Services (1)
- Software Change Log (1)
- Source Code (37)
- Space Curves (9)
- Spatial Database Functions (109)
- Spatial DB comparison (1)
- Spatial XML Processing (11)
- SQL Server Spatial (92)
- Standards (3)
- Stored Procedure (17)
- Tessellation or Gridding (10)
- Tools (2)
- Topological Relationships (1)
- Training (2)
- Triangulation (2)
How to apply spatial constraints to PostGIS tables
This article was written before TypeMod was introduced eg Geometry(Polygon,28355)
As I have pointed out in other blog articles, spatial data quality should not engender either/or solutions when building business applications.
That is, if I can only create points for parcel centroids that fall within land parcels, then I don’t just build the rule in to the editing software that implements the end-user edit capabilities of the system: I should also add such constraints to the database that is holding the application data model and data.
The ability of databases in the area of spatial data quality is variable: this is because of the comparative youthful age of current spatial object relational databases.
One of the benefits of the mathematics behind relational theory is that, where the prescriptions of the model are implemented and used, data quality is ensured.
We have many relational and object-relational databases available today (both commercially in Oracle, SQL Server etc and open source, MySQL, PostgreSQL etc) but these databases all implement relational theory (or the SQL standards that have taken over from the pure science) to lesser or greater extent.
A complaint of C.J. Date is that many of todays databases that purport to be relational are not; he even argues persuasively that SQL is not relational.
Prosaically, the sorts of constraints in relational databases that are of use in ensuring data quality are:
- Primary/Unique Constraints;
- Not Null
- Foreign Key Constraints
- Column Check Constraints
- Table Check Constraints.
In the SQL-92 standard there is the little know ASSERTION (constraint) that, as far as I know, no commercial database today implements.
While all these constraints are based on attribute data and not complex data types such as spatial data, only some can be used to control spatial data quality.
These are the Column and Table versions of the CHECK constraint.
PostGIS’s AddGeometryColumn() Function
PostGIS can ensure spatial data quality through both an ordinary and advanced use of the CHECK constraint.
One of the nice things about registering a table/column using PostGIS’s AddGeometryColumn() function is that it automatically adds in CHECK constraints that test that the entered geometry:
- Is of the right type ie POLYGON and not POINT
- Has right SRID (if supplied)
- Has right dimensionality
The following statements show how this is done.
-- 0 Start with a clean data model DROP TABLE simon.parcel_centroid; Query returned successfully WITH no RESULT IN 16 ms. -- DROP TABLE simon.parcel; Query returned successfully WITH no RESULT IN 16 ms. -- -- 1 Create bare bones table without geometry column CREATE TABLE simon.parcel ( gid serial NOT NULL PRIMARY KEY ) WITH ( OIDS=FALSE ); NOTICE: CREATE TABLE will CREATE implicit SEQUENCE "parcel_gid_seq" FOR serial COLUMN "parcel.gid" NOTICE: CREATE TABLE / PRIMARY KEY will CREATE implicit INDEX "parcel_pkey" FOR TABLE "parcel" Query returned successfully WITH no RESULT IN 109 ms. -- /* Table looks like this: ** CREATE TABLE simon.parcel ( gid serial NOT NULL, CONSTRAINT parcel_pkey PRIMARY KEY (gid) ) WITH ( OIDS=FALSE ); */ -- -- Grant ownership ALTER TABLE simon.parcel OWNER TO postgres; Query returned successfully WITH no RESULT IN 16 ms. -- -- 2. Add geometry column and CHECK constraints on geometry SELECT addGeometryColumn('simon','parcel','geom','28355','POLYGON','2');
addgeometry text |
---|
simon.parcel.geom SRID:28355 TYPE:POLYGON DIMS:2 |
/* Note that the table now has the following structure. CREATE TABLE simon.parcel ( gid serial NOT NULL, geom geometry, CONSTRAINT parcel_pkey PRIMARY KEY (gid), CONSTRAINT enforce_dims_geom CHECK (st_ndims(geom) = 2), CONSTRAINT enforce_geotype_geom CHECK (geometrytype(geom) = 'POLYGON'::text OR geom IS NULL), CONSTRAINT enforce_srid_geom CHECK (st_srid(geom) = 28355) ) */
There is something important to note about these simple CHECK constraints: they use functions to extract a value from the geometry object that can be tested in a first order predicate expression that returns true or false: “function() == value”.
We can now conduct some tests on the table created above to show how these CHECK constraints work.
-- 3. try and insert a POLYGON with wrong dimensionality INSERT INTO simon.parcel(gid,geom) VALUES (1,ST_GeomFromEWKT('POLYGON ((100 0 -9,120 0 -9,120 20 -9,100 20 -9,100 0 -9))')); ERROR: NEW ROW FOR relation "parcel" violates CHECK CONSTRAINT "enforce_dims_geom" -- -- 4. Try and insert POLYGON with right dimensionality INSERT INTO simon.parcel(gid,geom) VALUES (1,ST_PolygonFromText('POLYGON ((100 0,120 0,120 20,100 20,100 0))')); ERROR: NEW ROW FOR relation "parcel" violates CHECK CONSTRAINT "enforce_srid_geom" -- -- 5. Try and insert geometry with right SRID INSERT INTO simon.parcel(gid,geom) VALUES (1,ST_PolygonFromText('POLYGON ((100 0,120 0,120 20,100 20,100 0))',28355)); Query returned successfully: 1 ROWS affected, 16 ms execution TIME. -- -- 6. Insert Another POLYGON INSERT INTO simon.parcel(gid,geom) VALUES (2,ST_PolygonFromText('POLYGON ((0 0,20 0,20 20,0 20,0 0),(10 10,10 11,11 11,11 10,10 10),(5 5,5 7,7 7,7 5,5 5))',28355)); Query returned successfully: 1 ROWS affected, 16 ms execution TIME. -- -- 7. Now try and insert a MULTIPOLYGON INSERT INTO simon.parcel(gid,geom) VALUES (3,ST_MultiPolygonFromText('MULTIPOLYGON (((0 0,20 0,20 20,0 20,0 0),(10 10,10 11,11 11,11 10,10 10),(5 5,5 7,7 7,7 5,5 5)),((50 5,50 7,70 7,70 5,50 5)))',28355)); ERROR: NEW ROW FOR relation "parcel" violates CHECK CONSTRAINT "enforce_geotype_geom" -- -- How do we fix this if we want both POLYGON and MULTIPOLYGONS in our table? -- We could do this back at the original call to AddGeometryColumn but here we will show how to do it post-factum. -- -- 8. Modify the constraint directly ALTER TABLE simon.parcel DROP CONSTRAINT enforce_geotype_geom; Query returned successfully WITH no RESULT IN 15 ms. -- ALTER TABLE simon.parcel ADD CONSTRAINT enforce_geotype_geom CHECK ((geometrytype(geom) = ANY (ARRAY['MULTIPOLYGON'::text, 'POLYGON'::text])) OR geom IS NULL); Query returned successfully WITH no RESULT IN 31 ms. -- -- 9. Try again INSERT INTO simon.parcel(gid,geom) VALUES (3,ST_MultiPolygonFromText('MULTIPOLYGON (((0 0,20 0,20 20,0 20,0 0), (10 10,10 11,11 11,11 10,10 10), (5 5,5 7,7 7,7 5,5 5)), ((50 5,50 7,70 7,70 5,50 5)))',28355)); Query returned successfully: 1 ROWS affected, 32 ms execution TIME. -- SELECT gid, ST_AsText(geom) FROM simon.parcel;
gid integer |
st_astext text |
---|---|
1 | “POLYGON ((100 0,120 0,120 20,100 20,100 0))” |
2 | “POLYGON ((0 0,20 0,20 20,0 20,0 0), (10 10,10 11,11 11,11 10,10 10), (5 5,5 7,7 7,7 5,5 5))” |
3 | “MULTIPOLYGON (((0 0,20 0,20 20,0 20,0 0), (10 10,10 11,11 11,11 10,10 10), (5 5,5 7,7 7,7 5,5 5)), ((50 5,50 7,70 7,70 5,50 5)))” |
Parcel Centroid Points within Parcel Polygons
Let’s add a new rule that a land parcel has to have a (single) centroid point that falls within the polygon representing the parcel. We can implement this in a number of ways.
Two Column Table
Firstly, let’s start by adding a new column to our existing table. Tables with multiple geometric columns are not common mainly because GIS packages have been unable to deal with them: though some nowadays do. However, in this situation we have a single centroid point with no other attributes describing the land parcel so it makes sense to add it to the parcel table. Note: If your GIS can’t cope with a multi-geometry columned table try using views for both visualisation and update.
SELECT addGeometryColumn('simon','parcel','centroid','28355','POINT','2');
addgeometry text |
---|
simon.parcel.centroid SRID:28355 TYPE:POINT DIMS:2 |
Our table now looks like this.
CREATE TABLE simon.parcel ( gid serial NOT NULL, geom geometry, centroid geometry, CONSTRAINT parcel_pkey PRIMARY KEY (gid), CONSTRAINT enforce_dims_centroid CHECK (st_ndims(centroid) = 2), CONSTRAINT enforce_dims_geom CHECK (st_ndims(geom) = 2), CONSTRAINT enforce_geotype_centroid CHECK (geometrytype(centroid) = 'POINT'::text OR centroid IS NULL), CONSTRAINT enforce_geotype_geom CHECK ((geometrytype(geom) = ANY (ARRAY['MULTIPOLYGON'::text, 'POLYGON'::text])) OR geom IS NULL), CONSTRAINT enforce_srid_centroid CHECK (st_srid(centroid) = 28355), CONSTRAINT enforce_srid_geom CHECK (st_srid(geom) = 28355) ) WITH ( OIDS=FALSE );
How can we implement a spatial constraint to ensure that any point added/updated is checked to ensure it falls within the host polygon? Well, we can use the ST_Covers() function directly in the check constraint. However, we cannot apply this constraint as we have rows in the table with no centroids and PostgreSQL does not have a NOVALIDATE (as Oracle does – this means no not apply the constraint to existing records only inserts/updates from now on) option when adding a constraint.
-- 1 Add centroids to existing polygons UPDATE simon.parcel SET centroid = ST_Centroid(geom); Query returned successfully: 3 ROWS affected, 62 ms execution TIME. -- -- 2. Now, apply centroid constraint ALTER TABLE simon.parcel ADD CONSTRAINT centroid_in_parcel CHECK (centroid IS NOT NULL AND ST_Covers(geom,centroid) = TRUE); ERROR: CHECK CONSTRAINT "centroid_in_parcel" IS violated BY SOME ROW -- -- 3. Find which rows fail SELECT gid, ST_Covers(geom,centroid) FROM simon.parcel;
gid integer |
st_covers boolean |
---|---|
1 | t |
2 | f |
3 | t |
-- 4 Fix it UPDATE simon.parcel SET centroid = ST_PointOnSurface(geom) WHERE gid = 2; Query returned successfully: 1 ROWS affected, 63 ms execution TIME. -- -- 5. Check SELECT gid, ST_Covers(geom,centroid) FROM simon.parcel WHERE gid = 2;
gid integer |
st_covers boolean |
---|---|
2 | t |
-- 6. Now we can apply the constraint ALTER TABLE simon.parcel ADD CONSTRAINT centroid_in_parcel CHECK (centroid IS NOT NULL AND ST_Covers(geom,centroid) = TRUE); Query returned successfully WITH no RESULT IN 16 ms. -- /* Table now looks like this CREATE TABLE simon.parcel ( gid serial NOT NULL, geom geometry, centroid geometry, CONSTRAINT parcel_pkey PRIMARY KEY (gid), CONSTRAINT centroid_in_parcel CHECK (centroid IS NOT NULL AND st_covers(geom, centroid) = true), CONSTRAINT enforce_dims_centroid CHECK (st_ndims(centroid) = 2), CONSTRAINT enforce_dims_geom CHECK (st_ndims(geom) = 2), CONSTRAINT enforce_geotype_centroid CHECK (geometrytype(centroid) = 'POINT'::text OR centroid IS NULL), CONSTRAINT enforce_geotype_geom CHECK ((geometrytype(geom) = ANY (ARRAY['MULTIPOLYGON'::text, 'POLYGON'::text])) OR geom IS NULL), CONSTRAINT enforce_srid_centroid CHECK (st_srid(centroid) = 28355), CONSTRAINT enforce_srid_geom CHECK (st_srid(geom) = 28355) ) WITH ( OIDS=FALSE ); */
Two Table Solution with Foreign Key
It is not common to see the above modelling. Mostly one sees the parcel polygons in one table with another table being used to hold the parcel centroids. We can still do our centroid_in_parcel check constraint, however, but there is a little bit more involved.
-- 1. Create a table to hold the centroid DROP TABLE simon.parcel_centroid; Query returned successfully WITH no RESULT IN 47 ms. -- CREATE TABLE simon.parcel_centroid ( gid serial NOT NULL PRIMARY KEY, gid_parcel INTEGER NOT NULL, CONSTRAINT parcel_gid_fk FOREIGN KEY (gid_parcel) REFERENCES simon.parcel(gid) ) WITH ( OIDS=FALSE ); NOTICE: CREATE TABLE will CREATE implicit SEQUENCE "parcel_centroid_gid_seq" FOR serial COLUMN "parcel_centroid.gid" NOTICE: CREATE TABLE / PRIMARY KEY will CREATE implicit INDEX "parcel_centroid_pkey" FOR TABLE "parcel_centroid" Query returned successfully WITH no RESULT IN 156 ms. -- /* Table looks like this ** CREATE TABLE simon.parcel_centroid ( gid serial NOT NULL, gid_parcel integer NOT NULL, geom geometry, CONSTRAINT parcel_centroid_pkey PRIMARY KEY (gid), CONSTRAINT parcel_gid_fk FOREIGN KEY (gid_parcel) REFERENCES simon.parcel (gid) MATCH SIMPLE ON UPDATE NO ACTION ON DELETE NO ACTION ) WITH ( OIDS=FALSE ); */ -- -- Change ownership ALTER TABLE simon.parcel_centroid OWNER TO postgres; Query returned successfully WITH no RESULT IN 16 ms. -- -- 2. Add geometry column and CHECK constraints on geometry SELECT addGeometryColumn('simon','parcel_centroid','geom','28355','POINT','2');
addgeometry |
---|
text |
simon.parcel_centroid.geom SRID:28355 TYPE:POINT DIMS:2 |
Our parcel_centroid table now looks like this:
CREATE TABLE simon.parcel_centroid ( gid serial NOT NULL, gid_parcel INTEGER NOT NULL, geom geometry, CONSTRAINT parcel_centroid_pkey PRIMARY KEY (gid), CONSTRAINT parcel_gid_fk FOREIGN KEY (gid_parcel) REFERENCES simon.parcel (gid) MATCH SIMPLE ON UPDATE NO ACTION ON DELETE NO ACTION, CONSTRAINT enforce_dims_geom CHECK (st_ndims(geom) = 2), CONSTRAINT enforce_geotype_geom CHECK (geometrytype(geom) = 'POINT'::text OR geom IS NULL), CONSTRAINT enforce_srid_geom CHECK (st_srid(geom) = 28355) ) WITH ( OIDS=FALSE ); */ -- -- 3. Now, insert data via a query against the parcel table INSERT INTO simon.parcel_centroid(gid_parcel, geom) SELECT gid,ST_Centroid(geom) FROM simon.parcel; Query returned successfully: 3 ROWS affected, 16 ms execution TIME.
The only way we can check that these centroids fall inside the geometry polygons in the related, parcel, table is by constructing a function and using it instead of ST_Covers in our CHECK constraint
-- 4. Construction function CREATE OR REPLACE FUNCTION simon.centroid_in_parcel(geometry) RETURNS INTEGER AS $BODY$ SELECT COUNT(*)::INTEGER FROM simon.parcel p WHERE ST_Covers(p.geom,$1); $BODY$ LANGUAGE 'sql' IMMUTABLE COST 100; Query returned successfully WITH no RESULT IN 16 ms. -- ALTER FUNCTION simon.centroid_in_parcel(geometry) OWNER TO postgres; Query returned successfully WITH no RESULT IN 16 ms. -- -- 5. Check for validity before application SELECT c.gid, ST_Covers(p.geom,c.geom) FROM simon.parcel INNER JOIN simon.parcel_centroid c ON ( c.gid_parcel = p.gid );
gid integer |
st_covers boolean |
---|---|
1 | t |
2 | t |
3 | f |
-- 6. Fix gid = 3 UPDATE simon.parcel_centroid c SET geom = (SELECT ST_PointOnSurface(geom) FROM simon.parcel p WHERE p.gid = c.gid_parcel) WHERE gid = 3; Query returned successfully: 1 ROWS affected, 15 ms execution TIME. -- -- 7. Check again for validity before application SELECT c.gid, ST_Covers(p.geom,c.geom) FROM simon.parcel p INNER JOIN simon.parcel_centroid c ON ( c.gid_parcel = p.gid ) WHERE c.gid = 3;
gid integer |
st_covers boolean |
---|---|
3 | t |
-- 8. Now apply constraint ALTER TABLE simon.parcel_centroid ADD CONSTRAINT centroid_in_parcel_ck CHECK (simon.centroid_in_parcel(geom) > 0); Query returned successfully WITH no RESULT IN 16 ms. -- /* Table looks like this ** CREATE TABLE simon.parcel_centroid ( gid serial NOT NULL, gid_parcel integer NOT NULL, geom geometry, CONSTRAINT parcel_centroid_pkey PRIMARY KEY (gid), CONSTRAINT parcel_gid_fk FOREIGN KEY (gid_parcel) REFERENCES simon.parcel (gid) MATCH SIMPLE ON UPDATE NO ACTION ON DELETE NO ACTION, CONSTRAINT centroid_in_parcel_ck CHECK (simon.centroid_in_parcel(geom) > 0) , CONSTRAINT enforce_dims_geom CHECK (st_ndims(geom) = 2), CONSTRAINT enforce_geotype_geom CHECK (geometrytype(geom) = 'POINT'::text OR geom IS NULL), CONSTRAINT enforce_srid_geom CHECK (st_srid(geom) = 28355) ) WITH ( OIDS=FALSE ); */ -- -- 9. Now test with an invalid centroid UPDATE simon.parcel_centroid c SET geom = (SELECT ST_Centroid(geom) FROM simon.parcel p WHERE p.gid = c.gid_parcel) WHERE gid = 3; ERROR: NEW ROW FOR relation "parcel_centroid" violates CHECK CONSTRAINT "centroid_in_parcel_ck"
Excellent it works exactly as we wish: no-one can now write a centroid point that falls outside its land parcel!
Because PostgreSQL allows functions to be called from within a table’s CHECK constraints, powerful spatial data quality constraints can be added to a data model with spatial data embedded with it.
I hope this little article is of use to someone.
Documentation
- MySQL Spatial General Functions
- Oracle LRS Objects
- Oracle Spatial Exporter (Java + pl/SQL)
- Oracle Spatial Object Functions
- Oracle Spatial Object Functions (Multi Page)
- PostGIS pl/pgSQL Functions
- SC4O Oracle Java Topology Suite (Java + pl/SQL)
- SQL Server Spatial General TSQL Functions
- SQL Server Spatial LRS TSQL Functions