Re: declare column update expression - Mailing list pgsql-general

From Scott Marlowe
Subject Re: declare column update expression
Date
Msg-id dcc563d10809110853v4ccf21f6vee62863609f1fd76@mail.gmail.com
Whole thread Raw
In response to declare column update expression  ("Chris Velevitch" <chris.velevitch@gmail.com>)
Responses Re: declare column update expression  ("Chris Velevitch" <chris.velevitch@gmail.com>)
List pgsql-general
On Thu, Sep 11, 2008 at 1:35 AM, Chris Velevitch
<chris.velevitch@gmail.com> wrote:
> In 7.4, how do I declare that a column in a table is to be
> automatically set to the value of some fixed expression whenever a row
> is updated?
>
> Eg column last_modified is always set to current_timestamp

A trigger as Pavel said.  writing them in plpgsql seems a bit hard at
first, but it's a simple language and it's pretty easy to write stuff
like this in.

Here's a simple example of last modified trigger using plpgsql from way back:

-- FUNCTION --

CREATE FUNCTION modtime () RETURNS opaque AS '
    BEGIN
        new.lm :=''now'';
        RETURN new;
    END;
' LANGUAGE 'plpgsql';

-- TABLE --

CREATE TABLE dtest (
    id int primary key,
    fluff text,
    lm timestamp without time zone
);


--TRIGGER --

CREATE TRIGGER dtest
  BEFORE UPDATE or INSERT ON dtest FOR EACH ROW EXECUTE PROCEDURE
    modtime(lm);

-- SQL TESTS --

INSERT INTO dtest (id, fluff) VALUES (1,'this is a test');
INSERT INTO dtest (id, fluff) VALUES (2,'this is another test');
SELECT * FROM dtest;
  1 | this is a test       | 2003-04-02 10:33:12.577089
  2 | this is another test | 2003-04-02 10:33:18.591148
UPDATE dtest SET id=3 WHERE id=1;
  3 | this is a test | 2003-04-02 10:34:52.219963  [1]
UPDATE dtest SET fluff='now is the time' WHERE id=2;
SELECT * FROM dtest WHERE id=2;
  2 | now is the time | 2003-04-02 10:38:06.259443 [2]
UPDATE dtest SET lm='2003-04-02 08:30:00' WHERE id=3;
SELECT * FROM dtest WHERE id=3;
  3 | this is a test | 2003-04-02 10:36:15.45687 [3]

[1] The timestamp has changed for this record when we changed the id field.
[2] The timestamp also changes for the fluff field.
[3] We tried to set lm, but the trigger on that field in dtest
intercepted the change and forced it












>
>
>
> Chris
> --
> Chris Velevitch
> Manager - Adobe Platform Users Group, Sydney
> m: 0415 469 095
> www.apugs.org.au
>
> Adobe Platform Users Group, Sydney
> September meeting: It's Going To Be Brilliant
> Date: Mon 29th September 6pm for 6:30 start
> Details and RSVP on http://apugs2008september.eventbrite.com
>
> --
> Sent via pgsql-general mailing list (pgsql-general@postgresql.org)
> To make changes to your subscription:
> http://www.postgresql.org/mailpref/pgsql-general
>

pgsql-general by date:

Previous
From: Peter Eisentraut
Date:
Subject: Re: psql scripting tutorials
Next
From: Alvaro Herrera
Date:
Subject: Re: psql scripting tutorials