Ensuring primary key is referenced at least once upon commit - Mailing list pgsql-sql

From Albert REINER
Subject Ensuring primary key is referenced at least once upon commit
Date
Msg-id 20010103002650.B1265@frithjof
Whole thread Raw
List pgsql-sql
Saluton,

suppose we have PostgreSQL 7.0.2 and two tables, a and b, like:

a: id serial primary key  ...

b: a int4 not null references a(id)  ...

In general there will be several rows in b with the same b.a, but how
can I make sure there is AT LEAST ONE row referencing a given id from
table a?

It seems obvious to me that this can only be meaningful in a
transaction, like:

begin
insert into a ...;
insert into b (a,...) values (curr_val(a_id_seq),...);
commit

And the check can only be made before committing.

My first idea (which was not very good) was to add a table constraint
on table a similar to `... foreign key (a) references b(a) initially
deferred', because only a foreign key seems to allow checks to be
deferred, and I cannot tell from the docs whether a foreign key is
actually incompatible with a primary key declaration on the same
field. - Of course this does not work, as there is no table b by the
time a is created, or vice versa.

Looking at the documentation for CREATE TRIGGER, I do not see how to
get it to fire only just before commit - I would need a syntax like
create trigger ... before commit insert on a execute ..., which is not
what is there.

Rules - another one of those exotic things I never thought I might
actually need - do not seem to provide a solution, either.

As long as I know that nobody will mess around with the database
directly but only with scripts I provide, I can easily provide the
necessary checks etc., so this may be not so much of an issue really.
Still, it would be good to know that this works, and I am pretty sure
that this must be possible, but I seem to be looking in the wrong
direction. Any help would be appreciated.

Thanks in advance,

Albert.


-- 

--------------------------------------------------------------------------
Albert Reiner                                   <areiner@tph.tuwien.ac.at>
Deutsch       *       English       *       Esperanto       *       Latine
--------------------------------------------------------------------------


pgsql-sql by date:

Previous
From: "Albert REINER"
Date:
Subject: Support for arrays in PL/pgSQL
Next
From: "Francis Solomon"
Date:
Subject: RE: order by day or month, etc