如何获得带有描述的 table 属性(PostgreSQL 12+)?

How do I get table attributes (PostgreSQL 12+) with a description?

我想获取相关对象的属性:架构、table、名称、类型、PK、notnull、唯一、索引、约束、序列。 如果多个索引、约束或序列与它们关联,我的查询会重复属性... 我该如何避免这种情况? 同时,我希望索引、约束和序列是数组...

CREATE OR REPLACE VIEW public.my_attributes
AS SELECT
    ns.nspname AS "schema",
    ct.oid AS "tablerelid",
    ct.relname AS "tablename",
    a.attrelid AS "relid",
    a.attname AS "name",
    a.attnum AS "num",
    ( a.atttypid::regtype ) AS "type",
    a.atttypmod AS "typemod",
    ( CASE WHEN ( a.atttypid::regtype )::text = 'geometry' THEN postgis_typmod_type(a.atttypmod) END ) AS "typegeom",
    ( CASE WHEN ( a.atttypid::regtype )::text = 'geometry' THEN postgis_typmod_srid(a.atttypmod) END ) AS "typesrid",
    ia.indisprimary AS "pk",
    a.attnotnull AS "notnull",
    ia.indisunique AS "unique",
    ci.relname AS "index",
    cr.conname AS "constraint",
    pg_get_serial_sequence(quote_ident(ct.relname), quote_ident(a.attname)) AS "sequence"
FROM
    pg_attribute a
    LEFT JOIN pg_class ct ON ct.oid = a.attrelid
    LEFT JOIN pg_namespace ns ON ns.oid = ct.relnamespace
    LEFT JOIN pg_tablespace ts ON ts.oid = ct.reltablespace
    LEFT JOIN pg_index ia ON ia.indrelid = a.attrelid AND a.attnum = ANY(ia.indkey)
    LEFT JOIN pg_class ci ON ci.oid = ia.indexrelid
    LEFT JOIN pg_constraint cr ON cr.conrelid = a.attrelid AND cr.conkey @> ARRAY[a.attnum]
WHERE
    ns.nspname != 'information_schema'
    AND ns.nspname != 'pg_catalog'
    AND ns.nspname != 'tiger'
    AND ns.nspname != 'tiger_date'
    AND ns.nspname != 'topology'
    AND ct.relname != 'pointcloud_formats'
    AND ct.relname != 'spatial_ref_sys'
    AND ct.relname NOT LIKE 'pg_temp_%'
    AND ct.relkind = ANY( ARRAY['r'::"char", 'p'::"char"] )
    AND a.attnum > 0
    AND NOT a.attisdropped
ORDER BY
    lower(ns.nspname),
    lower(ct.relname),
    a.attnum;

您可以添加一个 GROUP BY 子句,其中 所有 列都是唯一的,例如 a.attnumct.relname。对于其他列,使用聚合函数,如 string_aggarray_agg.

我不能说获取 unique{f,t,f} 的行有多大用处,但是如果您想以不同的形式显示信息,则必须更改查询因此。