如何查询外键onupdate / ondelete?

时间:2016-07-26 16:26:28

标签: sql database postgresql database-schema

我有以下查询来返回外键详细信息:

SELECT
    tc.constraint_name,
    tc.table_name,
    kcu.column_name,
    ccu.table_schema AS foreign_table_schema,
    ccu.table_name AS foreign_table_name,
    ccu.column_name AS foreign_column_name,
    pg_catalog.pg_get_constraintdef(pg_constraint.oid, true) AS foreign_definition
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
    JOIN pg_constraint
      ON pg_constraint.conname = tc.constraint_name
WHERE constraint_type = 'FOREIGN KEY'

由此,我可以获得重新构建外键所需的大部分信息。唯一缺少的是更新和更新关于删除信息(尽管可以从foreign_definition解析)。我一直试图想办法接收这些细节而不解析它,但到目前为止我没有运气。

有没有人知道我可以在哪个表上找到更新和删除详细信息?

这是专门针对Postgres的。

1 个答案:

答案 0 :(得分:2)

像这样吗?..

SELECT
    tc.constraint_name,
    tc.table_name,
    kcu.column_name,
    ccu.table_schema AS foreign_table_schema,
    ccu.table_name AS foreign_table_name,
    ccu.column_name AS foreign_column_name,
    pg_catalog.pg_get_constraintdef(pg_constraint.oid, true) AS foreign_definition,
    update_rule,
    delete_rule
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
    JOIN pg_constraint
      ON pg_constraint.conname = tc.constraint_name
    LEFT OUTER JOIN information_schema.referential_constraints rc on tc.constraint_name = rc.constraint_name and ccu.table_schema = rc.constraint_schema

WHERE constraint_type = 'FOREIGN KEY'