查询PostgreSQL的表结构


select
    pt.schemaname as 模式名,
    --cast(obj_description(relfilenode, 'pg_class') as varchar) as 表描述,
    cast(obj_description(c.oid, 'pg_class') as varchar) as 表描述,
    pt.tableowner as 所有者,
    c.relname as 表名,
    a.attname as 列名,
    a.attnum as 序号,
    (
        case
            when a.attnotnull = true then true
            else false
        end
    ) as 是否非空,
    (
        select
            case
                when count(pg_constraint.*) > 0 then true
                else false
            end
        from
            pg_constraint
        inner join pg_class on
            pg_constraint.conrelid = pg_class.oid
        inner join pg_attribute on
            pg_attribute.attrelid = pg_class.oid
            and pg_attribute.attnum = any(pg_constraint.conkey)
        where
            pg_class.relname = c.relname
            and pg_constraint.contype = 'p'
            and pg_attribute.attname = a.attname
    ) as 是否是主键,
    t.typname as 字段类型1,
    format_type (
        A.atttypid,
        A.atttypmod
    ) as 字段类型2,
    (
        case
            when t.typname = 'numeric' then replace(replace(SUBSTRING(format_type(a.atttypid, a.atttypmod) from '\(.*\,'), '(', ''), ',', '')+ 0
            when a.attlen > 0 then a.attlen
            else a.atttypmod - 4
        end
    ) as 长度,
    replace(replace(SUBSTRING(format_type(a.atttypid, a.atttypmod) from '\,.*\)'), ')', ''), ',', '') as 精度,
    --( case     when a.attlen > 0 then a.attlen else a.atttypmod - 4 end ) as 长度2,
  (
        select
            d.description
        from
            pg_description d
        where
            d.objoid = a.attrelid
            and d.objsubid = a.attnum
    ) as 备注
from
    pg_tables pt,
    pg_class c,
    pg_attribute a ,
    pg_type t
where
    1 = 1
    and c.relname not like 'DEL%'
    and c.relname not like 'del%'
    --  and c.relname='dim_date'
    -- and t.typname  = 'float8'
    and pt.schemaname in ('skg_dm','skg_ods')
    and pt.tablename = c.relname
    and a.attnum>0
    and a.attrelid = c.oid
    and a.atttypid = t.oid
order by
    pt.schemaname,
    c.relname,
    是否是主键 desc,
    c.relname desc,
    a.attnum asc