Re: Foreign keys on array elements - Mailing list pgsql-hackers

From Pavel Stehule
Subject Re: Foreign keys on array elements
Date
Msg-id Pine.LNX.4.44.0504200923250.9405-100000@kix.fsv.cvut.cz
Whole thread Raw
In response to Foreign keys on array elements  (Christopher Kings-Lynne <chriskl@familyhealth.com.au>)
List pgsql-hackers
> Hi,
> 
> Can you put a foreign key constraint on an array column that says that 
> each element of the array must match a primary key?
> 
> If not, is this a TODO perhaps?
> 
> Chris
> 
Hello, 

Using array values for foreign key is very special. I not sure, so all 
people need it. More interesting is CHECK on array. But you can write 
simply trigger.

CREATE OR REPLACE FUNCTION check_() RETURNS TRIGGER AS $$
DECLARE _v integer;
BEGIN FOR _i IN array_lower(NEW.array_value,1) ..            array_upper(NEW.array_value,1)  LOOP   PERFORM 1 FROM
some_tabWHERE pk = NEW.array_value[_i];   IF NOT FOUND THEN     RAISE EXCEPTION '..........';   END IF; END LOOP;
RETURNNEW;
 
END; $$ LANGUAGE plpgsql;

CREATE TRIGGER foo BEFORE INSERT OR UPDATE ON ... FOR EACH ROW EXECUTE PROCEDURE check_();

Regards
Pavel Stehule



pgsql-hackers by date:

Previous
From: Klaus Naumann
Date:
Subject: Re: Problem with PITR recovery
Next
From: Andreas Pflug
Date:
Subject: Re: [GENERAL] Idea for the statistics collector