Go to content Go to navigation and search

Home

Current PostGIS Blog Articles


Search

Browse

RSS / Atom

Email me

textpattern

Creative Commons License
All Blog Articles, Data Models and Free Source Code by Simon Greener, The SpatialDB Advisor is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.

How to apply spatial constraints to PostGIS tables

Thursday May 14 2009 at 06:54

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 datat. 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:

  1. Primary/Unique Constraints;
  2. Not Null
  3. Foreign Key Constraints
  4. Column Check Constraints
  5. 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:

  1. Is of the right type ie POLYGON and not POINT
  2. Has right SRID (if supplied)
  3. 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 p
       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.

Creative Commons License

post this at del.icio.uspost this at Diggpost this at Technoratipost this at Redditpost this at Farkpost this at Yahoo! my webpost this at Windows Livepost this at Google Bookmarkspost this to Twitter

Comment [2]

great job Simon! I wonder if it is possible to use two different geometry tables and test whether a parcel is inside the Town boundary? What do you think?

— art lembo · 20 December 2009, 03:24 · #

Art,

Can you give me an example of two tables with some simple sample geometries?

regards
Simon

Simon · 20 December 2009, 06:49 · #