Skip site navigation (1) Skip section navigation (2)

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

From: "Marc Mamin" <M(dot)Mamin(at)intershop(dot)de>
To: <pgsql-admin(at)postgresql(dot)org>
Subject: How to enforce the use of the sequence for serial columns ?
Date: 2006-12-13 11:46:10
Message-ID: CA896D7906BF224F8A6D74A1B7E54AB319875F@JENMAIL01.ad.intershop.net (view raw or flat)
Thread:
Lists: 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

Responses

pgsql-admin by date

Next:From: Donald FraserDate: 2006-12-13 12:08:59
Subject: Re: How to enforce the use of the sequence for serial columns ?
Previous:From: Shoaib MirDate: 2006-12-13 11:22:41
Subject: Re: Backup

Privacy Policy | About PostgreSQL
Copyright © 1996-2014 The PostgreSQL Global Development Group