Re: handing created and updated fields - Mailing list pgsql-general

From Martijn van Oosterhout
Subject Re: handing created and updated fields
Date
Msg-id 20050110121527.GC18809@svana.org
Whole thread Raw
In response to handing created and updated fields  ("Jim C. Nasby" <decibel@decibel.org>)
List pgsql-general
On Mon, Jan 10, 2005 at 05:28:47AM -0600, Jim C. Nasby wrote:
> I think I saw something posted about this recently, but I can't find it
> in the archives now. :(
>
> I want to have created and updated fields in a table that are kept
> up-to-date by the database and can't be changed accidentally. I think
> this can be done with rules, but I'm not sure of the best way to do it.
> Basically:
>
> ON INSERT: force created and updated to be current_timestamp
> ON UPDATE: deny updated created. force updated to be set to
> current_timestamp

Nope, you want triggers. I don't remember the syntax, but the basic
structure would be...

ON INSERT DO TRIGGER set_timestamp
ON UPDATE DO TRIGGER update_timestamp

set_timestamp()
  NEW.created = now()
  NEW.updated = now()

update_timestamp()
  if OLD.created <> NEW.created then ERROR
  NEW.updated = now()

Hope this helps,
--
Martijn van Oosterhout   <kleptog@svana.org>   http://svana.org/kleptog/
> Patent. n. Genius is 5% inspiration and 95% perspiration. A patent is a
> tool for doing 5% of the work and then sitting around waiting for someone
> else to do the other 95% so you can sue them.

Attachment

pgsql-general by date:

Previous
From: Antony Paul
Date:
Subject: ORDER BY in UNION query
Next
From: Mark Rae
Date:
Subject: Re: PostgreSQL 8.0.0 Release Candidate 4