Created
April 22, 2014 19:05
-
-
Save christopher-b/11190658 to your computer and use it in GitHub Desktop.
Postgres - Drop / Recreate constraints
This file contains 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
# These queries generate *other* queries that can be used to drop and recreate constraints on all tables in the database. | |
# Both must be run while the constrains still exist | |
# Drop constraints | |
SELECT 'ALTER TABLE "'||nspname||'"."'||relname||'" DROP CONSTRAINT "'||conname||'";' | |
FROM pg_constraint | |
INNER JOIN pg_class ON conrelid=pg_class.oid | |
INNER JOIN pg_namespace ON pg_namespace.oid=pg_class.relnamespace | |
ORDER BY CASE WHEN contype='f' THEN 0 ELSE 1 END,contype,nspname,relname,conname | |
# Recreate constraints | |
SELECT 'ALTER TABLE "'||nspname||'"."'||relname||'" ADD CONSTRAINT "'||conname||'" '|| | |
pg_get_constraintdef(pg_constraint.oid)||';' | |
FROM pg_constraint | |
INNER JOIN pg_class ON conrelid=pg_class.oid | |
INNER JOIN pg_namespace ON pg_namespace.oid=pg_class.relnamespace | |
ORDER BY CASE WHEN contype='f' THEN 0 ELSE 1 END DESC,contype DESC,nspname DESC,relname DESC,conname DESC; | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment