postgresqldatabase-triggerpostgresql-triggers

Postgres Function Trigger Sequence Dependency Error


I have the following functions and trigger with sequence setup:

I want to create a function and trigger that anytime I add a new row to STRATEGY_SITES table, the 'SITE_NUM' field will have the new sequential number from SITENUM_SEQ. Schema name is gismgr.

I am getting the following error:Underlying DBMS error[Error:control reached end of trigger procedure without return Context: PL/pgSQL function process_sites_edit()(gismgr.strategy_sites)::SQLSTATE=2F005][gismgr.startegy_sites]

CREATE OR REPLACE FUNCTION process_sites_edit() RETURNS TRIGGER AS $SITE_EDIT_TRIGGER$
   begin
            new.SITE_NUM := nextval('gismgr.SITENUM_SEQ');
end;
$SITE_EDIT_TRIGGER$ LANGUAGE 'plpgsql';
create TRIGGER SITE_EDIT_TRIGGER
before insert or update on STRATEGY_SITES for each row
EXECUTE PROCEDURE process_strategy_sites_edit();
CREATE SEQUENCE gismgr."SITENUM_SEQ" owned by gismgr.strategy_Sites.site_num
    INCREMENT 1
    START 19080
    MINVALUE 19080
    MAXVALUE 9999999999999999
    CACHE 20;

Solution

  • This seems to be an ORACLEism which is unnecessary in Postgres. Assuming your table already exsists then just

    alter table *table_name* alter column site_num default nextval('gismgr.SITENUM_SEQ')
    

    Also make sure the insert does not mention the site_num column. If you feel you must continue with the trigger approach the your trigger function needs to specify the return value.

    CREATE OR REPLACE FUNCTION process_sites_edit() 
    RETURNS TRIGGER AS $SITE_EDIT_TRIGGER$
    begin
         new.SITE_NUM := nextval('gismgr.SITENUM_SEQ');
         return new;
    end;
    $SITE_EDIT_TRIGGER$ LANGUAGE 'plpgsql';
    

    I would also suggest you do not want to fire the trigger on updates. That will change the site number on any/every update of a given row Are there FK referencing it - they will not be updated the update would fail. Further the procedure executed must match the function name:

    create TRIGGER SITE_EDIT_TRIGGER
    before insert on STRATEGY_SITES for each row
    EXECUTE PROCEDURE process_sites_edit();