From: | Andreas Joseph Krogh <andreak(at)officenet(dot)no> |
---|---|
To: | pgsql-general <pgsql-general(at)postgresql(dot)org> |
Subject: | Dropping all foreign keys for a column in a table |
Date: | 2012-08-29 08:34:53 |
Message-ID: | 503DD42D.4040708@officenet.no |
Views: | Raw Message | Whole Thread | Download mbox | Resend email |
Thread: | |
Lists: | pgsql-general |
Here is a function for removing all FKs on a column (yes, PG for some
reason allows multiple similar FKs on a column):
create or replace function remove_fk_by_table_and_column(p_table_name
varchar, p_column_name varchar) returns INTEGER as $$
declare
v_fk_name varchar := NULL;
v_fk_num_removed INTEGER := 0;
begin
FOR v_fk_name IN (SELECT ss2.conname
FROM pg_attribute af, pg_attribute a,
(SELECT conname, conrelid,confrelid,conkey[i] AS conkey,
confkey[i] AS confkey
FROM (SELECT conname, conrelid,confrelid,conkey,confkey,
generate_series(1,array_upper(conkey,1)) AS i
FROM pg_constraint WHERE contype = 'f') ss) ss2
WHERE af.attnum = confkey
AND af.attrelid = confrelid
AND a.attnum = conkey
AND a.attrelid = conrelid
AND a.attrelid = p_table_name::regclass
AND a.attname = p_column_name) LOOP
execute 'alter table ' || quote_ident(p_table_name) || ' drop
constraint ' || quote_ident(v_fk_name);
v_fk_num_removed = v_fk_num_removed + 1;
END LOOP;
return v_fk_num_removed;
end;
$$ language plpgsql;
Usage:
select remove_fk_by_table_and_column('my_table', 'some_column');
I find myself often having to remove FK-constraints on a column because
they are refactored to point to other columns or whatever, and I thought
this might be useful to others.
--
Andreas Joseph Krogh<andreak(at)officenet(dot)no> - mob: +47 909 56 963
Senior Software Developer / CEO - OfficeNet AS - http://www.officenet.no
Public key: http://home.officenet.no/~andreak/public_key.asc
From | Date | Subject | |
---|---|---|---|
Next Message | Sergey Konoplev | 2012-08-29 08:35:27 | Re: Dropping a column on parent table doesn't propagate to children? |
Previous Message | Chris Travers | 2012-08-29 00:40:02 | Re: Which postgresql should i choose to migrate from 8.3 ? 8.4 or 9.1? |