Re: Index/trigger implementation for accessing latest records - Mailing list pgsql-general

From Alvaro Herrera
Subject Re: Index/trigger implementation for accessing latest records
Date
Msg-id 20180502203236.lbua3y77zx2k7qg4@alvherre.pgsql
Whole thread Raw
In response to Index/trigger implementation for accessing latest records  (Alastair McKinley <a.mckinley@analyticsengines.com>)
List pgsql-general
Alastair McKinley wrote:

> create function latest_record_update() returns trigger as
> $$
> BEGIN
>         update location_records set latest_record = false where person_id = new.person_id and latest_record is true
andid != new.id;
 
>         return new;
> END;
> $$ language plpgsql;
> 
> create trigger latest_record_trigger before insert on location_records
> for each row execute procedure latest_record_update();

For maximum safety, you should use BEFORE trigger only to modify the row
being inserted/updated (or to abort the operation); any change to other
rows should occur in an AFTER trigger.  One risk associated with failing
to do that is that some other BEFORE trigger further modifies the new
row, making your trigger-invoked UPDATE wrong.  Also, be sure to think
about possible infinite recursion.

Another angle to keep in mind is what happens with insertions of
historical records, i.e. those that are not latest (today you think "ah,
but that never happens" and three months from now this is requested as a
feature.  Time to rethink the whole development ...)  You'd clobber the
latest_record flag without a replacement for it, which is probably
undesirable.

-- 
Álvaro Herrera                https://www.2ndQuadrant.com/
PostgreSQL Development, 24x7 Support, Remote DBA, Training & Services


pgsql-general by date:

Previous
From: Gavin Flower
Date:
Subject: Re: Index/trigger implementation for accessing latest records
Next
From: Jim Michaels
Date:
Subject: CSVQL? CSV SQL? tab-separated table I/O? RENAME COLUMN