concept trigger in category postgis

appears as: trigger, triggers, The trigger, trigger, A trigger
PostGIS in Action, Third Edition

This is an excerpt from Manning's book PostGIS in Action, Third Edition.

  • You have to ensure the second geometry field is updated when your main geometry field is, which means putting in a trigger. Someone may get confused and update the secondary geometry field instead of the primary geometry field.
  • A trigger is a piece of procedural code that does one of the following:

    14.5.2 Using INSTEAD OF triggers

    In the auto-updatable view created in listing 14.11, the default insert behavior isn’t what you’d want, because the feature_type columns won’t be set, also would be nice to set the arrondissment if it is not passed in. To fix that issue, you can override the default insert behavior with a INSTEAD OF trigger. INSTEAD OF triggers are only supported for views. Listing 14.12 demonstrates an INSTEAD OF insert trigger that will be run instead of the default insert behavior when a record is inserted into the ch14.stations view.

    Listing 14.12. Instead of trigger on a view
    CREATE OR REPLACE FUNCTION trig_subway_insert()
      RETURNS trigger AS  #1
    $$
    BEGIN
        INSERT INTO ch14.paris_points (
            gid, osm_id, ar_num, feature_name, feature_type, geom
        )
        VALUES (
            DEFAULT,
            NEW.osm_id,
            COALESCE(NEW.ar_num,
                     (SELECT a.ar_num
                        FROM ch14.arrondissements AS a
                      WHERE ST_Intersects(NEW.geom, a.geom )) ) ,
            NEW.feature_name,
            'subway',
            NEW.geom
        );
        RETURN NEW;
    END;
      $$ language plpgsql;
    
    CREATE TRIGGER t01_trig_subway_insert #2
      INSTEAD OF INSERT
      ON ch14.subways
      FOR EACH ROW
      EXECUTE PROCEDURE trig_subway_insert();

    A trigger always involves at least two parts -

  • a function that returns a trigger