PostgreSQL:用于获取表的所有外键引用的列表的 SQL 脚本

Ste*_*Gon 2 sql database postgresql foreign-keys information-schema

我有一个表,breeds其主键为breed_name,并且希望获取引用的所有表、列和约束的列表,breeds无论 中引用的列如何breeds。如果还有另一个表,cats并且该表具有如下约束:

CREATE TABLE cats 
(
    cat_name  text,
    cat_breed text,

    CONSTRAINT cat_breed_name 
        FOREIGN KEY (cat_breed) REFERENCES breeds(breed_name)
)
Run Code Online (Sandbox Code Playgroud)

我应该返回如下一行:

base_table     base_col    referencing_table   referencing_col  constraint_sql
breeds         breed_name  cats                cat_breed        CONSTRAINT cat_breed_name FOREIGN KEY (cat_breed) REFERENCES breeds(breed_name)
Run Code Online (Sandbox Code Playgroud)

还应该列出非主键引用,并且它应该处理复合键。

Ste*_*Gon 7

您必须加入pg_constraintpg_attribute取消嵌套列数组(可以是复合键)才能获取基表中引用的列名称。您必须使用pg_class来获取表名。 pg_get_constraintdef为您提供用于创建约束的实际 SQL 行。

SELECT (select  r.relname from pg_class r where r.oid = c.confrelid) as base_table,
       a.attname as base_col,
       (select r.relname from pg_class r where r.oid = c.conrelid) as referencing_table,
       UNNEST((select array_agg(attname) from pg_attribute where attrelid = c.conrelid and array[attnum] <@ c.conkey)) as referencing_col,
       pg_get_constraintdef(c.oid) contraint_sql
  FROM pg_constraint c join pg_attribute a on c.confrelid=a.attrelid and a.attnum = ANY(confkey)
 WHERE c.confrelid = (select oid from pg_class where relname = 'breeds')
   AND c.confrelid!=c.conrelid;
Run Code Online (Sandbox Code Playgroud)