Created
May 12, 2025 18:11
-
-
Save JPBM135/1f7079edd83673eab3da62814f40efb3 to your computer and use it in GitHub Desktop.
Find table FK deps postgres
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
WITH RECURSIVE DependencyTree AS ( | |
-- Anchor member | |
SELECT | |
fk.confrelid AS referenced_oid, | |
fk.conrelid AS referencing_oid, | |
ns_child.nspname AS referencing_schema, | |
cl_child.relname AS referencing_table, | |
ns_parent.nspname AS referenced_schema, | |
cl_parent.relname AS referenced_table, | |
0 AS depth, | |
ARRAY[fk.confrelid, fk.conrelid] AS path_oids | |
FROM pg_constraint fk | |
JOIN pg_class cl_child ON fk.conrelid = cl_child.oid | |
JOIN pg_namespace ns_child ON cl_child.relnamespace = ns_child.oid | |
JOIN pg_class cl_parent ON fk.confrelid = cl_parent.oid | |
JOIN pg_namespace ns_parent ON cl_parent.relnamespace = ns_parent.oid | |
WHERE fk.contype = 'f' | |
AND cl_parent.relname = 'TABELA_AQUI' -- TABELA AQUI | |
AND ns_parent.nspname = 'public' | |
UNION ALL | |
-- Recursive member | |
SELECT | |
fk.confrelid AS referenced_oid, | |
fk.conrelid AS referencing_oid, | |
ns_child.nspname AS referencing_schema, | |
cl_child.relname AS referencing_table, | |
dt.referencing_schema AS referenced_schema, | |
dt.referencing_table AS referenced_table, | |
dt.depth + 1 AS depth, | |
dt.path_oids || fk.conrelid | |
FROM pg_constraint fk | |
JOIN pg_class cl_child ON fk.conrelid = cl_child.oid | |
JOIN pg_namespace ns_child ON cl_child.relnamespace = ns_child.oid | |
JOIN DependencyTree dt ON fk.confrelid = dt.referencing_oid | |
WHERE fk.contype = 'f' | |
AND NOT fk.conrelid = ANY(dt.path_oids) -- Prevent cycles | |
), | |
AllTablesToDelete AS ( | |
SELECT DISTINCT | |
referencing_schema, | |
referencing_table, | |
depth, | |
FORMAT('DELETE FROM "%I"."%I";', referencing_schema, referencing_table) AS delete_sql | |
FROM DependencyTree | |
UNION ALL | |
SELECT | |
'public' AS referencing_schema, | |
'TABELA_AQUI' AS referencing_table, | |
-1 AS depth, | |
'DELETE FROM "public"."TABELA_AQUI";' AS delete_sql | |
) | |
SELECT * | |
FROM AllTablesToDelete | |
ORDER BY depth DESC, referencing_schema, referencing_table; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment