Foreign key behavior different in a function and outside

From: Mridula Mahadevan <mmahadevan(at)stratify(dot)com>
To: "pgsql-general(at)postgresql(dot)org" <pgsql-general(at)postgresql(dot)org>
Subject: Foreign key behavior different in a function and outside
Date: 2010-03-05 00:19:02
Message-ID: 0A59BA5B590B7E4A8D441196A9F17E904C701E04EB@corpmail11.calpurnia.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

I have 3 tables say A, B, C

CREATE TABLE A
(
A_id integer NOT NULL,
CONSTRAINT A_pkey PRIMARY KEY (A_id)
)
;

CREATE TABLE B
(
B_id serial NOT NULL,
A_id integer NOT NULL,
CONSTRAINT B_pkey PRIMARY KEY (B_id),
CONSTRAINT fkd08b6eeeb4f3a730 FOREIGN KEY (A_id)
REFERENCES A(A_id) MATCH SIMPLE
ON UPDATE NO ACTION ON DELETE NO ACTION
)
;

CREATE TABLE C
(
C_id serial NOT NULL,
B_id integer NOT NULL,
CONSTRAINT C_pkey PRIMARY KEY (C_id),
CONSTRAINT fk31a4865653f36b09 FOREIGN KEY (B_id)
REFERENCES B(B_id) MATCH SIMPLE
ON UPDATE NO ACTION ON DELETE NO ACTION
)
;

Insert into A values (1);
Insert into B values (1,1);
Insert into C values (1,1);

I try this query -
delete from B where B_id = 1;

As expected I get this error -
ERROR: update or delete on table "b" violates foreign key constraint "fk31a4865653f36b09" on table "c"
DETAIL: Key (b_id)=(1) is still referenced from table "c".

********** Error **********

ERROR: update or delete on table "b" violates foreign key constraint "fk31a4865653f36b09" on table "c"
SQL state: 23503
Detail: Key (b_id)=(1) is still referenced from table "c".

Now if I have this delete within a function

CREATE OR REPLACE FUNCTION delete_B(id integer)
RETURNS void AS
$BODY$
declare
vSql varchar;
BEGIN
delete from B where id = id;

END;
$BODY$
LANGUAGE 'plpgsql' VOLATILE
COST 100;

And I try to execute this -
select delete_B(1)

This even with no cascade delete, will succeed and child records are deleted from C. This does not happen on all my set ups but has been happening consistently on more than one. Any known issue here?

-mridula

Responses

Browse pgsql-general by date

  From Date Subject
Next Message John R Pierce 2010-03-05 01:03:13 Re: Optimal database table optimization method
Previous Message Wang, Mary Y 2010-03-04 23:52:45 Restore Data Encountered the ERROR: literal carriage return found in data Error