Skip site navigation (1) Skip section navigation (2)

Re: freezing a particular field in a table

From: hubert depesz lubaczewski <depesz(at)gmail(dot)com>
To: fmiddleton(at)verizon(dot)net
Cc: pgsql-admin(at)postgresql(dot)org
Subject: Re: freezing a particular field in a table
Date: 2005-11-23 09:28:01
Message-ID: 9e4684ce0511230128y77557be3k2507d6eb1575c1e4@mail.gmail.com (view raw or flat)
Thread:
Lists: pgsql-admin
On 11/23/05, Ferindo Middleton Jr <fmiddleton(at)verizon(dot)net> wrote:
>
> Is there a way where you can implement a situation in a postgres table
> where a particular field cannot be changed when saved initially. I have
>

CREATE OR REPLACE FUNCTION impossible_to_change() RETURNS TRIGGER AS
$BODY$
DECLARE
BEGIN
        IF
                (NEW.some_field IS NULL AND OLD.some_field IS NOT NULL)
                OR
                (NEW.some_field IS NOT NULL AND OLD.some_field IS NULL)
                OR
                (NEW.some_field IS NOT NULL AND OLD.some_field IS NOT NULL
AND NEW.some_field <> OLD.some_field)
        THEN
                raise exception 'some_field cannod be changed!';
        END IF;
        RETURN NEW;
END;
$BODY$
LANGUAGE 'plpgsql';
CREATE TRIGGER impossible_to_change BEFORE UPDATE ON some_table FOR EACH ROW
EXECUTE PROCEDURE impossible_to_change();

in this way - whenever somebody will try to alter the value, it will raise
exception.
in case you dont want exceptions, and just want old value to stick (i would
vote against it), then just change body of the function to:
DECLARE
BEGIN
NEW.some_field := OLD.some_field;
return NEW;
END;

will work.

depesz

In response to

Responses

pgsql-admin by date

Next:From: Michael FuhrDate: 2005-11-23 17:55:22
Subject: Re: freezing a particular field in a table
Previous:From: Jason MinionDate: 2005-11-22 23:38:31
Subject: Re: freezing a particular field in a table

Privacy Policy | About PostgreSQL
Copyright © 1996-2014 The PostgreSQL Global Development Group