Re: Index/trigger implementation for accessing latest records

From: Alvaro Herrera <alvherre(at)2ndquadrant(dot)com>
To: Alastair McKinley <a(dot)mckinley(at)analyticsengines(dot)com>
Cc: "pgsql-general(at)lists(dot)postgresql(dot)org" <pgsql-general(at)lists(dot)postgresql(dot)org>
Subject: Re: Index/trigger implementation for accessing latest records
Date: 2018-05-02 20:32:36
Message-ID: 20180502203236.lbua3y77zx2k7qg4@alvherre.pgsql
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: 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 and id != 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

In response to

Browse pgsql-general by date

  From Date Subject
Next Message Jim Michaels 2018-05-02 21:29:08 CSVQL? CSV SQL? tab-separated table I/O? RENAME COLUMN
Previous Message Gavin Flower 2018-05-02 10:36:12 Re: Index/trigger implementation for accessing latest records