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

时间:2016-01-29 05:04:45

标签: postgresql cascade

有没有办法获得一个表格列表,这些表格也会被postgres中的TRUNCATE CASCADE截断?

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

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

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

1 个答案:

答案 0 :(得分:1)

this回答的帮助下,您可以通过此查询获取外部表名称

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'

<强> OR

使用其他查询创建视图

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'