Re: Denormalized field - Mailing list pgsql-general

From Luca Ferrari
Subject Re: Denormalized field
Date
Msg-id CAKoxK+5mhHy6v_L3u+A5mwA+AfQYSThDjeRq2-nDiqaA07gG9Q@mail.gmail.com
Whole thread Raw
In response to Denormalized field  (Robert James <srobertjames@gmail.com>)
List pgsql-general
On Sun, Aug 18, 2013 at 5:56 AM, Robert James <srobertjames@gmail.com> wrote:
> What's the best way to do this automatically? Can this be done with
> triggers? (On UPDATE or INSERT, SET slow_function_f =
> slow_function(new_f) ) How?
>

Define  a before trigger that updates your column. For instance:

CREATE OR REPLACE FUNCTION f_trigger() RETURNS TRIGGER AS $$ BEGIN
NEW.f_field := f_function( NEW.pk ); RETURN NEW; END $$ LANGUAGE
plpgsql;

CREATE TRIGGER tr_foo BEFORE INSERT OR UPDATE ON foo FOR EACH ROW
EXECUTE PROCEDURE f_trigger();

Of course, adjust the trigger and the trigger function to check
against some conditions (e.g., insert, update, nulls).

> Will creating an index on slow_function(f) do this?
>

You can create the index on the function result, assuming it is immutable.

Luca


pgsql-general by date:

Previous
From: Vik Fearing
Date:
Subject: Re: Denormalized field
Next
From: Giuseppe Broccolo
Date:
Subject: Re: Query on a record variable