you can do the following steps to avoid the foreign key error during truncate
create automated script that DROPS all foreign keys and constraints (do NOT run it yet)
create automated script that RE-CREATES all foreign keys and constraints
Run drop script
run normal TRUNCATE your_table
run recreate keys script
with these steps the TRUNCATE command runs fine because there are no foreign keys.
the drop and re-create scripts are taken from https://blog.hagander.net/automatically-dropping-and-creating-constraints-131/
DROP SCRIPT:
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 SCRIPT:
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;