获取将被级联截断的表列表

Get list of tables that would be truncated by a cascade

有没有办法获取在 postgres 中也会被 TRUNCATE CASCADE 截断的表列表?

例如,假设我们有三个表:

a
b (depends on a)
c (depends on b)

TRUNCATE a CASCADE; 也会截断 bc。我们怎么能提前检查呢?

this 答案的帮助下,您可以通过此查询获得外国 table 名称

SELECT tc.constraint_name
      ,tc.table_name
      ,kcu.column_name
      ,ccu.table_name AS foreign_table_name
      ,ccu.column_name AS foreign_column_name 
FROM 
    information_schema.table_constraints AS tc 
    JOIN information_schema.key_column_usage AS kcu
      ON tc.constraint_name = kcu.constraint_name
    JOIN information_schema.constraint_column_usage AS ccu
      ON ccu.constraint_name = tc.constraint_name
WHERE constraint_type = 'FOREIGN KEY' AND ccu.table_name = 'a'

使用另一个查询创建视图

CREATE VIEW vdepend_table
AS
SELECT s1.constraint_name
    ,s1.table_name
    ,s1.column_name
    ,s1.ordinal_position
    ,s2.table_name_ref
    ,s2.column_name_ref
    ,s2.ordinal_position_ref
FROM (
    SELECT key_column_usage.constraint_name
        ,key_column_usage.table_name
        ,key_column_usage.column_name
        ,columns.ordinal_position
    FROM information_schema.key_column_usage
    JOIN information_schema.columns USING (
            table_name
            ,column_name
            )
    ) s1
JOIN (
    SELECT constraint_column_usage.constraint_name
        ,constraint_column_usage.table_name AS table_name_ref
        ,constraint_column_usage.column_name AS column_name_ref
        ,cols_ref.ordinal_position AS ordinal_position_ref
    FROM information_schema.constraint_column_usage
    JOIN information_schema.columns cols_ref ON cols_ref.table_name::TEXT = constraint_column_usage.table_name::TEXT
        AND cols_ref.column_name::TEXT = constraint_column_usage.column_name::TEXT
    ) s2 ON s1.constraint_name::TEXT = s2.constraint_name::TEXT
    AND NOT s1.table_name::TEXT = s2.table_name_ref::TEXT;

用法:

 select table_name from vdepend_table where table_name_ref='a'