外部キーは複数の列に基づいている可能性があります。conkey
とconfkey
は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)
ありがとうございました。あなたの答えはとても役に立ちました – tavogus