Last active
September 8, 2015 12:33
-
-
Save akheron/368ed409dea96706d2a3 to your computer and use it in GitHub Desktop.
Change foreign key constraints to point to a different table
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- PostgreSQL | |
SELECT | |
'ALTER TABLE ' || source_tbl.relname || ' ' || | |
'DROP CONSTRAINT '|| constr.conname ||'; ' || | |
'ALTER TABLE ' || source_tbl.relname || ' ' || | |
'ADD CONSTRAINT ' || constr.conname || ' ' || | |
'FOREIGN KEY (' || source_col.attname || ') ' || | |
'REFERENCES new_table_name (primary_key_name);' | |
FROM pg_constraint constr | |
INNER JOIN pg_class target_tbl ON constr.confrelid = target_tbl.oid | |
INNER JOIN pg_attribute target_col ON target_tbl.oid = target_col.attrelid | |
INNER JOIN pg_class source_tbl ON constr.conrelid = source_tbl.oid | |
INNER JOIN pg_attribute source_col ON source_tbl.oid = source_col.attrelid | |
WHERE target_tbl.relname = 'target_table_name' | |
AND target_col.attname = 'primary_key_name' | |
AND source_col.attnum = constr.conkey[1]; | |
-- Outputs the following statements for all foreign key constraints that refer | |
-- target_table_name (primary_key_name): | |
-- ALTER TABLE source_table_name DROP CONSTRAINT old_constraint_name; | |
-- ALTER TABLE source_table_name | |
-- ADD CONSTRAINT old_constraint_name | |
-- FOREIGN KEY (referencing_column_name) REFERENCES new_table_name (primary_key_name); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment