外键可能基于多个列,因此conkey
and confkey
of pg_constraint
是数组。您必须取消数组的嵌套才能获取列名称或类型的列表。您可以使用这些功能:
create or replace function get_col_names(rel regclass, cols int2[])
returns text language sql as $$
select string_agg(attname, ', ' order by ordinality)
from pg_attribute,
unnest(cols) with ordinality
where attrelid = rel
and attnum = unnest
$$;
create or replace function get_col_types(rel regclass, cols int2[])
returns text language sql as $$
select string_agg(typname, ', ' order by ordinality)
from pg_attribute a
join pg_type t on t.oid = atttypid,
unnest(cols) with ordinality
where attrelid = rel
and attnum = unnest
$$;
这些函数在查询约束和索引时可能非常方便。您的查询对他们来说很好而且简单:
select
conrelid::regclass,
get_col_names(conrelid, conkey) col_names,
get_col_types(conrelid, conkey) col_types,
conname
from pg_constraint
where contype ='f';
conrelid | col_names | col_types | conname
----------+-----------+-----------+------------------------
products | image_id | int4 | products_image_id_fkey
(1 row)