Re: Enforcing serial uniqueness?

From: Jim Nasby <jnasby(at)pervasive(dot)com>
To: Steven Brown <swbrown(at)ucsd(dot)edu>
Cc: Tom Lane <tgl(at)sss(dot)pgh(dot)pa(dot)us>, kleptog(at)svana(dot)org, pgsql-general(at)postgresql(dot)org
Subject: Re: Enforcing serial uniqueness?
Date: 2006-03-23 17:51:39
Message-ID: AEB55622-A1D2-4608-9067-690738005F09@pervasive.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general


On Mar 23, 2006, at 3:33 AM, Steven Brown wrote:
> -- On INSERT, fill id from the sequence - creator has UPDATE
> permission.
> -- Block attempts to force the id.
> CREATE OR REPLACE FUNCTION foo_id_insert_procedure() RETURNS
> trigger SECURITY DEFINER AS '
> BEGIN
> IF NEW.id != 0 THEN
> RAISE EXCEPTION ''Setting id to a non-default is not allowed'';
> ELSE
> NEW.id := nextval(''foo_id_seq'');

BTW, with some clever use of TG_RELNAME you could probably make that
function generic, so that you could use it with any table; ie:
NEW.id := nextval( TG_RELNAME || ''_id_seq'');

Same holds true for the update function. You might also want to
create a function that does all the legwork of defining the sequence
and triggers for you.
--
Jim C. Nasby, Sr. Engineering Consultant jnasby(at)pervasive(dot)com
Pervasive Software http://pervasive.com work: 512-231-6117
vcard: http://jim.nasby.net/pervasive.vcf cell: 512-569-9461

In response to

Browse pgsql-general by date

  From Date Subject
Next Message Jim Nasby 2006-03-23 17:54:51 Re: Some pgbench results
Previous Message Jim Nasby 2006-03-23 17:41:07 Re: how to update structural & data changes between PostgreSQL