Skip to content
Advertisement

Handle pg_error on generated columns

I have a table that consists of some PostGIS related data. These data are generated automatically on INSERT or UPDATE.

Sometimes the data provided on the polygon column might not fit the generation function and cause an error. I wanted to handle this error and set a default value when it fail.

— Last resort options —

  1. Creating postgres functions that handle this task but that would disassociate the work from the codebase.

Advertisement

Answer

As you’re using ST_MakePolygon I assume that the column "polygon" contains LINESTRINGs and sometimes they are invalid, which is raising an error in your DDL statement.

What you could do is to create a CASE conditional that validates the geometry before trying to create the polygon. For instance, this query checks if the geometry is valid, if it is a LINESTRING and if its ring is closed before attempting to create the POLYGON. In case it fails, it generates an empty polygon (change it to NULL if you want):

Demo: db<>fiddle

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement