Skip to content

Instantly share code, notes, and snippets.

@gtors
Created October 19, 2016 21:38
Show Gist options
  • Save gtors/a913bf73e048ded33adab5629ae96aca to your computer and use it in GitHub Desktop.
Save gtors/a913bf73e048ded33adab5629ae96aca to your computer and use it in GitHub Desktop.
Add ON DELETE CASCADE to all foreign keys in scheme
do $$
declare
rec record;
namespace_restriction text;
begin
namespace_restriction = 'public';
for rec in select
conrelid::oid::regclass::text as constraint_table,
conname as constraint_name,
pg_catalog.pg_get_constraintdef(oid) as constraint_definition
from
pg_catalog.pg_constraint
where
-- type == foreign keys
contype = 'f' and
-- on_delete != cascade
confdeltype != 'c' and
-- namespace == your_namespace
connamespace = (select oid from pg_catalog.pg_namespace where nspname = namespace_restriction)
loop
execute
'alter table ' || rec.constraint_table || ' ' ||
'drop constraint ' || rec.constraint_name || ', ' ||
'add constraint ' || rec.constraint_name || ' ' || rec.constraint_definition || ' on delete cascade';
end loop;
end $$;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment