Postgresql insert trigger to set value

前端 未结 2 991
天涯浪人
天涯浪人 2020-12-08 03:58

Assume in Postgresql, I have a table T and one of its column is C1.

I want to trigger a function when a new record is adding to the table

2条回答
  •  再見小時候
    2020-12-08 04:34

    It is possible but you are likely to be better off setting a default constraint on the column instead. When creating the table that would look like:

    create table mytable as (
        C1 thetype not null default X
    );
    

    This says that if you add a row to the table and don't specify the value for C1 then X will be used instead. The not null is not necessary, but prevents updates from nulling that column assuming that's what you want.

    EDIT: This only works for constant X, from your comments it seems there are two possible solutions.

    Using a trigger would look something like this:

    create function update_row_trigger() returns trigger as $$
    begin
        if new.C1 is NULL then
            new.C1 := X;
        end if;
        return new;
    end
    $$ language plpgsql;
    
    create trigger mytrigger before insert on mytable for each row execute procedure update_row_trigger();
    

    The new variable in a trigger function is special, representing the row being inserted. Specifying the trigger as a before insert trigger means you can modify the row before it is written to the table.

    The second solution would be to use a computed column which Postgres defines in an unusual way:

    create or replace function C1(row mytable) returns columntype immutable as $$
    begin
        return X; -- where X is an expression using values from `row`
    end
    $$ language plpgsql;
    

    This creates a function that takes a row of your table and returns a value, you can call it using . notation though, meaning you can do:

    select
        *,
        t.C1
    from
        mytable t;
    

    The declaration of the function being immutable is optional, but it's needed if you want to index the "column". You would be able to index this column like this:

    create index on mytable (C1(mytable));
    

提交回复
热议问题