Search code examples
postgresqltriggerssql-updaterow

Build a trigger that avoids to update the values of one column


I have a table in PostgretSQL. I want to build a trigger that avoids to update colb1 column. This column has five alternatives: Rea, Can, Loa, Mul, Alm. So the trigger doesn't let upload values from Rea to Can.

I've built this function but this is fail.

CREATE OR REPLACE FUNCTION example_trigger()
  RETURNS trigger AS
$BODY$
BEGIN
     new.colb1.tabl1 = 'Rea' := old.colb1.tabl1 = 'Can';
     new.colb1.tabl1 = 'Can' := old.colb1.tabl1 = 'Rea';
     RETURN new;
END
$BODY$
  LANGUAGE plpgsql VOLATILE
  COST 100;


DROP TRIGGER IF EXISTS trigger_name ON table1;
  CREATE TRIGGER trigger_name BEFORE UPDATE ON table1
    FOR EACH ROW EXECUTE PROCEDURE example_trigger();

I edited my post with changes:

CREATE OR REPLACE FUNCTION example_trigger()
    RETURNS TRIGGER AS
$$
BEGIN
    NEW.colb1 := OLD.colb1;
    RETURN NEW;
END;
$$ LANGUAGE plpgsql;


CREATE TRIGGER not_changes
 BEFORE UPDATE 
 ON tabl1
 FOR EACH ROW
 EXECUTE PROCEDURE example_trigger();

It's not exactly that I want because I want that the values Loa, Mul and Alm can be update.


Solution

  • A slight modification of your function to stop the modification of colb1 from Rea or Can to Can or Rea.

    CREATE OR REPLACE FUNCTION example_trigger()
        RETURNS TRIGGER AS
    $$
    BEGIN
        IF OLD.colb1 in ('Rea', Can') AND NEW.colb1 IN ('Rea', 'Can') THEN
           NEW.colb1 := OLD.colb1;
        END IF;
        RETURN NEW;
    END;
    $$ LANGUAGE plpgsql;
    

    This will not stop a user from using an intermediate UPDATE to change to one of Loa/Mul/Alm and then to either Rea or Can