How to enforce the use of the sequence for serial columns ?

Поиск
Список
Период
Сортировка
От Marc Mamin
Тема How to enforce the use of the sequence for serial columns ?
Дата
Msg-id CA896D7906BF224F8A6D74A1B7E54AB319875F@JENMAIL01.ad.intershop.net
обсуждение исходный текст
Ответы Re: How to enforce the use of the sequence for serial columns ?  (Jerry Sievers <jerry@jerrysievers.com>)
Список pgsql-admin

I'd like to ensure that nobody provide the ID in an insert statement when the id is linked to a sequence.
I tried it with a trigger, but the id value is fed before the "BEFORE INSERT" test is performed (see below)...

Any Idea ?

Cheers,

Marc

CREATE FUNCTION serialtest() RETURNS trigger AS $serialtest$
    BEGIN
        -- Check that the id is provided
        IF NEW.id IS NOT NULL THEN
            RAISE EXCEPTION 'id will be set from a sequence; do not provide it!';
        END IF;
       
        RETURN NEW;
    END;
$serialtest$ LANGUAGE plpgsql;

CREATE TABLE test_table
(
  id serial primary key,
  foo int
);

CREATE TRIGGER test BEFORE INSERT OR UPDATE ON test_table    
FOR EACH ROW EXECUTE PROCEDURE serialtest();

insert into test_table(foo)values(1);

ERROR: id will be set from a sequence; do not provide it!
SQL state: P0001

В списке pgsql-admin по дате отправления:

Предыдущее
От: "Shoaib Mir"
Дата:
Сообщение: Re: Backup
Следующее
От: "Donald Fraser"
Дата:
Сообщение: Re: How to enforce the use of the sequence for serial columns ?